[
  {
    "path": ".editorconfig",
    "content": "# editorconfig.org\r\n\r\n# top-most EditorConfig file\r\nroot = true\r\n\r\n# Default settings:\r\n# A newline ending every file\r\n# Use 4 spaces as indentation\r\n[*]\r\ntrim_trailing_whitespace = true\r\ninsert_final_newline = true\r\nindent_style = space\r\nindent_size = 4\r\n\r\n# Xml project files\r\n[*.{csproj,vcxproj,vcxproj.filters,proj,nativeproj,locproj}]\r\nindent_size = 2\r\n\r\n# Xml files\r\n[*.{xml,stylecop,resx,ruleset}]\r\nindent_size = 2\r\n\r\n# Xml config files\r\n[*.{props,targets,config,nuspec}]\r\nindent_size = 2\r\n\r\n# Shell scripts\r\n[*.sh]\r\nend_of_line = lf\r\n[*.{cmd,bat,ps1}]\r\nend_of_line = crlf\r\n"
  },
  {
    "path": ".gitattributes",
    "content": "* -crlf"
  },
  {
    "path": ".github/CONTRIBUTING.md",
    "content": "# How to contribute\r\n\r\nFirst of all, thank you for wanting to contribute to Nancy! We really appreciate all the awesome support we get from our community. We want to keep it as easy as possible to contribute changes that get things working in your environment. There are a few guidelines that we need contributors to follow so that we have a chance of keeping on top of things.\r\n\r\n- [Making Changes](#making-changes)\r\n  - [Handling Updates from Upstream/Master](#handling-updates-from-upstreammaster)\r\n  - [Sending a Pull Request](#sending-a-pull-request)\r\n- [Style Guidelines](#style-guidelines)\r\n\r\n## Making Changes\r\n\r\n1. [Fork](http://help.github.com/forking/) on GitHub\r\n1. Clone your fork locally\r\n1. Configure the upstream repo (`git remote add upstream git://github.com/NancyFx/Nancy`)\r\n1. Create a local branch (`git checkout -b myBranch`)\r\n1. Work on your feature\r\n1. Rebase if required (see below)\r\n1. Push the branch up to GitHub (`git push origin myBranch`)\r\n1. Send a Pull Request on GitHub\r\n\r\nYou should **never** work on a clone of master, and you should **never** send a pull request from master - always from a branch. The reasons for this are detailed below.\r\n\r\n### Handling Updates from Upstream/Master\r\n\r\nWhile you're working away in your branch it's quite possible that your upstream master (most likely the canonical NancyFx version) may be updated. If this happens you should:\r\n\r\n1. [Stash](http://git-scm.com/book/en/Git-Tools-Stashing) any un-committed changes you need to\r\n1. `git checkout master`\r\n1. `git pull upstream master`\r\n1. `git checkout myBranch`\r\n1. `git rebase master myBranch`\r\n1. `git push origin master` - (optional) this makes sure your remote master is up to date\r\n\r\nThis ensures that your history is \"clean\" i.e. you have one branch off from master followed by your changes in a straight line. Failing to do this ends up with several \"messy\" merges in your history, which we don't want. This is the reason why you should always work in a branch and you should never be working in, or sending pull requests from, master.\r\n\r\nIf you're working on a long running feature then you may want to do this quite often, rather than run the risk of potential merge issues further down the line.\r\n\r\n### Sending a Pull Request\r\n\r\nWhile working on your feature you may well create several branches, which is fine, but before you send a pull request you should ensure that you have rebased back to a single \"Feature branch\". We care about your commits, and we care about your feature branch; but we don't care about how many or which branches you created while you were working on it :smile:.\r\n\r\nWhen you're ready to go you should confirm that you are up to date and rebased with upstream/master (see \"Handling Updates from Upstream/Master\" above), and then:\r\n\r\n1. `git push origin myBranch`\r\n1. Send a descriptive [Pull Request](http://help.github.com/pull-requests/) on GitHub - making sure you have selected the correct branch in the GitHub UI!\r\n1. Wait for @TheCodeJunkie to merge your changes in and reformat all of your code because he has StyleCop OCD :wink:.\r\n\r\nAnd remember; **A pull-request with tests is a pull-request that's likely to be pulled in.** :grin: Bonus points if you document your feature in our [wiki](https://github.com/NancyFx/Nancy/wiki) once it has been pulled in\r\n\r\n## Style Guidelines\r\n\r\n- Indent with 4 spaces, **not** tabs.\r\n- No underscore (`_`) prefix for member names.\r\n- Use `this` when accessing instance members, e.g. `this.Name = \"TheCodeJunkie\";`.\r\n- Use the `var` keyword unless the inferred type is not obvious.\r\n- Use the C# type aliases for types that have them, e.g. `int` instead of `Int32`, `string` instead of `String` etc.\r\n- Use meaningful names (no hungarian notation).\r\n- Wrap `if`, `else` and `using` blocks (or blocks in general, really) in curly braces, even if it's a single line.\r\n- Put `using` statements inside namespace.\r\n- Pay attention to whitespace and extra blank lines\r\n- Absolutely **no** regions\r\n\r\n> If you are a ReSharper user, you can make use of our `.DotSettings` file to ensure you cover as many of our style guidelines as possible. There may be some style guidelines which are not covered by the file, so please pay attention to the style of existing code.\r\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE.md",
    "content": "### Prerequisites\r\n\r\n- [ ] I have written a descriptive issue title\r\n- [ ] I have verified that I am running the latest version of Nancy\r\n- [ ] I have verified if the problem exist in both `DEBUG` and `RELEASE` mode\r\n- [ ] I have searched [open](https://github.com/NancyFx/Nancy/issues) and [closed](https://github.com/NancyFx/Nancy/issues?q=is%3Aissue+is%3Aclosed) issues to ensure it has not already been reported\r\n\r\n### Description\r\n<!-- A description of the bug or feature -->\r\n\r\n### Steps to Reproduce\r\n<!-- List of steps, sample code, failing test or link to a project that reproduces the behavior -->\r\n\r\n### System Configuration\r\n<!-- Tell us about the environment where you are experiencing the bug -->\r\n\r\n- Nancy version:\r\n- Nancy host\r\n  - [ ] Nancy.Hosting.Aspnet\r\n  - [ ] Nancy.Hosting.Self\r\n  - [ ] Nancy.Owin (<!-- Name your OWIN server here, for example HttpListener, HttpSysServer, Kestrel, Nowin, System.Web -->)\r\n  - [ ] Other:\r\n- Other Nancy packages and versions:\r\n- Environment (Operating system, version and so on):\r\n- .NET Framework version:\r\n- Additional information:\r\n\r\n<!-- Thanks for reporting the issue to Nancy! -->\r\n"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "content": "### Prerequisites\r\n\r\n- [ ] I have written a descriptive pull-request title\r\n- [ ] I have verified that there are no overlapping [pull-requests](https://github.com/NancyFx/Nancy/pulls) open\r\n- [ ] I have verified that I am following the Nancy [code style guidelines](https://github.com/NancyFx/Nancy/blob/45238076ad0b7f6ecabd6bae8469e30458d02efe/CONTRIBUTING.md#style-guidelines)\r\n- [ ] I have provided test coverage for my change (where applicable)\r\n\r\n### Description\r\n<!-- A description of the changes proposed in the pull-request -->\r\n\r\n<!-- Thanks for contributing to Nancy! -->\r\n"
  },
  {
    "path": ".gitignore",
    "content": "*.[Cc]ache\r\n*.csproj.user\r\n*.[Rr]e[Ss]harper*\r\n*.sln.cache\r\n*.suo\r\n*.user\r\n*.orig\r\n*.pidb\r\n*.ide\r\n*.userprefs\r\n/AssemblyInfo.cs\r\n.DS_Store\r\ndeploy/\r\n/build/\r\n[Bb]in/\r\n[Dd]ebug/\r\n[Oo]bj/\r\n[Rr]elease/\r\n_[Rr]e[Ss]harper*/\r\n*.docstates\r\n*.tss\r\n*.ncrunchproject\r\n*.ncrunchsolution\r\n*.dotCover\r\nsrc/_NCrunch_Nancy/\r\nThumbs.db\r\n.idea\r\n*.GhostDoc.xml\r\nGemfile.lock\r\n.vs/\r\npackages/\r\nproject.lock.json\r\nTestAssembly.dll\r\n[Tt]ools/Cake.*\r\n.vscode/\r\n.dotnet/\r\n[Tt]ools/Addins/\r\nTestResults/\r\n"
  },
  {
    "path": ".mailmap",
    "content": "Andreas Håkansson <andreas@thecodejunkie.com> <andreas@selfinflicted.org>\r\nAndreas Håkansson <andreas@thecodejunkie.com> <andreas@thecodejunkie.com>\r\nAndreas Håkansson <andreas@thecodejunkie.com> <thecodejunkie@users.noreply.github.com>\r\nAndreas Håkansson <andreas@thecodejunkie.com> <andreas@selfinflicted.org>\r\n\r\nSteven Robbins <grumpydev@users.noreply.github.com> <ste.robbins@gmail.com>\r\nSteven Robbins <grumpydev@users.noreply.github.com> <steve@robbins.me.uk>\r\nSteven Robbins <grumpydev@users.noreply.github.com> <grumpydev@users.noreply.github.com>\r\n\r\nBrendan Forster <brendan@github.com> <shift.key@gmail.com>\r\nBrendan Forster <brendan@github.com> <brendan@github.com>\r\n\r\nJonathan Channon <jonathan.channon@gmail.com> <jonathan.channon@gmail.com>\r\nJonathan Channon <jonathan.channon@gmail.com> <jonathan@jonathanchannon.com>\r\n\r\nBrendan Tompkins <brendan.tompkins@gmail.com> <brendan.tompkins@gmail.com>\r\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: csharp\r\nos:\r\n  - linux\r\n  - osx\r\n\r\nsudo: required\r\ndist: trusty\r\n\r\nmono:\r\n  - 4.4.2\r\n\r\ndotnet: 2.1.4\r\n\r\nscript:\r\n  - ./build.sh --verbosity=minimal\r\n\r\nnotifications:\r\n  email:\r\n    - nancy@nancyfx.org\r\n"
  },
  {
    "path": "Nancy.ruleset",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<RuleSet Name=\"Nancy\" ToolsVersion=\"14.0\">\r\n  <Include Path=\"allrules.ruleset\" Action=\"Default\" />\r\n  <Rules AnalyzerId=\"AsyncUsageAnalyzers\" RuleNamespace=\"AsyncUsageAnalyzers\">\r\n    <Rule Id=\"AvoidAsyncSuffix\" Action=\"None\" />\r\n    <Rule Id=\"AvoidAsyncVoid\" Action=\"None\" />\r\n    <Rule Id=\"UseAsyncSuffix\" Action=\"None\" />\r\n    <Rule Id=\"UseConfigureAwait\" Action=\"Error\" />\r\n  </Rules>\r\n  <Rules AnalyzerId=\"Microsoft.Analyzers.ManagedCodeAnalysis\" RuleNamespace=\"Microsoft.Rules.Managed\">\r\n    <Rule Id=\"CA1000\" Action=\"None\" />\r\n    <Rule Id=\"CA1001\" Action=\"None\" />\r\n    <Rule Id=\"CA1002\" Action=\"None\" />\r\n    <Rule Id=\"CA1003\" Action=\"None\" />\r\n    <Rule Id=\"CA1004\" Action=\"None\" />\r\n    <Rule Id=\"CA1005\" Action=\"None\" />\r\n    <Rule Id=\"CA1006\" Action=\"None\" />\r\n    <Rule Id=\"CA1007\" Action=\"None\" />\r\n    <Rule Id=\"CA1008\" Action=\"None\" />\r\n    <Rule Id=\"CA1009\" Action=\"None\" />\r\n    <Rule Id=\"CA1010\" Action=\"None\" />\r\n    <Rule Id=\"CA1011\" Action=\"None\" />\r\n    <Rule Id=\"CA1012\" Action=\"None\" />\r\n    <Rule Id=\"CA1013\" Action=\"None\" />\r\n    <Rule Id=\"CA1014\" Action=\"None\" />\r\n    <Rule Id=\"CA1016\" Action=\"None\" />\r\n    <Rule Id=\"CA1017\" Action=\"None\" />\r\n    <Rule Id=\"CA1018\" Action=\"None\" />\r\n    <Rule Id=\"CA1019\" Action=\"None\" />\r\n    <Rule Id=\"CA1020\" Action=\"None\" />\r\n    <Rule Id=\"CA1021\" Action=\"None\" />\r\n    <Rule Id=\"CA1023\" Action=\"None\" />\r\n    <Rule Id=\"CA1024\" Action=\"None\" />\r\n    <Rule Id=\"CA1025\" Action=\"None\" />\r\n    <Rule Id=\"CA1026\" Action=\"None\" />\r\n    <Rule Id=\"CA1027\" Action=\"None\" />\r\n    <Rule Id=\"CA1028\" Action=\"None\" />\r\n    <Rule Id=\"CA1030\" Action=\"None\" />\r\n    <Rule Id=\"CA1031\" Action=\"None\" />\r\n    <Rule Id=\"CA1032\" Action=\"None\" />\r\n    <Rule Id=\"CA1033\" Action=\"None\" />\r\n    <Rule Id=\"CA1034\" Action=\"None\" />\r\n    <Rule Id=\"CA1035\" Action=\"None\" />\r\n    <Rule Id=\"CA1036\" Action=\"None\" />\r\n    <Rule Id=\"CA1038\" Action=\"None\" />\r\n    <Rule Id=\"CA1039\" Action=\"None\" />\r\n    <Rule Id=\"CA1040\" Action=\"None\" />\r\n    <Rule Id=\"CA1041\" Action=\"None\" />\r\n    <Rule Id=\"CA1043\" Action=\"None\" />\r\n    <Rule Id=\"CA1044\" Action=\"None\" />\r\n    <Rule Id=\"CA1045\" Action=\"None\" />\r\n    <Rule Id=\"CA1046\" Action=\"None\" />\r\n    <Rule Id=\"CA1047\" Action=\"None\" />\r\n    <Rule Id=\"CA1048\" Action=\"None\" />\r\n    <Rule Id=\"CA1049\" Action=\"None\" />\r\n    <Rule Id=\"CA1050\" Action=\"None\" />\r\n    <Rule Id=\"CA1051\" Action=\"None\" />\r\n    <Rule Id=\"CA1052\" Action=\"None\" />\r\n    <Rule Id=\"CA1053\" Action=\"None\" />\r\n    <Rule Id=\"CA1054\" Action=\"None\" />\r\n    <Rule Id=\"CA1055\" Action=\"None\" />\r\n    <Rule Id=\"CA1056\" Action=\"None\" />\r\n    <Rule Id=\"CA1057\" Action=\"None\" />\r\n    <Rule Id=\"CA1058\" Action=\"None\" />\r\n    <Rule Id=\"CA1059\" Action=\"None\" />\r\n    <Rule Id=\"CA1060\" Action=\"None\" />\r\n    <Rule Id=\"CA1061\" Action=\"None\" />\r\n    <Rule Id=\"CA1062\" Action=\"None\" />\r\n    <Rule Id=\"CA1063\" Action=\"None\" />\r\n    <Rule Id=\"CA1064\" Action=\"None\" />\r\n    <Rule Id=\"CA1065\" Action=\"None\" />\r\n    <Rule Id=\"CA1300\" Action=\"None\" />\r\n    <Rule Id=\"CA1301\" Action=\"None\" />\r\n    <Rule Id=\"CA1302\" Action=\"None\" />\r\n    <Rule Id=\"CA1303\" Action=\"None\" />\r\n    <Rule Id=\"CA1304\" Action=\"None\" />\r\n    <Rule Id=\"CA1305\" Action=\"None\" />\r\n    <Rule Id=\"CA1306\" Action=\"None\" />\r\n    <Rule Id=\"CA1307\" Action=\"None\" />\r\n    <Rule Id=\"CA1308\" Action=\"None\" />\r\n    <Rule Id=\"CA1309\" Action=\"None\" />\r\n    <Rule Id=\"CA1400\" Action=\"None\" />\r\n    <Rule Id=\"CA1401\" Action=\"None\" />\r\n    <Rule Id=\"CA1402\" Action=\"None\" />\r\n    <Rule Id=\"CA1403\" Action=\"None\" />\r\n    <Rule Id=\"CA1404\" Action=\"None\" />\r\n    <Rule Id=\"CA1405\" Action=\"None\" />\r\n    <Rule Id=\"CA1406\" Action=\"None\" />\r\n    <Rule Id=\"CA1407\" Action=\"None\" />\r\n    <Rule Id=\"CA1408\" Action=\"None\" />\r\n    <Rule Id=\"CA1409\" Action=\"None\" />\r\n    <Rule Id=\"CA1410\" Action=\"None\" />\r\n    <Rule Id=\"CA1411\" Action=\"None\" />\r\n    <Rule Id=\"CA1412\" Action=\"None\" />\r\n    <Rule Id=\"CA1413\" Action=\"None\" />\r\n    <Rule Id=\"CA1414\" Action=\"None\" />\r\n    <Rule Id=\"CA1415\" Action=\"None\" />\r\n    <Rule Id=\"CA1500\" Action=\"None\" />\r\n    <Rule Id=\"CA1501\" Action=\"None\" />\r\n    <Rule Id=\"CA1502\" Action=\"None\" />\r\n    <Rule Id=\"CA1504\" Action=\"None\" />\r\n    <Rule Id=\"CA1505\" Action=\"None\" />\r\n    <Rule Id=\"CA1506\" Action=\"None\" />\r\n    <Rule Id=\"CA1600\" Action=\"None\" />\r\n    <Rule Id=\"CA1601\" Action=\"None\" />\r\n    <Rule Id=\"CA1700\" Action=\"None\" />\r\n    <Rule Id=\"CA1701\" Action=\"None\" />\r\n    <Rule Id=\"CA1702\" Action=\"None\" />\r\n    <Rule Id=\"CA1703\" Action=\"None\" />\r\n    <Rule Id=\"CA1704\" Action=\"None\" />\r\n    <Rule Id=\"CA1707\" Action=\"None\" />\r\n    <Rule Id=\"CA1708\" Action=\"None\" />\r\n    <Rule Id=\"CA1709\" Action=\"None\" />\r\n    <Rule Id=\"CA1710\" Action=\"None\" />\r\n    <Rule Id=\"CA1711\" Action=\"None\" />\r\n    <Rule Id=\"CA1712\" Action=\"None\" />\r\n    <Rule Id=\"CA1713\" Action=\"None\" />\r\n    <Rule Id=\"CA1714\" Action=\"None\" />\r\n    <Rule Id=\"CA1715\" Action=\"None\" />\r\n    <Rule Id=\"CA1716\" Action=\"None\" />\r\n    <Rule Id=\"CA1717\" Action=\"None\" />\r\n    <Rule Id=\"CA1719\" Action=\"None\" />\r\n    <Rule Id=\"CA1720\" Action=\"None\" />\r\n    <Rule Id=\"CA1721\" Action=\"None\" />\r\n    <Rule Id=\"CA1722\" Action=\"None\" />\r\n    <Rule Id=\"CA1724\" Action=\"None\" />\r\n    <Rule Id=\"CA1725\" Action=\"None\" />\r\n    <Rule Id=\"CA1726\" Action=\"None\" />\r\n    <Rule Id=\"CA1800\" Action=\"None\" />\r\n    <Rule Id=\"CA1801\" Action=\"None\" />\r\n    <Rule Id=\"CA1802\" Action=\"None\" />\r\n    <Rule Id=\"CA1804\" Action=\"None\" />\r\n    <Rule Id=\"CA1806\" Action=\"None\" />\r\n    <Rule Id=\"CA1809\" Action=\"None\" />\r\n    <Rule Id=\"CA1810\" Action=\"None\" />\r\n    <Rule Id=\"CA1811\" Action=\"None\" />\r\n    <Rule Id=\"CA1812\" Action=\"None\" />\r\n    <Rule Id=\"CA1813\" Action=\"None\" />\r\n    <Rule Id=\"CA1814\" Action=\"None\" />\r\n    <Rule Id=\"CA1815\" Action=\"None\" />\r\n    <Rule Id=\"CA1816\" Action=\"None\" />\r\n    <Rule Id=\"CA1819\" Action=\"None\" />\r\n    <Rule Id=\"CA1820\" Action=\"None\" />\r\n    <Rule Id=\"CA1821\" Action=\"None\" />\r\n    <Rule Id=\"CA1822\" Action=\"None\" />\r\n    <Rule Id=\"CA1823\" Action=\"None\" />\r\n    <Rule Id=\"CA1824\" Action=\"None\" />\r\n    <Rule Id=\"CA1900\" Action=\"None\" />\r\n    <Rule Id=\"CA1901\" Action=\"None\" />\r\n    <Rule Id=\"CA1903\" Action=\"None\" />\r\n    <Rule Id=\"CA2000\" Action=\"None\" />\r\n    <Rule Id=\"CA2001\" Action=\"None\" />\r\n    <Rule Id=\"CA2002\" Action=\"None\" />\r\n    <Rule Id=\"CA2003\" Action=\"None\" />\r\n    <Rule Id=\"CA2004\" Action=\"None\" />\r\n    <Rule Id=\"CA2006\" Action=\"None\" />\r\n    <Rule Id=\"CA2100\" Action=\"None\" />\r\n    <Rule Id=\"CA2101\" Action=\"None\" />\r\n    <Rule Id=\"CA2102\" Action=\"None\" />\r\n    <Rule Id=\"CA2103\" Action=\"None\" />\r\n    <Rule Id=\"CA2104\" Action=\"None\" />\r\n    <Rule Id=\"CA2105\" Action=\"None\" />\r\n    <Rule Id=\"CA2106\" Action=\"None\" />\r\n    <Rule Id=\"CA2107\" Action=\"None\" />\r\n    <Rule Id=\"CA2108\" Action=\"None\" />\r\n    <Rule Id=\"CA2109\" Action=\"None\" />\r\n    <Rule Id=\"CA2111\" Action=\"None\" />\r\n    <Rule Id=\"CA2112\" Action=\"None\" />\r\n    <Rule Id=\"CA2114\" Action=\"None\" />\r\n    <Rule Id=\"CA2115\" Action=\"None\" />\r\n    <Rule Id=\"CA2116\" Action=\"None\" />\r\n    <Rule Id=\"CA2117\" Action=\"None\" />\r\n    <Rule Id=\"CA2118\" Action=\"None\" />\r\n    <Rule Id=\"CA2119\" Action=\"None\" />\r\n    <Rule Id=\"CA2120\" Action=\"None\" />\r\n    <Rule Id=\"CA2121\" Action=\"None\" />\r\n    <Rule Id=\"CA2122\" Action=\"None\" />\r\n    <Rule Id=\"CA2123\" Action=\"None\" />\r\n    <Rule Id=\"CA2124\" Action=\"None\" />\r\n    <Rule Id=\"CA2126\" Action=\"None\" />\r\n    <Rule Id=\"CA2130\" Action=\"None\" />\r\n    <Rule Id=\"CA2131\" Action=\"None\" />\r\n    <Rule Id=\"CA2132\" Action=\"None\" />\r\n    <Rule Id=\"CA2133\" Action=\"None\" />\r\n    <Rule Id=\"CA2134\" Action=\"None\" />\r\n    <Rule Id=\"CA2135\" Action=\"None\" />\r\n    <Rule Id=\"CA2136\" Action=\"None\" />\r\n    <Rule Id=\"CA2137\" Action=\"None\" />\r\n    <Rule Id=\"CA2138\" Action=\"None\" />\r\n    <Rule Id=\"CA2139\" Action=\"None\" />\r\n    <Rule Id=\"CA2140\" Action=\"None\" />\r\n    <Rule Id=\"CA2141\" Action=\"None\" />\r\n    <Rule Id=\"CA2142\" Action=\"None\" />\r\n    <Rule Id=\"CA2143\" Action=\"None\" />\r\n    <Rule Id=\"CA2144\" Action=\"None\" />\r\n    <Rule Id=\"CA2145\" Action=\"None\" />\r\n    <Rule Id=\"CA2146\" Action=\"None\" />\r\n    <Rule Id=\"CA2147\" Action=\"None\" />\r\n    <Rule Id=\"CA2149\" Action=\"None\" />\r\n    <Rule Id=\"CA2151\" Action=\"None\" />\r\n    <Rule Id=\"CA2200\" Action=\"None\" />\r\n    <Rule Id=\"CA2201\" Action=\"None\" />\r\n    <Rule Id=\"CA2202\" Action=\"None\" />\r\n    <Rule Id=\"CA2204\" Action=\"None\" />\r\n    <Rule Id=\"CA2205\" Action=\"None\" />\r\n    <Rule Id=\"CA2207\" Action=\"None\" />\r\n    <Rule Id=\"CA2208\" Action=\"None\" />\r\n    <Rule Id=\"CA2210\" Action=\"None\" />\r\n    <Rule Id=\"CA2211\" Action=\"None\" />\r\n    <Rule Id=\"CA2212\" Action=\"None\" />\r\n    <Rule Id=\"CA2213\" Action=\"None\" />\r\n    <Rule Id=\"CA2214\" Action=\"None\" />\r\n    <Rule Id=\"CA2215\" Action=\"None\" />\r\n    <Rule Id=\"CA2216\" Action=\"None\" />\r\n    <Rule Id=\"CA2217\" Action=\"None\" />\r\n    <Rule Id=\"CA2218\" Action=\"None\" />\r\n    <Rule Id=\"CA2219\" Action=\"None\" />\r\n    <Rule Id=\"CA2220\" Action=\"None\" />\r\n    <Rule Id=\"CA2221\" Action=\"None\" />\r\n    <Rule Id=\"CA2222\" Action=\"None\" />\r\n    <Rule Id=\"CA2223\" Action=\"None\" />\r\n    <Rule Id=\"CA2224\" Action=\"None\" />\r\n    <Rule Id=\"CA2225\" Action=\"None\" />\r\n    <Rule Id=\"CA2226\" Action=\"None\" />\r\n    <Rule Id=\"CA2227\" Action=\"None\" />\r\n    <Rule Id=\"CA2228\" Action=\"None\" />\r\n    <Rule Id=\"CA2229\" Action=\"None\" />\r\n    <Rule Id=\"CA2230\" Action=\"None\" />\r\n    <Rule Id=\"CA2231\" Action=\"None\" />\r\n    <Rule Id=\"CA2232\" Action=\"None\" />\r\n    <Rule Id=\"CA2233\" Action=\"None\" />\r\n    <Rule Id=\"CA2234\" Action=\"None\" />\r\n    <Rule Id=\"CA2235\" Action=\"None\" />\r\n    <Rule Id=\"CA2236\" Action=\"None\" />\r\n    <Rule Id=\"CA2237\" Action=\"None\" />\r\n    <Rule Id=\"CA2238\" Action=\"None\" />\r\n    <Rule Id=\"CA2239\" Action=\"None\" />\r\n    <Rule Id=\"CA2240\" Action=\"None\" />\r\n    <Rule Id=\"CA2241\" Action=\"None\" />\r\n    <Rule Id=\"CA2242\" Action=\"None\" />\r\n    <Rule Id=\"CA2243\" Action=\"None\" />\r\n    <Rule Id=\"CA5122\" Action=\"None\" />\r\n  </Rules>\r\n  <Rules AnalyzerId=\"Microsoft.CodeAnalysis.CSharp\" RuleNamespace=\"Microsoft.CodeAnalysis.CSharp\">\r\n    <Rule Id=\"AD0001\" Action=\"None\" />\r\n    <Rule Id=\"CS0028\" Action=\"None\" />\r\n    <Rule Id=\"CS0078\" Action=\"None\" />\r\n    <Rule Id=\"CS0105\" Action=\"None\" />\r\n    <Rule Id=\"CS0108\" Action=\"None\" />\r\n    <Rule Id=\"CS0109\" Action=\"None\" />\r\n    <Rule Id=\"CS0114\" Action=\"None\" />\r\n    <Rule Id=\"CS0162\" Action=\"None\" />\r\n    <Rule Id=\"CS0164\" Action=\"None\" />\r\n    <Rule Id=\"CS0168\" Action=\"None\" />\r\n    <Rule Id=\"CS0183\" Action=\"None\" />\r\n    <Rule Id=\"CS0184\" Action=\"None\" />\r\n    <Rule Id=\"CS0197\" Action=\"None\" />\r\n    <Rule Id=\"CS0219\" Action=\"None\" />\r\n    <Rule Id=\"CS0251\" Action=\"None\" />\r\n    <Rule Id=\"CS0252\" Action=\"None\" />\r\n    <Rule Id=\"CS0253\" Action=\"None\" />\r\n    <Rule Id=\"CS0278\" Action=\"None\" />\r\n    <Rule Id=\"CS0279\" Action=\"None\" />\r\n    <Rule Id=\"CS0280\" Action=\"None\" />\r\n    <Rule Id=\"CS0282\" Action=\"None\" />\r\n    <Rule Id=\"CS0402\" Action=\"None\" />\r\n    <Rule Id=\"CS0419\" Action=\"None\" />\r\n    <Rule Id=\"CS0420\" Action=\"None\" />\r\n    <Rule Id=\"CS0435\" Action=\"None\" />\r\n    <Rule Id=\"CS0436\" Action=\"None\" />\r\n    <Rule Id=\"CS0437\" Action=\"None\" />\r\n    <Rule Id=\"CS0440\" Action=\"None\" />\r\n    <Rule Id=\"CS0458\" Action=\"None\" />\r\n    <Rule Id=\"CS0464\" Action=\"None\" />\r\n    <Rule Id=\"CS0465\" Action=\"None\" />\r\n    <Rule Id=\"CS0469\" Action=\"None\" />\r\n    <Rule Id=\"CS0472\" Action=\"None\" />\r\n    <Rule Id=\"CS0473\" Action=\"None\" />\r\n    <Rule Id=\"CS0612\" Action=\"None\" />\r\n    <Rule Id=\"CS0618\" Action=\"None\" />\r\n    <Rule Id=\"CS0626\" Action=\"None\" />\r\n    <Rule Id=\"CS0628\" Action=\"None\" />\r\n    <Rule Id=\"CS0642\" Action=\"None\" />\r\n    <Rule Id=\"CS0652\" Action=\"None\" />\r\n    <Rule Id=\"CS0657\" Action=\"None\" />\r\n    <Rule Id=\"CS0658\" Action=\"None\" />\r\n    <Rule Id=\"CS0659\" Action=\"None\" />\r\n    <Rule Id=\"CS0660\" Action=\"None\" />\r\n    <Rule Id=\"CS0661\" Action=\"None\" />\r\n    <Rule Id=\"CS0665\" Action=\"None\" />\r\n    <Rule Id=\"CS0672\" Action=\"None\" />\r\n    <Rule Id=\"CS0675\" Action=\"None\" />\r\n    <Rule Id=\"CS0684\" Action=\"None\" />\r\n    <Rule Id=\"CS0693\" Action=\"None\" />\r\n    <Rule Id=\"CS0728\" Action=\"None\" />\r\n    <Rule Id=\"CS0809\" Action=\"None\" />\r\n    <Rule Id=\"CS0811\" Action=\"None\" />\r\n    <Rule Id=\"CS0824\" Action=\"None\" />\r\n    <Rule Id=\"CS1030\" Action=\"None\" />\r\n    <Rule Id=\"CS1058\" Action=\"None\" />\r\n    <Rule Id=\"CS1062\" Action=\"None\" />\r\n    <Rule Id=\"CS1064\" Action=\"None\" />\r\n    <Rule Id=\"CS1066\" Action=\"None\" />\r\n    <Rule Id=\"CS1072\" Action=\"None\" />\r\n    <Rule Id=\"CS1522\" Action=\"None\" />\r\n    <Rule Id=\"CS1570\" Action=\"None\" />\r\n    <Rule Id=\"CS1571\" Action=\"None\" />\r\n    <Rule Id=\"CS1572\" Action=\"None\" />\r\n    <Rule Id=\"CS1573\" Action=\"None\" />\r\n    <Rule Id=\"CS1574\" Action=\"None\" />\r\n    <Rule Id=\"CS1580\" Action=\"None\" />\r\n    <Rule Id=\"CS1581\" Action=\"None\" />\r\n    <Rule Id=\"CS1584\" Action=\"None\" />\r\n    <Rule Id=\"CS1587\" Action=\"None\" />\r\n    <Rule Id=\"CS1589\" Action=\"None\" />\r\n    <Rule Id=\"CS1590\" Action=\"None\" />\r\n    <Rule Id=\"CS1591\" Action=\"None\" />\r\n    <Rule Id=\"CS1592\" Action=\"None\" />\r\n    <Rule Id=\"CS1616\" Action=\"None\" />\r\n    <Rule Id=\"CS1633\" Action=\"None\" />\r\n    <Rule Id=\"CS1634\" Action=\"None\" />\r\n    <Rule Id=\"CS1635\" Action=\"None\" />\r\n    <Rule Id=\"CS1645\" Action=\"None\" />\r\n    <Rule Id=\"CS1658\" Action=\"None\" />\r\n    <Rule Id=\"CS1668\" Action=\"None\" />\r\n    <Rule Id=\"CS1685\" Action=\"None\" />\r\n    <Rule Id=\"CS1687\" Action=\"None\" />\r\n    <Rule Id=\"CS1690\" Action=\"None\" />\r\n    <Rule Id=\"CS1692\" Action=\"None\" />\r\n    <Rule Id=\"CS1695\" Action=\"None\" />\r\n    <Rule Id=\"CS1696\" Action=\"None\" />\r\n    <Rule Id=\"CS1697\" Action=\"None\" />\r\n    <Rule Id=\"CS1700\" Action=\"None\" />\r\n    <Rule Id=\"CS1701\" Action=\"None\" />\r\n    <Rule Id=\"CS1702\" Action=\"None\" />\r\n    <Rule Id=\"CS1710\" Action=\"None\" />\r\n    <Rule Id=\"CS1711\" Action=\"None\" />\r\n    <Rule Id=\"CS1712\" Action=\"None\" />\r\n    <Rule Id=\"CS1717\" Action=\"None\" />\r\n    <Rule Id=\"CS1718\" Action=\"None\" />\r\n    <Rule Id=\"CS1720\" Action=\"None\" />\r\n    <Rule Id=\"CS1723\" Action=\"None\" />\r\n    <Rule Id=\"CS1734\" Action=\"None\" />\r\n    <Rule Id=\"CS1735\" Action=\"None\" />\r\n    <Rule Id=\"CS1762\" Action=\"None\" />\r\n    <Rule Id=\"CS1927\" Action=\"None\" />\r\n    <Rule Id=\"CS1956\" Action=\"None\" />\r\n    <Rule Id=\"CS1957\" Action=\"None\" />\r\n    <Rule Id=\"CS1974\" Action=\"None\" />\r\n    <Rule Id=\"CS1981\" Action=\"None\" />\r\n    <Rule Id=\"CS1998\" Action=\"None\" />\r\n    <Rule Id=\"CS2002\" Action=\"None\" />\r\n    <Rule Id=\"CS2008\" Action=\"None\" />\r\n    <Rule Id=\"CS2023\" Action=\"None\" />\r\n    <Rule Id=\"CS2029\" Action=\"None\" />\r\n    <Rule Id=\"CS2038\" Action=\"None\" />\r\n    <Rule Id=\"CS3000\" Action=\"None\" />\r\n    <Rule Id=\"CS3001\" Action=\"None\" />\r\n    <Rule Id=\"CS3002\" Action=\"None\" />\r\n    <Rule Id=\"CS3003\" Action=\"None\" />\r\n    <Rule Id=\"CS3005\" Action=\"None\" />\r\n    <Rule Id=\"CS3006\" Action=\"None\" />\r\n    <Rule Id=\"CS3007\" Action=\"None\" />\r\n    <Rule Id=\"CS3008\" Action=\"None\" />\r\n    <Rule Id=\"CS3009\" Action=\"None\" />\r\n    <Rule Id=\"CS3010\" Action=\"None\" />\r\n    <Rule Id=\"CS3011\" Action=\"None\" />\r\n    <Rule Id=\"CS3012\" Action=\"None\" />\r\n    <Rule Id=\"CS3013\" Action=\"None\" />\r\n    <Rule Id=\"CS3014\" Action=\"None\" />\r\n    <Rule Id=\"CS3015\" Action=\"None\" />\r\n    <Rule Id=\"CS3016\" Action=\"None\" />\r\n    <Rule Id=\"CS3017\" Action=\"None\" />\r\n    <Rule Id=\"CS3018\" Action=\"None\" />\r\n    <Rule Id=\"CS3019\" Action=\"None\" />\r\n    <Rule Id=\"CS3021\" Action=\"None\" />\r\n    <Rule Id=\"CS3022\" Action=\"None\" />\r\n    <Rule Id=\"CS3023\" Action=\"None\" />\r\n    <Rule Id=\"CS3024\" Action=\"None\" />\r\n    <Rule Id=\"CS3026\" Action=\"None\" />\r\n    <Rule Id=\"CS3027\" Action=\"None\" />\r\n    <Rule Id=\"CS4014\" Action=\"None\" />\r\n    <Rule Id=\"CS4024\" Action=\"None\" />\r\n    <Rule Id=\"CS4025\" Action=\"None\" />\r\n    <Rule Id=\"CS4026\" Action=\"None\" />\r\n    <Rule Id=\"CS7022\" Action=\"None\" />\r\n    <Rule Id=\"CS7033\" Action=\"None\" />\r\n    <Rule Id=\"CS7035\" Action=\"None\" />\r\n    <Rule Id=\"CS7080\" Action=\"None\" />\r\n    <Rule Id=\"CS7081\" Action=\"None\" />\r\n    <Rule Id=\"CS7082\" Action=\"None\" />\r\n    <Rule Id=\"CS7090\" Action=\"None\" />\r\n    <Rule Id=\"CS7095\" Action=\"None\" />\r\n    <Rule Id=\"CS8001\" Action=\"None\" />\r\n    <Rule Id=\"CS8002\" Action=\"None\" />\r\n    <Rule Id=\"CS8009\" Action=\"None\" />\r\n    <Rule Id=\"CS8012\" Action=\"None\" />\r\n    <Rule Id=\"CS8018\" Action=\"None\" />\r\n    <Rule Id=\"CS8019\" Action=\"None\" />\r\n    <Rule Id=\"CS8020\" Action=\"None\" />\r\n    <Rule Id=\"CS8021\" Action=\"None\" />\r\n    <Rule Id=\"CS8029\" Action=\"None\" />\r\n    <Rule Id=\"CS8032\" Action=\"None\" />\r\n    <Rule Id=\"CS8033\" Action=\"None\" />\r\n    <Rule Id=\"CS8034\" Action=\"None\" />\r\n    <Rule Id=\"CS8040\" Action=\"None\" />\r\n    <Rule Id=\"CS8073\" Action=\"None\" />\r\n    <Rule Id=\"CS8094\" Action=\"None\" />\r\n    <Rule Id=\"CS8105\" Action=\"None\" />\r\n  </Rules>\r\n  <Rules AnalyzerId=\"Microsoft.CodeAnalysis.CSharp.EditorFeatures\" RuleNamespace=\"Microsoft.CodeAnalysis.CSharp.EditorFeatures\">\r\n    <Rule Id=\"UseAutoProperty\" Action=\"None\" />\r\n    <Rule Id=\"UseAutoPropertyFadedToken\" Action=\"None\" />\r\n  </Rules>\r\n  <Rules AnalyzerId=\"Microsoft.CodeAnalysis.CSharp.Features\" RuleNamespace=\"Microsoft.CodeAnalysis.CSharp.Features\">\r\n    <Rule Id=\"IDE0001\" Action=\"None\" />\r\n    <Rule Id=\"IDE0002\" Action=\"None\" />\r\n    <Rule Id=\"IDE0003\" Action=\"None\" />\r\n    <Rule Id=\"IDE0004\" Action=\"None\" />\r\n    <Rule Id=\"IDE0005\" Action=\"None\" />\r\n    <Rule Id=\"IDE1005\" Action=\"None\" />\r\n  </Rules>\r\n</RuleSet>\r\n"
  },
  {
    "path": "Nancy.sln",
    "content": "Microsoft Visual Studio Solution File, Format Version 12.00\r\n# Visual Studio 15\r\nVisualStudioVersion = 15.0.27130.2010\r\nMinimumVisualStudioVersion = 10.0.40219.1\r\nProject(\"{2150E333-8FDC-42A3-9474-1A3956D46DE8}\") = \"src\", \"src\", \"{5734E9DC-CF67-4337-B28E-695280598B88}\"\r\n\tProjectSection(SolutionItems) = preProject\r\n\t\tsrc\\Directory.Build.props = src\\Directory.Build.props\r\n\tEndProjectSection\r\nEndProject\r\nProject(\"{2150E333-8FDC-42A3-9474-1A3956D46DE8}\") = \"build\", \"build\", \"{AAB0D92A-7B90-478A-8360-3E6A20BD0B71}\"\r\n\tProjectSection(SolutionItems) = preProject\r\n\t\tNuGet.config = NuGet.config\r\n\tEndProjectSection\r\nEndProject\r\nProject(\"{2150E333-8FDC-42A3-9474-1A3956D46DE8}\") = \"samples\", \"samples\", \"{AA791E28-7914-439A-B59A-580B8D8FE95D}\"\r\nEndProject\r\nProject(\"{2150E333-8FDC-42A3-9474-1A3956D46DE8}\") = \"test\", \"test\", \"{058BCE2A-8F81-4404-83D3-844CE030E513}\"\r\n\tProjectSection(SolutionItems) = preProject\r\n\t\ttest\\Directory.Build.props = test\\Directory.Build.props\r\n\tEndProjectSection\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.ViewEngines.Razor.Tests.Models\", \"test\\Nancy.ViewEngines.Razor.Tests.Models\\Nancy.ViewEngines.Razor.Tests.Models.csproj\", \"{0E7E06C1-C223-4975-A9DB-D338EBF0A9BC}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.ViewEngines.Razor.Tests\", \"test\\Nancy.ViewEngines.Razor.Tests\\Nancy.ViewEngines.Razor.Tests.csproj\", \"{06B9857A-02A6-430D-B579-98A762C281D3}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy\", \"src\\Nancy\\Nancy.csproj\", \"{ADAB2C6B-10FE-4B31-BCD2-E2EFA69D5A66}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.Testing\", \"src\\Nancy.Testing\\Nancy.Testing.csproj\", \"{66119997-5949-45D6-9175-F1C7C599A8F5}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.ViewEngines.Razor\", \"src\\Nancy.ViewEngines.Razor\\Nancy.ViewEngines.Razor.csproj\", \"{D1D2622E-ACF7-479C-ABC8-E1B94E41D9D5}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.Authentication.Forms\", \"src\\Nancy.Authentication.Forms\\Nancy.Authentication.Forms.csproj\", \"{09F5EB90-1063-4338-A146-25F7BE8BFF43}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.ViewEngines.Markdown.Tests\", \"test\\Nancy.ViewEngines.Markdown.Tests\\Nancy.ViewEngines.Markdown.Tests.csproj\", \"{1CA8D3D3-B6A6-4006-AA96-671CB41D6391}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.ViewEngines.Markdown\", \"src\\Nancy.ViewEngines.Markdown\\Nancy.ViewEngines.Markdown.csproj\", \"{CCB5075B-C50A-4CD1-983A-2D51DC2430F4}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.ViewEngines.DotLiquid.Tests\", \"test\\Nancy.ViewEngines.DotLiquid.Tests\\Nancy.ViewEngines.DotLiquid.Tests.csproj\", \"{89C49FF5-9441-4DE8-A33F-1B2852401A54}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.ViewEngines.DotLiquid\", \"src\\Nancy.ViewEngines.DotLiquid\\Nancy.ViewEngines.DotLiquid.csproj\", \"{9F16EBDF-4546-43C2-82B8-7D698F7A1E89}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.Validation.FluentValidation.Tests\", \"test\\Nancy.Validation.FluentValidation.Tests\\Nancy.Validation.FluentValidation.Tests.csproj\", \"{0E9B466C-1151-4AE9-A55A-6377A25F8235}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.Validation.FluentValidation\", \"src\\Nancy.Validation.FluentValidation\\Nancy.Validation.FluentValidation.csproj\", \"{33D5FB92-074E-4C13-BFD6-21184DD0013A}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.Validation.DataAnnotations.Tests\", \"test\\Nancy.Validation.DataAnnotations.Tests\\Nancy.Validation.DataAnnotations.Tests.csproj\", \"{EF3149F4-59C1-4896-989E-59D9D5F9050A}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.Validation.DataAnnotations\", \"src\\Nancy.Validation.DataAnnotations\\Nancy.Validation.DataAnnotations.csproj\", \"{FA2462FE-A439-48C5-976D-491F73C25CE1}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.Tests.Functional\", \"test\\Nancy.Tests.Functional\\Nancy.Tests.Functional.csproj\", \"{7944AA31-16BA-43A8-A9CB-2ED758518C9E}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.Tests\", \"test\\Nancy.Tests\\Nancy.Tests.csproj\", \"{9C383F09-8936-42ED-B9A6-ED3300AECB1C}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.Testing.Tests\", \"test\\Nancy.Testing.Tests\\Nancy.Testing.Tests.csproj\", \"{5E5AF23F-61F6-4B44-B682-2D141B54DF5C}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.Owin.Tests\", \"test\\Nancy.Owin.Tests\\Nancy.Owin.Tests.csproj\", \"{C0A85A7D-9D7F-4A6C-BA33-9E79050CF522}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.Owin\", \"src\\Nancy.Owin\\Nancy.Owin.csproj\", \"{23C68B10-36FD-41DE-AAA3-77BEDFD63945}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.Metadata.Modules.Tests\", \"test\\Nancy.Metadata.Modules.Tests\\Nancy.Metadata.Modules.Tests.csproj\", \"{8302F65E-035F-45D7-B894-915B68B72711}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.Metadata.Modules\", \"src\\Nancy.Metadata.Modules\\Nancy.Metadata.Modules.csproj\", \"{89DED7A5-7334-4852-A1FC-9266AD0EF388}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.Hosting.Self.Tests\", \"test\\Nancy.Hosting.Self.Tests\\Nancy.Hosting.Self.Tests.csproj\", \"{8909AB97-EDD6-4AB2-B733-A543ACB957CA}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.Hosting.Self\", \"src\\Nancy.Hosting.Self\\Nancy.Hosting.Self.csproj\", \"{AA837BCA-A2D6-4F74-95BC-1F6A66146562}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.Hosting.Aspnet.Tests\", \"test\\Nancy.Hosting.Aspnet.Tests\\Nancy.Hosting.Aspnet.Tests.csproj\", \"{53FB25E0-C8CB-4D65-8D94-6FA627BF9760}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.Hosting.Aspnet\", \"src\\Nancy.Hosting.Aspnet\\Nancy.Hosting.Aspnet.csproj\", \"{833A65BC-5B37-468D-8BB4-2343CEFDFA5D}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.Encryption.MachineKey.Tests\", \"test\\Nancy.Encryption.MachineKey.Tests\\Nancy.Encryption.MachineKey.Tests.csproj\", \"{C42C352E-F3E2-41F6-A446-0CACDA5096AF}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.Encryption.MachineKey\", \"src\\Nancy.Encryption.MachineKey\\Nancy.Encryption.MachineKey.csproj\", \"{EF313B39-68CF-45D1-9094-BDDCCAC9DB2D}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.Embedded.Tests\", \"test\\Nancy.Embedded.Tests\\Nancy.Embedded.Tests.csproj\", \"{8A936050-5B84-4711-A235-2BA36A445B26}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.Embedded\", \"src\\Nancy.Embedded\\Nancy.Embedded.csproj\", \"{8120B952-D9BC-450A-B691-C030177CD24D}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.Authentication.Forms.Tests\", \"test\\Nancy.Authentication.Forms.Tests\\Nancy.Authentication.Forms.Tests.csproj\", \"{E3C25A1C-2754-4134-8780-1F0A247D6850}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.Authentication.Basic.Tests\", \"test\\Nancy.Authentication.Basic.Tests\\Nancy.Authentication.Basic.Tests.csproj\", \"{5323D32E-0CF2-41B6-AF91-37F744AC1554}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.Authentication.Basic\", \"src\\Nancy.Authentication.Basic\\Nancy.Authentication.Basic.csproj\", \"{22E99FEC-8DFC-4E87-90EE-BC7F6E988DAD}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.ViewEngines.Spark\", \"src\\Nancy.ViewEngines.Spark\\Nancy.ViewEngines.Spark.csproj\", \"{0E546413-BBF8-40B3-8534-8D1D986AA888}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.ViewEngines.Razor.BuildProviders\", \"src\\Nancy.ViewEngines.Razor.BuildProviders\\Nancy.ViewEngines.Razor.BuildProviders.csproj\", \"{D92ADA88-361B-480A-81D2-AE1F7B2E0660}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.ViewEngines.Nustache\", \"src\\Nancy.ViewEngines.Nustache\\Nancy.ViewEngines.Nustache.csproj\", \"{4FB42026-81C2-47B3-99A4-751452E64814}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.Authentication.Stateless\", \"src\\Nancy.Authentication.Stateless\\Nancy.Authentication.Stateless.csproj\", \"{EEEE504F-24AC-4932-9B28-F684AB20FB50}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.Demo.Hosting.Kestrel\", \"samples\\Nancy.Demo.Hosting.Kestrel\\Nancy.Demo.Hosting.Kestrel.csproj\", \"{3AF8D59E-D10A-46DE-97A6-0A6C156F22CD}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Nancy.ViewEngines.Spark.Tests\", \"test\\Nancy.ViewEngines.Spark.Tests\\Nancy.ViewEngines.Spark.Tests.csproj\", \"{08C1D823-E8E1-4D86-8F73-A9F3AE8FEFC7}\"\r\nEndProject\r\nGlobal\r\n\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\r\n\t\tDebug|Any CPU = Debug|Any CPU\r\n\t\tDebug|x64 = Debug|x64\r\n\t\tDebug|x86 = Debug|x86\r\n\t\tRelease|Any CPU = Release|Any CPU\r\n\t\tRelease|x64 = Release|x64\r\n\t\tRelease|x86 = Release|x86\r\n\tEndGlobalSection\r\n\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\r\n\t\t{0E7E06C1-C223-4975-A9DB-D338EBF0A9BC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{0E7E06C1-C223-4975-A9DB-D338EBF0A9BC}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{0E7E06C1-C223-4975-A9DB-D338EBF0A9BC}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{0E7E06C1-C223-4975-A9DB-D338EBF0A9BC}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{0E7E06C1-C223-4975-A9DB-D338EBF0A9BC}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{0E7E06C1-C223-4975-A9DB-D338EBF0A9BC}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{0E7E06C1-C223-4975-A9DB-D338EBF0A9BC}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{0E7E06C1-C223-4975-A9DB-D338EBF0A9BC}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{0E7E06C1-C223-4975-A9DB-D338EBF0A9BC}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{0E7E06C1-C223-4975-A9DB-D338EBF0A9BC}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{0E7E06C1-C223-4975-A9DB-D338EBF0A9BC}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{0E7E06C1-C223-4975-A9DB-D338EBF0A9BC}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{06B9857A-02A6-430D-B579-98A762C281D3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{06B9857A-02A6-430D-B579-98A762C281D3}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{06B9857A-02A6-430D-B579-98A762C281D3}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{06B9857A-02A6-430D-B579-98A762C281D3}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{06B9857A-02A6-430D-B579-98A762C281D3}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{06B9857A-02A6-430D-B579-98A762C281D3}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{06B9857A-02A6-430D-B579-98A762C281D3}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{06B9857A-02A6-430D-B579-98A762C281D3}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{06B9857A-02A6-430D-B579-98A762C281D3}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{06B9857A-02A6-430D-B579-98A762C281D3}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{06B9857A-02A6-430D-B579-98A762C281D3}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{06B9857A-02A6-430D-B579-98A762C281D3}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{ADAB2C6B-10FE-4B31-BCD2-E2EFA69D5A66}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{ADAB2C6B-10FE-4B31-BCD2-E2EFA69D5A66}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{ADAB2C6B-10FE-4B31-BCD2-E2EFA69D5A66}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{ADAB2C6B-10FE-4B31-BCD2-E2EFA69D5A66}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{ADAB2C6B-10FE-4B31-BCD2-E2EFA69D5A66}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{ADAB2C6B-10FE-4B31-BCD2-E2EFA69D5A66}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{ADAB2C6B-10FE-4B31-BCD2-E2EFA69D5A66}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{ADAB2C6B-10FE-4B31-BCD2-E2EFA69D5A66}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{ADAB2C6B-10FE-4B31-BCD2-E2EFA69D5A66}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{ADAB2C6B-10FE-4B31-BCD2-E2EFA69D5A66}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{ADAB2C6B-10FE-4B31-BCD2-E2EFA69D5A66}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{ADAB2C6B-10FE-4B31-BCD2-E2EFA69D5A66}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{66119997-5949-45D6-9175-F1C7C599A8F5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{66119997-5949-45D6-9175-F1C7C599A8F5}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{66119997-5949-45D6-9175-F1C7C599A8F5}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{66119997-5949-45D6-9175-F1C7C599A8F5}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{66119997-5949-45D6-9175-F1C7C599A8F5}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{66119997-5949-45D6-9175-F1C7C599A8F5}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{66119997-5949-45D6-9175-F1C7C599A8F5}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{66119997-5949-45D6-9175-F1C7C599A8F5}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{66119997-5949-45D6-9175-F1C7C599A8F5}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{66119997-5949-45D6-9175-F1C7C599A8F5}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{66119997-5949-45D6-9175-F1C7C599A8F5}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{66119997-5949-45D6-9175-F1C7C599A8F5}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{D1D2622E-ACF7-479C-ABC8-E1B94E41D9D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{D1D2622E-ACF7-479C-ABC8-E1B94E41D9D5}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{D1D2622E-ACF7-479C-ABC8-E1B94E41D9D5}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{D1D2622E-ACF7-479C-ABC8-E1B94E41D9D5}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{D1D2622E-ACF7-479C-ABC8-E1B94E41D9D5}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{D1D2622E-ACF7-479C-ABC8-E1B94E41D9D5}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{D1D2622E-ACF7-479C-ABC8-E1B94E41D9D5}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{D1D2622E-ACF7-479C-ABC8-E1B94E41D9D5}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{D1D2622E-ACF7-479C-ABC8-E1B94E41D9D5}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{D1D2622E-ACF7-479C-ABC8-E1B94E41D9D5}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{D1D2622E-ACF7-479C-ABC8-E1B94E41D9D5}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{D1D2622E-ACF7-479C-ABC8-E1B94E41D9D5}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{09F5EB90-1063-4338-A146-25F7BE8BFF43}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{09F5EB90-1063-4338-A146-25F7BE8BFF43}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{09F5EB90-1063-4338-A146-25F7BE8BFF43}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{09F5EB90-1063-4338-A146-25F7BE8BFF43}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{09F5EB90-1063-4338-A146-25F7BE8BFF43}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{09F5EB90-1063-4338-A146-25F7BE8BFF43}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{09F5EB90-1063-4338-A146-25F7BE8BFF43}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{09F5EB90-1063-4338-A146-25F7BE8BFF43}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{09F5EB90-1063-4338-A146-25F7BE8BFF43}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{09F5EB90-1063-4338-A146-25F7BE8BFF43}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{09F5EB90-1063-4338-A146-25F7BE8BFF43}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{09F5EB90-1063-4338-A146-25F7BE8BFF43}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{1CA8D3D3-B6A6-4006-AA96-671CB41D6391}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{1CA8D3D3-B6A6-4006-AA96-671CB41D6391}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{1CA8D3D3-B6A6-4006-AA96-671CB41D6391}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{1CA8D3D3-B6A6-4006-AA96-671CB41D6391}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{1CA8D3D3-B6A6-4006-AA96-671CB41D6391}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{1CA8D3D3-B6A6-4006-AA96-671CB41D6391}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{1CA8D3D3-B6A6-4006-AA96-671CB41D6391}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{1CA8D3D3-B6A6-4006-AA96-671CB41D6391}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{1CA8D3D3-B6A6-4006-AA96-671CB41D6391}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{1CA8D3D3-B6A6-4006-AA96-671CB41D6391}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{1CA8D3D3-B6A6-4006-AA96-671CB41D6391}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{1CA8D3D3-B6A6-4006-AA96-671CB41D6391}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{CCB5075B-C50A-4CD1-983A-2D51DC2430F4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{CCB5075B-C50A-4CD1-983A-2D51DC2430F4}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{CCB5075B-C50A-4CD1-983A-2D51DC2430F4}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{CCB5075B-C50A-4CD1-983A-2D51DC2430F4}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{CCB5075B-C50A-4CD1-983A-2D51DC2430F4}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{CCB5075B-C50A-4CD1-983A-2D51DC2430F4}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{CCB5075B-C50A-4CD1-983A-2D51DC2430F4}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{CCB5075B-C50A-4CD1-983A-2D51DC2430F4}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{CCB5075B-C50A-4CD1-983A-2D51DC2430F4}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{CCB5075B-C50A-4CD1-983A-2D51DC2430F4}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{CCB5075B-C50A-4CD1-983A-2D51DC2430F4}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{CCB5075B-C50A-4CD1-983A-2D51DC2430F4}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{89C49FF5-9441-4DE8-A33F-1B2852401A54}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{89C49FF5-9441-4DE8-A33F-1B2852401A54}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{89C49FF5-9441-4DE8-A33F-1B2852401A54}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{89C49FF5-9441-4DE8-A33F-1B2852401A54}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{89C49FF5-9441-4DE8-A33F-1B2852401A54}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{89C49FF5-9441-4DE8-A33F-1B2852401A54}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{89C49FF5-9441-4DE8-A33F-1B2852401A54}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{89C49FF5-9441-4DE8-A33F-1B2852401A54}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{89C49FF5-9441-4DE8-A33F-1B2852401A54}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{89C49FF5-9441-4DE8-A33F-1B2852401A54}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{89C49FF5-9441-4DE8-A33F-1B2852401A54}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{89C49FF5-9441-4DE8-A33F-1B2852401A54}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{9F16EBDF-4546-43C2-82B8-7D698F7A1E89}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{9F16EBDF-4546-43C2-82B8-7D698F7A1E89}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{9F16EBDF-4546-43C2-82B8-7D698F7A1E89}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{9F16EBDF-4546-43C2-82B8-7D698F7A1E89}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{9F16EBDF-4546-43C2-82B8-7D698F7A1E89}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{9F16EBDF-4546-43C2-82B8-7D698F7A1E89}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{9F16EBDF-4546-43C2-82B8-7D698F7A1E89}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{9F16EBDF-4546-43C2-82B8-7D698F7A1E89}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{9F16EBDF-4546-43C2-82B8-7D698F7A1E89}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{9F16EBDF-4546-43C2-82B8-7D698F7A1E89}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{9F16EBDF-4546-43C2-82B8-7D698F7A1E89}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{9F16EBDF-4546-43C2-82B8-7D698F7A1E89}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{0E9B466C-1151-4AE9-A55A-6377A25F8235}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{0E9B466C-1151-4AE9-A55A-6377A25F8235}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{0E9B466C-1151-4AE9-A55A-6377A25F8235}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{0E9B466C-1151-4AE9-A55A-6377A25F8235}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{0E9B466C-1151-4AE9-A55A-6377A25F8235}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{0E9B466C-1151-4AE9-A55A-6377A25F8235}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{0E9B466C-1151-4AE9-A55A-6377A25F8235}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{0E9B466C-1151-4AE9-A55A-6377A25F8235}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{0E9B466C-1151-4AE9-A55A-6377A25F8235}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{0E9B466C-1151-4AE9-A55A-6377A25F8235}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{0E9B466C-1151-4AE9-A55A-6377A25F8235}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{0E9B466C-1151-4AE9-A55A-6377A25F8235}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{33D5FB92-074E-4C13-BFD6-21184DD0013A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{33D5FB92-074E-4C13-BFD6-21184DD0013A}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{33D5FB92-074E-4C13-BFD6-21184DD0013A}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{33D5FB92-074E-4C13-BFD6-21184DD0013A}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{33D5FB92-074E-4C13-BFD6-21184DD0013A}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{33D5FB92-074E-4C13-BFD6-21184DD0013A}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{33D5FB92-074E-4C13-BFD6-21184DD0013A}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{33D5FB92-074E-4C13-BFD6-21184DD0013A}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{33D5FB92-074E-4C13-BFD6-21184DD0013A}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{33D5FB92-074E-4C13-BFD6-21184DD0013A}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{33D5FB92-074E-4C13-BFD6-21184DD0013A}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{33D5FB92-074E-4C13-BFD6-21184DD0013A}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{EF3149F4-59C1-4896-989E-59D9D5F9050A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{EF3149F4-59C1-4896-989E-59D9D5F9050A}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{EF3149F4-59C1-4896-989E-59D9D5F9050A}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{EF3149F4-59C1-4896-989E-59D9D5F9050A}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{EF3149F4-59C1-4896-989E-59D9D5F9050A}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{EF3149F4-59C1-4896-989E-59D9D5F9050A}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{EF3149F4-59C1-4896-989E-59D9D5F9050A}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{EF3149F4-59C1-4896-989E-59D9D5F9050A}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{EF3149F4-59C1-4896-989E-59D9D5F9050A}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{EF3149F4-59C1-4896-989E-59D9D5F9050A}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{EF3149F4-59C1-4896-989E-59D9D5F9050A}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{EF3149F4-59C1-4896-989E-59D9D5F9050A}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{FA2462FE-A439-48C5-976D-491F73C25CE1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{FA2462FE-A439-48C5-976D-491F73C25CE1}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{FA2462FE-A439-48C5-976D-491F73C25CE1}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{FA2462FE-A439-48C5-976D-491F73C25CE1}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{FA2462FE-A439-48C5-976D-491F73C25CE1}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{FA2462FE-A439-48C5-976D-491F73C25CE1}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{FA2462FE-A439-48C5-976D-491F73C25CE1}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{FA2462FE-A439-48C5-976D-491F73C25CE1}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{FA2462FE-A439-48C5-976D-491F73C25CE1}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{FA2462FE-A439-48C5-976D-491F73C25CE1}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{FA2462FE-A439-48C5-976D-491F73C25CE1}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{FA2462FE-A439-48C5-976D-491F73C25CE1}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{7944AA31-16BA-43A8-A9CB-2ED758518C9E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{7944AA31-16BA-43A8-A9CB-2ED758518C9E}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{7944AA31-16BA-43A8-A9CB-2ED758518C9E}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{7944AA31-16BA-43A8-A9CB-2ED758518C9E}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{7944AA31-16BA-43A8-A9CB-2ED758518C9E}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{7944AA31-16BA-43A8-A9CB-2ED758518C9E}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{7944AA31-16BA-43A8-A9CB-2ED758518C9E}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{7944AA31-16BA-43A8-A9CB-2ED758518C9E}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{7944AA31-16BA-43A8-A9CB-2ED758518C9E}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{7944AA31-16BA-43A8-A9CB-2ED758518C9E}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{7944AA31-16BA-43A8-A9CB-2ED758518C9E}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{7944AA31-16BA-43A8-A9CB-2ED758518C9E}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{9C383F09-8936-42ED-B9A6-ED3300AECB1C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{9C383F09-8936-42ED-B9A6-ED3300AECB1C}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{9C383F09-8936-42ED-B9A6-ED3300AECB1C}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{9C383F09-8936-42ED-B9A6-ED3300AECB1C}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{9C383F09-8936-42ED-B9A6-ED3300AECB1C}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{9C383F09-8936-42ED-B9A6-ED3300AECB1C}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{9C383F09-8936-42ED-B9A6-ED3300AECB1C}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{9C383F09-8936-42ED-B9A6-ED3300AECB1C}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{9C383F09-8936-42ED-B9A6-ED3300AECB1C}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{9C383F09-8936-42ED-B9A6-ED3300AECB1C}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{9C383F09-8936-42ED-B9A6-ED3300AECB1C}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{9C383F09-8936-42ED-B9A6-ED3300AECB1C}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{5E5AF23F-61F6-4B44-B682-2D141B54DF5C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{5E5AF23F-61F6-4B44-B682-2D141B54DF5C}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{5E5AF23F-61F6-4B44-B682-2D141B54DF5C}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{5E5AF23F-61F6-4B44-B682-2D141B54DF5C}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{5E5AF23F-61F6-4B44-B682-2D141B54DF5C}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{5E5AF23F-61F6-4B44-B682-2D141B54DF5C}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{5E5AF23F-61F6-4B44-B682-2D141B54DF5C}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{5E5AF23F-61F6-4B44-B682-2D141B54DF5C}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{5E5AF23F-61F6-4B44-B682-2D141B54DF5C}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{5E5AF23F-61F6-4B44-B682-2D141B54DF5C}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{5E5AF23F-61F6-4B44-B682-2D141B54DF5C}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{5E5AF23F-61F6-4B44-B682-2D141B54DF5C}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{C0A85A7D-9D7F-4A6C-BA33-9E79050CF522}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{C0A85A7D-9D7F-4A6C-BA33-9E79050CF522}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{C0A85A7D-9D7F-4A6C-BA33-9E79050CF522}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{C0A85A7D-9D7F-4A6C-BA33-9E79050CF522}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{C0A85A7D-9D7F-4A6C-BA33-9E79050CF522}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{C0A85A7D-9D7F-4A6C-BA33-9E79050CF522}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{C0A85A7D-9D7F-4A6C-BA33-9E79050CF522}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{C0A85A7D-9D7F-4A6C-BA33-9E79050CF522}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{C0A85A7D-9D7F-4A6C-BA33-9E79050CF522}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{C0A85A7D-9D7F-4A6C-BA33-9E79050CF522}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{C0A85A7D-9D7F-4A6C-BA33-9E79050CF522}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{C0A85A7D-9D7F-4A6C-BA33-9E79050CF522}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{23C68B10-36FD-41DE-AAA3-77BEDFD63945}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{23C68B10-36FD-41DE-AAA3-77BEDFD63945}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{23C68B10-36FD-41DE-AAA3-77BEDFD63945}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{23C68B10-36FD-41DE-AAA3-77BEDFD63945}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{23C68B10-36FD-41DE-AAA3-77BEDFD63945}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{23C68B10-36FD-41DE-AAA3-77BEDFD63945}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{23C68B10-36FD-41DE-AAA3-77BEDFD63945}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{23C68B10-36FD-41DE-AAA3-77BEDFD63945}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{23C68B10-36FD-41DE-AAA3-77BEDFD63945}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{23C68B10-36FD-41DE-AAA3-77BEDFD63945}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{23C68B10-36FD-41DE-AAA3-77BEDFD63945}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{23C68B10-36FD-41DE-AAA3-77BEDFD63945}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{8302F65E-035F-45D7-B894-915B68B72711}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{8302F65E-035F-45D7-B894-915B68B72711}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{8302F65E-035F-45D7-B894-915B68B72711}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{8302F65E-035F-45D7-B894-915B68B72711}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{8302F65E-035F-45D7-B894-915B68B72711}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{8302F65E-035F-45D7-B894-915B68B72711}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{8302F65E-035F-45D7-B894-915B68B72711}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{8302F65E-035F-45D7-B894-915B68B72711}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{8302F65E-035F-45D7-B894-915B68B72711}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{8302F65E-035F-45D7-B894-915B68B72711}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{8302F65E-035F-45D7-B894-915B68B72711}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{8302F65E-035F-45D7-B894-915B68B72711}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{89DED7A5-7334-4852-A1FC-9266AD0EF388}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{89DED7A5-7334-4852-A1FC-9266AD0EF388}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{89DED7A5-7334-4852-A1FC-9266AD0EF388}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{89DED7A5-7334-4852-A1FC-9266AD0EF388}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{89DED7A5-7334-4852-A1FC-9266AD0EF388}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{89DED7A5-7334-4852-A1FC-9266AD0EF388}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{89DED7A5-7334-4852-A1FC-9266AD0EF388}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{89DED7A5-7334-4852-A1FC-9266AD0EF388}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{89DED7A5-7334-4852-A1FC-9266AD0EF388}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{89DED7A5-7334-4852-A1FC-9266AD0EF388}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{89DED7A5-7334-4852-A1FC-9266AD0EF388}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{89DED7A5-7334-4852-A1FC-9266AD0EF388}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{8909AB97-EDD6-4AB2-B733-A543ACB957CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{8909AB97-EDD6-4AB2-B733-A543ACB957CA}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{8909AB97-EDD6-4AB2-B733-A543ACB957CA}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{8909AB97-EDD6-4AB2-B733-A543ACB957CA}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{8909AB97-EDD6-4AB2-B733-A543ACB957CA}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{8909AB97-EDD6-4AB2-B733-A543ACB957CA}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{8909AB97-EDD6-4AB2-B733-A543ACB957CA}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{8909AB97-EDD6-4AB2-B733-A543ACB957CA}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{8909AB97-EDD6-4AB2-B733-A543ACB957CA}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{8909AB97-EDD6-4AB2-B733-A543ACB957CA}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{8909AB97-EDD6-4AB2-B733-A543ACB957CA}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{8909AB97-EDD6-4AB2-B733-A543ACB957CA}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{AA837BCA-A2D6-4F74-95BC-1F6A66146562}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{AA837BCA-A2D6-4F74-95BC-1F6A66146562}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{AA837BCA-A2D6-4F74-95BC-1F6A66146562}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{AA837BCA-A2D6-4F74-95BC-1F6A66146562}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{AA837BCA-A2D6-4F74-95BC-1F6A66146562}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{AA837BCA-A2D6-4F74-95BC-1F6A66146562}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{AA837BCA-A2D6-4F74-95BC-1F6A66146562}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{AA837BCA-A2D6-4F74-95BC-1F6A66146562}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{AA837BCA-A2D6-4F74-95BC-1F6A66146562}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{AA837BCA-A2D6-4F74-95BC-1F6A66146562}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{AA837BCA-A2D6-4F74-95BC-1F6A66146562}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{AA837BCA-A2D6-4F74-95BC-1F6A66146562}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{53FB25E0-C8CB-4D65-8D94-6FA627BF9760}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{53FB25E0-C8CB-4D65-8D94-6FA627BF9760}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{53FB25E0-C8CB-4D65-8D94-6FA627BF9760}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{53FB25E0-C8CB-4D65-8D94-6FA627BF9760}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{53FB25E0-C8CB-4D65-8D94-6FA627BF9760}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{53FB25E0-C8CB-4D65-8D94-6FA627BF9760}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{53FB25E0-C8CB-4D65-8D94-6FA627BF9760}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{53FB25E0-C8CB-4D65-8D94-6FA627BF9760}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{53FB25E0-C8CB-4D65-8D94-6FA627BF9760}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{53FB25E0-C8CB-4D65-8D94-6FA627BF9760}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{53FB25E0-C8CB-4D65-8D94-6FA627BF9760}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{53FB25E0-C8CB-4D65-8D94-6FA627BF9760}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{833A65BC-5B37-468D-8BB4-2343CEFDFA5D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{833A65BC-5B37-468D-8BB4-2343CEFDFA5D}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{833A65BC-5B37-468D-8BB4-2343CEFDFA5D}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{833A65BC-5B37-468D-8BB4-2343CEFDFA5D}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{833A65BC-5B37-468D-8BB4-2343CEFDFA5D}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{833A65BC-5B37-468D-8BB4-2343CEFDFA5D}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{833A65BC-5B37-468D-8BB4-2343CEFDFA5D}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{833A65BC-5B37-468D-8BB4-2343CEFDFA5D}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{833A65BC-5B37-468D-8BB4-2343CEFDFA5D}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{833A65BC-5B37-468D-8BB4-2343CEFDFA5D}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{833A65BC-5B37-468D-8BB4-2343CEFDFA5D}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{833A65BC-5B37-468D-8BB4-2343CEFDFA5D}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{C42C352E-F3E2-41F6-A446-0CACDA5096AF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{C42C352E-F3E2-41F6-A446-0CACDA5096AF}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{C42C352E-F3E2-41F6-A446-0CACDA5096AF}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{C42C352E-F3E2-41F6-A446-0CACDA5096AF}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{C42C352E-F3E2-41F6-A446-0CACDA5096AF}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{C42C352E-F3E2-41F6-A446-0CACDA5096AF}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{C42C352E-F3E2-41F6-A446-0CACDA5096AF}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{C42C352E-F3E2-41F6-A446-0CACDA5096AF}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{C42C352E-F3E2-41F6-A446-0CACDA5096AF}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{C42C352E-F3E2-41F6-A446-0CACDA5096AF}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{C42C352E-F3E2-41F6-A446-0CACDA5096AF}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{C42C352E-F3E2-41F6-A446-0CACDA5096AF}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{EF313B39-68CF-45D1-9094-BDDCCAC9DB2D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{EF313B39-68CF-45D1-9094-BDDCCAC9DB2D}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{EF313B39-68CF-45D1-9094-BDDCCAC9DB2D}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{EF313B39-68CF-45D1-9094-BDDCCAC9DB2D}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{EF313B39-68CF-45D1-9094-BDDCCAC9DB2D}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{EF313B39-68CF-45D1-9094-BDDCCAC9DB2D}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{EF313B39-68CF-45D1-9094-BDDCCAC9DB2D}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{EF313B39-68CF-45D1-9094-BDDCCAC9DB2D}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{EF313B39-68CF-45D1-9094-BDDCCAC9DB2D}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{EF313B39-68CF-45D1-9094-BDDCCAC9DB2D}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{EF313B39-68CF-45D1-9094-BDDCCAC9DB2D}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{EF313B39-68CF-45D1-9094-BDDCCAC9DB2D}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{8A936050-5B84-4711-A235-2BA36A445B26}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{8A936050-5B84-4711-A235-2BA36A445B26}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{8A936050-5B84-4711-A235-2BA36A445B26}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{8A936050-5B84-4711-A235-2BA36A445B26}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{8A936050-5B84-4711-A235-2BA36A445B26}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{8A936050-5B84-4711-A235-2BA36A445B26}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{8A936050-5B84-4711-A235-2BA36A445B26}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{8A936050-5B84-4711-A235-2BA36A445B26}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{8A936050-5B84-4711-A235-2BA36A445B26}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{8A936050-5B84-4711-A235-2BA36A445B26}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{8A936050-5B84-4711-A235-2BA36A445B26}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{8A936050-5B84-4711-A235-2BA36A445B26}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{8120B952-D9BC-450A-B691-C030177CD24D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{8120B952-D9BC-450A-B691-C030177CD24D}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{8120B952-D9BC-450A-B691-C030177CD24D}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{8120B952-D9BC-450A-B691-C030177CD24D}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{8120B952-D9BC-450A-B691-C030177CD24D}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{8120B952-D9BC-450A-B691-C030177CD24D}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{8120B952-D9BC-450A-B691-C030177CD24D}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{8120B952-D9BC-450A-B691-C030177CD24D}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{8120B952-D9BC-450A-B691-C030177CD24D}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{8120B952-D9BC-450A-B691-C030177CD24D}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{8120B952-D9BC-450A-B691-C030177CD24D}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{8120B952-D9BC-450A-B691-C030177CD24D}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{E3C25A1C-2754-4134-8780-1F0A247D6850}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{E3C25A1C-2754-4134-8780-1F0A247D6850}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{E3C25A1C-2754-4134-8780-1F0A247D6850}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{E3C25A1C-2754-4134-8780-1F0A247D6850}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{E3C25A1C-2754-4134-8780-1F0A247D6850}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{E3C25A1C-2754-4134-8780-1F0A247D6850}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{E3C25A1C-2754-4134-8780-1F0A247D6850}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{E3C25A1C-2754-4134-8780-1F0A247D6850}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{E3C25A1C-2754-4134-8780-1F0A247D6850}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{E3C25A1C-2754-4134-8780-1F0A247D6850}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{E3C25A1C-2754-4134-8780-1F0A247D6850}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{E3C25A1C-2754-4134-8780-1F0A247D6850}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{5323D32E-0CF2-41B6-AF91-37F744AC1554}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{5323D32E-0CF2-41B6-AF91-37F744AC1554}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{5323D32E-0CF2-41B6-AF91-37F744AC1554}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{5323D32E-0CF2-41B6-AF91-37F744AC1554}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{5323D32E-0CF2-41B6-AF91-37F744AC1554}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{5323D32E-0CF2-41B6-AF91-37F744AC1554}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{5323D32E-0CF2-41B6-AF91-37F744AC1554}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{5323D32E-0CF2-41B6-AF91-37F744AC1554}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{5323D32E-0CF2-41B6-AF91-37F744AC1554}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{5323D32E-0CF2-41B6-AF91-37F744AC1554}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{5323D32E-0CF2-41B6-AF91-37F744AC1554}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{5323D32E-0CF2-41B6-AF91-37F744AC1554}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{22E99FEC-8DFC-4E87-90EE-BC7F6E988DAD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{22E99FEC-8DFC-4E87-90EE-BC7F6E988DAD}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{22E99FEC-8DFC-4E87-90EE-BC7F6E988DAD}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{22E99FEC-8DFC-4E87-90EE-BC7F6E988DAD}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{22E99FEC-8DFC-4E87-90EE-BC7F6E988DAD}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{22E99FEC-8DFC-4E87-90EE-BC7F6E988DAD}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{22E99FEC-8DFC-4E87-90EE-BC7F6E988DAD}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{22E99FEC-8DFC-4E87-90EE-BC7F6E988DAD}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{22E99FEC-8DFC-4E87-90EE-BC7F6E988DAD}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{22E99FEC-8DFC-4E87-90EE-BC7F6E988DAD}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{22E99FEC-8DFC-4E87-90EE-BC7F6E988DAD}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{22E99FEC-8DFC-4E87-90EE-BC7F6E988DAD}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{0E546413-BBF8-40B3-8534-8D1D986AA888}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{0E546413-BBF8-40B3-8534-8D1D986AA888}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{0E546413-BBF8-40B3-8534-8D1D986AA888}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{0E546413-BBF8-40B3-8534-8D1D986AA888}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{0E546413-BBF8-40B3-8534-8D1D986AA888}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{0E546413-BBF8-40B3-8534-8D1D986AA888}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{0E546413-BBF8-40B3-8534-8D1D986AA888}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{0E546413-BBF8-40B3-8534-8D1D986AA888}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{0E546413-BBF8-40B3-8534-8D1D986AA888}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{0E546413-BBF8-40B3-8534-8D1D986AA888}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{0E546413-BBF8-40B3-8534-8D1D986AA888}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{0E546413-BBF8-40B3-8534-8D1D986AA888}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{D92ADA88-361B-480A-81D2-AE1F7B2E0660}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{D92ADA88-361B-480A-81D2-AE1F7B2E0660}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{D92ADA88-361B-480A-81D2-AE1F7B2E0660}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{D92ADA88-361B-480A-81D2-AE1F7B2E0660}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{D92ADA88-361B-480A-81D2-AE1F7B2E0660}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{D92ADA88-361B-480A-81D2-AE1F7B2E0660}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{D92ADA88-361B-480A-81D2-AE1F7B2E0660}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{D92ADA88-361B-480A-81D2-AE1F7B2E0660}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{D92ADA88-361B-480A-81D2-AE1F7B2E0660}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{D92ADA88-361B-480A-81D2-AE1F7B2E0660}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{D92ADA88-361B-480A-81D2-AE1F7B2E0660}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{D92ADA88-361B-480A-81D2-AE1F7B2E0660}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{4FB42026-81C2-47B3-99A4-751452E64814}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{4FB42026-81C2-47B3-99A4-751452E64814}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{4FB42026-81C2-47B3-99A4-751452E64814}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{4FB42026-81C2-47B3-99A4-751452E64814}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{4FB42026-81C2-47B3-99A4-751452E64814}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{4FB42026-81C2-47B3-99A4-751452E64814}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{4FB42026-81C2-47B3-99A4-751452E64814}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{4FB42026-81C2-47B3-99A4-751452E64814}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{4FB42026-81C2-47B3-99A4-751452E64814}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{4FB42026-81C2-47B3-99A4-751452E64814}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{4FB42026-81C2-47B3-99A4-751452E64814}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{4FB42026-81C2-47B3-99A4-751452E64814}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{EEEE504F-24AC-4932-9B28-F684AB20FB50}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{EEEE504F-24AC-4932-9B28-F684AB20FB50}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{EEEE504F-24AC-4932-9B28-F684AB20FB50}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{EEEE504F-24AC-4932-9B28-F684AB20FB50}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{EEEE504F-24AC-4932-9B28-F684AB20FB50}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{EEEE504F-24AC-4932-9B28-F684AB20FB50}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{EEEE504F-24AC-4932-9B28-F684AB20FB50}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{EEEE504F-24AC-4932-9B28-F684AB20FB50}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{EEEE504F-24AC-4932-9B28-F684AB20FB50}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{EEEE504F-24AC-4932-9B28-F684AB20FB50}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{EEEE504F-24AC-4932-9B28-F684AB20FB50}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{EEEE504F-24AC-4932-9B28-F684AB20FB50}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{3AF8D59E-D10A-46DE-97A6-0A6C156F22CD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{3AF8D59E-D10A-46DE-97A6-0A6C156F22CD}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{3AF8D59E-D10A-46DE-97A6-0A6C156F22CD}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{3AF8D59E-D10A-46DE-97A6-0A6C156F22CD}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{3AF8D59E-D10A-46DE-97A6-0A6C156F22CD}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{3AF8D59E-D10A-46DE-97A6-0A6C156F22CD}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{3AF8D59E-D10A-46DE-97A6-0A6C156F22CD}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{3AF8D59E-D10A-46DE-97A6-0A6C156F22CD}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{3AF8D59E-D10A-46DE-97A6-0A6C156F22CD}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{3AF8D59E-D10A-46DE-97A6-0A6C156F22CD}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{3AF8D59E-D10A-46DE-97A6-0A6C156F22CD}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{3AF8D59E-D10A-46DE-97A6-0A6C156F22CD}.Release|x86.Build.0 = Release|Any CPU\r\n\t\t{08C1D823-E8E1-4D86-8F73-A9F3AE8FEFC7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{08C1D823-E8E1-4D86-8F73-A9F3AE8FEFC7}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{08C1D823-E8E1-4D86-8F73-A9F3AE8FEFC7}.Debug|x64.ActiveCfg = Debug|Any CPU\r\n\t\t{08C1D823-E8E1-4D86-8F73-A9F3AE8FEFC7}.Debug|x64.Build.0 = Debug|Any CPU\r\n\t\t{08C1D823-E8E1-4D86-8F73-A9F3AE8FEFC7}.Debug|x86.ActiveCfg = Debug|Any CPU\r\n\t\t{08C1D823-E8E1-4D86-8F73-A9F3AE8FEFC7}.Debug|x86.Build.0 = Debug|Any CPU\r\n\t\t{08C1D823-E8E1-4D86-8F73-A9F3AE8FEFC7}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{08C1D823-E8E1-4D86-8F73-A9F3AE8FEFC7}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{08C1D823-E8E1-4D86-8F73-A9F3AE8FEFC7}.Release|x64.ActiveCfg = Release|Any CPU\r\n\t\t{08C1D823-E8E1-4D86-8F73-A9F3AE8FEFC7}.Release|x64.Build.0 = Release|Any CPU\r\n\t\t{08C1D823-E8E1-4D86-8F73-A9F3AE8FEFC7}.Release|x86.ActiveCfg = Release|Any CPU\r\n\t\t{08C1D823-E8E1-4D86-8F73-A9F3AE8FEFC7}.Release|x86.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{0E7E06C1-C223-4975-A9DB-D338EBF0A9BC} = {058BCE2A-8F81-4404-83D3-844CE030E513}\r\n\t\t{06B9857A-02A6-430D-B579-98A762C281D3} = {058BCE2A-8F81-4404-83D3-844CE030E513}\r\n\t\t{ADAB2C6B-10FE-4B31-BCD2-E2EFA69D5A66} = {5734E9DC-CF67-4337-B28E-695280598B88}\r\n\t\t{66119997-5949-45D6-9175-F1C7C599A8F5} = {5734E9DC-CF67-4337-B28E-695280598B88}\r\n\t\t{D1D2622E-ACF7-479C-ABC8-E1B94E41D9D5} = {5734E9DC-CF67-4337-B28E-695280598B88}\r\n\t\t{09F5EB90-1063-4338-A146-25F7BE8BFF43} = {5734E9DC-CF67-4337-B28E-695280598B88}\r\n\t\t{1CA8D3D3-B6A6-4006-AA96-671CB41D6391} = {058BCE2A-8F81-4404-83D3-844CE030E513}\r\n\t\t{CCB5075B-C50A-4CD1-983A-2D51DC2430F4} = {5734E9DC-CF67-4337-B28E-695280598B88}\r\n\t\t{89C49FF5-9441-4DE8-A33F-1B2852401A54} = {058BCE2A-8F81-4404-83D3-844CE030E513}\r\n\t\t{9F16EBDF-4546-43C2-82B8-7D698F7A1E89} = {5734E9DC-CF67-4337-B28E-695280598B88}\r\n\t\t{0E9B466C-1151-4AE9-A55A-6377A25F8235} = {058BCE2A-8F81-4404-83D3-844CE030E513}\r\n\t\t{33D5FB92-074E-4C13-BFD6-21184DD0013A} = {5734E9DC-CF67-4337-B28E-695280598B88}\r\n\t\t{EF3149F4-59C1-4896-989E-59D9D5F9050A} = {058BCE2A-8F81-4404-83D3-844CE030E513}\r\n\t\t{FA2462FE-A439-48C5-976D-491F73C25CE1} = {5734E9DC-CF67-4337-B28E-695280598B88}\r\n\t\t{7944AA31-16BA-43A8-A9CB-2ED758518C9E} = {058BCE2A-8F81-4404-83D3-844CE030E513}\r\n\t\t{9C383F09-8936-42ED-B9A6-ED3300AECB1C} = {058BCE2A-8F81-4404-83D3-844CE030E513}\r\n\t\t{5E5AF23F-61F6-4B44-B682-2D141B54DF5C} = {058BCE2A-8F81-4404-83D3-844CE030E513}\r\n\t\t{C0A85A7D-9D7F-4A6C-BA33-9E79050CF522} = {058BCE2A-8F81-4404-83D3-844CE030E513}\r\n\t\t{23C68B10-36FD-41DE-AAA3-77BEDFD63945} = {5734E9DC-CF67-4337-B28E-695280598B88}\r\n\t\t{8302F65E-035F-45D7-B894-915B68B72711} = {058BCE2A-8F81-4404-83D3-844CE030E513}\r\n\t\t{89DED7A5-7334-4852-A1FC-9266AD0EF388} = {5734E9DC-CF67-4337-B28E-695280598B88}\r\n\t\t{8909AB97-EDD6-4AB2-B733-A543ACB957CA} = {058BCE2A-8F81-4404-83D3-844CE030E513}\r\n\t\t{AA837BCA-A2D6-4F74-95BC-1F6A66146562} = {5734E9DC-CF67-4337-B28E-695280598B88}\r\n\t\t{53FB25E0-C8CB-4D65-8D94-6FA627BF9760} = {058BCE2A-8F81-4404-83D3-844CE030E513}\r\n\t\t{833A65BC-5B37-468D-8BB4-2343CEFDFA5D} = {5734E9DC-CF67-4337-B28E-695280598B88}\r\n\t\t{C42C352E-F3E2-41F6-A446-0CACDA5096AF} = {058BCE2A-8F81-4404-83D3-844CE030E513}\r\n\t\t{EF313B39-68CF-45D1-9094-BDDCCAC9DB2D} = {5734E9DC-CF67-4337-B28E-695280598B88}\r\n\t\t{8A936050-5B84-4711-A235-2BA36A445B26} = {058BCE2A-8F81-4404-83D3-844CE030E513}\r\n\t\t{8120B952-D9BC-450A-B691-C030177CD24D} = {5734E9DC-CF67-4337-B28E-695280598B88}\r\n\t\t{E3C25A1C-2754-4134-8780-1F0A247D6850} = {058BCE2A-8F81-4404-83D3-844CE030E513}\r\n\t\t{5323D32E-0CF2-41B6-AF91-37F744AC1554} = {058BCE2A-8F81-4404-83D3-844CE030E513}\r\n\t\t{22E99FEC-8DFC-4E87-90EE-BC7F6E988DAD} = {5734E9DC-CF67-4337-B28E-695280598B88}\r\n\t\t{0E546413-BBF8-40B3-8534-8D1D986AA888} = {5734E9DC-CF67-4337-B28E-695280598B88}\r\n\t\t{D92ADA88-361B-480A-81D2-AE1F7B2E0660} = {5734E9DC-CF67-4337-B28E-695280598B88}\r\n\t\t{4FB42026-81C2-47B3-99A4-751452E64814} = {5734E9DC-CF67-4337-B28E-695280598B88}\r\n\t\t{EEEE504F-24AC-4932-9B28-F684AB20FB50} = {5734E9DC-CF67-4337-B28E-695280598B88}\r\n\t\t{3AF8D59E-D10A-46DE-97A6-0A6C156F22CD} = {AA791E28-7914-439A-B59A-580B8D8FE95D}\r\n\t\t{08C1D823-E8E1-4D86-8F73-A9F3AE8FEFC7} = {058BCE2A-8F81-4404-83D3-844CE030E513}\r\n\tEndGlobalSection\r\n\tGlobalSection(ExtensibilityGlobals) = postSolution\r\n\t\tSolutionGuid = {781C77FF-8818-4AF3-BCAF-C82B52FFF0C0}\r\n\tEndGlobalSection\r\nEndGlobal\r\n"
  },
  {
    "path": "Nancy.sln.DotSettings",
    "content": "﻿<wpf:ResourceDictionary xml:space=\"preserve\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" xmlns:s=\"clr-namespace:System;assembly=mscorlib\" xmlns:ss=\"urn:shemas-jetbrains-com:settings-storage-xaml\" xmlns:wpf=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">\n\t<s:Boolean x:Key=\"/Default/CodeInspection/ExcludedFiles/FileMasksToSkip/=_002A_002Ecshtml/@EntryIndexedValue\">True</s:Boolean>\n\t<s:String x:Key=\"/Default/CodeInspection/Highlighting/InspectionSeverities/=ArrangeTypeMemberModifiers/@EntryIndexedValue\">WARNING</s:String>\n\t<s:String x:Key=\"/Default/CodeInspection/Highlighting/InspectionSeverities/=ArrangeTypeModifiers/@EntryIndexedValue\">WARNING</s:String>\n\t<s:String x:Key=\"/Default/CodeInspection/Highlighting/InspectionSeverities/=BuiltInTypeReferenceStyle/@EntryIndexedValue\">WARNING</s:String>\n\t<s:String x:Key=\"/Default/CodeInspection/Highlighting/InspectionSeverities/=SuggestVarOrType_005FBuiltInTypes/@EntryIndexedValue\">WARNING</s:String>\n\t<s:String x:Key=\"/Default/CodeInspection/Highlighting/InspectionSeverities/=SuggestVarOrType_005FElsewhere/@EntryIndexedValue\">WARNING</s:String>\n\t<s:String x:Key=\"/Default/CodeInspection/Highlighting/InspectionSeverities/=SuggestVarOrType_005FSimpleTypes/@EntryIndexedValue\">WARNING</s:String>\n\t<s:String x:Key=\"/Default/CodeStyle/CodeCleanup/Profiles/=NancyStandard/@EntryIndexedValue\">&lt;?xml version=\"1.0\" encoding=\"utf-16\"?&gt;&lt;Profile name=\"NancyStandard\"&gt;&lt;CSUseVar&gt;&lt;BehavourStyle&gt;CAN_CHANGE_TO_IMPLICIT&lt;/BehavourStyle&gt;&lt;LocalVariableStyle&gt;ALWAYS_IMPLICIT&lt;/LocalVariableStyle&gt;&lt;ForeachVariableStyle&gt;ALWAYS_IMPLICIT&lt;/ForeachVariableStyle&gt;&lt;/CSUseVar&gt;&lt;CSOptimizeUsings&gt;&lt;OptimizeUsings&gt;True&lt;/OptimizeUsings&gt;&lt;EmbraceInRegion&gt;False&lt;/EmbraceInRegion&gt;&lt;RegionName&gt;&lt;/RegionName&gt;&lt;/CSOptimizeUsings&gt;&lt;CSReformatCode&gt;True&lt;/CSReformatCode&gt;&lt;CSShortenReferences&gt;True&lt;/CSShortenReferences&gt;&lt;CSReorderTypeMembers&gt;True&lt;/CSReorderTypeMembers&gt;&lt;CSMakeFieldReadonly&gt;True&lt;/CSMakeFieldReadonly&gt;&lt;CSCodeStyleAttributes ArrangeTypeAccessModifier=\"True\" ArrangeTypeMemberAccessModifier=\"True\" SortModifiers=\"True\" RemoveRedundantParentheses=\"True\" AddMissingParentheses=\"True\" ArrangeBraces=\"True\" ArrangeAttributes=\"False\" ArrangeArgumentsStyle=\"False\" /&gt;&lt;/Profile&gt;</s:String>\n\t<s:String x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/BRACES_FOR_DOWHILE/@EntryValue\">Required</s:String>\n\t<s:String x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/BRACES_FOR_FIXED/@EntryValue\">Required</s:String>\n\t<s:String x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/BRACES_FOR_FOR/@EntryValue\">Required</s:String>\n\t<s:String x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/BRACES_FOR_FOREACH/@EntryValue\">Required</s:String>\n\t<s:String x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/BRACES_FOR_IFELSE/@EntryValue\">Required</s:String>\n\t<s:String x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/BRACES_FOR_LOCK/@EntryValue\">Required</s:String>\n\t<s:String x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/BRACES_FOR_USING/@EntryValue\">Required</s:String>\n\t<s:String x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/BRACES_FOR_WHILE/@EntryValue\">Required</s:String>\n\t<s:String x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/ThisQualifier/INSTANCE_MEMBERS_QUALIFY_MEMBERS/@EntryValue\">All</s:String>\n\t<s:Boolean x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/ALIGN_MULTILINE_BINARY_EXPRESSIONS_CHAIN/@EntryValue\">False</s:Boolean>\n\t<s:String x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/ANONYMOUS_METHOD_DECLARATION_BRACES/@EntryValue\">NEXT_LINE</s:String>\n\t<s:Int64 x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/BLANK_LINES_AROUND_INVOCABLE/@EntryValue\">1</s:Int64>\n\t<s:Int64 x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/BLANK_LINES_AROUND_SINGLE_LINE_AUTO_PROPERTY/@EntryValue\">1</s:Int64>\n\t<s:Int64 x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/BLANK_LINES_AROUND_SINGLE_LINE_FIELD/@EntryValue\">1</s:Int64>\n\t<s:Int64 x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/BLANK_LINES_AROUND_SINGLE_LINE_INVOCABLE/@EntryValue\">1</s:Int64>\n\t<s:Int64 x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/BLANK_LINES_AROUND_SINGLE_LINE_PROPERTY/@EntryValue\">1</s:Int64>\n\t<s:Int64 x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/BLANK_LINES_BETWEEN_USING_GROUPS/@EntryValue\">0</s:Int64>\n\t<s:String x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/FORCE_FIXED_BRACES_STYLE/@EntryValue\">ALWAYS_ADD</s:String>\n\t<s:String x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/FORCE_FOR_BRACES_STYLE/@EntryValue\">ALWAYS_ADD</s:String>\n\t<s:String x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/FORCE_FOREACH_BRACES_STYLE/@EntryValue\">ALWAYS_ADD</s:String>\n\t<s:String x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/FORCE_IFELSE_BRACES_STYLE/@EntryValue\">ALWAYS_ADD</s:String>\n\t<s:String x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/FORCE_USING_BRACES_STYLE/@EntryValue\">ALWAYS_ADD</s:String>\n\t<s:String x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/FORCE_WHILE_BRACES_STYLE/@EntryValue\">ALWAYS_ADD</s:String>\n\t<s:String x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/INITIALIZER_BRACES/@EntryValue\">NEXT_LINE</s:String>\n\t<s:Int64 x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_BLANK_LINES_IN_CODE/@EntryValue\">1</s:Int64>\n\t<s:Int64 x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_BLANK_LINES_IN_DECLARATIONS/@EntryValue\">1</s:Int64>\n\t<s:Boolean x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/LINE_FEED_AT_FILE_END/@EntryValue\">True</s:Boolean>\n\t<s:String x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/REDUNDANT_THIS_QUALIFIER_STYLE/@EntryValue\">ALWAYS_USE</s:String>\n\t<s:String x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/SIMPLE_EMBEDDED_STATEMENT_STYLE/@EntryValue\">LINE_BREAK</s:String>\n\t<s:Boolean x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/SPACE_AFTER_TYPECAST_PARENTHESES/@EntryValue\">False</s:Boolean>\n\t<s:Boolean x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/SPACE_AROUND_MULTIPLICATIVE_OP/@EntryValue\">True</s:Boolean>\n\t<s:Boolean x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/SPACE_BEFORE_SIZEOF_PARENTHESES/@EntryValue\">False</s:Boolean>\n\t<s:Boolean x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/SPACE_BEFORE_TYPEOF_PARENTHESES/@EntryValue\">False</s:Boolean>\n\t<s:Boolean x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/SPACE_WITHIN_SINGLE_LINE_ARRAY_INITIALIZER_BRACES/@EntryValue\">True</s:Boolean>\n\t<s:Boolean x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/STICK_COMMENT/@EntryValue\">False</s:Boolean>\n\t<s:Boolean x:Key=\"/Default/CodeStyle/CSharpUsing/AddImportsToDeepestScope/@EntryValue\">True</s:Boolean>\n\t<s:Boolean x:Key=\"/Default/CodeStyle/CSharpUsing/QualifiedUsingAtNestedScope/@EntryValue\">True</s:Boolean>\n\t<s:String x:Key=\"/Default/CodeStyle/FileHeader/FileHeaderRegionName/@EntryValue\"></s:String>\n\t<s:String x:Key=\"/Default/CodeStyle/FileHeader/FileHeaderText/@EntryValue\"></s:String>\n\t<s:String x:Key=\"/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=MethodPropertyEvent/@EntryIndexedValue\">&lt;Policy Inspect=\"True\" Prefix=\"\" Suffix=\"\" Style=\"AaBb\"&gt;&lt;ExtraRule Prefix=\"\" Suffix=\"\" Style=\"Aa_bb\" /&gt;&lt;/Policy&gt;</s:String>\n\t<s:String x:Key=\"/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=PrivateInstanceFields/@EntryIndexedValue\">&lt;Policy Inspect=\"True\" Prefix=\"\" Suffix=\"\" Style=\"aaBb\" /&gt;</s:String>\n\t<s:String x:Key=\"/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=PrivateStaticFields/@EntryIndexedValue\">&lt;Policy Inspect=\"True\" Prefix=\"\" Suffix=\"\" Style=\"aaBb\" /&gt;</s:String>\n\t<s:Boolean x:Key=\"/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EAddAccessorOwnerDeclarationBracesMigration/@EntryIndexedValue\">True</s:Boolean>\n\t<s:Boolean x:Key=\"/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateBlankLinesAroundFieldToBlankLinesAroundProperty/@EntryIndexedValue\">True</s:Boolean>\n\t<s:Boolean x:Key=\"/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateThisQualifierSettings/@EntryIndexedValue\">True</s:Boolean>\n\t<s:String x:Key=\"/Default/FilterSettingsManager/CoverageFilterXml/@EntryValue\">&lt;data&gt;&lt;IncludeFilters /&gt;&lt;ExcludeFilters /&gt;&lt;/data&gt;</s:String>\n\t<s:String x:Key=\"/Default/FilterSettingsManager/AttributeFilterXml/@EntryValue\">&lt;data /&gt;</s:String>\n</wpf:ResourceDictionary>\n\n"
  },
  {
    "path": "NuGet.config",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n\r\n<configuration>\r\n  <packageSources>\r\n    <add key=\"api.nuget.org\" value=\"https://api.nuget.org/v3/index.json\" />\r\n  </packageSources>\r\n</configuration>\r\n"
  },
  {
    "path": "README.md",
    "content": "# ** Announcement ** - Nancy is no longer being maintained! \n\nWe would like to thank all the thousands of users of Nancy, all the people who wrote blog posts, conference speakers, video producers and those that spread the word of Nancy.  \n\nWe would like to thank the 150+ contributors to Nancy that made it what it became, without you the work would have been much harder and opportunities missed.  \n\nWe would like to thank [VQ](http://www.vqcomms.com) for financially sponsoring our open source efforts.  \n\nWe would like to thank the core contributors to Nancy [@jchannon](https://github.com/jchannon), [@khellang](https://github.com/khellang), [@damianh](https://github.com/damianh), [@phillip-haydon](https://github.com/phillip-haydon), [@prabirshrestha](https://github.com/prabirshrestha), [@horsdal](https://github.com/horsdal) for working hard into the nights coding, testing and writing docs but most importantly the founders of Nancy itself [@thecodejunkie](https://github.com/thecodejunkie) and [@grumpydev](https://github.com/grumpydev) whose vision made Nancy what it was, a fun, performant and enjoyable web framework.\n\n## Support\nWe understand that organisations may have services and products that still depend on Nancy in production. A couple of members of the team can offer a support, maintenance, migration services on commercial terms. Please reach out to [nancyfx.help@gmail.com](mailto:nancyfx.help@gmail.com) to discuss options.\n\n## Forking\nNancy's licence is permissible so we encourage forking if you need to perform maintenance. However, the logos and name are copyright to Andreas Håkansson and Steven Robbins and are not for re-use or editing. Please see full licence information [here](https://github.com/NancyFx/Nancy.Portfolio/blob/master/license.txt)\n\n\n------------------------------------------------------------------------------------------------------------------------------------------\n# Meet Nancy [![NuGet Version](http://img.shields.io/nuget/v/Nancy.svg?style=flat)](https://www.nuget.org/packages/Nancy/) [![Slack Status](http://slack.nancyfx.org/badge.svg)](http://slack.nancyfx.org)\n\nNancy is a lightweight, low-ceremony, framework for building HTTP based services on .NET Framework/Core and [Mono](http://mono-project.com). The goal of the framework is to stay out of the way as much as possible and provide a super-duper-happy-path to all interactions.\n\nNancy is designed to handle `DELETE`, `GET`, `HEAD`, `OPTIONS`, `POST`, `PUT` and `PATCH` requests and provides a simple, elegant, [Domain Specific Language (DSL)](http://en.wikipedia.org/wiki/Domain-specific_language) for returning a response with just a couple of keystrokes, leaving you with more time to focus on the important bits..\n**your** code and **your** application.\n\nWrite your application\n```csharp\npublic class Module : NancyModule\n{\n    public Module()\n    {\n        Get(\"/greet/{name}\", x => {\n            return string.Concat(\"Hello \", x.name);\n        });\n    }\n}\n```\n\nCompile, run and enjoy the simple, elegant design!\n\n## Features\n\n* Built from the bottom up, not simply a DSL on top of an existing framework. Removing limitations and feature hacks of an underlying framework, as well as the need to reference more assemblies than you need. _keep it light_\n* Run anywhere. Nancy is not built on any specific hosting technology can be run anywhere. Out of the box, Nancy supports running on ASP.NET/IIS, WCF, Self-hosting and any [OWIN](http://owin.org)\n* Ultra lightweight action declarations for GET, HEAD, PUT, POST, DELETE, OPTIONS and PATCH requests\n* View engine integration (Razor, Spark, dotLiquid, our own SuperSimpleViewEngine and many more)\n* Powerful request path matching that includes advanced parameter capabilities. The path matching strategy can be replaced with custom implementations to fit your exact needs\n* Easy response syntax, enabling you to return things like int, string, HttpStatusCode and Action<Stream> elements without having to explicitly cast or wrap your response - you just return it and Nancy _will_ do the work for you\n* A powerful, light-weight, testing framework to help you verify the behavior of your application\n* Content negotiation\n* And much, much more\n\n## The super-duper-happy-path\n\nThe \"super-duper-happy-path\" (or SDHP if you’re ‘down with the kids’ ;-)) is a phrase we coined to describe the ethos of Nancy; and providing the “super-duper-happy-path” experience is something we strive for in all of our APIs.\n\nWhile it’s hard to pin down exactly what it is, it’s a very emotive term after all, but the basic ideas behind it are:\n\n* “It just works” - you should be able to pick things up and use them without any mucking about. Added a new module? That’s automatically discovered for you. Brought in a new View Engine? All wired up and ready to go without you having to do anything else. Even if you add a new dependency to your module, by default we’ll locate that and inject it for you - no configuration required.\n* “Easily customisable” - even though “it just works”, there shouldn’t be any barriers that get in the way of customisation should you want to work the way you want to work with the components that you want to use. Want to use another container? No problem! Want to tweak the way routes are selected? Go ahead! Through our bootstrapper approach all of these things should be a piece of cake.\n* “Low ceremony” - the amount of “Nancy code” you should need in your application should be minimal. The important part of any Nancy application is your code - our code should get out of your way and let you get on with building awesome applications. As a testament to this it’s actually possible to fit a functional Nancy application into a single Tweet :-)\n* “Low friction” - when building software with Nancy the APIs should help you get where you want to go, rather than getting in your way. Naming should be obvious, required configuration should be minimal, but power and extensibility should still be there when you need it.\n\nAbove all, creating an application with Nancy should be a pleasure, and hopefully fun! But without sacrificing the power or extensibility that you may need as your application grows.\n\n## Getting started\n\nAs a start several working samples are provided in the `/sample` directory. Simply run the build script `build.ps1` (for Windows PowerShell) or `build.sh` (for \\*nix-Bash) first.\n\n## Community\n\nNancy followers can be found on Slack [NancyFx team](http://nancyfx.slack.com). You can also find Nancy on Twitter using the #NancyFx hashtag.\n\n## Help out\n\nThere are many ways you can contribute to Nancy. Like most open-source software projects, contributing code\nis just one of many outlets where you can help improve. Some of the things that you could help out with in\nNancy are:\n\n* Documentation (both code and features)\n* Bug reports\n* Bug fixes\n* Feature requests\n* Feature implementations\n* Test coverage\n* Code quality\n* Sample applications\n\n## Continuous integration builds\n\n| Platform                    | Status                                                                                                                                  |\n|-----------------------------|-----------------------------------------------------------------------------------------------------------------------------------------|\n| AppVeyor (.NET & .NET Core) | [![Build Status](https://ci.appveyor.com/api/projects/status/mpd9lbxvithu16vg/branch/master?svg=true)](https://ci.appveyor.com/project/NancyFx/nancy) |\n| Travis (Mono)               | [![Build Status](https://travis-ci.org/NancyFx/Nancy.png?branch=master)](https://travis-ci.org/NancyFx/Nancy)                           |\n\nTo get build artifacts of latest `master`, please use our [MyGet feed](https://www.myget.org/gallery/nancyfx)\n\n## Contributors\n\nNancy is not a one man project and many of the features that are available would not have been possible without the awesome contributions from the community!\n\nFor a full list of contributors, please see [the website](http://www.nancyfx.org/contribs.html).\n\n## Code of Conduct\n\nThis project has adopted the code of conduct defined by the [Contributor Covenant](http://contributor-covenant.org/) to clarify expected behavior in our community. For more information see the [.NET Foundation Code of Conduct](http://www.dotnetfoundation.org/code-of-conduct).\n\n## Contribution License Agreement\n\nContributing to Nancy requires you to sign a [contribution license agreement](https://cla2.dotnetfoundation.org/) (CLA) for anything other than a trivial change. By signing the contribution license agreement, the community is free to use your contribution to .NET Foundation projects.\n\n## .NET Foundation\n\nThis project is supported by the [.NET Foundation](http://www.dotnetfoundation.org).\n\n## Copyright\n\nCopyright © 2010 Andreas Håkansson, Steven Robbins and contributors\n\n## License\n\nNancy is licensed under [MIT](http://www.opensource.org/licenses/mit-license.php \"Read more about the MIT license form\"). Refer to license.txt for more information.\n"
  },
  {
    "path": "SharedAssemblyInfo.cs",
    "content": "using System.Runtime.InteropServices;\r\nusing System.Reflection;\r\n\r\n[assembly: AssemblyTitle(\"Nancy\")]\r\n[assembly: AssemblyDescription(\"A Sinatra inspired web framework for the .NET platform\")]\r\n[assembly: AssemblyCompany(\"Nancy\")]\r\n[assembly: AssemblyProduct(\"Nancy\")]\r\n[assembly: AssemblyCopyright(\"Copyright (C) Andreas Hakansson, Steven Robbins and contributors\")]\r\n[assembly: AssemblyVersion(\"2.0.0\")]\r\n[assembly: AssemblyInformationalVersion(\"2.0.0-alpha\")]\r\n"
  },
  {
    "path": "appveyor.yml",
    "content": "image: Visual Studio 2017\r\n\r\nversion: 2.0.0-ci000{build}\r\nconfiguration: Release\r\ncache: C:\\Users\\appveyor\\.nuget\\packages\r\n\r\nnuget:\r\n  disable_publish_on_pr: true\r\n\r\npull_requests:\r\n  do_not_increment_build_number: true\r\n\r\ninstall:\r\n- set PATH=C:\\Program Files (x86)\\MSBuild\\14.0\\Bin;%PATH%\r\n\r\nbuild_script:\r\n- ps: .\\build.ps1 -verbosity=minimal\r\n\r\nartifacts:\r\n- path: build\\nuget\\*.nupkg\r\n  name: NuGet\r\n\r\ndeploy:\r\n- provider: NuGet\r\n  server: https://www.myget.org/F/nancyfx/api/v2/package\r\n  api_key:\r\n    secure: +D460p+eBTZg/1k7YpDwGp8G74VhOhjxp62EypsjVyul8DT/6B8o3taDbQCZCJ6+\r\n  skip_symbols: true\r\n  on:\r\n    branch: master\r\n\r\ntest: off\r\n"
  },
  {
    "path": "build.cake",
    "content": "// Usings\r\nusing System.Text.RegularExpressions;\r\n\r\n// Arguments\r\nvar target = Argument<string>(\"target\", \"Default\");\r\nvar source = Argument<string>(\"source\", null);\r\nvar apiKey = Argument<string>(\"apikey\", null);\r\nvar version = Argument<string>(\"targetversion\", \"2.0.0-pre\" + (EnvironmentVariable(\"APPVEYOR_BUILD_NUMBER\") ?? \"0\"));\r\nvar nogit = Argument<bool>(\"nogit\", false);\r\n\r\n// Variables\r\nvar configuration = \"Release\";\r\nvar fullFrameworkTarget = \"net452\";\r\nvar netStandardTarget = \"netstandard2.0\";\r\nvar netCoreTarget = \"netcoreapp2.0\";\r\n\r\n// Directories\r\nvar output = Directory(\"build\");\r\nvar outputBinaries = output + Directory(\"binaries\");\r\nvar outputBinariesNet452 = outputBinaries + Directory(fullFrameworkTarget);\r\nvar outputBinariesNetstandard = outputBinaries + Directory(netStandardTarget);\r\nvar outputPackages = output + Directory(\"packages\");\r\nvar outputNuGet = output + Directory(\"nuget\");\r\n\r\n/*\r\n/ TASK DEFINITIONS\r\n*/\r\n\r\nTask(\"Default\")\r\n    .IsDependentOn(\"Test\")\r\n    .IsDependentOn(\"Update-Version\")\r\n    .IsDependentOn(\"Package-NuGet\");\r\n\r\nTask(\"Clean\")\r\n    .Does(() =>\r\n    {\r\n        CleanDirectories(new DirectoryPath[] {\r\n            output,\r\n            outputBinaries,\r\n            outputPackages,\r\n            outputNuGet,\r\n            outputBinariesNet452,\r\n            outputBinariesNetstandard\r\n        });\r\n\r\n        CleanDirectories(\"./src/**/\" + configuration);\r\n        CleanDirectories(\"./test/**/\" + configuration);\r\n        CleanDirectories(\"./samples/**/\" + configuration);\r\n    });\r\n\r\nTask(\"Compile\")\r\n    .Description(\"Builds all the projects in the solution\")\r\n    .IsDependentOn(\"Clean\")\r\n    .IsDependentOn(\"Restore-NuGet-Packages\")\r\n    .Does(() =>\r\n    {\r\n        var projects =\r\n            GetFiles(\"./**/*.csproj\") -\r\n            GetFiles(\"./samples/**/*.csproj\");\r\n\r\n        if (projects.Count == 0)\r\n        {\r\n            throw new CakeException(\"Unable to find any projects to build.\");\r\n        }\r\n\r\n        foreach(var project in projects)\r\n        {\r\n            var content =\r\n                System.IO.File.ReadAllText(project.FullPath, Encoding.UTF8);\r\n\r\n            if (IsRunningOnUnix() && content.Contains(\">\" + fullFrameworkTarget + \"<\"))\r\n            {\r\n                Information(project.GetFilename() + \" only supports \" +fullFrameworkTarget + \" and cannot be built on *nix. Skipping.\");\r\n                continue;\r\n            }\r\n\r\n            DotNetCoreBuild(project.GetDirectory().FullPath, new DotNetCoreBuildSettings {\r\n                ArgumentCustomization = args => {\r\n                    if (IsRunningOnUnix())\r\n                    {\r\n                        args.Append(string.Concat(\"-f \", project.GetDirectory().GetDirectoryName().Contains(\".Tests\") ? netCoreTarget : netStandardTarget));\r\n                    }\r\n\r\n                    return args;\r\n                },\r\n                Configuration = configuration\r\n            });\r\n        }\r\n    });\r\n\r\nTask(\"Package\")\r\n    .Description(\"Zips up the built binaries for easy distribution\")\r\n    .IsDependentOn(\"Publish\")\r\n    .Does(() =>\r\n    {\r\n        var package =\r\n            outputPackages + File(\"Nancy-Latest.zip\");\r\n\r\n        var files =\r\n            GetFiles(outputBinaries.Path.FullPath + \"/**/*\");\r\n\r\n        Zip(outputBinaries, package, files);\r\n    });\r\n\r\nTask(\"Package-NuGet\")\r\n    .Description(\"Generates NuGet packages for each project\")\r\n    .Does(() =>\r\n    {\r\n        foreach(var project in GetFiles(\"./src/**/*.csproj\"))\r\n        {\r\n            Information(\"Packaging \" + project.GetFilename().FullPath);\r\n\r\n            var content =\r\n                System.IO.File.ReadAllText(project.FullPath, Encoding.UTF8);\r\n\r\n            if (IsRunningOnUnix() && content.Contains(\">\" + fullFrameworkTarget + \"<\"))\r\n            {\r\n                Information(project.GetFilename() + \" only supports \" +fullFrameworkTarget + \" and cannot be packaged on *nix. Skipping.\");\r\n                continue;\r\n            }\r\n\r\n            DotNetCorePack(project.GetDirectory().FullPath, new DotNetCorePackSettings {\r\n                Configuration = configuration,\r\n                OutputDirectory = outputNuGet\r\n            });\r\n        }\r\n    });\r\n\r\nTask(\"Publish\")\r\n    .Description(\"Gathers output files and copies them to the output folder\")\r\n    .IsDependentOn(\"Compile\")\r\n    .Does(() =>\r\n    {\r\n        // Copy net452 binaries.\r\n        CopyFiles(GetFiles(\"./src/**/bin/\" + configuration + \"/\" + fullFrameworkTarget + \"/*.dll\")\r\n            + GetFiles(\"./src/**/bin/\" + configuration + \"/\" + fullFrameworkTarget + \"/*.xml\")\r\n            + GetFiles(\"./src/**/bin/\" + configuration + \"/\" + fullFrameworkTarget + \"/*.pdb\")\r\n            + GetFiles(\"./src/**/*.ps1\"), outputBinariesNet452);\r\n\r\n        // Copy netstandard binaries.\r\n        CopyFiles(GetFiles(\"./src/**/bin/\" + configuration + \"/\" + netStandardTarget + \"/*.dll\")\r\n            + GetFiles(\"./src/**/bin/\" + configuration + \"/\" + netStandardTarget + \"/*.xml\")\r\n            + GetFiles(\"./src/**/bin/\" + configuration + \"/\" + netStandardTarget + \"/*.pdb\")\r\n            + GetFiles(\"./src/**/*.ps1\"), outputBinariesNetstandard);\r\n    });\r\n\r\nTask(\"Publish-NuGet\")\r\n    .Description(\"Pushes the nuget packages in the nuget folder to a NuGet source. Also publishes the packages into the feeds.\")\r\n    .Does(() =>\r\n    {\r\n        if(string.IsNullOrWhiteSpace(apiKey))\r\n        {\r\n            throw new CakeException(\"No NuGet API key provided. You need to pass in --apikey=\\\"xyz\\\"\");\r\n        }\r\n\r\n        var packages =\r\n            GetFiles(outputNuGet.Path.FullPath + \"/*.nupkg\") -\r\n            GetFiles(outputNuGet.Path.FullPath + \"/*.symbols.nupkg\");\r\n\r\n        foreach(var package in packages)\r\n        {\r\n            NuGetPush(package, new NuGetPushSettings {\r\n                Source = source,\r\n                ApiKey = apiKey\r\n            });\r\n        }\r\n    });\r\n\r\nTask(\"Prepare-Release\")\r\n    .IsDependentOn(\"Update-Version\")\r\n    .Does(() =>\r\n    {\r\n        // Add\r\n        foreach (var file in GetFiles(\"./src/**/*.csproj\"))\r\n        {\r\n            if (nogit)\r\n            {\r\n                Information(\"git \" + string.Format(\"add {0}\", file.FullPath));\r\n            }\r\n            else\r\n            {\r\n                StartProcess(\"git\", new ProcessSettings {\r\n                    Arguments = string.Format(\"add {0}\", file.FullPath)\r\n                });\r\n            }\r\n        }\r\n\r\n        // Commit\r\n        if (nogit)\r\n        {\r\n            Information(\"git \" + string.Format(\"commit -m \\\"Updated version to {0}\\\"\", version));\r\n        }\r\n        else\r\n        {\r\n            StartProcess(\"git\", new ProcessSettings {\r\n                Arguments = string.Format(\"commit -m \\\"Updated version to {0}\\\"\", version)\r\n            });\r\n        }\r\n\r\n        // Tag\r\n        if (nogit)\r\n        {\r\n            Information(\"git \" + string.Format(\"tag \\\"v{0}\\\"\", version));\r\n        }\r\n        else\r\n        {\r\n            StartProcess(\"git\", new ProcessSettings {\r\n                Arguments = string.Format(\"tag \\\"v{0}\\\"\", version)\r\n            });\r\n        }\r\n\r\n        //Push\r\n        if (nogit)\r\n        {\r\n            Information(\"git push origin master\");\r\n            Information(\"git push --tags\");\r\n        }\r\n        else\r\n        {\r\n            StartProcess(\"git\", new ProcessSettings {\r\n                Arguments = \"push origin master\"\r\n            });\r\n\r\n            StartProcess(\"git\", new ProcessSettings {\r\n                Arguments = \"push --tags\"\r\n            });\r\n        }\r\n    });\r\n\r\nTask(\"Restore-NuGet-Packages\")\r\n    .Description(\"Restores NuGet packages for all projects\")\r\n    .Does(() =>\r\n    {\r\n        DotNetCoreRestore(new DotNetCoreRestoreSettings {\r\n            ArgumentCustomization = args => {\r\n                args.Append(\"--verbosity minimal\");\r\n                return args;\r\n            }\r\n        });\r\n    });\r\n\r\nTask(\"Tag\")\r\n    .Description(\"Tags the current release\")\r\n    .Does(() =>\r\n    {\r\n        StartProcess(\"git\", new ProcessSettings {\r\n            Arguments = string.Format(\"tag \\\"v{0}\\\"\", version)\r\n        });\r\n    });\r\n\r\nTask(\"Test\")\r\n    .Description(\"Executes unit tests for all projects\")\r\n    .IsDependentOn(\"Compile\")\r\n    .Does(() =>\r\n    {\r\n        /*\r\n            Exclude Nancy.ViewEngines.Spark.Tests from test execution until their problem\r\n            with duplicate assembly references (if the same assembly exists more than once\r\n            in the application domain, it fails to compile the views) has been fixed.\r\n        */\r\n\r\n        var projects =\r\n            GetFiles(\"./test/**/*.csproj\") -\r\n            GetFiles(\"./test/Nancy.ViewEngines.Spark.Tests/Nancy.ViewEngines.Spark.Tests.csproj\");\r\n\r\n        if (projects.Count == 0)\r\n        {\r\n            throw new CakeException(\"Unable to find any projects to test.\");\r\n        }\r\n\r\n        foreach(var project in projects)\r\n        {\r\n            var content =\r\n                System.IO.File.ReadAllText(project.FullPath, Encoding.UTF8);\r\n\r\n            if (IsRunningOnUnix() && content.Contains(\">\" + fullFrameworkTarget + \"<\"))\r\n            {\r\n                Information(project.GetFilename() + \" only supports \" +fullFrameworkTarget + \" and tests cannot be executed on *nix. Skipping.\");\r\n                continue;\r\n            }\r\n\r\n            var settings = new ProcessSettings {\r\n                Arguments = string.Concat(\"xunit -configuration \", configuration, \" -nobuild\"),\r\n                WorkingDirectory = project.GetDirectory()\r\n            };\r\n\r\n            if (IsRunningOnUnix())\r\n            {\r\n                settings.Arguments.Append(string.Concat(\"-framework \", netCoreTarget));\r\n            }\r\n\r\n            Information(\"Executing tests for \" + project.GetFilename() + \" with arguments: \" + settings.Arguments.Render());\r\n\r\n            if (StartProcess(\"dotnet\", settings) != 0)\r\n            {\r\n                throw new CakeException(\"One or more tests failed during execution of: \" + project.GetFilename());\r\n            }\r\n        }\r\n    });\r\n\r\nTask(\"Update-Version\")\r\n    .Does(() =>\r\n    {\r\n        Information(\"Setting version to \" + version);\r\n\r\n        if(string.IsNullOrWhiteSpace(version))\r\n        {\r\n            throw new CakeException(\"No version specified! You need to pass in --targetversion=\\\"x.y.z\\\"\");\r\n        }\r\n\r\n        var file =\r\n            MakeAbsolute(File(\"./src/Directory.Build.props\"));\r\n\r\n        Information(file.FullPath);\r\n\r\n        var project =\r\n            System.IO.File.ReadAllText(file.FullPath, Encoding.UTF8);\r\n\r\n        var projectVersion =\r\n            new Regex(@\"<Version>.+<\\/Version>\");\r\n\r\n        project =\r\n            projectVersion.Replace(project, string.Concat(\"<Version>\", version, \"</Version>\"));\r\n\r\n        System.IO.File.WriteAllText(file.FullPath, project, Encoding.UTF8);\r\n    });\r\n\r\n/*\r\n/ RUN BUILD TARGET\r\n*/\r\n\r\nRunTarget(target);\r\n"
  },
  {
    "path": "build.ps1",
    "content": "$CakeVersion = \"0.24.0\"\r\n$DotNetVersion = select-string -Path .\\global.json -Pattern '[\\d]\\.[\\d]\\.[\\d]' | % {$_.Matches} | % {$_.Value };\r\n$DotNetInstallerUri = \"https://raw.githubusercontent.com/dotnet/cli/v$DotNetVersion/scripts/obtain/dotnet-install.ps1\";\r\n\r\n# Make sure tools folder exists\r\n$PSScriptRoot = $pwd\r\n\r\n$ToolPath = Join-Path $PSScriptRoot \"tools\"\r\nif (!(Test-Path $ToolPath)) {\r\n    Write-Verbose \"Creating tools directory...\"\r\n    New-Item -Path $ToolPath -Type directory | out-null\r\n}\r\n\r\n###########################################################################\r\n# INSTALL .NET CORE CLI\r\n###########################################################################\r\n\r\nFunction Remove-PathVariable([string]$VariableToRemove)\r\n{\r\n    $path = [Environment]::GetEnvironmentVariable(\"PATH\", \"User\")\r\n    if ($path -ne $null)\r\n    {\r\n        $newItems = $path.Split(';', [StringSplitOptions]::RemoveEmptyEntries) | Where-Object { \"$($_)\" -inotlike $VariableToRemove }\r\n        [Environment]::SetEnvironmentVariable(\"PATH\", [System.String]::Join(';', $newItems), \"User\")\r\n    }\r\n\r\n    $path = [Environment]::GetEnvironmentVariable(\"PATH\", \"Process\")\r\n    if ($path -ne $null)\r\n    {\r\n        $newItems = $path.Split(';', [StringSplitOptions]::RemoveEmptyEntries) | Where-Object { \"$($_)\" -inotlike $VariableToRemove }\r\n        [Environment]::SetEnvironmentVariable(\"PATH\", [System.String]::Join(';', $newItems), \"Process\")\r\n    }\r\n}\r\n\r\n# Get .NET Core CLI path if installed.\r\n$FoundDotNetCliVersion = $null;\r\nif (Get-Command dotnet -ErrorAction SilentlyContinue) {\r\n    $FoundDotNetCliVersion = dotnet --version;\r\n}\r\n\r\nif($FoundDotNetCliVersion -ne $DotNetVersion) {\r\n    $InstallPath = Join-Path $PSScriptRoot \".dotnet\"\r\n    if (!(Test-Path $InstallPath)) {\r\n        mkdir -Force $InstallPath | Out-Null;\r\n    }\r\n\r\n    (New-Object System.Net.WebClient).DownloadFile($DotNetInstallerUri, \"$InstallPath\\dotnet-install.ps1\");\r\n    & $InstallPath\\dotnet-install.ps1 -Channel Current -Version $DotNetVersion -InstallDir $InstallPath;\r\n\r\n    Remove-PathVariable \"$InstallPath\"\r\n    $env:PATH = \"$InstallPath;$env:PATH\"\r\n    $env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1\r\n    $env:DOTNET_CLI_TELEMETRY_OPTOUT=1\r\n\r\n    & dotnet --info\r\n}\r\n\r\n###########################################################################\r\n# INSTALL CAKE\r\n###########################################################################\r\n\r\nAdd-Type -AssemblyName System.IO.Compression.FileSystem\r\nFunction Unzip\r\n{\r\n    param([string]$zipfile, [string]$outpath)\r\n\r\n    [System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath)\r\n}\r\n\r\n\r\n# Make sure Cake has been installed.\r\n$CakePath = Join-Path $ToolPath \"Cake.$CakeVersion/Cake.exe\"\r\nif (!(Test-Path $CakePath)) {\r\n    Write-Host \"Installing Cake...\"\r\n    (New-Object System.Net.WebClient).DownloadFile(\"https://www.nuget.org/api/v2/package/Cake/$CakeVersion\", \"$ToolPath\\Cake.zip\")\r\n    Unzip \"$ToolPath\\Cake.zip\" \"$ToolPath/Cake.$CakeVersion\"\r\n    Remove-Item \"$ToolPath\\Cake.zip\"\r\n}\r\n\r\n###########################################################################\r\n# RUN BUILD SCRIPT\r\n###########################################################################\r\n\r\n& \"$CakePath\" $args\r\nexit $LASTEXITCODE\r\n"
  },
  {
    "path": "build.sh",
    "content": "#!/usr/bin/env bash\n\n# Define directories.\nSCRIPT_DIR=$PWD\nTOOLS_DIR=$SCRIPT_DIR/tools\nCAKE_VERSION=0.24.0\nCAKE_DLL=$TOOLS_DIR/Cake.$CAKE_VERSION/Cake.exe\nDOTNET_VERSION=$(cat \"$SCRIPT_DIR/global.json\" | grep -o '[0-9]\\.[0-9]\\.[0-9]')\nDOTNET_INSTRALL_URI=https://raw.githubusercontent.com/dotnet/cli/v$DOTNET_VERSION/scripts/obtain/dotnet-install.sh\n\n# Make sure the tools folder exist.\nif [ ! -d \"$TOOLS_DIR\" ]; then\n  mkdir \"$TOOLS_DIR\"\nfi\n\n###########################################################################\n# INSTALL .NET CORE CLI\n###########################################################################\n\necho \"Installing .NET CLI...\"\nif [ ! -d \"$SCRIPT_DIR/.dotnet\" ]; then\n  mkdir \"$SCRIPT_DIR/.dotnet\"\nfi\ncurl -Lsfo \"$SCRIPT_DIR/.dotnet/dotnet-install.sh\" $DOTNET_INSTRALL_URI\nsudo bash \"$SCRIPT_DIR/.dotnet/dotnet-install.sh\" -c current --version $DOTNET_VERSION --install-dir .dotnet --no-path\nexport PATH=\"$SCRIPT_DIR/.dotnet\":$PATH\nexport DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1\nexport DOTNET_CLI_TELEMETRY_OPTOUT=1\n\"$SCRIPT_DIR/.dotnet/dotnet\" --info\n\n###########################################################################\n# INSTALL CAKE\n###########################################################################\n\nif [ ! -f \"$CAKE_DLL\" ]; then\n    curl -Lsfo Cake.zip \"https://www.nuget.org/api/v2/package/Cake/$CAKE_VERSION\" && unzip -q Cake.zip -d \"$TOOLS_DIR/Cake.$CAKE_VERSION\" && rm -f Cake.zip\n    if [ $? -ne 0 ]; then\n        echo \"An error occured while installing Cake.\"\n        exit 1\n    fi\nfi\n\n# Make sure that Cake has been installed.\nif [ ! -f \"$CAKE_DLL\" ]; then\n    echo \"Could not find Cake.exe at '$CAKE_DLL'.\"\n    exit 1\nfi\n\n###########################################################################\n# RUN BUILD SCRIPT\n###########################################################################\n\n# Point net452 to Mono assemblies\nexport FrameworkPathOverride=$(dirname $(which mono))/../lib/mono/4.5/\n\n# Start Cake\nexec mono \"$CAKE_DLL\" \"$@\"\n"
  },
  {
    "path": "favicon.license.txt",
    "content": "The Nancy logo is copyright ©2011 by Andreas Håkansson and Steven Robbins. Please consult the usage guidelines in the Nancy.Portfolio repository (https://github.com/NancyFx/Nancy.Portfolio) for information on how it may be used.\n"
  },
  {
    "path": "global.json",
    "content": "{\r\n    \"sdk\": {\r\n        \"version\": \"2.1.4\"\r\n    }\r\n}\r\n"
  },
  {
    "path": "how_to_build.txt",
    "content": "How to build Nancy\r\n==================\r\n\r\n*NOTE* These instructions are *only* for building with Cake - if you just want to build Nancy manually you can do so just by loading the solution into Visual Studio 2017 and pressing build :-)\r\n\r\nBuilding Nancy\r\n--------------\r\n\r\n1. At the command prompt, navigate to the Nancy root folder (should contain build.cake)\r\n2. To run the default build (which will compile, test and package Nancy) type the following command:\r\n  * On Windows type:\r\n    ./build.ps1\r\n  * On Linux/MacOS type:\r\n    ./build.sh\r\n\r\n*NOTE* On Linux/MacOS you need to have Mono >= 4.4 installed because Nancy targets .NET 4.5.2 for the full-framework build\r\n\r\nAfter the build has completed, there will be a new folder in the root called \"build\". It contains the following folders:\r\n\r\n  * binaries -> All the Nancy assembilies and their dependencies\r\n  * packages -> Zip file containing the binaries (other configurations might be added in the future)\r\n  * nuget -> NuGet packages generated from this build\r\n  \r\n"
  },
  {
    "path": "license.txt",
    "content": "The MIT License\r\n\r\nCopyright (c) 2010 Andreas Hkansson, Steven Robbins and contributors\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the \"Software\"), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in\r\nall copies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\nTHE SOFTWARE."
  },
  {
    "path": "samples/Nancy.Demo.Async/App.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n<configuration>\r\n    <startup> \r\n        <supportedRuntime version=\"v4.0\" sku=\".NETFramework,Version=v4.5\"/>\r\n    </startup>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Async/MainModule.cs",
    "content": "﻿namespace Nancy.Demo.Async\r\n{\r\n    using System;\r\n    using System.Net.Http;\r\n    using System.Threading.Tasks;\r\n\r\n    public class MainModule : NancyModule\r\n    {\r\n        public MainModule()\r\n        {\r\n            Before += async (ctx, ct) =>\r\n                {\r\n                    this.AddToLog(\"Before Hook Delay\\n\");\r\n                    await Task.Delay(5000);\r\n\r\n                    return null;\r\n                };\r\n\r\n            After += async (ctx, ct) =>\r\n                {\r\n                    this.AddToLog(\"After Hook Delay\\n\");\r\n                    await Task.Delay(5000);\r\n                    this.AddToLog(\"After Hook Complete\\n\");\r\n\r\n                    ctx.Response = this.GetLog();\r\n                };\r\n\r\n            Get[\"/\", true] = async (x, ct) =>\r\n                {\r\n                    this.AddToLog(\"Delay 1\\n\");\r\n                    await Task.Delay(1000);\r\n\r\n                    this.AddToLog(\"Delay 2\\n\");\r\n                    await Task.Delay(1000);\r\n\r\n                    this.AddToLog(\"Executing async http client\\n\");\r\n                    var client = new HttpClient();\r\n                    var res = await client.GetAsync(\"http://nancyfx.org\");\r\n                    var content = await res.Content.ReadAsStringAsync();\r\n\r\n                    this.AddToLog(\"Response: \" + content.Split('\\n')[0] + \"\\n\");\r\n\r\n                    return (Response)this.GetLog();\r\n                };\r\n        }\r\n\r\n        private void AddToLog(string logLine)\r\n        {\r\n            if (!this.Context.Items.ContainsKey(\"Log\"))\r\n            {\r\n                this.Context.Items[\"Log\"] = string.Empty;\r\n            }\r\n\r\n            this.Context.Items[\"Log\"] = (string)this.Context.Items[\"Log\"] + DateTime.Now.ToLongTimeString() + \" : \" + logLine;\r\n        }\r\n\r\n        private string GetLog()\r\n        {\r\n            if (!this.Context.Items.ContainsKey(\"Log\"))\r\n            {\r\n                this.Context.Items[\"Log\"] = string.Empty;\r\n            }\r\n\r\n            return (string)this.Context.Items[\"Log\"];\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Async/Nancy.Demo.Async.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\r\n  <PropertyGroup>\r\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\r\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\r\n    <ProjectGuid>{B4A5FF43-DE97-48CF-A759-1A868824791B}</ProjectGuid>\r\n    <OutputType>Exe</OutputType>\r\n    <AppDesignerFolder>Properties</AppDesignerFolder>\r\n    <RootNamespace>Nancy.Demo.Async</RootNamespace>\r\n    <AssemblyName>Nancy.Demo.Async</AssemblyName>\r\n    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\r\n    <FileAlignment>512</FileAlignment>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <DebugType>full</DebugType>\r\n    <Optimize>false</Optimize>\r\n    <OutputPath>bin\\Debug\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <DebugType>pdbonly</DebugType>\r\n    <Optimize>true</Optimize>\r\n    <OutputPath>bin\\Release\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoDebug|AnyCPU'\">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <OutputPath>bin\\MonoDebug\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <DebugType>full</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>true</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoRelease|AnyCPU'\">\r\n    <OutputPath>bin\\MonoRelease\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <Optimize>true</Optimize>\r\n    <DebugType>pdbonly</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>true</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <ItemGroup>\r\n    <Reference Include=\"System\" />\r\n    <Reference Include=\"System.Core\" />\r\n    <Reference Include=\"System.Net.Http\" />\r\n    <Reference Include=\"System.Xml.Linq\" />\r\n    <Reference Include=\"System.Data.DataSetExtensions\" />\r\n    <Reference Include=\"Microsoft.CSharp\" />\r\n    <Reference Include=\"System.Data\" />\r\n    <Reference Include=\"System.Xml\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Compile Include=\"..\\..\\SharedAssemblyInfo.cs\">\r\n      <Link>Properties\\SharedAssemblyInfo.cs</Link>\r\n    </Compile>\r\n    <Compile Include=\"MainModule.cs\" />\r\n    <Compile Include=\"Program.cs\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <None Include=\"App.config\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ProjectReference Include=\"..\\Nancy\\Nancy.csproj\">\r\n      <Project>{34576216-0DCA-4B0F-A0DC-9075E75A676F}</Project>\r\n      <Name>Nancy</Name>\r\n    </ProjectReference>\r\n  </ItemGroup>\r\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\r\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r\n       Other similar extension points exist, see Microsoft.Common.targets.\r\n  <Target Name=\"BeforeBuild\">\r\n  </Target>\r\n  <Target Name=\"AfterBuild\">\r\n  </Target>\r\n  -->\r\n</Project>"
  },
  {
    "path": "samples/Nancy.Demo.Async/Program.cs",
    "content": "﻿namespace Nancy.Demo.Async\r\n{\r\n    using System;\r\n    using System.IO;\r\n    using System.Text;\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n\r\n    using Nancy.Bootstrapper;\r\n\r\n    class Program\r\n    {\r\n        static void Main(string[] args)\r\n        {\r\n            ShowHeader();\r\n\r\n            var engine = GetEngine();\r\n            var request = GetRequest();\r\n\r\n            var tcs = new TaskCompletionSource<NancyContext>(); \r\n            var completionTask = tcs.Task;\r\n            \r\n            Console.Write(\"Running: \");\r\n\r\n            engine.HandleRequest(request, tcs.SetResult, tcs.SetException);\r\n\r\n            while (!completionTask.IsCompleted && !completionTask.IsFaulted)\r\n            {\r\n                Console.Write(\"*\");\r\n                Thread.Sleep(100);\r\n            }\r\n\r\n            string result = \"Unknown\";\r\n            if (completionTask.IsFaulted && completionTask.Exception != null)\r\n            {\r\n                result = completionTask.Exception.GetType().ToString();\r\n            }\r\n\r\n            if (completionTask.IsCompleted && completionTask.Result != null)\r\n            {\r\n                result = GetBody(completionTask.Result);\r\n            }\r\n\r\n            Console.WriteLine(\"\\nResult: \\n\\n{0}\", result);\r\n            Console.WriteLine(\"\\nPress any key to close.\");\r\n            Console.ReadKey();\r\n        }\r\n\r\n        private static INancyEngine GetEngine()\r\n        {\r\n            var bootstrapper = NancyBootstrapperLocator.Bootstrapper;\r\n            bootstrapper.Initialise();\r\n\r\n            var engine = bootstrapper.GetEngine();\r\n            return engine;\r\n        }\r\n\r\n        private static void ShowHeader()\r\n        {\r\n            Console.WriteLine(\"Async Demo\");\r\n            Console.WriteLine();\r\n            Console.WriteLine(\"A long running async request will be executed and until it is complete\");\r\n            Console.WriteLine(\"a series of '*' characters should appear every 100 milliseconds. If this was\");\r\n            Console.WriteLine(\"executed syncronously then the main thread would block and no characters\");\r\n            Console.WriteLine(\"would appear.\");\r\n            Console.WriteLine();\r\n        }\r\n\r\n        private static string GetBody(NancyContext result)\r\n        {\r\n            string output;\r\n\r\n            using (var memoryStream = new MemoryStream())\r\n            {\r\n                result.Response.Contents.Invoke(memoryStream);\r\n                output = Encoding.UTF8.GetString(memoryStream.GetBuffer());\r\n            }\r\n\r\n            return output;\r\n        }\r\n\r\n        private static Request GetRequest(string path = \"/\")\r\n        {\r\n            return new Request(\"GET\", path, \"http\");\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Authentication/AnotherVerySecureModule.cs",
    "content": "namespace Nancy.Demo.Authentication\r\n{\r\n    using System.Security.Claims;\r\n    using Nancy.Demo.Authentication.Models;\r\n    using Nancy.Security;\r\n\r\n    /// <summary>\r\n    /// A module that only people with SuperSecure clearance are allowed to access\r\n    /// </summary>\r\n    public class AnotherVerySecureModule : NancyModule\r\n    {\r\n        public AnotherVerySecureModule() : base(\"/superSecure\")\r\n        {\r\n            this.RequiresClaims(c => c.Type == ClaimTypes.Role && c.Value == \"SuperSecure\");\r\n\r\n            Get(\"/\", args =>\r\n            {\r\n                var model = new UserModel(this.Context.CurrentUser.Identity.Name);\r\n                return View[\"superSecure.cshtml\", model];\r\n            });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Authentication/AuthenticationBootstrapper.cs",
    "content": "namespace Nancy.Demo.Authentication\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Security.Claims;\r\n\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Responses;\r\n    using Nancy.TinyIoc;\r\n\r\n    public class AuthenticationBootstrapper : DefaultNancyBootstrapper\r\n    {\r\n        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)\r\n        {\r\n            base.ApplicationStartup(container, pipelines);\r\n\r\n            // In reality you would use a pre-built authentication/claims provider\r\n            pipelines.BeforeRequest += ctx =>\r\n            {\r\n                // World's-worse-authentication (TM)\r\n                // Pull the username out of the querystring if it exists\r\n                // and build claims from it\r\n                var username = ctx.Request.Query.username;\r\n\r\n                if (username.HasValue)\r\n                {\r\n                    ctx.CurrentUser = new ClaimsPrincipal(new ClaimsIdentity(BuildClaims(username), \"querystring\"));\r\n                }\r\n\r\n                return null;\r\n            };\r\n\r\n            pipelines.AfterRequest += ctx =>\r\n            {\r\n                // If status code comes back as Unauthorized then\r\n                // forward the user to the login page\r\n                if (ctx.Response.StatusCode == HttpStatusCode.Unauthorized)\r\n                {\r\n                    ctx.Response = new RedirectResponse(\"/login?returnUrl=\" + Uri.EscapeDataString(ctx.Request.Path));\r\n                }\r\n            };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Build claims based on username\r\n        /// </summary>\r\n        /// <param name=\"userName\">Current username</param>\r\n        /// <returns>IEnumerable of claims</returns>\r\n        private static IEnumerable<Claim> BuildClaims(string userName)\r\n        {\r\n            var claims = new List<Claim>();\r\n\r\n            // Only bob can have access to SuperSecure\r\n            if (String.Equals(userName, \"bob\", StringComparison.OrdinalIgnoreCase))\r\n            {\r\n                claims.Add(new Claim(ClaimTypes.Role, \"SuperSecure\"));\r\n            }\r\n\r\n            return claims;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Authentication/MainModule.cs",
    "content": "namespace Nancy.Demo.Authentication\r\n{\r\n    public class MainModule : NancyModule\r\n    {\r\n        public MainModule()\r\n        {\r\n            Get(\"/\", args => {\r\n                return View[\"Index.cshtml\"];\r\n            });\r\n\r\n            Get(\"/login\", args => {\r\n                return View[\"Login.cshtml\", this.Request.Query.returnUrl];\r\n            });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Authentication/Models/UserModel.cs",
    "content": "﻿namespace Nancy.Demo.Authentication.Models\r\n{\r\n    public class UserModel\r\n    {\r\n        public string Username { get; set; }\r\n\r\n        public UserModel(string username)\r\n        {\r\n            this.Username = username;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Authentication/Nancy.Demo.Authentication.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\r\n  <PropertyGroup>\r\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\r\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\r\n    <SchemaVersion>2.0</SchemaVersion>\r\n    <ProjectGuid>{5F2DD52D-471B-4946-8F7B-F050C88EFC52}</ProjectGuid>\r\n    <ProjectTypeGuids>{349C5851-65DF-11DA-9384-00065B846F21};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>\r\n    <OutputType>Library</OutputType>\r\n    <AppDesignerFolder>Properties</AppDesignerFolder>\r\n    <RootNamespace>Nancy.Demo.Authentication</RootNamespace>\r\n    <AssemblyName>Nancy.Demo.Authentication</AssemblyName>\r\n    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\r\n    <UseIISExpress>false</UseIISExpress>\r\n    <OldToolsVersion>4.0</OldToolsVersion>\r\n    <IISExpressSSLPort />\r\n    <IISExpressAnonymousAuthentication />\r\n    <IISExpressWindowsAuthentication />\r\n    <IISExpressUseClassicPipelineMode />\r\n    <UseGlobalApplicationHostFile />\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <DebugType>full</DebugType>\r\n    <Optimize>false</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\r\n    <DebugType>pdbonly</DebugType>\r\n    <Optimize>true</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoDebug|AnyCPU'\">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <DebugType>full</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.Authentication.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRules>false</CodeAnalysisIgnoreBuiltInRules>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Optimize>false</Optimize>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoRelease|AnyCPU'\">\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <Optimize>true</Optimize>\r\n    <DebugType>pdbonly</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.Authentication.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRules>true</CodeAnalysisIgnoreBuiltInRules>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <ItemGroup>\r\n    <Reference Include=\"Microsoft.CSharp\" />\r\n    <Reference Include=\"System\" />\r\n    <Reference Include=\"System.Data\" />\r\n    <Reference Include=\"System.Drawing\" />\r\n    <Reference Include=\"System.Web\" />\r\n    <Reference Include=\"System.Xml\" />\r\n    <Reference Include=\"System.Configuration\" />\r\n    <Reference Include=\"System.Xml.Linq\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Web.config\" />\r\n    <Content Include=\"Web.Debug.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n    <Content Include=\"Web.Release.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Compile Include=\"..\\..\\SharedAssemblyInfo.cs\">\r\n      <Link>Properties\\SharedAssemblyInfo.cs</Link>\r\n    </Compile>\r\n    <Compile Include=\"AuthenticationBootstrapper.cs\" />\r\n    <Compile Include=\"AnotherVerySecureModule.cs\" />\r\n    <Compile Include=\"MainModule.cs\" />\r\n    <Compile Include=\"Models\\UserModel.cs\" />\r\n    <Compile Include=\"SecureModule.cs\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.Hosting.Aspnet.MSBuild\\Nancy.Hosting.Aspnet.csproj\">\r\n      <Project>{15B7F794-0BB2-4B66-AD78-4A951F1209B2}</Project>\r\n      <Name>Nancy.Hosting.Aspnet</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.ViewEngines.Razor.MSBuild\\Nancy.ViewEngines.Razor.csproj\">\r\n      <Project>{2C6F51DF-015C-4DB6-B44C-0E5E4F25E2A9}</Project>\r\n      <Name>Nancy.ViewEngines.Razor</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.MSBuild\\Nancy.csproj\">\r\n      <Project>{34576216-0DCA-4B0F-A0DC-9075E75A676F}</Project>\r\n      <Name>Nancy</Name>\r\n    </ProjectReference>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Views\\Index.cshtml\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Views\\secure.cshtml\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Views\\Login.cshtml\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Views\\superSecure.cshtml\" />\r\n  </ItemGroup>\r\n  <PropertyGroup>\r\n    <VisualStudioVersion Condition=\"'$(VisualStudioVersion)' == ''\">10.0</VisualStudioVersion>\r\n    <VSToolsPath Condition=\"'$(VSToolsPath)' == ''\">$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)</VSToolsPath>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\r\n  <Import Project=\"$(VSToolsPath)\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"'$(VSToolsPath)' != ''\" />\r\n  <Import Project=\"$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v10.0\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"false\" />\r\n  <ProjectExtensions>\r\n    <VisualStudio>\r\n      <FlavorProperties GUID=\"{349C5851-65DF-11DA-9384-00065B846F21}\">\r\n        <WebProjectProperties>\r\n          <UseIIS>False</UseIIS>\r\n          <AutoAssignPort>True</AutoAssignPort>\r\n          <DevelopmentServerPort>1712</DevelopmentServerPort>\r\n          <DevelopmentServerVPath>/</DevelopmentServerVPath>\r\n          <IISUrl>\r\n          </IISUrl>\r\n          <NTLMAuthentication>False</NTLMAuthentication>\r\n          <UseCustomServer>False</UseCustomServer>\r\n          <CustomServerUrl>\r\n          </CustomServerUrl>\r\n          <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>\r\n        </WebProjectProperties>\r\n      </FlavorProperties>\r\n    </VisualStudio>\r\n    <MonoDevelop>\r\n      <Properties VerifyCodeBehindFields=\"true\" VerifyCodeBehindEvents=\"true\">\r\n        <XspParameters Port=\"8080\" Address=\"127.0.0.1\" SslMode=\"None\" SslProtocol=\"Default\" KeyType=\"None\" CertFile=\"\" KeyFile=\"\" PasswordOptions=\"None\" Password=\"\" Verbose=\"true\" />\r\n      </Properties>\r\n    </MonoDevelop>\r\n  </ProjectExtensions>\r\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r\n       Other similar extension points exist, see Microsoft.Common.targets.\r\n  <Target Name=\"BeforeBuild\">\r\n  </Target>\r\n  <Target Name=\"AfterBuild\">\r\n  </Target>\r\n  -->\r\n</Project>"
  },
  {
    "path": "samples/Nancy.Demo.Authentication/README.txt",
    "content": "﻿"
  },
  {
    "path": "samples/Nancy.Demo.Authentication/SecureModule.cs",
    "content": "namespace Nancy.Demo.Authentication\r\n{\r\n    using Nancy.Demo.Authentication.Models;\r\n    using Nancy.Security;\r\n\r\n    public class SecureModule : NancyModule\r\n    {\r\n        public SecureModule() : base(\"/secure\")\r\n        {\r\n            this.RequiresAuthentication();\r\n\r\n            Get(\"/\", args => {\r\n                var model = new UserModel(this.Context.CurrentUser.Identity.Name);\r\n                return View[\"secure.cshtml\", model];\r\n            });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Authentication/Views/Index.cshtml",
    "content": "﻿<html>\r\n<head>\r\n    <title>Index</title>\r\n</head>\r\n<body>\r\n    <h1>Nancy Authentication Demo</h1>\r\n    <a href=\"/secure\">Secure Pages</a>\r\n    <a href=\"/superSecure\">Super Secure Pages</a>\r\n    <a href=\"/superSecureToo\">More Super Secure Pages</a>\r\n</body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Authentication/Views/Login.cshtml",
    "content": "﻿<html>\r\n<head>\r\n    <title>Login</title>\r\n</head>\r\n<body>\r\n    <h1>Super Secure Login Page 4000</h1>\r\n    <form action=\"@Model\" method=\"get\">\r\n        <input name=\"username\" />\r\n        <input type=\"submit\" value=\"Submit\"/>\r\n    </form>\r\n    <a href=\"/\">Home</a>\r\n</body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Authentication/Views/secure.cshtml",
    "content": "﻿<html>\r\n<head>\r\n    <title>Index</title>\r\n</head>\r\n<body>\r\n    <h1>Secure Page</h1>\r\n    Hello @Model.Username\r\n    <a href=\"/\">Home</a>\r\n</body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Authentication/Views/superSecure.cshtml",
    "content": "﻿<html>\r\n<head>\r\n    <title>Index</title>\r\n</head>\r\n<body>\r\n    <h1>Super Secure Page</h1>\r\n    Hello @Model.Username\r\n    <a href=\"/\">Home</a>\r\n</body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Authentication/Web.Debug.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Authentication/Web.Release.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n    <compilation xdt:Transform=\"RemoveAttributes(debug)\" />\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Authentication/Web.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n<configuration>\r\n  <system.web>\r\n    <httpHandlers>\r\n      <add verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </httpHandlers>\r\n  </system.web>\r\n  <system.webServer>\r\n    <modules runAllManagedModulesForAllRequests=\"true\" />\r\n    <validation validateIntegratedModeConfiguration=\"false\" />\r\n    <handlers>\r\n      <add name=\"Nancy\" verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </handlers>\r\n  </system.webServer>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Basic/AuthenticationBootstrapper.cs",
    "content": "﻿namespace Nancy.Demo.Authentication.Basic\r\n{\r\n    using Nancy.Authentication.Basic;\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.TinyIoc;\r\n\r\n    public class AuthenticationBootstrapper : DefaultNancyBootstrapper\r\n    {\r\n        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)\r\n        {\r\n            base.ApplicationStartup(container, pipelines);\r\n\r\n            pipelines.EnableBasicAuthentication(new BasicAuthenticationConfiguration(\r\n                container.Resolve<IUserValidator>(),\r\n                \"MyRealm\"));\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Basic/MainModule.cs",
    "content": "﻿namespace Nancy.Demo.Authentication.Basic\r\n{\r\n    public class MainModule : NancyModule\r\n    {\r\n        public MainModule()\r\n        {\r\n            Get(\"/\", args => \"<a href='/secure'>Enter</a>\");\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Basic/Nancy.Demo.Authentication.Basic.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\r\n  <PropertyGroup>\r\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\r\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\r\n    <SchemaVersion>2.0</SchemaVersion>\r\n    <ProjectGuid>{911196F4-B88F-4940-B1FD-D30F5290D06D}</ProjectGuid>\r\n    <ProjectTypeGuids>{349C5851-65DF-11DA-9384-00065B846F21};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>\r\n    <OutputType>Library</OutputType>\r\n    <AppDesignerFolder>Properties</AppDesignerFolder>\r\n    <RootNamespace>Nancy.Demo.Authentication.Basic</RootNamespace>\r\n    <AssemblyName>Nancy.Demo.Authentication.Basic</AssemblyName>\r\n    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\r\n    <UseIISExpress>false</UseIISExpress>\r\n    <OldToolsVersion>4.0</OldToolsVersion>\r\n    <IISExpressSSLPort />\r\n    <IISExpressAnonymousAuthentication />\r\n    <IISExpressWindowsAuthentication />\r\n    <IISExpressUseClassicPipelineMode />\r\n    <UseGlobalApplicationHostFile />\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <DebugType>full</DebugType>\r\n    <Optimize>false</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\r\n    <DebugType>pdbonly</DebugType>\r\n    <Optimize>true</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoDebug|AnyCPU'\">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <DebugType>full</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.Authentication.Basic.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRules>false</CodeAnalysisIgnoreBuiltInRules>\r\n    <CodeAnalysisFailOnMissingRules>false</CodeAnalysisFailOnMissingRules>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Optimize>false</Optimize>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoRelease|AnyCPU'\">\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <Optimize>true</Optimize>\r\n    <DebugType>pdbonly</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.Authentication.Basic.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRules>false</CodeAnalysisIgnoreBuiltInRules>\r\n    <CodeAnalysisFailOnMissingRules>false</CodeAnalysisFailOnMissingRules>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <ItemGroup>\r\n    <Reference Include=\"Microsoft.CSharp\" />\r\n    <Reference Include=\"System\" />\r\n    <Reference Include=\"System.Data\" />\r\n    <Reference Include=\"System.Drawing\" />\r\n    <Reference Include=\"System.Web\" />\r\n    <Reference Include=\"System.Xml\" />\r\n    <Reference Include=\"System.Configuration\" />\r\n    <Reference Include=\"System.Xml.Linq\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Web.config\" />\r\n    <Content Include=\"Web.Debug.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n    <Content Include=\"Web.Release.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Compile Include=\"AuthenticationBootstrapper.cs\" />\r\n    <Compile Include=\"MainModule.cs\" />\r\n    <Compile Include=\"SecureModule.cs\" />\r\n    <Compile Include=\"UserValidator.cs\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.Authentication.Basic.MSBuild\\Nancy.Authentication.Basic.csproj\">\r\n      <Project>{BD72B98D-C81A-4013-B606-94B4BA2273E5}</Project>\r\n      <Name>Nancy.Authentication.Basic</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.Hosting.Aspnet.MSBuild\\Nancy.Hosting.Aspnet.csproj\">\r\n      <Project>{15B7F794-0BB2-4B66-AD78-4A951F1209B2}</Project>\r\n      <Name>Nancy.Hosting.Aspnet</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.MSBuild\\Nancy.csproj\">\r\n      <Project>{34576216-0DCA-4B0F-A0DC-9075E75A676F}</Project>\r\n      <Name>Nancy</Name>\r\n    </ProjectReference>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Folder Include=\"Properties\\\" />\r\n  </ItemGroup>\r\n  <PropertyGroup>\r\n    <VisualStudioVersion Condition=\"'$(VisualStudioVersion)' == ''\">10.0</VisualStudioVersion>\r\n    <VSToolsPath Condition=\"'$(VSToolsPath)' == ''\">$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)</VSToolsPath>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\r\n  <Import Project=\"$(VSToolsPath)\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"'$(VSToolsPath)' != ''\" />\r\n  <Import Project=\"$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v10.0\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"false\" />\r\n  <ProjectExtensions>\r\n    <VisualStudio>\r\n      <FlavorProperties GUID=\"{349C5851-65DF-11DA-9384-00065B846F21}\">\r\n        <WebProjectProperties>\r\n          <UseIIS>False</UseIIS>\r\n          <AutoAssignPort>True</AutoAssignPort>\r\n          <DevelopmentServerPort>12615</DevelopmentServerPort>\r\n          <DevelopmentServerVPath>/</DevelopmentServerVPath>\r\n          <IISUrl>\r\n          </IISUrl>\r\n          <NTLMAuthentication>False</NTLMAuthentication>\r\n          <UseCustomServer>False</UseCustomServer>\r\n          <CustomServerUrl>\r\n          </CustomServerUrl>\r\n          <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>\r\n        </WebProjectProperties>\r\n      </FlavorProperties>\r\n    </VisualStudio>\r\n    <MonoDevelop>\r\n      <Properties VerifyCodeBehindFields=\"true\" VerifyCodeBehindEvents=\"true\">\r\n        <XspParameters Port=\"8080\" Address=\"127.0.0.1\" SslMode=\"None\" SslProtocol=\"Default\" KeyType=\"None\" CertFile=\"\" KeyFile=\"\" PasswordOptions=\"None\" Password=\"\" Verbose=\"true\" />\r\n      </Properties>\r\n    </MonoDevelop>\r\n  </ProjectExtensions>\r\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r\n       Other similar extension points exist, see Microsoft.Common.targets.\r\n  <Target Name=\"BeforeBuild\">\r\n  </Target>\r\n  <Target Name=\"AfterBuild\">\r\n  </Target>\r\n  -->\r\n</Project>"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Basic/SecureModule.cs",
    "content": "﻿namespace Nancy.Demo.Authentication.Basic\r\n{\r\n    using Nancy.Security;\r\n\r\n    public class SecureModule : NancyModule\r\n    {\r\n        public SecureModule() : base(\"/secure\")\r\n        {\r\n            this.RequiresAuthentication();\r\n\r\n            Get(\"/\", args => \"Hello \" + this.Context.CurrentUser.Identity.Name);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Basic/UserValidator.cs",
    "content": "﻿namespace Nancy.Demo.Authentication.Basic\r\n{\r\n    using System.Security.Claims;\r\n    using System.Security.Principal;\r\n\r\n    using Nancy.Authentication.Basic;\r\n\r\n    public class UserValidator : IUserValidator\r\n    {\r\n        public ClaimsPrincipal Validate(string username, string password)\r\n        {\r\n            if (username == \"demo\" && password == \"demo\")\r\n            {\r\n                return new ClaimsPrincipal(new GenericIdentity(username));\r\n            }\r\n\r\n            // Not recognised => anonymous.\r\n            return null;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Basic/Web.Debug.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Basic/Web.Release.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n    <compilation xdt:Transform=\"RemoveAttributes(debug)\" />\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Basic/Web.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n<configuration>\r\n  <system.web>\r\n    <compilation debug=\"true\" targetFramework=\"4.0\" />\r\n    <httpHandlers>\r\n      <add verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </httpHandlers>\r\n  </system.web>\r\n\r\n  <system.webServer>\r\n    <modules runAllManagedModulesForAllRequests=\"true\" />\r\n    <validation validateIntegratedModeConfiguration=\"false\" />\r\n    <handlers>\r\n      <add name=\"Nancy\" verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </handlers>\r\n  </system.webServer>\r\n</configuration>"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Forms/FormsAuthBootstrapper.cs",
    "content": "namespace Nancy.Demo.Authentication.Forms\r\n{\r\n    using Nancy.Authentication.Forms;\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.TinyIoc;\r\n\r\n    public class FormsAuthBootstrapper : DefaultNancyBootstrapper\r\n    {\r\n        protected override void ConfigureApplicationContainer(TinyIoCContainer container)\r\n        {\r\n            // We don't call \"base\" here to prevent auto-discovery of\r\n            // types/dependencies\r\n        }\r\n\r\n        protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)\r\n        {\r\n            base.ConfigureRequestContainer(container, context);\r\n\r\n            // Here we register our user mapper as a per-request singleton.\r\n            // As this is now per-request we could inject a request scoped\r\n            // database \"context\" or other request scoped services.\r\n            container.Register<IUserMapper, UserDatabase>();\r\n        }\r\n\r\n        protected override void RequestStartup(TinyIoCContainer requestContainer, IPipelines pipelines, NancyContext context)\r\n        {\r\n            // At request startup we modify the request pipelines to\r\n            // include forms authentication - passing in our now request\r\n            // scoped user name mapper.\r\n            //\r\n            // The pipelines passed in here are specific to this request,\r\n            // so we can add/remove/update items in them as we please.\r\n            var formsAuthConfiguration =\r\n                new FormsAuthenticationConfiguration()\r\n                {\r\n                    RedirectUrl = \"~/login\",\r\n                    UserMapper = requestContainer.Resolve<IUserMapper>(),\r\n                };\r\n\r\n            FormsAuthentication.Enable(pipelines, formsAuthConfiguration);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Forms/MainModule.cs",
    "content": "namespace Nancy.Demo.Authentication.Forms\r\n{\r\n    using System;\r\n    using System.Dynamic;\r\n\r\n    using Nancy.Authentication.Forms;\r\n    using Nancy.Extensions;\r\n\r\n    public class MainModule : NancyModule\r\n    {\r\n        public MainModule()\r\n        {\r\n            Get(\"/\", args => {\r\n                return View[\"index\"];\r\n            });\r\n\r\n            Get(\"/login\", args =>\r\n            {\r\n                dynamic model = new ExpandoObject();\r\n                model.Errored = this.Request.Query.error.HasValue;\r\n\r\n                return View[\"login\", model];\r\n            });\r\n\r\n            Post(\"/login\", args => {\r\n                var userGuid = UserDatabase.ValidateUser((string)this.Request.Form.Username, (string)this.Request.Form.Password);\r\n\r\n                if (userGuid == null)\r\n                {\r\n                    return this.Context.GetRedirect(\"~/login?error=true&username=\" + (string)this.Request.Form.Username);\r\n                }\r\n\r\n                DateTime? expiry = null;\r\n                if (this.Request.Form.RememberMe.HasValue)\r\n                {\r\n                    expiry = DateTime.Now.AddDays(7);\r\n                }\r\n\r\n                return this.LoginAndRedirect(userGuid.Value, expiry);\r\n            });\r\n\r\n            Get(\"/logout\", args => {\r\n                return this.LogoutAndRedirect(\"~/\");\r\n            });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Forms/Models/UserModel.cs",
    "content": "﻿namespace Nancy.Demo.Authentication.Forms.Models\r\n{\r\n    public class UserModel\r\n    {\r\n        public string Username { get; private set; }\r\n\r\n        public UserModel(string username)\r\n        {\r\n            Username = username;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Forms/Nancy.Demo.Authentication.Forms.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\r\n  <PropertyGroup>\r\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\r\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\r\n    <SchemaVersion>2.0</SchemaVersion>\r\n    <ProjectGuid>{98940A30-1B48-4F71-A6BA-85F0AAF31A2F}</ProjectGuid>\r\n    <ProjectTypeGuids>{349C5851-65DF-11DA-9384-00065B846F21};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>\r\n    <OutputType>Library</OutputType>\r\n    <AppDesignerFolder>Properties</AppDesignerFolder>\r\n    <RootNamespace>Nancy.Demo.Authentication.Forms</RootNamespace>\r\n    <AssemblyName>Nancy.Demo.Authentication.Forms</AssemblyName>\r\n    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\r\n    <UseIISExpress>false</UseIISExpress>\r\n    <OldToolsVersion>4.0</OldToolsVersion>\r\n    <IISExpressSSLPort />\r\n    <IISExpressAnonymousAuthentication />\r\n    <IISExpressWindowsAuthentication />\r\n    <IISExpressUseClassicPipelineMode />\r\n    <UseGlobalApplicationHostFile />\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <DebugType>full</DebugType>\r\n    <Optimize>false</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\r\n    <DebugType>pdbonly</DebugType>\r\n    <Optimize>true</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoDebug|AnyCPU'\">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <DebugType>full</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.Authentication.Forms.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRules>false</CodeAnalysisIgnoreBuiltInRules>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Optimize>false</Optimize>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoRelease|AnyCPU'\">\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <Optimize>true</Optimize>\r\n    <DebugType>pdbonly</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.Authentication.Forms.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRules>false</CodeAnalysisIgnoreBuiltInRules>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <ItemGroup>\r\n    <Reference Include=\"Microsoft.CSharp\" />\r\n    <Reference Include=\"System\" />\r\n    <Reference Include=\"System.Data\" />\r\n    <Reference Include=\"System.Drawing\" />\r\n    <Reference Include=\"System.Web\" />\r\n    <Reference Include=\"System.Xml\" />\r\n    <Reference Include=\"System.Configuration\" />\r\n    <Reference Include=\"System.Xml.Linq\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Web.config\" />\r\n    <Content Include=\"Web.Debug.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n    <Content Include=\"Web.Release.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Compile Include=\"..\\..\\SharedAssemblyInfo.cs\">\r\n      <Link>Properties\\SharedAssemblyInfo.cs</Link>\r\n    </Compile>\r\n    <Compile Include=\"SecureModule.cs\" />\r\n    <Compile Include=\"FormsAuthBootstrapper.cs\" />\r\n    <Compile Include=\"MainModule.cs\" />\r\n    <Compile Include=\"Models\\UserModel.cs\" />\r\n    <Compile Include=\"PartlySecureModule.cs\" />\r\n    <Compile Include=\"UserDatabase.cs\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.Authentication.Forms.MSBuild\\Nancy.Authentication.Forms.csproj\">\r\n      <Project>{E8B18958-7C8A-4FBA-AF00-3041C34A20CE}</Project>\r\n      <Name>Nancy.Authentication.Forms</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.Hosting.Aspnet.MSBuild\\Nancy.Hosting.Aspnet.csproj\">\r\n      <Project>{15B7F794-0BB2-4B66-AD78-4A951F1209B2}</Project>\r\n      <Name>Nancy.Hosting.Aspnet</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.ViewEngines.Razor.MSBuild\\Nancy.ViewEngines.Razor.csproj\">\r\n      <Project>{2C6F51DF-015C-4DB6-B44C-0E5E4F25E2A9}</Project>\r\n      <Name>Nancy.ViewEngines.Razor</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.MSBuild\\Nancy.csproj\">\r\n      <Project>{34576216-0DCA-4B0F-A0DC-9075E75A676F}</Project>\r\n      <Name>Nancy</Name>\r\n    </ProjectReference>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Views\\login.cshtml\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Views\\index.cshtml\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Views\\secure.cshtml\" />\r\n  </ItemGroup>\r\n  <PropertyGroup>\r\n    <VisualStudioVersion Condition=\"'$(VisualStudioVersion)' == ''\">10.0</VisualStudioVersion>\r\n    <VSToolsPath Condition=\"'$(VSToolsPath)' == ''\">$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)</VSToolsPath>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\r\n  <Import Project=\"$(VSToolsPath)\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"'$(VSToolsPath)' != ''\" />\r\n  <Import Project=\"$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v10.0\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"false\" />\r\n  <ProjectExtensions>\r\n    <VisualStudio>\r\n      <FlavorProperties GUID=\"{349C5851-65DF-11DA-9384-00065B846F21}\">\r\n        <WebProjectProperties>\r\n          <UseIIS>False</UseIIS>\r\n          <AutoAssignPort>True</AutoAssignPort>\r\n          <DevelopmentServerPort>2146</DevelopmentServerPort>\r\n          <DevelopmentServerVPath>/forms</DevelopmentServerVPath>\r\n          <IISUrl>\r\n          </IISUrl>\r\n          <NTLMAuthentication>False</NTLMAuthentication>\r\n          <UseCustomServer>False</UseCustomServer>\r\n          <CustomServerUrl>\r\n          </CustomServerUrl>\r\n          <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>\r\n        </WebProjectProperties>\r\n      </FlavorProperties>\r\n    </VisualStudio>\r\n    <MonoDevelop>\r\n      <Properties VerifyCodeBehindFields=\"true\" VerifyCodeBehindEvents=\"true\">\r\n        <XspParameters Port=\"8080\" Address=\"127.0.0.1\" SslMode=\"None\" SslProtocol=\"Default\" KeyType=\"None\" CertFile=\"\" KeyFile=\"\" PasswordOptions=\"None\" Password=\"\" Verbose=\"true\" />\r\n      </Properties>\r\n    </MonoDevelop>\r\n  </ProjectExtensions>\r\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r\n       Other similar extension points exist, see Microsoft.Common.targets.\r\n  <Target Name=\"BeforeBuild\">\r\n  </Target>\r\n  <Target Name=\"AfterBuild\">\r\n  </Target>\r\n  -->\r\n</Project>"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Forms/PartlySecureModule.cs",
    "content": "namespace Nancy.Demo.Authentication.Forms\r\n{\r\n    using Nancy.Demo.Authentication.Forms.Models;\r\n    using Nancy.Security;\r\n\r\n    public class PartlySecureModule : NancyModule\r\n    {\r\n        public PartlySecureModule()\r\n            : base(\"/partlysecure\")\r\n        {\r\n            Get(\"/\", args => \"No auth needed! <a href='partlysecure/secured'>Enter the secure bit!</a>\");\r\n\r\n            Get(\"/secured\", args => {\r\n                this.RequiresAuthentication();\r\n\r\n                var model = new UserModel(this.Context.CurrentUser.Identity.Name);\r\n                return View[\"secure.cshtml\", model];\r\n            });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Forms/README.txt",
    "content": "﻿"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Forms/SecureModule.cs",
    "content": "namespace Nancy.Demo.Authentication.Forms\r\n{\r\n    using Nancy.Demo.Authentication.Forms.Models;\r\n    using Nancy.Security;\r\n\r\n    public class SecureModule : NancyModule\r\n    {\r\n        public SecureModule() : base(\"/secure\")\r\n        {\r\n            this.RequiresAuthentication();\r\n\r\n            Get(\"/\", args => {\r\n                var model = new UserModel(this.Context.CurrentUser.Identity.Name);\r\n                return View[\"secure.cshtml\", model];\r\n            });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Forms/UserDatabase.cs",
    "content": "namespace Nancy.Demo.Authentication.Forms\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Security.Claims;\r\n    using System.Security.Principal;\r\n\r\n    using Nancy.Authentication.Forms;\r\n\r\n    public class UserDatabase : IUserMapper\r\n    {\r\n        private static List<Tuple<string, string, Guid>> users = new List<Tuple<string, string, Guid>>();\r\n\r\n        static UserDatabase()\r\n        {\r\n            users.Add(new Tuple<string, string, Guid>(\"admin\", \"password\", new Guid(\"55E1E49E-B7E8-4EEA-8459-7A906AC4D4C0\")));\r\n            users.Add(new Tuple<string, string, Guid>(\"user\", \"password\", new Guid(\"56E1E49E-B7E8-4EEA-8459-7A906AC4D4C0\")));\r\n        }\r\n\r\n        public ClaimsPrincipal GetUserFromIdentifier(Guid identifier, NancyContext context)\r\n        {\r\n            var userRecord = users.FirstOrDefault(u => u.Item3 == identifier);\r\n\r\n            return userRecord == null\r\n                       ? null\r\n                       : new ClaimsPrincipal(new GenericIdentity(userRecord.Item1));\r\n        }\r\n\r\n        public static Guid? ValidateUser(string username, string password)\r\n        {\r\n            var userRecord = users.FirstOrDefault(u => u.Item1 == username && u.Item2 == password);\r\n\r\n            if (userRecord == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            return userRecord.Item3;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Forms/Views/index.cshtml",
    "content": "﻿<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n    <title>Forms Authentication Demo</title>\r\n</head>\r\n<body>\r\n    <a href=\"secure\">Enter the \"Secure Zone\"!</a><br/>\r\n\r\n    <a href=\"partlysecure\">Enter the \"Partly Secure Zone\"!</a><br/>\r\n</body>\r\n</html>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Forms/Views/login.cshtml",
    "content": "﻿<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n    <title>Login</title>\r\n</head>\r\n<body>\r\n    <form method=\"POST\">\r\n        Username <input type=\"text\" name=\"Username\" />\r\n        <br />\r\n        Password <input name=\"Password\" type=\"password\" />\r\n        <br />\r\n        Remember Me <input name=\"RememberMe\" type=\"checkbox\" value=\"True\" />\r\n        <br />\r\n        <input type=\"submit\" value=\"Login\" />\r\n    </form>\r\n    @if (Model.Errored) {\r\n        <div id=\"errorBox\" class=\"floatingError\">Invalid Username or Password</div>\r\n    }\r\n</body>\r\n</html>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Forms/Views/secure.cshtml",
    "content": "﻿<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n    <title>Secure Page!</title>\r\n</head>\r\n<body>\r\n    Welcome to the secure area @Model.Username !\r\n\r\n    <br />\r\n    <br />\r\n    <a href=\"@Url.Content(\"~/logout\")\">Logout</a>\r\n</body>\r\n</html>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Forms/Web.Debug.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Forms/Web.Release.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n    <compilation xdt:Transform=\"RemoveAttributes(debug)\" />\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Forms/Web.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n<configuration>\r\n  <system.web>\r\n    <compilation debug=\"true\" targetFramework=\"4.5\"/>\r\n    <httpHandlers>\r\n      <add verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </httpHandlers>\r\n  </system.web>\r\n  <system.webServer>\r\n    <modules runAllManagedModulesForAllRequests=\"true\" />\r\n    <validation validateIntegratedModeConfiguration=\"false\" />\r\n    <handlers>\r\n      <add name=\"Nancy\" verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </handlers>\r\n  </system.webServer>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Forms.TestingDemo/LoginFixture.cs",
    "content": "namespace Nancy.Demo.Authentication.Forms.TestingDemo\r\n{\r\n    using System;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Testing;\r\n\r\n    using Xunit;\r\n\r\n    public class LoginFixture\r\n    {\r\n        private readonly Browser browser;\r\n\r\n        public LoginFixture()\r\n        {\r\n            var bootstrapper = new TestBootstrapper();\r\n            this.browser = new Browser(bootstrapper);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_redirect_to_login_with_error_querystring_if_username_or_password_incorrect()\r\n        {\r\n            // Given, When\r\n            var response = await browser.Post(\"/login/\", (with) =>\r\n            {\r\n                with.HttpRequest();\r\n                with.FormValue(\"Username\", \"username\");\r\n                with.FormValue(\"Password\", \"wrongpassword\");\r\n            });\r\n\r\n            response.ShouldHaveRedirectedTo(\"/login?error=true&username=username\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_display_error_message_when_error_passed()\r\n        {\r\n            // Given, When\r\n            var response = await browser.Get(\"/login\", (with) =>\r\n                {\r\n                    with.HttpRequest();\r\n                    with.Query(\"error\", \"true\");\r\n                });\r\n\r\n            response.Body[\"#errorBox\"]\r\n                .ShouldExistOnce()\r\n                .And.ShouldBeOfClass(\"floatingError\")\r\n                .And.ShouldContain(\"invalid\", StringComparison.OrdinalIgnoreCase);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Forms.TestingDemo/Nancy.Demo.Authentication.Forms.TestingDemo.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <PropertyGroup>\r\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\r\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\r\n    <ProductVersion>8.0.30703</ProductVersion>\r\n    <SchemaVersion>2.0</SchemaVersion>\r\n    <ProjectGuid>{948A8EF6-D50C-45EA-9AFD-7A4723ADAB0B}</ProjectGuid>\r\n    <OutputType>Library</OutputType>\r\n    <AppDesignerFolder>Properties</AppDesignerFolder>\r\n    <RootNamespace>Nancy.Demo.Authentication.Forms.TestingDemo</RootNamespace>\r\n    <AssemblyName>Nancy.Demo.Authentication.Forms.TestingDemo</AssemblyName>\r\n    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\r\n    <FileAlignment>512</FileAlignment>\r\n    <PublishUrl>publish\\</PublishUrl>\r\n    <Install>true</Install>\r\n    <InstallFrom>Disk</InstallFrom>\r\n    <UpdateEnabled>false</UpdateEnabled>\r\n    <UpdateMode>Foreground</UpdateMode>\r\n    <UpdateInterval>7</UpdateInterval>\r\n    <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r\n    <UpdatePeriodically>false</UpdatePeriodically>\r\n    <UpdateRequired>false</UpdateRequired>\r\n    <MapFileExtensions>true</MapFileExtensions>\r\n    <ApplicationRevision>0</ApplicationRevision>\r\n    <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r\n    <IsWebBootstrapper>false</IsWebBootstrapper>\r\n    <UseApplicationTrust>false</UseApplicationTrust>\r\n    <BootstrapperEnabled>true</BootstrapperEnabled>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <DebugType>full</DebugType>\r\n    <Optimize>false</Optimize>\r\n    <OutputPath>bin\\Debug\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\r\n    <DebugType>pdbonly</DebugType>\r\n    <Optimize>true</Optimize>\r\n    <OutputPath>bin\\Release\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoDebug|AnyCPU'\">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <OutputPath>bin\\MonoDebug\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <DebugType>full</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Debug\\Nancy.Demo.Authentication.Forms.TestingDemo.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Optimize>false</Optimize>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoRelease|AnyCPU'\">\r\n    <OutputPath>bin\\MonoRelease\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <Optimize>true</Optimize>\r\n    <DebugType>pdbonly</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Release\\Nancy.Demo.Authentication.Forms.TestingDemo.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <ItemGroup>\r\n    <Reference Include=\"System\" />\r\n    <Reference Include=\"System.Core\" />\r\n    <Reference Include=\"System.Xml.Linq\" />\r\n    <Reference Include=\"Microsoft.CSharp\" />\r\n    <Reference Include=\"System.Data\" />\r\n    <Reference Include=\"System.Xml\" />\r\n    <Reference Include=\"xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\r\n      <HintPath>..\\..\\packages\\xunit.abstractions.2.0.0\\lib\\net35\\xunit.abstractions.dll</HintPath>\r\n      <Private>True</Private>\r\n    </Reference>\r\n    <Reference Include=\"xunit.assert, Version=2.1.0.3179, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\r\n      <HintPath>..\\..\\packages\\xunit.assert.2.1.0\\lib\\dotnet\\xunit.assert.dll</HintPath>\r\n      <Private>True</Private>\r\n    </Reference>\r\n    <Reference Include=\"xunit.core, Version=2.1.0.3179, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\r\n      <HintPath>..\\..\\packages\\xunit.extensibility.core.2.1.0\\lib\\dotnet\\xunit.core.dll</HintPath>\r\n      <Private>True</Private>\r\n    </Reference>\r\n    <Reference Include=\"xunit.execution.desktop, Version=2.1.0.3179, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\r\n      <HintPath>..\\..\\packages\\xunit.extensibility.execution.2.1.0\\lib\\net45\\xunit.execution.desktop.dll</HintPath>\r\n      <Private>True</Private>\r\n    </Reference>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Compile Include=\"..\\..\\test\\Nancy.Tests\\ShouldExtensions.cs\">\r\n      <Link>ShouldExtensions.cs</Link>\r\n    </Compile>\r\n    <Compile Include=\"..\\..\\SharedAssemblyInfo.cs\">\r\n      <Link>Properties\\SharedAssemblyInfo.cs</Link>\r\n    </Compile>\r\n    <Compile Include=\"LoginFixture.cs\" />\r\n    <Compile Include=\"TestBootstrapper.cs\" />\r\n    <Compile Include=\"TestRootPathProvider.cs\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.Testing.MSBuild\\Nancy.Testing.csproj\">\r\n      <Project>{d79203c0-b672-4751-9c95-c3ab7d3fefbe}</Project>\r\n      <Name>Nancy.Testing</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\Nancy.Demo.Authentication.Forms\\Nancy.Demo.Authentication.Forms.csproj\">\r\n      <Project>{98940A30-1B48-4F71-A6BA-85F0AAF31A2F}</Project>\r\n      <Name>Nancy.Demo.Authentication.Forms</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.Hosting.Aspnet.MSBuild\\Nancy.Hosting.Aspnet.csproj\">\r\n      <Project>{15B7F794-0BB2-4B66-AD78-4A951F1209B2}</Project>\r\n      <Name>Nancy.Hosting.Aspnet</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.ViewEngines.Razor.MSBuild\\Nancy.ViewEngines.Razor.csproj\">\r\n      <Project>{2C6F51DF-015C-4DB6-B44C-0E5E4F25E2A9}</Project>\r\n      <Name>Nancy.ViewEngines.Razor</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.MSBuild\\Nancy.csproj\">\r\n      <Project>{34576216-0DCA-4B0F-A0DC-9075E75A676F}</Project>\r\n      <Name>Nancy</Name>\r\n    </ProjectReference>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <None Include=\"packages.config\" />\r\n  </ItemGroup>\r\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\r\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.\r\n       Other similar extension points exist, see Microsoft.Common.targets.\r\n  <Target Name=\"BeforeBuild\">\r\n  </Target>\r\n  <Target Name=\"AfterBuild\">\r\n  </Target>\r\n  -->\r\n</Project>"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Forms.TestingDemo/TestBootstrapper.cs",
    "content": "namespace Nancy.Demo.Authentication.Forms.TestingDemo\r\n{\r\n    public class TestBootstrapper : FormsAuthBootstrapper\r\n    {\r\n        protected override IRootPathProvider RootPathProvider\r\n        {\r\n            get { return new TestRootPathProvider(); }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Forms.TestingDemo/TestRootPathProvider.cs",
    "content": "namespace Nancy.Demo.Authentication.Forms.TestingDemo\r\n{\r\n    using System;\r\n    using System.IO;\r\n    using Nancy.Testing;\r\n\r\n    public class TestRootPathProvider : IRootPathProvider\r\n    {\r\n        public string GetRootPath()\r\n        {\r\n            var assemblyFilePath =\r\n                new Uri(typeof(FormsAuthBootstrapper).Assembly.CodeBase).LocalPath;\r\n\r\n            var assemblyPath =\r\n                Path.GetDirectoryName(assemblyFilePath);\r\n\r\n            var rootPath =\r\n                PathHelper.GetParent(assemblyPath, 3);\r\n\r\n            rootPath =\r\n                Path.Combine(rootPath, @\"Nancy.Demo.Authentication.Forms\");\r\n\r\n            return rootPath;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Forms.TestingDemo/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<packages>\r\n  <package id=\"xunit\" version=\"2.1.0\" targetFramework=\"net45\" />\r\n  <package id=\"xunit.abstractions\" version=\"2.0.0\" targetFramework=\"net45\" />\r\n  <package id=\"xunit.assert\" version=\"2.1.0\" targetFramework=\"net45\" />\r\n  <package id=\"xunit.core\" version=\"2.1.0\" targetFramework=\"net45\" />\r\n  <package id=\"xunit.extensibility.core\" version=\"2.1.0\" targetFramework=\"net45\" />\r\n  <package id=\"xunit.extensibility.execution\" version=\"2.1.0\" targetFramework=\"net45\" />\r\n</packages>"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Stateless/AuthModule.cs",
    "content": "﻿namespace Nancy.Demo.Authentication.Stateless\r\n{\r\n    public class AuthModule : NancyModule\r\n    {\r\n        public AuthModule() : base(\"/auth/\")\r\n        {\r\n            //the Post[\"/login\"] method is used mainly to fetch the api key for subsequent calls\r\n            Post(\"/\", args =>\r\n            {\r\n                var apiKey = UserDatabase.ValidateUser(\r\n                    (string) this.Request.Form.Username,\r\n                    (string) this.Request.Form.Password);\r\n\r\n                return string.IsNullOrEmpty(apiKey)\r\n                    ? new Response {StatusCode = HttpStatusCode.Unauthorized}\r\n                    : this.Response.AsJson(new {ApiKey = apiKey});\r\n            });\r\n\r\n            //do something to destroy the api key, maybe?\r\n            Delete(\"/\", args =>\r\n            {\r\n                var apiKey = (string) this.Request.Form.ApiKey;\r\n                UserDatabase.RemoveApiKey(apiKey);\r\n                return new Response {StatusCode = HttpStatusCode.OK};\r\n            });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Stateless/Models/UserModel.cs",
    "content": "﻿namespace Nancy.Demo.Authentication.Stateless.Models\r\n{\r\n    public class UserModel\r\n    {\r\n        public string Username { get; private set; }\r\n\r\n        public UserModel(string username)\r\n        {\r\n            Username = username;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Stateless/Nancy.Demo.Authentication.Stateless.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoDebug|AnyCPU'\">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <DebugType>full</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.Authentication.Stateless.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoRelease|AnyCPU'\">\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <Optimize>true</Optimize>\r\n    <DebugType>pdbonly</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.Authentication.Stateless.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\r\n  <PropertyGroup>\r\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\r\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\r\n    <SchemaVersion>2.0</SchemaVersion>\r\n    <ProjectGuid>{BAE74CD5-57C2-40E3-8F7A-EDE5721C2ACC}</ProjectGuid>\r\n    <ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>\r\n    <OutputType>Library</OutputType>\r\n    <AppDesignerFolder>Properties</AppDesignerFolder>\r\n    <RootNamespace>Nancy.Demo.Authentication.Stateless</RootNamespace>\r\n    <AssemblyName>Nancy.Demo.Authentication.Stateless</AssemblyName>\r\n    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\r\n    <UseIISExpress>false</UseIISExpress>\r\n    <OldToolsVersion>4.0</OldToolsVersion>\r\n    <IISExpressSSLPort />\r\n    <IISExpressAnonymousAuthentication />\r\n    <IISExpressWindowsAuthentication />\r\n    <IISExpressUseClassicPipelineMode />\r\n    <UseGlobalApplicationHostFile />\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <DebugType>full</DebugType>\r\n    <Optimize>false</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\r\n    <DebugType>pdbonly</DebugType>\r\n    <Optimize>true</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <ItemGroup>\r\n    <Reference Include=\"Microsoft.CSharp\" />\r\n    <Reference Include=\"System\" />\r\n    <Reference Include=\"System.Data\" />\r\n    <Reference Include=\"System.Drawing\" />\r\n    <Reference Include=\"System.Web\" />\r\n    <Reference Include=\"System.Xml\" />\r\n    <Reference Include=\"System.Configuration\" />\r\n    <Reference Include=\"System.Xml.Linq\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Web.config\" />\r\n    <Content Include=\"Web.Debug.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n    <Content Include=\"Web.Release.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Compile Include=\"..\\..\\SharedAssemblyInfo.cs\">\r\n      <Link>Properties\\SharedAssemblyInfo.cs</Link>\r\n    </Compile>\r\n    <Compile Include=\"AuthModule.cs\" />\r\n    <Compile Include=\"Models\\UserModel.cs\" />\r\n    <Compile Include=\"RootModule.cs\" />\r\n    <Compile Include=\"SecureModule.cs\" />\r\n    <Compile Include=\"StatelessAuthBootstrapper.cs\" />\r\n    <Compile Include=\"UserDatabase.cs\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.Authentication.Stateless.MSBuild\\Nancy.Authentication.Stateless.csproj\">\r\n      <Project>{211560C3-FDDF-46D6-AB0C-F3BC04B173B5}</Project>\r\n      <Name>Nancy.Authentication.Stateless</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.Hosting.Aspnet.MSBuild\\Nancy.Hosting.Aspnet.csproj\">\r\n      <Project>{15B7F794-0BB2-4B66-AD78-4A951F1209B2}</Project>\r\n      <Name>Nancy.Hosting.Aspnet</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.MSBuild\\Nancy.csproj\">\r\n      <Project>{34576216-0DCA-4B0F-A0DC-9075E75A676F}</Project>\r\n      <Name>Nancy</Name>\r\n    </ProjectReference>\r\n  </ItemGroup>\r\n  <PropertyGroup>\r\n    <VisualStudioVersion Condition=\"'$(VisualStudioVersion)' == ''\">10.0</VisualStudioVersion>\r\n    <VSToolsPath Condition=\"'$(VSToolsPath)' == ''\">$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)</VSToolsPath>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\r\n  <Import Project=\"$(VSToolsPath)\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"'$(VSToolsPath)' != ''\" />\r\n  <Import Project=\"$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v10.0\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"false\" />\r\n  <ProjectExtensions>\r\n    <VisualStudio>\r\n      <FlavorProperties GUID=\"{349c5851-65df-11da-9384-00065b846f21}\">\r\n        <WebProjectProperties>\r\n          <UseIIS>False</UseIIS>\r\n          <AutoAssignPort>False</AutoAssignPort>\r\n          <DevelopmentServerPort>55581</DevelopmentServerPort>\r\n          <DevelopmentServerVPath>/restApi</DevelopmentServerVPath>\r\n          <IISUrl>\r\n          </IISUrl>\r\n          <NTLMAuthentication>False</NTLMAuthentication>\r\n          <UseCustomServer>False</UseCustomServer>\r\n          <CustomServerUrl>\r\n          </CustomServerUrl>\r\n          <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>\r\n        </WebProjectProperties>\r\n      </FlavorProperties>\r\n    </VisualStudio>\r\n  </ProjectExtensions>\r\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r\n       Other similar extension points exist, see Microsoft.Common.targets.\r\n  <Target Name=\"BeforeBuild\">\r\n  </Target>\r\n  <Target Name=\"AfterBuild\">\r\n  </Target>\r\n  -->\r\n</Project>"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Stateless/RootModule.cs",
    "content": "namespace Nancy.Demo.Authentication.Stateless\r\n{\r\n    public class RootModule : NancyModule\r\n    {\r\n        public RootModule()\r\n        {\r\n            Get(\"/\", args => this.Response.AsText(\"This is a REST API. It is in another VS project to \" +\r\n                                                 \"demonstrate how a common REST API might behave when \" +\r\n                                                 \"accessing it from another website or application. To \" +\r\n                                                 \"see how a website can access this API, run the \" +\r\n                                                 \"Nancy.Demo.Authentication.Stateless.Website project \" +\r\n                                                 \"(in the same Nancy solution).\"));\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Stateless/SecureModule.cs",
    "content": "namespace Nancy.Demo.Authentication.Stateless\r\n{\r\n    using System;\r\n    using Nancy.Demo.Authentication.Stateless.Models;\r\n    using Nancy.Security;\r\n\r\n    public class SecureModule : NancyModule\r\n    {\r\n        //by this time, the api key should have already been pulled out of our querystring\r\n        //and, using the api key, an identity assigned to our NancyContext\r\n        public SecureModule()\r\n        {\r\n            this.RequiresAuthentication();\r\n\r\n            Get(\"secure\", args =>\r\n            {\r\n                //Context.CurrentUser was set by StatelessAuthentication earlier in the pipeline\r\n                var identity = this.Context.CurrentUser;\r\n\r\n                //return the secure information in a json response\r\n                var userModel = new UserModel(identity.Identity.Name);\r\n                return this.Response.AsJson(new\r\n                    {\r\n                        SecureContent = \"here's some secure content that you can only see if you provide a correct apiKey\",\r\n                        User = userModel\r\n                    });\r\n            });\r\n\r\n            Post(\"secure/create_user\", args =>\r\n            {\r\n                Tuple<string, string> user = UserDatabase.CreateUser(this.Context.Request.Form[\"username\"], this.Context.Request.Form[\"password\"]);\r\n                return this.Response.AsJson(new { username = user.Item1 });\r\n            });\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Stateless/StatelessAuthBootstrapper.cs",
    "content": "namespace Nancy.Demo.Authentication.Stateless\r\n{\r\n    using Nancy.Authentication.Stateless;\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.TinyIoc;\r\n\r\n    public class StatelessAuthBootstrapper : DefaultNancyBootstrapper\r\n    {\r\n        protected override void RequestStartup(TinyIoCContainer requestContainer, IPipelines pipelines, NancyContext context)\r\n        {\r\n            // At request startup we modify the request pipelines to\r\n            // include stateless authentication\r\n            //\r\n            // Configuring stateless authentication is simple. Just use the\r\n            // NancyContext to get the apiKey. Then, use the apiKey to get\r\n            // your user's identity.\r\n            var configuration =\r\n                new StatelessAuthenticationConfiguration(nancyContext =>\r\n                    {\r\n                        //for now, we will pull the apiKey from the querystring,\r\n                        //but you can pull it from any part of the NancyContext\r\n                        var apiKey = (string) nancyContext.Request.Query.ApiKey.Value;\r\n\r\n                        //get the user identity however you choose to (for now, using a static class/method)\r\n                        return UserDatabase.GetUserFromApiKey(apiKey);\r\n                    });\r\n\r\n            AllowAccessToConsumingSite(pipelines);\r\n\r\n            StatelessAuthentication.Enable(pipelines, configuration);\r\n        }\r\n\r\n        static void AllowAccessToConsumingSite(IPipelines pipelines)\r\n        {\r\n            pipelines.AfterRequest.AddItemToEndOfPipeline(x =>\r\n                {\r\n                    x.Response.Headers.Add(\"Access-Control-Allow-Origin\", \"*\");\r\n                    x.Response.Headers.Add(\"Access-Control-Allow-Methods\", \"POST,GET,DELETE,PUT,OPTIONS\");\r\n                });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Stateless/UserDatabase.cs",
    "content": "namespace Nancy.Demo.Authentication.Stateless\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Security.Claims;\r\n    using System.Security.Principal;\r\n\r\n    public class UserDatabase\r\n    {\r\n        static readonly List<Tuple<string, string>> ActiveApiKeys = new List<Tuple<string, string>>();\r\n        private static readonly List<Tuple<string, string>> Users = new List<Tuple<string, string>>();\r\n\r\n        static UserDatabase()\r\n        {\r\n            Users.Add(new Tuple<string, string>(\"admin\", \"password\"));\r\n            Users.Add(new Tuple<string, string>(\"user\", \"password\"));\r\n        }\r\n\r\n        public static ClaimsPrincipal GetUserFromApiKey(string apiKey)\r\n        {\r\n            var activeKey = ActiveApiKeys.FirstOrDefault(x => x.Item2 == apiKey);\r\n\r\n            if(activeKey==null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            var userRecord = Users.First(u => u.Item1 == activeKey.Item1);\r\n            return new ClaimsPrincipal(new GenericIdentity(userRecord.Item1, \"stateless\"));\r\n        }\r\n\r\n        public static string ValidateUser(string username, string password)\r\n        {\r\n            //try to get a user from the \"database\" that matches the given username and password\r\n            var userRecord = Users.FirstOrDefault(u => u.Item1 == username && u.Item2 == password);\r\n\r\n            if(userRecord==null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            //now that the user is validated, create an api key that can be used for subsequent requests\r\n            var apiKey = Guid.NewGuid().ToString();\r\n            ActiveApiKeys.Add(new Tuple<string, string>(username, apiKey));\r\n            return apiKey;\r\n        }\r\n\r\n        public static void RemoveApiKey(string apiKey)\r\n        {\r\n            var apiKeyToRemove = ActiveApiKeys.First(x => x.Item2 == apiKey);\r\n            ActiveApiKeys.Remove(apiKeyToRemove);\r\n        }\r\n\r\n        public static Tuple<string, string> CreateUser(string username, string password)\r\n        {\r\n            var user = new Tuple<string, string>(username, password);\r\n            Users.Add(user);\r\n            return user;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Stateless/Web.Debug.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Stateless/Web.Release.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n    <compilation xdt:Transform=\"RemoveAttributes(debug)\" />\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Stateless/Web.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n<configuration>\r\n  <system.web>\r\n    <httpHandlers>\r\n      <add verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </httpHandlers>\r\n  </system.web>\r\n  <system.webServer>\r\n    <modules runAllManagedModulesForAllRequests=\"true\" />\r\n    <validation validateIntegratedModeConfiguration=\"false\" />\r\n    <handlers>\r\n      <add name=\"Nancy\" verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </handlers>\r\n  </system.webServer>\r\n</configuration>"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Stateless.Website/Nancy.Demo.Authentication.Stateless.Website.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoDebug|AnyCPU'\">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <DebugType>full</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.Authentication.Stateless.Website.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoRelease|AnyCPU'\">\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <Optimize>true</Optimize>\r\n    <DebugType>pdbonly</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.Authentication.Stateless.Website.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\r\n  <PropertyGroup>\r\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\r\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\r\n    <SchemaVersion>2.0</SchemaVersion>\r\n    <ProjectGuid>{B5E3586D-81DE-49C3-83BC-062684795127}</ProjectGuid>\r\n    <ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>\r\n    <OutputType>Library</OutputType>\r\n    <AppDesignerFolder>Properties</AppDesignerFolder>\r\n    <RootNamespace>Nancy.Demo.Authentication.Stateless.Website</RootNamespace>\r\n    <AssemblyName>Nancy.Demo.Authentication.Stateless.Website</AssemblyName>\r\n    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\r\n    <UseIISExpress>false</UseIISExpress>\r\n    <OldToolsVersion>4.0</OldToolsVersion>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <DebugType>full</DebugType>\r\n    <Optimize>false</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\r\n    <DebugType>pdbonly</DebugType>\r\n    <Optimize>true</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <ItemGroup>\r\n    <Reference Include=\"System\" />\r\n    <Reference Include=\"System.Web\" />\r\n    <Reference Include=\"System.Xml.Linq\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"index.html\">\r\n      <CopyToOutputDirectory>Always</CopyToOutputDirectory>\r\n    </Content>\r\n    <Content Include=\"login.html\">\r\n      <CopyToOutputDirectory>Always</CopyToOutputDirectory>\r\n    </Content>\r\n    <Content Include=\"Scripts\\api.js\" />\r\n    <Content Include=\"Scripts\\apiToken.js\" />\r\n    <Content Include=\"secure.html\">\r\n      <CopyToOutputDirectory>Always</CopyToOutputDirectory>\r\n    </Content>\r\n    <Content Include=\"Web.config\" />\r\n    <Content Include=\"Web.Debug.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n    <Content Include=\"Web.Release.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Compile Include=\"..\\..\\SharedAssemblyInfo.cs\">\r\n      <Link>Properties\\SharedAssemblyInfo.cs</Link>\r\n    </Compile>\r\n  </ItemGroup>\r\n  <PropertyGroup>\r\n    <VisualStudioVersion Condition=\"'$(VisualStudioVersion)' == ''\">10.0</VisualStudioVersion>\r\n    <VSToolsPath Condition=\"'$(VSToolsPath)' == ''\">$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)</VSToolsPath>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\r\n  <Import Project=\"$(VSToolsPath)\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"'$(VSToolsPath)' != ''\" />\r\n  <Import Project=\"$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v10.0\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"false\" />\r\n  <ProjectExtensions>\r\n    <VisualStudio>\r\n      <FlavorProperties GUID=\"{349c5851-65df-11da-9384-00065b846f21}\">\r\n        <WebProjectProperties>\r\n          <UseIIS>False</UseIIS>\r\n          <AutoAssignPort>False</AutoAssignPort>\r\n          <DevelopmentServerPort>51101</DevelopmentServerPort>\r\n          <DevelopmentServerVPath>/statelessWebsite</DevelopmentServerVPath>\r\n          <NTLMAuthentication>False</NTLMAuthentication>\r\n          <UseCustomServer>False</UseCustomServer>\r\n          <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>\r\n        </WebProjectProperties>\r\n      </FlavorProperties>\r\n    </VisualStudio>\r\n  </ProjectExtensions>\r\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r\n       Other similar extension points exist, see Microsoft.Common.targets.\r\n  <Target Name=\"BeforeBuild\">\r\n  </Target>\r\n  <Target Name=\"AfterBuild\">\r\n  </Target>\r\n  -->\r\n</Project>"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Stateless.Website/Scripts/api.js",
    "content": "﻿var api = {\r\n    auth: \"http://localhost:55581/restApi/auth\",\r\n    secure: \"http://localhost:55581/restApi/secure\",\r\n    create_user: \"http://localhost:55581/restApi/secure/create_user\"\r\n};\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Stateless.Website/Scripts/apiToken.js",
    "content": "﻿var apiKeyKey = \"sample_apiKey\";\r\nvar usernameKey = \"sample_username\";\r\n\r\nvar ApiToken = {\r\n\r\n    Set: function (username, apiKey, rememberMe) {\r\n        var days = rememberMe ? 10 : 0;\r\n        createCookie(apiKeyKey, apiKey, days);\r\n        createCookie(usernameKey, username, days);\r\n    },\r\n\r\n    Get: function () {\r\n        var key = readCookie(apiKeyKey);\r\n        var username = readCookie(usernameKey);\r\n        var token = { Key: key, Username: username, IsValid: key != null };\r\n        return token;\r\n    },\r\n\r\n    Delete: function () {\r\n        eraseCookie(apiKeyKey);\r\n        eraseCookie(usernameKey);\r\n    }\r\n};\r\n\r\nfunction createCookie(name, value, days) {\r\n    if (days) {\r\n        var date = new Date();\r\n        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));\r\n        var expires = \"; expires=\" + date.toGMTString();\r\n    } else var expires = \"\";\r\n    document.cookie = name + \"=\" + value + expires + \"; path=/\";\r\n    console.log(document.cookie);\r\n}\r\n\r\nfunction readCookie(name) {\r\n    var cookieValue = null;\r\n    var nameEQ = name + \"=\";\r\n    var ca = document.cookie.split(';');\r\n    for (var i = 0; i < ca.length; i++) {\r\n        var c = ca[i];\r\n        while (c.charAt(0) == ' ') c = c.substring(1, c.length);\r\n        if (c.indexOf(nameEQ) == 0) {\r\n            var found = c.substring(nameEQ.length, c.length);\r\n            cookieValue = found;\r\n        }\r\n    }\r\n    return cookieValue;\r\n}\r\n\r\nfunction eraseCookie(name) {\r\n    createCookie(name, \"\", -1);\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Stateless.Website/Web.Debug.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Stateless.Website/Web.Release.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n    <compilation xdt:Transform=\"RemoveAttributes(debug)\" />\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Stateless.Website/Web.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration>\r\n  <system.web>\r\n    <compilation debug=\"true\" />\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Stateless.Website/index.html",
    "content": "﻿<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n    <title>Stateless Authentication Demo</title>\r\n    <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js\"> </script>\r\n    <script src=\"Scripts/apiToken.js\"> </script>\r\n    <script src=\"Scripts/api.js\"> </script>\r\n</head>\r\n    <body>\r\n        <div id='loggedIn' style='display: none;'><p>Welcome <span id='username'></span>. <a href='#' id='logout'>Logout</a></p></div>\r\n\r\n        <h1>Non-Secure Zone</h1>\r\n        <p><a href=\"secure.html\">Enter the \"Secure Zone\"!</a></p>\r\n\r\n\r\n        <script type=\"text/javascript\">\r\n            $(document).ready(function () {\r\n                var apiToken = ApiToken.Get();\r\n                if (apiToken.IsValid) {\r\n\r\n                    $(\"#loggedIn\").show();\r\n\r\n                    $(\"#username\").html(apiToken.Username);\r\n\r\n                    $(\"#logout\").click(function () {\r\n\r\n                        var request = { apiKey: apiToken.Key };\r\n\r\n                        var success = function () {\r\n                            ApiToken.Delete();\r\n                            window.location = \"index.html\";\r\n                        };\r\n\r\n                        $.ajax({\r\n                            type: 'DELETE',\r\n                            url: api.auth,\r\n                            data: request,\r\n                            success: success,\r\n                            dataType: \"json\"\r\n                        });\r\n                    });\r\n                }\r\n            });\r\n        </script>\r\n    </body>\r\n</html>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Stateless.Website/login.html",
    "content": "﻿<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n    <head>\r\n        <title>Login</title>\r\n        <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js\"> </script>\r\n        <script src=\"Scripts/apiToken.js\"> </script>\r\n        <script src=\"Scripts/api.js\"> </script>\r\n    </head>\r\n    <body>\r\n        <div>\r\n            Username <input type=\"text\" id=\"Username\" />\r\n            <br />\r\n            Password <input id=\"Password\" type=\"password\" />\r\n            <br />\r\n            Remember Me <input id=\"RememberMe\" type=\"checkbox\" value=\"True\" />\r\n            <br />\r\n            <button id=\"submitButton\">Login</button>\r\n        </div>\r\n        <div id=\"errorBox\" style=\"display: none;\">Invalid Username or Password</div>\r\n\r\n        <script type=\"text/javascript\">\r\n            $(document).ready(function () {\r\n                $(\"#submitButton\").click(function () {\r\n\r\n                    $(\"#errorBox\").hide();\r\n\r\n                    var authRequest = {\r\n                        username: $(\"#Username\").val(),\r\n                        password: $(\"#Password\").val(),\r\n                        rememberMe: $(\"#RememberMe\").val()\r\n                    };\r\n\r\n                    var success = function (response) {\r\n                        ApiToken.Set(authRequest.username, response.ApiKey, authRequest.rememberMe);\r\n                        window.location = \"index.html\";\r\n                    };\r\n\r\n                    var error = function () {\r\n                        $(\"#errorBox\").show();\r\n                    };\r\n\r\n                    $.ajax({\r\n                        type: 'POST',\r\n                        url: api.auth,\r\n                        data: authRequest,\r\n                        success: success,\r\n                        error: error,\r\n                        dataType: \"json\"\r\n                    });\r\n                });\r\n            });\r\n        </script>\r\n    </body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Authentication.Stateless.Website/secure.html",
    "content": "﻿<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n    <head>\r\n        <title>Stateless Authentication Demo</title>\r\n        <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js\"> </script>\r\n        <script src=\"Scripts/apiToken.js\"> </script>\r\n        <script src=\"Scripts/api.js\"> </script>\r\n        <style type=\"text/css\">\r\n        \t.secure { color: blue;}\r\n        </style>\r\n    </head>\r\n    <body style='display: none;'>\r\n        <div>\r\n            <a href='index.html'>&lt;&lt; Home</a>\r\n            <div id='loggedIn' style='display: none;'><p>Welcome <span id='username'></span>. <a href='#' id='logout'>Logout</a></p></div>\r\n\r\n            <h1>Secure Zone</h1>\r\n            <div>Secure Content: <span id=\"secureContent\" class='secure'></span></div>\r\n\r\n            <div>\r\n                Username <input type=\"text\" id=\"newusername\"/><br/>\r\n                Password <input id=\"newpassword\" type=\"password\"/><br/>\r\n                <input type=\"button\" onclick=\"createUser()\"/>\r\n                <div id=\"createuserresult\"></div>\r\n            </div>\r\n        </div>\r\n\r\n        <script type=\"text/javascript\">\r\n            $(document).ready(function () {\r\n\r\n                //if the apiKey is present, it means the user is logged in\r\n                //check if the apiKey is present\r\n                var apiToken = ApiToken.Get();\r\n                if (apiToken.IsValid) {\r\n\r\n                    //user is logged in\r\n                    //get and display secure content\r\n                    //using the apiKey that we stored in a cookie\r\n                    var request = { apiKey: apiToken.Key };\r\n\r\n                    //populate the view on success\r\n                    var success = function (response) {\r\n                        $(\"#username\").html(apiToken.Username);\r\n                        $(\"#secureContent\").html(response.SecureContent);\r\n                        $(\"body\").show();\r\n                    };\r\n\r\n                    //redirect the user to the login page on 401 (or display an alert if it's something worse)\r\n                    var error = function (response) {\r\n                        if (response.status == 401) {\r\n                            window.location = \"login.html\";\r\n                            return;\r\n                        }\r\n\r\n                        alert(\"Something went wrong. \" + response.error);\r\n                    };\r\n\r\n                    $.ajax({\r\n                        url: api.secure,\r\n                        data: request,\r\n                        success: success,\r\n                        error: error,\r\n                        dataType: \"json\"\r\n                    });\r\n\r\n                } else {\r\n                    //if we don't have the apiToken saved, it means the user has not logged in yet\r\n                    //send 'em packing to the login page\r\n                    window.location = \"login.html\";\r\n                }\r\n\r\n\r\n                if (apiToken.IsValid) {\r\n\r\n                    $(\"#loggedIn\").show();\r\n                    $(\"#username\").html(apiToken.Username);\r\n                    $(\"#logout\").click(function () {\r\n\r\n                        //sending the apiKey to the API to be destroyed\r\n                        var request = { apiKey: apiToken.Key };\r\n                        \r\n                        //when the deed has been done on the server,\r\n                        //delete the cookie in the client and redirect to the home page.\r\n                        var success = function () {\r\n                            ApiToken.Delete();\r\n                            window.location = \"index.html\";\r\n                        };\r\n\r\n                        $.ajax({\r\n                            type: 'DELETE',\r\n                            url: api.auth,\r\n                            data: request,\r\n                            success: success,\r\n                            dataType: \"json\"\r\n                        });\r\n                    });\r\n                }\r\n            });\r\n\r\n            function createUser() {\r\n                var apiToken = ApiToken.Get();\r\n                if (apiToken.IsValid) {\r\n                    //user is logged in\r\n                    var request = {\r\n                        username: $(\"#newusername\").val(),\r\n                        password: $(\"#newpassword\").val()\r\n                    };\r\n\r\n                    //populate the view on success\r\n                    var success = function (response) {\r\n                        $(\"#createuserresult\").html(\"User \" + response.username + \" has been created\");\r\n                    };\r\n\r\n                    //redirect the user to the login page on 401 (or display an alert if it's something worse)\r\n                    var error = function (response) {\r\n                      if (response.status == 401) {\r\n                        window.location = \"login.html\";\r\n                        return;\r\n                      }\r\n\r\n                      alert(\"Something went wrong. \" + response.error);\r\n                    };\r\n\r\n                    $.ajax({\r\n                      type: 'POST',\r\n                      url: api.create_user + \"?ApiKey=\" + apiToken.Key,\r\n                      data: request,\r\n                      success: success,\r\n                      error: error,\r\n                      dataType: \"json\"\r\n                    });\r\n                }\r\n                else {\r\n                    //if we don't have the apiToken saved, it means the user has not logged in yet\r\n                    //send 'em packing to the login page\r\n                    window.location = \"login.html\";\r\n                }\r\n            }\r\n        </script>\r\n    </body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Bootstrapper.Aspnet/ApplicationDependencyClass.cs",
    "content": "namespace Nancy.AspNetBootstrapperDemo\r\n{\r\n    using System;\r\n\r\n    using Nancy.Demo.Bootstrapping.Aspnet;\r\n\r\n    /// <summary>\r\n    /// A module dependency that will have an application lifetime scope.\r\n    /// </summary>\r\n    public class ApplicationDependencyClass : IApplicationDependency\r\n    {\r\n        private readonly DateTime currentDateTime;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the RequestDependencyClass class.\r\n        /// </summary>\r\n        public ApplicationDependencyClass()\r\n        {\r\n            this.currentDateTime = DateTime.Now;\r\n        }\r\n\r\n        public string GetContent()\r\n        {\r\n            return \"This is an application level dependency, constructed on: \" + this.currentDateTime.ToLongTimeString();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Bootstrapper.Aspnet/Bootstrapper.cs",
    "content": "namespace Nancy.AspNetBootstrapperDemo\r\n{\r\n    using Nancy.Demo.Bootstrapping.Aspnet;\r\n    using Nancy.Hosting.Aspnet;\r\n    using Nancy.TinyIoc;\r\n\r\n    public class Bootstrapper : DefaultNancyAspNetBootstrapper\r\n    {\r\n        protected override void ConfigureApplicationContainer(TinyIoCContainer container)\r\n        {\r\n            // Register our app dependency as a normal singleton\r\n            container.Register<IApplicationDependency, ApplicationDependencyClass>().AsSingleton();\r\n\r\n            // Register our per-request dependency as a per-request singleton\r\n            container.Register<IRequestDependency, RequestDependencyClass>().AsPerRequestSingleton();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Bootstrapper.Aspnet/DependencyModule.cs",
    "content": "﻿namespace Nancy.Demo.Bootstrapping.Aspnet\r\n{\r\n    using Nancy.Demo.Bootstrapping.Aspnet.Models;\r\n\r\n    public class DependencyModule : NancyModule\r\n    {\r\n        private readonly IApplicationDependency applicationDependency;\r\n        private readonly IRequestDependency requestDependency;\r\n\r\n        public DependencyModule(IApplicationDependency applicationDependency, IRequestDependency requestDependency)\r\n        {\r\n            this.applicationDependency = applicationDependency;\r\n            this.requestDependency = requestDependency;\r\n\r\n            Get(\"/\", args => {\r\n                var model =\r\n                    new RatPackWithDependencyText\r\n                    {\r\n                        FirstName = \"Bob\",\r\n                        ApplicationDependencyText = this.applicationDependency.GetContent(),\r\n                        RequestDependencyText = this.requestDependency.GetContent()\r\n                    };\r\n\r\n                return View[\"razor-dependency\", model];\r\n            });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Bootstrapper.Aspnet/IApplicationDependency.cs",
    "content": "namespace Nancy.Demo.Bootstrapping.Aspnet\r\n{\r\n    public interface IApplicationDependency\r\n    {\r\n        string GetContent();\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Bootstrapper.Aspnet/IRequestDependency.cs",
    "content": "namespace Nancy.Demo.Bootstrapping.Aspnet\r\n{\r\n    public interface IRequestDependency\r\n    {\r\n        string GetContent();\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Bootstrapper.Aspnet/Models/RatPack.cs",
    "content": "﻿namespace Nancy.Demo.Bootstrapping.Aspnet.Models\r\n{\r\n    public class RatPack\r\n    {\r\n        public string FirstName { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Bootstrapper.Aspnet/Models/RatPackWithDependencyText.cs",
    "content": "﻿namespace Nancy.Demo.Bootstrapping.Aspnet.Models\r\n{\r\n    public class RatPackWithDependencyText : RatPack\r\n    {\r\n        public string ApplicationDependencyText { get; set; }\r\n\r\n        public string RequestDependencyText { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Bootstrapper.Aspnet/Nancy.Demo.Bootstrapping.Aspnet.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\r\n  <PropertyGroup>\r\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\r\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\r\n    <SchemaVersion>2.0</SchemaVersion>\r\n    <ProjectGuid>{EF660223-4DFD-4E36-BF36-9DD6AFB3F837}</ProjectGuid>\r\n    <ProjectTypeGuids>{349C5851-65DF-11DA-9384-00065B846F21};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>\r\n    <OutputType>Library</OutputType>\r\n    <AppDesignerFolder>Properties</AppDesignerFolder>\r\n    <RootNamespace>Nancy.Demo.Bootstrapping.Aspnet</RootNamespace>\r\n    <AssemblyName>Nancy.Demo.Bootstrapping.Aspnet</AssemblyName>\r\n    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\r\n    <UseIISExpress>false</UseIISExpress>\r\n    <OldToolsVersion>4.0</OldToolsVersion>\r\n    <IISExpressSSLPort />\r\n    <IISExpressAnonymousAuthentication />\r\n    <IISExpressWindowsAuthentication />\r\n    <IISExpressUseClassicPipelineMode />\r\n    <UseGlobalApplicationHostFile />\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <DebugType>full</DebugType>\r\n    <Optimize>false</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\r\n    <DebugType>pdbonly</DebugType>\r\n    <Optimize>true</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoDebug|AnyCPU'\">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <DebugType>full</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.Bootstrapping.Aspnet.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRuleSets>true</CodeAnalysisIgnoreBuiltInRuleSets>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRules>true</CodeAnalysisIgnoreBuiltInRules>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Optimize>false</Optimize>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoRelease|AnyCPU'\">\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <Optimize>true</Optimize>\r\n    <DebugType>pdbonly</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.Bootstrapping.Aspnet.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRules>false</CodeAnalysisIgnoreBuiltInRules>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <ItemGroup>\r\n    <Reference Include=\"Microsoft.CSharp\" />\r\n    <Reference Include=\"System\" />\r\n    <Reference Include=\"System.Data\" />\r\n    <Reference Include=\"System.Drawing\" />\r\n    <Reference Include=\"System.Web\" />\r\n    <Reference Include=\"System.Xml\" />\r\n    <Reference Include=\"System.Configuration\" />\r\n    <Reference Include=\"System.Xml.Linq\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Web.config\" />\r\n    <Content Include=\"Web.Debug.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n    <Content Include=\"Web.Release.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Compile Include=\"..\\..\\SharedAssemblyInfo.cs\">\r\n      <Link>Properties\\SharedAssemblyInfo.cs</Link>\r\n    </Compile>\r\n    <Compile Include=\"ApplicationDependencyClass.cs\" />\r\n    <Compile Include=\"Bootstrapper.cs\" />\r\n    <Compile Include=\"DependencyModule.cs\" />\r\n    <Compile Include=\"IApplicationDependency.cs\" />\r\n    <Compile Include=\"IRequestDependency.cs\" />\r\n    <Compile Include=\"Models\\RatPack.cs\" />\r\n    <Compile Include=\"Models\\RatPackWithDependencyText.cs\" />\r\n    <Compile Include=\"RequestDependencyClass.cs\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.Hosting.Aspnet.MSBuild\\Nancy.Hosting.Aspnet.csproj\">\r\n      <Project>{15B7F794-0BB2-4B66-AD78-4A951F1209B2}</Project>\r\n      <Name>Nancy.Hosting.Aspnet</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.ViewEngines.Razor.MSBuild\\Nancy.ViewEngines.Razor.csproj\">\r\n      <Project>{2C6F51DF-015C-4DB6-B44C-0E5E4F25E2A9}</Project>\r\n      <Name>Nancy.ViewEngines.Razor</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.MSBuild\\Nancy.csproj\">\r\n      <Project>{34576216-0DCA-4B0F-A0DC-9075E75A676F}</Project>\r\n      <Name>Nancy</Name>\r\n    </ProjectReference>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Views\\razor-dependency.cshtml\" />\r\n  </ItemGroup>\r\n  <PropertyGroup>\r\n    <VisualStudioVersion Condition=\"'$(VisualStudioVersion)' == ''\">10.0</VisualStudioVersion>\r\n    <VSToolsPath Condition=\"'$(VSToolsPath)' == ''\">$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)</VSToolsPath>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\r\n  <Import Project=\"$(VSToolsPath)\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"'$(VSToolsPath)' != ''\" />\r\n  <Import Project=\"$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v10.0\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"false\" />\r\n  <ProjectExtensions>\r\n    <VisualStudio>\r\n      <FlavorProperties GUID=\"{349C5851-65DF-11DA-9384-00065B846F21}\">\r\n        <WebProjectProperties>\r\n          <UseIIS>False</UseIIS>\r\n          <AutoAssignPort>True</AutoAssignPort>\r\n          <DevelopmentServerPort>10220</DevelopmentServerPort>\r\n          <DevelopmentServerVPath>/</DevelopmentServerVPath>\r\n          <IISUrl>\r\n          </IISUrl>\r\n          <NTLMAuthentication>False</NTLMAuthentication>\r\n          <UseCustomServer>False</UseCustomServer>\r\n          <CustomServerUrl>\r\n          </CustomServerUrl>\r\n          <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>\r\n        </WebProjectProperties>\r\n      </FlavorProperties>\r\n    </VisualStudio>\r\n    <MonoDevelop>\r\n      <Properties VerifyCodeBehindFields=\"true\" VerifyCodeBehindEvents=\"true\">\r\n        <XspParameters Port=\"8080\" Address=\"127.0.0.1\" SslMode=\"None\" SslProtocol=\"Default\" KeyType=\"None\" CertFile=\"\" KeyFile=\"\" PasswordOptions=\"None\" Password=\"\" Verbose=\"true\" />\r\n      </Properties>\r\n    </MonoDevelop>\r\n  </ProjectExtensions>\r\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r\n       Other similar extension points exist, see Microsoft.Common.targets.\r\n  <Target Name=\"BeforeBuild\">\r\n  </Target>\r\n  <Target Name=\"AfterBuild\">\r\n  </Target>\r\n  -->\r\n</Project>"
  },
  {
    "path": "samples/Nancy.Demo.Bootstrapper.Aspnet/README.txt",
    "content": "﻿"
  },
  {
    "path": "samples/Nancy.Demo.Bootstrapper.Aspnet/RequestDependencyClass.cs",
    "content": "namespace Nancy.Demo.Bootstrapping.Aspnet\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// A module dependency that will have a per-request lifetime scope.\r\n    /// </summary>\r\n    public class RequestDependencyClass : IRequestDependency\r\n    {\r\n        private readonly DateTime currentDateTime;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the RequestDependencyClass class.\r\n        /// </summary>\r\n        public RequestDependencyClass()\r\n        {\r\n            this.currentDateTime = DateTime.Now;\r\n        }\r\n\r\n        public string GetContent()\r\n\t\t{\r\n            return \"This is a per-request dependency, constructed on: \" + this.currentDateTime.ToLongTimeString();\r\n\t\t}\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Bootstrapper.Aspnet/Views/razor-dependency.cshtml",
    "content": "﻿<html>\r\n<head>\r\n    <title>Razor View Engine Demo</title>\r\n</head>\r\n<body>\r\n    <h1>Hello @Model.FirstName</h1>\r\n\t<p>This is a Razor view..</p>\r\n    <p>@Model.ApplicationDependencyText</p>\r\n    <p>@Model.RequestDependencyText</p>\r\n</body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Bootstrapper.Aspnet/Web.Debug.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Bootstrapper.Aspnet/Web.Release.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n    <compilation xdt:Transform=\"RemoveAttributes(debug)\" />\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Bootstrapper.Aspnet/Web.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n<configuration>\r\n  <system.web>\r\n    <compilation debug=\"true\" targetFramework=\"4.0\" />\r\n    <httpHandlers>\r\n      <add verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </httpHandlers>\r\n  </system.web>\r\n\r\n  <system.webServer>\r\n    <modules runAllManagedModulesForAllRequests=\"true\" />\r\n    <validation validateIntegratedModeConfiguration=\"false\" />\r\n    <handlers>\r\n      <add name=\"Nancy\" verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </handlers>\r\n  </system.webServer>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Caching/CachedResponse.cs",
    "content": "﻿namespace Nancy.Demo.Caching\r\n{\r\n    using System;\r\n    using System.IO;\r\n    using System.Text;\r\n    using System.Threading.Tasks;\r\n    using Nancy;\r\n\r\n    /// <summary>\r\n    /// Wraps a regular response in a cached response\r\n    /// The cached response invokes the old response and stores it as a string.\r\n    /// Obviously this only works for ASCII text based responses, so don't use this\r\n    /// in a real application :-)\r\n    /// </summary>\r\n    public class CachedResponse : Response\r\n    {\r\n        private readonly Response response;\r\n\r\n        public CachedResponse(Response response)\r\n        {\r\n            this.response = response;\r\n\r\n            this.ContentType = response.ContentType;\r\n            this.Headers = response.Headers;\r\n            this.StatusCode = response.StatusCode;\r\n            this.Contents = this.GetContents();\r\n        }\r\n\r\n        public override Task PreExecute(NancyContext context)\r\n        {\r\n            return this.response.PreExecute(context);\r\n        }\r\n\r\n        private Action<Stream> GetContents()\r\n        {\r\n            return stream =>\r\n            {\r\n                using (var memoryStream = new MemoryStream())\r\n                {\r\n                    this.response.Contents.Invoke(memoryStream);\r\n\r\n                    var contents =\r\n                        Encoding.ASCII.GetString(memoryStream.GetBuffer());\r\n\r\n                    var writer =\r\n                        new StreamWriter(stream) { AutoFlush = true };\r\n\r\n                    writer.Write(contents);\r\n                }\r\n            };\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Caching/CachingBootstrapper.cs",
    "content": "namespace Nancy.Demo.Caching\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Demo.Caching.CachingExtensions;\r\n    using Nancy.TinyIoc;\r\n\r\n    public class CachingBootstrapper : DefaultNancyBootstrapper\r\n    {\r\n        private const int CACHE_SECONDS = 30;\r\n\r\n        private readonly Dictionary<string, Tuple<DateTime, Response, int>> cachedResponses = new Dictionary<string, Tuple<DateTime, Response, int>>();\r\n\r\n        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)\r\n        {\r\n            base.ApplicationStartup(container, pipelines);\r\n\r\n            pipelines.BeforeRequest += CheckCache;\r\n\r\n            pipelines.AfterRequest += SetCache;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Check to see if we have a cache entry - if we do, see if it has expired or not,\r\n        /// if it hasn't then return it, otherwise return null;\r\n        /// </summary>\r\n        /// <param name=\"context\">Current context</param>\r\n        /// <returns>Request or null</returns>\r\n        public Response CheckCache(NancyContext context)\r\n        {\r\n            Tuple<DateTime, Response, int> cacheEntry;\r\n\r\n            if (this.cachedResponses.TryGetValue(context.Request.Path, out cacheEntry))\r\n            {\r\n                if (cacheEntry.Item1.AddSeconds(cacheEntry.Item3) > DateTime.Now)\r\n                {\r\n                    return cacheEntry.Item2;\r\n                }\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds the current response to the cache if required\r\n        /// Only stores by Path and stores the response in a dictionary.\r\n        /// Do not use this as an actual cache :-)\r\n        /// </summary>\r\n        /// <param name=\"context\">Current context</param>\r\n        public void SetCache(NancyContext context)\r\n        {\r\n            if (context.Response.StatusCode != HttpStatusCode.OK)\r\n            {\r\n                return;\r\n            }\r\n\r\n            object cacheSecondsObject;\r\n            if (!context.Items.TryGetValue(ContextExtensions.OUTPUT_CACHE_TIME_KEY, out cacheSecondsObject))\r\n            {\r\n                return;\r\n            }\r\n\r\n            int cacheSeconds;\r\n            if (!int.TryParse(cacheSecondsObject.ToString(), out cacheSeconds))\r\n            {\r\n                return;\r\n            }\r\n\r\n            var cachedResponse = new CachedResponse(context.Response);\r\n\r\n            this.cachedResponses[context.Request.Path] = new Tuple<DateTime, Response, int>(DateTime.Now, cachedResponse, cacheSeconds);\r\n\r\n            context.Response = cachedResponse;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Caching/CachingExtensions/ContextExtensions.cs",
    "content": "﻿namespace Nancy.Demo.Caching.CachingExtensions\r\n{\r\n    public static class ContextExtensions\r\n    {\r\n        public const string OUTPUT_CACHE_TIME_KEY = \"OUTPUT_CACHE_TIME\";\r\n\r\n        /// <summary>\r\n        /// Enable output caching for this route\r\n        /// </summary>\r\n        /// <param name=\"context\">Current context</param>\r\n        /// <param name=\"seconds\">Seconds to cache for</param>\r\n        public static void EnableOutputCache(this NancyContext context, int seconds)\r\n        {\r\n            context.Items[OUTPUT_CACHE_TIME_KEY] = seconds;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Disable the output cache for this route\r\n        /// </summary>\r\n        /// <param name=\"context\">Current context</param>\r\n        public static void DisableOutputCache(this NancyContext context)\r\n        {\r\n            context.Items.Remove(OUTPUT_CACHE_TIME_KEY);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Caching/MainModule.cs",
    "content": "namespace Nancy.Demo.Caching\r\n{\r\n    using System;\r\n    using Nancy.Demo.Caching.CachingExtensions;\r\n\r\n    public class MainModule : NancyModule\r\n    {\r\n        public MainModule()\r\n        {\r\n            Get(\"/\", args => {\r\n                return View[\"Index.cshtml\", DateTime.Now.ToString()];\r\n            });\r\n\r\n            Get(\"/cached\", args => {\r\n                this.Context.EnableOutputCache(30);\r\n                return View[\"Payload.cshtml\", DateTime.Now.ToString()];\r\n            });\r\n\r\n            Get(\"/uncached\", args => {\r\n                this.Context.DisableOutputCache();\r\n                return View[\"Payload.cshtml\", DateTime.Now.ToString()];\r\n            });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Caching/Nancy.Demo.Caching.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\r\n  <PropertyGroup>\r\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\r\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\r\n    <SchemaVersion>2.0</SchemaVersion>\r\n    <ProjectGuid>{28F9EA8B-90F7-4974-BB40-0B7FA9309D02}</ProjectGuid>\r\n    <ProjectTypeGuids>{349C5851-65DF-11DA-9384-00065B846F21};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>\r\n    <OutputType>Library</OutputType>\r\n    <AppDesignerFolder>Properties</AppDesignerFolder>\r\n    <RootNamespace>Nancy.Demo.Caching</RootNamespace>\r\n    <AssemblyName>Nancy.Demo.Caching</AssemblyName>\r\n    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\r\n    <UseIISExpress>false</UseIISExpress>\r\n    <OldToolsVersion>4.0</OldToolsVersion>\r\n    <IISExpressSSLPort />\r\n    <IISExpressAnonymousAuthentication />\r\n    <IISExpressWindowsAuthentication />\r\n    <IISExpressUseClassicPipelineMode />\r\n    <UseGlobalApplicationHostFile />\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <DebugType>full</DebugType>\r\n    <Optimize>false</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\r\n    <DebugType>pdbonly</DebugType>\r\n    <Optimize>true</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoDebug|AnyCPU'\">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <DebugType>full</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.Caching.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRules>false</CodeAnalysisIgnoreBuiltInRules>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Optimize>false</Optimize>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoRelease|AnyCPU'\">\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <Optimize>true</Optimize>\r\n    <DebugType>pdbonly</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.Caching.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRules>false</CodeAnalysisIgnoreBuiltInRules>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <ItemGroup>\r\n    <Reference Include=\"Microsoft.CSharp\" />\r\n    <Reference Include=\"System\" />\r\n    <Reference Include=\"System.Data\" />\r\n    <Reference Include=\"System.Drawing\" />\r\n    <Reference Include=\"System.Web\" />\r\n    <Reference Include=\"System.Xml\" />\r\n    <Reference Include=\"System.Configuration\" />\r\n    <Reference Include=\"System.Xml.Linq\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Web.config\" />\r\n    <Content Include=\"Web.Debug.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n    <Content Include=\"Web.Release.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Compile Include=\"..\\..\\SharedAssemblyInfo.cs\">\r\n      <Link>Properties\\SharedAssemblyInfo.cs</Link>\r\n    </Compile>\r\n    <Compile Include=\"CachedResponse.cs\" />\r\n    <Compile Include=\"CachingBootstrapper.cs\" />\r\n    <Compile Include=\"CachingExtensions\\ContextExtensions.cs\" />\r\n    <Compile Include=\"MainModule.cs\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.Hosting.Aspnet.MSBuild\\Nancy.Hosting.Aspnet.csproj\">\r\n      <Project>{15B7F794-0BB2-4B66-AD78-4A951F1209B2}</Project>\r\n      <Name>Nancy.Hosting.Aspnet</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.ViewEngines.Razor.MSBuild\\Nancy.ViewEngines.Razor.csproj\">\r\n      <Project>{2C6F51DF-015C-4DB6-B44C-0E5E4F25E2A9}</Project>\r\n      <Name>Nancy.ViewEngines.Razor</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.MSBuild\\Nancy.csproj\">\r\n      <Project>{34576216-0DCA-4B0F-A0DC-9075E75A676F}</Project>\r\n      <Name>Nancy</Name>\r\n    </ProjectReference>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Views\\Index.cshtml\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Views\\Payload.cshtml\" />\r\n  </ItemGroup>\r\n  <PropertyGroup>\r\n    <VisualStudioVersion Condition=\"'$(VisualStudioVersion)' == ''\">10.0</VisualStudioVersion>\r\n    <VSToolsPath Condition=\"'$(VSToolsPath)' == ''\">$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)</VSToolsPath>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\r\n  <Import Project=\"$(VSToolsPath)\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"'$(VSToolsPath)' != ''\" />\r\n  <Import Project=\"$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v10.0\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"false\" />\r\n  <ProjectExtensions>\r\n    <VisualStudio>\r\n      <FlavorProperties GUID=\"{349C5851-65DF-11DA-9384-00065B846F21}\">\r\n        <WebProjectProperties>\r\n          <UseIIS>False</UseIIS>\r\n          <AutoAssignPort>True</AutoAssignPort>\r\n          <DevelopmentServerPort>3486</DevelopmentServerPort>\r\n          <DevelopmentServerVPath>/</DevelopmentServerVPath>\r\n          <IISUrl>\r\n          </IISUrl>\r\n          <NTLMAuthentication>False</NTLMAuthentication>\r\n          <UseCustomServer>False</UseCustomServer>\r\n          <CustomServerUrl>\r\n          </CustomServerUrl>\r\n          <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>\r\n        </WebProjectProperties>\r\n      </FlavorProperties>\r\n    </VisualStudio>\r\n    <MonoDevelop>\r\n      <Properties VerifyCodeBehindFields=\"true\" VerifyCodeBehindEvents=\"true\">\r\n        <XspParameters Port=\"8080\" Address=\"127.0.0.1\" SslMode=\"None\" SslProtocol=\"Default\" KeyType=\"None\" CertFile=\"\" KeyFile=\"\" PasswordOptions=\"None\" Password=\"\" Verbose=\"true\" />\r\n      </Properties>\r\n    </MonoDevelop>\r\n  </ProjectExtensions>\r\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r\n       Other similar extension points exist, see Microsoft.Common.targets.\r\n  <Target Name=\"BeforeBuild\">\r\n  </Target>\r\n  <Target Name=\"AfterBuild\">\r\n  </Target>\r\n  -->\r\n</Project>"
  },
  {
    "path": "samples/Nancy.Demo.Caching/README.txt",
    "content": "﻿"
  },
  {
    "path": "samples/Nancy.Demo.Caching/Views/Index.cshtml",
    "content": "﻿<html>\r\n<head>\r\n    <title>Index</title>\r\n</head>\r\n<body>\r\n    <h1>Nancy Caching Demo</h1>\r\n    <p><a href=\"/cached\">Cached</a></p>\r\n    <p><a href=\"/uncached\">Uncached</a></p>\r\n</body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Caching/Views/Payload.cshtml",
    "content": "﻿<html>\r\n<head>\r\n    <title>Index</title>\r\n</head>\r\n<body>\r\n    <h1>Nancy Caching Demo</h1>\r\n    <p>This page was created on: @Model</p>\r\n    <p>This may or may not be cached :-)</p>\r\n    <a href=\"/\">Home</a>\r\n</body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Caching/Web.Debug.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Caching/Web.Release.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n    <compilation xdt:Transform=\"RemoveAttributes(debug)\" />\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Caching/Web.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n<configuration>\r\n  <system.web>\r\n    <httpHandlers>\r\n      <add verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </httpHandlers>\r\n  </system.web>\r\n  <system.webServer>\r\n    <modules runAllManagedModulesForAllRequests=\"true\" />\r\n    <validation validateIntegratedModeConfiguration=\"false\" />\r\n    <handlers>\r\n      <add name=\"Nancy\" verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </handlers>\r\n  </system.webServer>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.ConstraintRouting/ConstraintRoutingModule.cs",
    "content": "﻿namespace Nancy.Demo.ModelBinding\r\n{\r\n    public class ConstraintRoutingModule : NancyModule\r\n    {\r\n        public ConstraintRoutingModule()\r\n        {\r\n            Get(\"/\", args => View[\"Index\"]);\r\n\r\n            Get(\"/intConstraint/{value:int}\", args => \"Value \" + args.value + \" is an integer.\");\r\n\r\n            Get(\"/decimalConstraint/{value:decimal}\", args => \"Value \" + args.value + \" is a decimal.\");\r\n\r\n            Get(\"/guidConstraint/{value:guid}\", args => \"Value \" + args.value + \" is a guid.\");\r\n\r\n            Get(\"/boolConstraint/{value:bool}\", args => \"Value \" + args.value + \" is a boolean.\");\r\n\r\n            Get(\"/alphaConstraint/{value:alpha}\", args => \"Value \" + args.value + \" is only letters.\");\r\n\r\n            Get(\"/datetimeConstraint/{value:datetime}\", args => \"Value \" + args.value + \" is a date time.\");\r\n\r\n            Get(\"/customDatetimeConstraint/{value:datetime(yyyy-MM-dd)}\", args => \"Value \" + args.value + \" is a date time with format 'yyyy-MM-dd'.\");\r\n\r\n            Get(\"/minConstraint/{value:min(4)}\", args => \"Value \" + args.value + \" is an integer greater than 4.\");\r\n\r\n            Get(\"/maxConstraint/{value:max(6)}\", args => \"Value \" + args.value + \" is an integer less than 6.\");\r\n\r\n            Get(\"/rangeConstraint/{value:range(10, 20)}\", args => \"Value \" + args.value + \"  is an integer between 10 and 20.\");\r\n\r\n            Get(\"/minlengthConstraint/{value:minlength(4)}\", args => \"Value \" + args.value + \" is a string with length greater than 4.\");\r\n\r\n            Get(\"/maxlengthConstraint/{value:maxlength(10)}\", args => \"Value \" + args.value + \" is a string with length less than 10.\");\r\n\r\n            Get(\"/lengthConstraint/{value:length(1, 20)}\", args => \"Value \" + args.value + \" is a string with length between 1 and 20.\");\r\n\r\n            Get(\"/versionConstraint/{value:version}\", args => \"Value \" + args.value + \" is a version number.\");\r\n\r\n            Get(\"/emailConstraint/{value:email}\", args => \"Value \" + args.value + \" is an e-mail address (according to @jchannon).\");\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.ConstraintRouting/EmailRouteSegmentConstraint.cs",
    "content": "﻿namespace Nancy.Demo.ModelBinding\r\n{\r\n    using Nancy.Routing.Constraints;\r\n\r\n    public class EmailRouteSegmentConstraint : RouteSegmentConstraintBase<string>\r\n    {\r\n        public override string Name\r\n        {\r\n            get { return \"email\"; }\r\n        }\r\n\r\n        protected override bool TryMatch(string constraint, string segment, out string matchedValue)\r\n        {\r\n            // Using @jchannon logic for validating e-mail address\r\n            if (segment.Contains(\"@\") && segment.Contains(\".\"))\r\n            {\r\n                matchedValue = segment;\r\n                return true;\r\n            }\r\n\r\n            matchedValue = null;\r\n            return false;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.ConstraintRouting/Nancy.Demo.ConstraintRouting.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\r\n  <PropertyGroup>\r\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\r\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\r\n    <SchemaVersion>2.0</SchemaVersion>\r\n    <ProjectGuid>{972C2D45-49B6-4109-9A3A-0C8BC9225B95}</ProjectGuid>\r\n    <ProjectTypeGuids>{349C5851-65DF-11DA-9384-00065B846F21};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>\r\n    <OutputType>Library</OutputType>\r\n    <AppDesignerFolder>Properties</AppDesignerFolder>\r\n    <RootNamespace>Nancy.Demo.ModelBinding</RootNamespace>\r\n    <AssemblyName>Nancy.Demo.ModelBinding</AssemblyName>\r\n    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\r\n    <UseIISExpress>false</UseIISExpress>\r\n    <OldToolsVersion>4.0</OldToolsVersion>\r\n    <IISExpressSSLPort />\r\n    <IISExpressAnonymousAuthentication />\r\n    <IISExpressWindowsAuthentication />\r\n    <IISExpressUseClassicPipelineMode />\r\n    <UseGlobalApplicationHostFile />\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <DebugType>full</DebugType>\r\n    <Optimize>false</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\r\n    <DebugType>pdbonly</DebugType>\r\n    <Optimize>true</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoDebug|AnyCPU'\">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <DebugType>full</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.ModelBinding.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Optimize>false</Optimize>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoRelease|AnyCPU'\">\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <Optimize>true</Optimize>\r\n    <DebugType>pdbonly</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.ModelBinding.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Views\\Index.html\" />\r\n    <Content Include=\"Web.config\" />\r\n    <Content Include=\"Web.Debug.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n    <Content Include=\"Web.Release.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Compile Include=\"..\\..\\SharedAssemblyInfo.cs\">\r\n      <Link>Properties\\SharedAssemblyInfo.cs</Link>\r\n    </Compile>\r\n    <Compile Include=\"ConstraintRoutingModule.cs\" />\r\n    <Compile Include=\"EmailRouteSegmentConstraint.cs\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Reference Include=\"Microsoft.CSharp\" />\r\n    <Reference Include=\"System.Xml.Linq\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.Hosting.Aspnet.MSBuild\\Nancy.Hosting.Aspnet.csproj\">\r\n      <Project>{15b7f794-0bb2-4b66-ad78-4a951f1209b2}</Project>\r\n      <Name>Nancy.Hosting.Aspnet</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.MSBuild\\Nancy.csproj\">\r\n      <Project>{34576216-0dca-4b0f-a0dc-9075e75a676f}</Project>\r\n      <Name>Nancy</Name>\r\n    </ProjectReference>\r\n  </ItemGroup>\r\n  <PropertyGroup>\r\n    <VisualStudioVersion Condition=\"'$(VisualStudioVersion)' == ''\">10.0</VisualStudioVersion>\r\n    <VSToolsPath Condition=\"'$(VSToolsPath)' == ''\">$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)</VSToolsPath>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\r\n  <Import Project=\"$(VSToolsPath)\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"'$(VSToolsPath)' != ''\" />\r\n  <Import Project=\"$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v10.0\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"false\" />\r\n  <ProjectExtensions>\r\n    <VisualStudio>\r\n      <FlavorProperties GUID=\"{349C5851-65DF-11DA-9384-00065B846F21}\">\r\n        <WebProjectProperties>\r\n          <UseIIS>False</UseIIS>\r\n          <AutoAssignPort>True</AutoAssignPort>\r\n          <DevelopmentServerPort>56281</DevelopmentServerPort>\r\n          <DevelopmentServerVPath>/</DevelopmentServerVPath>\r\n          <IISUrl>\r\n          </IISUrl>\r\n          <NTLMAuthentication>False</NTLMAuthentication>\r\n          <UseCustomServer>False</UseCustomServer>\r\n          <CustomServerUrl>\r\n          </CustomServerUrl>\r\n          <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>\r\n        </WebProjectProperties>\r\n      </FlavorProperties>\r\n    </VisualStudio>\r\n    <MonoDevelop>\r\n      <Properties VerifyCodeBehindFields=\"true\" VerifyCodeBehindEvents=\"true\">\r\n        <XspParameters Port=\"8080\" Address=\"127.0.0.1\" SslMode=\"None\" SslProtocol=\"Default\" KeyType=\"None\" CertFile=\"\" KeyFile=\"\" PasswordOptions=\"None\" Password=\"\" Verbose=\"true\" />\r\n      </Properties>\r\n    </MonoDevelop>\r\n  </ProjectExtensions>\r\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r\n       Other similar extension points exist, see Microsoft.Common.targets.\r\n  <Target Name=\"BeforeBuild\">\r\n  </Target>\r\n  <Target Name=\"AfterBuild\">\r\n  </Target>\r\n  -->\r\n</Project>"
  },
  {
    "path": "samples/Nancy.Demo.ConstraintRouting/Views/Index.html",
    "content": "﻿<!DOCTYPE html>\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n    <title></title>\r\n    <style>\r\n        table {\r\n            border-collapse: collapse;\r\n        }\r\n\r\n        table, th, td {\r\n            border: 1px solid black;\r\n            padding: 2px 3px;\r\n        }\r\n    </style>\r\n</head>\r\n<body>\r\n    <h1>Constraint Routing</h1>\r\n    <table>\r\n        Constraint\r\n    </table>\r\n    <table>\r\n        <thead>\r\n            <tr>\r\n                <th>Constraint</th>\r\n                <th>Description</th>\r\n                <th>Expression</th>\r\n                <th>Example</th>\r\n            </tr>\r\n        </thead>\r\n        <tbody>\r\n            <tr>\r\n                <td>alpha</td>\r\n                <td>Matches uppercase or lowercase Latin alphabet characters (a-z, A-Z)</td>\r\n                <td>{x:alpha}</td>\r\n                <td><a href=\"/alphaConstraint/foo\">Success</a> <a href=\"/alphaConstraint/1\">Failure</a></td>\r\n            </tr>\r\n            <tr>\r\n                <td>bool</td>\r\n                <td>Matches a Boolean value.</td>\r\n                <td>{x:bool}</td>\r\n                <td><a href=\"/boolConstraint/true\">Success</a> <a href=\"/boolConstraint/foo\">Failure</a></td>\r\n            </tr>\r\n            <tr>\r\n                <td>datetime</td>\r\n                <td>Matches a <strong>DateTime</strong> value.</td>\r\n                <td>{x:datetime}</td>\r\n                <td><a href=\"/datetimeConstraint/1-1-2010\">Success</a> <a href=\"/datetimeConstraint/foo\">Failure</a></td>\r\n            </tr>\r\n            <tr>\r\n                <td>datetime</td>\r\n                <td>Matches a <strong>DateTime</strong> value with a custom format.</td>\r\n                <td>{x:datetime(yyyy-MM-dd)}</td>\r\n                <td><a href=\"/customDatetimeConstraint/2013-02-03\">Success</a> <a href=\"/customDatetimeConstraint/2013-23-02\">Failure</a></td>\r\n            </tr>\r\n            <tr>\r\n                <td>decimal</td>\r\n                <td>Matches a decimal value.</td>\r\n                <td>{x:decimal}</td>\r\n                <td><a href=\"/decimalConstraint/1.5555555555555555555555555555\">Success</a> <a href=\"/decimalConstraint/foo\">Failure</a></td>\r\n            </tr>\r\n            <tr>\r\n                <td>guid</td>\r\n                <td>Matches a GUID value.</td>\r\n                <td>{x:guid}</td>\r\n                <td><a href=\"/guidConstraint/7439018c-5057-46c1-95f9-d9b75d4d1647\">Success</a> <a href=\"/guidConstraint/7439018c-5057-46c1-95f9-d9b75d4d1647d\">Failure</a></td>\r\n            </tr>\r\n            <tr>\r\n                <td>int</td>\r\n                <td>Matches a integer value.</td>\r\n                <td>{x:int}</td>\r\n                <td><a href=\"/intConstraint/1\">Success</a> <a href=\"/intConstraint/foo\">Failure</a></td>\r\n            </tr>\r\n            <tr>\r\n                <td>length</td>\r\n                <td>Matches a string with the specified length or within a specified range of lengths.</td>\r\n                <td>{x:length(6)}<br>{x:length(1,20)}</td>\r\n                <td><a href=\"/lengthConstraint/foobar\">Success</a> <a href=\"/lengthConstraint/foobarfoobarfoobarfoobar\">Failure</a></td>\r\n            </tr>\r\n            <tr>\r\n                <td>max</td>\r\n                <td>Matches an integer with a maximum value.</td>\r\n                <td>{x:max(6)}</td>\r\n                <td><a href=\"/maxConstraint/5\">Success</a> <a href=\"/maxConstraint/20\">Failure</a></td>\r\n            </tr>\r\n            <tr>\r\n                <td>maxlength</td>\r\n                <td>Matches a string with a maximum length.</td>\r\n                <td>{x:maxlength(10)}</td>\r\n                <td><a href=\"/maxlengthConstraint/foobar\">Success</a> <a href=\"/maxlengthConstraint/foobarfoobar\">Failure</a></td>\r\n            </tr>\r\n            <tr>\r\n                <td>min</td>\r\n                <td>Matches an integer with a minimum value.</td>\r\n                <td>{x:min(4)}</td>\r\n                <td><a href=\"/minConstraint/5\">Success</a> <a href=\"/minConstraint/2\">Failure</a></td>\r\n            </tr>\r\n            <tr>\r\n                <td>minlength</td>\r\n                <td>Matches a string with a minimum length.</td>\r\n                <td>{x:minlength(4)}</td>\r\n                <td><a href=\"/minlengthConstraint/foobar\">Success</a> <a href=\"/minlengthConstraint/foo\">Failure</a></td>\r\n            </tr>\r\n            <tr>\r\n                <td>range</td>\r\n                <td>Matches an integer within a range of values.</td>\r\n                <td>{x:range(10,20)}</td>\r\n                <td><a href=\"/rangeConstraint/15\">Success</a> <a href=\"/rangeConstraint/25\">Failure</a></td>\r\n            </tr>\r\n            <tr>\r\n                <td>version</td>\r\n                <td>Matches a version number.</td>\r\n                <td>{x:version}</td>\r\n                <td><a href=\"/versionConstraint/3.2.1\">Success</a> <a href=\"/versionConstraint/-4\">Failure</a></td>\r\n            </tr>\r\n            <tr>\r\n                <td>email</td>\r\n                <td>Matches an e-mail address (according to @jchannon).</td>\r\n                <td>{x:email}</td>\r\n                <td><a href=\"/emailConstraint/mail@domain.com\">Success</a> <a href=\"/emailConstraint/maild@asdsacom\">Failure</a></td>\r\n            </tr>\r\n        </tbody>\r\n    </table>\r\n</body>\r\n</html>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.ConstraintRouting/Web.Debug.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.ConstraintRouting/Web.Release.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n    <compilation xdt:Transform=\"RemoveAttributes(debug)\" />\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.ConstraintRouting/Web.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n\r\n<configuration>\r\n  <system.web>\r\n    <compilation debug=\"true\" targetFramework=\"4.0\" />\r\n    <httpHandlers>\r\n      <add verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </httpHandlers>\r\n  </system.web>\r\n\r\n  <system.webServer>\r\n    <modules runAllManagedModulesForAllRequests=\"true\" />\r\n    <validation validateIntegratedModeConfiguration=\"false\" />\r\n    <handlers>\r\n      <add name=\"Nancy\" verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </handlers>\r\n  </system.webServer>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.CustomModule/DemoBootstrapper.cs",
    "content": "﻿namespace Nancy.Demo.CustomModule\r\n{\r\n    using Nancy.Configuration;\r\n    using Nancy.Diagnostics;\r\n\r\n    public class DemoBootstrapper : DefaultNancyBootstrapper\r\n    {\r\n        public override void Configure(INancyEnvironment environment)\r\n        {\r\n            environment.Diagnostics(\r\n                enabled: true,\r\n                password: \"password\");\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "samples/Nancy.Demo.CustomModule/MainModule.cs",
    "content": "﻿namespace Nancy.Demo.CustomModule\r\n{\r\n    public class MainModule : UglifiedNancyModule\r\n    {\r\n        [NancyRoute(\"GET\", \"/\")]\r\n        public dynamic Root(dynamic parameters)\r\n        {\r\n            return View[\"Index\", new { Name = \"Jimbo!\" }];\r\n        }\r\n\r\n        public bool FilteredFilter(NancyContext context)\r\n        {\r\n            return false;\r\n        }\r\n\r\n        [NancyRoute(\"GET\", \"/filtered\")]\r\n        public dynamic Filtered(dynamic parameters)\r\n        {\r\n            return \"This is filtered\";\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.CustomModule/Nancy.Demo.CustomModule.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\r\n  <PropertyGroup>\r\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\r\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\r\n    <SchemaVersion>2.0</SchemaVersion>\r\n    <ProjectGuid>{F56F3983-0C34-4AEC-B418-A8AFFA63F1C4}</ProjectGuid>\r\n    <ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>\r\n    <OutputType>Library</OutputType>\r\n    <AppDesignerFolder>Properties</AppDesignerFolder>\r\n    <RootNamespace>Nancy.Demo.CustomModule</RootNamespace>\r\n    <AssemblyName>Nancy.Demo.CustomModule</AssemblyName>\r\n    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\r\n    <UseIISExpress>true</UseIISExpress>\r\n    <IISExpressSSLPort />\r\n    <IISExpressAnonymousAuthentication />\r\n    <IISExpressWindowsAuthentication />\r\n    <IISExpressUseClassicPipelineMode />\r\n    <UseGlobalApplicationHostFile />\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <DebugType>full</DebugType>\r\n    <Optimize>false</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\r\n    <DebugType>pdbonly</DebugType>\r\n    <Optimize>true</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <ItemGroup>\r\n    <Reference Include=\"Microsoft.CSharp\" />\r\n    <Reference Include=\"System.ComponentModel.DataAnnotations\" />\r\n    <Reference Include=\"System\" />\r\n    <Reference Include=\"System.Data\" />\r\n    <Reference Include=\"System.Drawing\" />\r\n    <Reference Include=\"System.Web\" />\r\n    <Reference Include=\"System.Xml\" />\r\n    <Reference Include=\"System.Configuration\" />\r\n    <Reference Include=\"System.Xml.Linq\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Views\\Index.html\" />\r\n    <Content Include=\"Web.config\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <None Include=\"Web.Debug.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </None>\r\n    <None Include=\"Web.Release.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </None>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.Hosting.Aspnet.MSBuild\\Nancy.Hosting.Aspnet.csproj\">\r\n      <Project>{15b7f794-0bb2-4b66-ad78-4a951f1209b2}</Project>\r\n      <Name>Nancy.Hosting.Aspnet</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.MSBuild\\Nancy.csproj\">\r\n      <Project>{34576216-0dca-4b0f-a0dc-9075e75a676f}</Project>\r\n      <Name>Nancy</Name>\r\n    </ProjectReference>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Compile Include=\"..\\..\\SharedAssemblyInfo.cs\">\r\n      <Link>SharedAssemblyInfo.cs</Link>\r\n    </Compile>\r\n    <Compile Include=\"DemoBootstrapper.cs\" />\r\n    <Compile Include=\"MainModule.cs\" />\r\n    <Compile Include=\"NancyRouteAttribute.cs\" />\r\n    <Compile Include=\"UglifiedNancyModule.cs\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Folder Include=\"Properties\\\" />\r\n  </ItemGroup>\r\n  <PropertyGroup>\r\n    <VisualStudioVersion Condition=\"'$(VisualStudioVersion)' == ''\">10.0</VisualStudioVersion>\r\n    <VSToolsPath Condition=\"'$(VSToolsPath)' == ''\">$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)</VSToolsPath>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoDebug|AnyCPU'\">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <DebugType>full</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoRelease|AnyCPU'\">\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <Optimize>true</Optimize>\r\n    <DebugType>pdbonly</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\r\n  <Import Project=\"$(VSToolsPath)\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"'$(VSToolsPath)' != ''\" />\r\n  <Import Project=\"$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v10.0\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"false\" />\r\n  <ProjectExtensions>\r\n    <VisualStudio>\r\n      <FlavorProperties GUID=\"{349c5851-65df-11da-9384-00065b846f21}\">\r\n        <WebProjectProperties>\r\n          <UseIIS>False</UseIIS>\r\n          <AutoAssignPort>True</AutoAssignPort>\r\n          <DevelopmentServerPort>56673</DevelopmentServerPort>\r\n          <DevelopmentServerVPath>/</DevelopmentServerVPath>\r\n          <IISUrl>http://localhost:53007/</IISUrl>\r\n          <NTLMAuthentication>False</NTLMAuthentication>\r\n          <UseCustomServer>False</UseCustomServer>\r\n          <CustomServerUrl>\r\n          </CustomServerUrl>\r\n          <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>\r\n        </WebProjectProperties>\r\n      </FlavorProperties>\r\n    </VisualStudio>\r\n  </ProjectExtensions>\r\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r\n       Other similar extension points exist, see Microsoft.Common.targets.\r\n  <Target Name=\"BeforeBuild\">\r\n  </Target>\r\n  <Target Name=\"AfterBuild\">\r\n  </Target>\r\n  -->\r\n</Project>"
  },
  {
    "path": "samples/Nancy.Demo.CustomModule/NancyRouteAttribute.cs",
    "content": "﻿namespace Nancy.Demo.CustomModule\r\n{\r\n    using System;\r\n\r\n    public class NancyRouteAttribute : Attribute\r\n    {\r\n        /// <summary>\r\n        /// The method for the route\r\n        /// </summary>\r\n        public string Method { get; set; }\r\n\r\n        /// <summary>\r\n        /// The path for the route\r\n        /// </summary>\r\n        public string Path { get; set; }\r\n\r\n        public NancyRouteAttribute(string method, string path)\r\n        {\r\n            this.Method = method;\r\n            this.Path = path;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.CustomModule/UglifiedNancyModule.cs",
    "content": "﻿namespace Nancy.Demo.CustomModule\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n    using Nancy.ModelBinding;\r\n    using Nancy.Responses.Negotiation;\r\n    using Nancy.Routing;\r\n    using Nancy.Validation;\r\n    using Nancy.ViewEngines;\r\n\r\n    /// <summary>\r\n    /// A custom INancyModule implementation that uses\r\n    /// attributes on methods (eugh!) to define routes.\r\n    /// Nobody in their right mind would write a web framework\r\n    /// that uses attributes for routing ;-)\r\n    /// </summary>\r\n    public abstract class UglifiedNancyModule : INancyModule\r\n    {\r\n        public AfterPipeline After { get; set; }\r\n\r\n        public BeforePipeline Before { get; set; }\r\n\r\n        public ErrorPipeline OnError { get; set; }\r\n\r\n        public NancyContext Context { get; set; }\r\n\r\n        public IResponseFormatter Response { get; set; }\r\n\r\n        public IModelBinderLocator ModelBinderLocator { get; set; }\r\n\r\n        public ModelValidationResult ModelValidationResult { get; set; }\r\n\r\n        public IModelValidatorLocator ValidatorLocator { get; set; }\r\n\r\n        public Request Request { get; set; }\r\n\r\n        public IViewFactory ViewFactory { get; set; }\r\n\r\n        public string ModulePath { get; private set; }\r\n\r\n        public ViewRenderer View\r\n        {\r\n            get { return new ViewRenderer(this); }\r\n        }\r\n\r\n        public Negotiator Negotiate\r\n        {\r\n            get { return new Negotiator(this.Context); }\r\n        }\r\n\r\n        public UglifiedNancyModule()\r\n            : this(string.Empty)\r\n        {\r\n        }\r\n\r\n        public IEnumerable<Route> Routes\r\n        {\r\n            get\r\n            {\r\n                return this.GetRoutes();\r\n            }\r\n        }\r\n\r\n        public dynamic Text { get; set; }\r\n\r\n        private UglifiedNancyModule(string modulePath)\r\n        {\r\n            this.After = new AfterPipeline();\r\n            this.Before = new BeforePipeline();\r\n            this.OnError = new ErrorPipeline();\r\n\r\n            this.ModulePath = modulePath;\r\n        }\r\n\r\n        private IEnumerable<Route> GetRoutes()\r\n        {\r\n            // Run through all the methods on the class looking\r\n            // for our attribute. If we were to do this for a real\r\n            // app we'd be checking parameters and return types etc\r\n            // but for simplicity we won't bother here.\r\n            var routes = new List<Route>();\r\n            var type = this.GetType();\r\n\r\n            var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public);\r\n\r\n            foreach (var method in methods)\r\n            {\r\n                var attribute = method.GetCustomAttributes(typeof(NancyRouteAttribute), false).FirstOrDefault() as NancyRouteAttribute;\r\n\r\n                if (attribute == null)\r\n                {\r\n                    continue;\r\n                }\r\n\r\n                var routeDelegate = WrapFunc((Func<dynamic, dynamic>)Delegate.CreateDelegate(typeof(Func<dynamic, dynamic>), this, method.Name));\r\n\r\n                var filter = this.GetFilter(method.Name);\r\n\r\n                var fullPath = string.Concat(this.ModulePath, attribute.Path);\r\n\r\n                routes.Add(new Route<object>(attribute.Method.ToUpper(), fullPath, filter, routeDelegate));\r\n            }\r\n\r\n            return routes.AsReadOnly();\r\n        }\r\n\r\n        private Func<NancyContext, bool> GetFilter(string routeMethodName)\r\n        {\r\n            var type = this.GetType();\r\n            var method = type.GetMethod(routeMethodName + \"Filter\", BindingFlags.Public | BindingFlags.Instance);\r\n\r\n            if (method == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            return (Func<NancyContext, bool>)Delegate.CreateDelegate(typeof(Func<NancyContext, bool>), this, method.Name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Wraps a sync delegate in a delegate that returns a task\r\n        /// </summary>\r\n        /// <param name=\"syncFunc\">Sync delegate</param>\r\n        /// <returns>Task wrapped version</returns>\r\n        private static Func<dynamic, CancellationToken, Task<dynamic>> WrapFunc(Func<object, object> syncFunc)\r\n        {\r\n            return (p, ct) =>\r\n            {\r\n                var tcs = new TaskCompletionSource<dynamic>();\r\n\r\n                try\r\n                {\r\n                    var result = syncFunc.Invoke(p);\r\n\r\n                    tcs.SetResult(result);\r\n                }\r\n                catch (Exception e)\r\n                {\r\n                    tcs.SetException(e);\r\n                }\r\n\r\n                return tcs.Task;\r\n            };\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.CustomModule/Views/Index.html",
    "content": "﻿<!DOCTYPE html>\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n    <title>Hello!</title>\r\n</head>\r\n<body>\r\n    <h1>Hello @Model.Name - this was rendered using a custom module type.</h1>\r\n</body>\r\n</html>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.CustomModule/Web.Debug.config",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.CustomModule/Web.Release.config",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n    <compilation xdt:Transform=\"RemoveAttributes(debug)\" />\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.CustomModule/Web.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration>\r\n  <system.web>\r\n    <compilation debug=\"true\" targetFramework=\"4.0\" />\r\n    <httpHandlers>\r\n      <add verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </httpHandlers>\r\n  </system.web>\r\n\r\n  <system.webServer>\r\n    <modules runAllManagedModulesForAllRequests=\"true\" />\r\n    <validation validateIntegratedModeConfiguration=\"false\" />\r\n    <handlers>\r\n      <add name=\"Nancy\" verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </handlers>\r\n  </system.webServer>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/ApplicationDependencyClass.cs",
    "content": "namespace Nancy.Demo.Hosting.Aspnet\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// A module dependency that will have an application lifetime scope.\r\n    /// </summary>\r\n    public class ApplicationDependencyClass : IApplicationDependency\r\n    {\r\n        private readonly DateTime currentDateTime;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the RequestDependencyClass class.\r\n        /// </summary>\r\n        public ApplicationDependencyClass()\r\n        {\r\n            this.currentDateTime = DateTime.Now;\r\n        }\r\n\r\n        public string GetContent()\r\n        {\r\n            return \"This is an application level dependency, constructed on: \" + this.currentDateTime.ToLongTimeString();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Content/main.css",
    "content": "﻿body {\r\n    background-color: #fcfcfc;\r\n    font-family: Verdana, Tahoma, \"Sans-Serif\";\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Content/scripts.js",
    "content": "﻿alert(\"This script was loaded by Nancy\");"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/CustomStatusHandler.cs",
    "content": "﻿namespace Nancy.Demo.Hosting.Aspnet\r\n{\r\n    using Nancy.ErrorHandling;\r\n\r\n    public class CustomStatusCodeHandler : IStatusCodeHandler\r\n    {\r\n        /// <summary>\r\n        /// Check if the error handler can handle errors of the provided status code.\r\n        /// </summary>\r\n        /// <param name=\"statusCode\">Status code</param>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> instance of the current request.</param>\r\n        /// <returns>True if handled, false otherwise</returns>\r\n        public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context)\r\n        {\r\n            return statusCode == HttpStatusCode.ImATeapot;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Handle the error code\r\n        /// </summary>\r\n        /// <param name=\"statusCode\">Status code</param>\r\n        /// <param name=\"context\">Current context</param>\r\n        public void Handle(HttpStatusCode statusCode, NancyContext context)\r\n        {\r\n            context.Response = \"Response generated by a custom error handler\";\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/DefaultRouteMetadataProvider.cs",
    "content": "﻿namespace Nancy.Demo.Hosting.Aspnet\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using Nancy.Routing;\r\n\r\n    public class DefaultRouteMetadataProvider : RouteMetadataProvider<MyRouteMetadata>\r\n    {\r\n        // Returns object so you can have you own application-specific\r\n        // metadata for your routes.\r\n        protected override MyRouteMetadata GetRouteMetadata(INancyModule module, RouteDescription routeDescription)\r\n        {\r\n            // Return the same metadata for all routes in this sample\r\n            // You would use the Path & Method of the routeDescription\r\n            // to determine route specific metadata\r\n            return new MyRouteMetadata(routeDescription.Method, routeDescription.Path);\r\n        }\r\n    }\r\n\r\n    public class MyRouteMetadata\r\n    {\r\n        public MyRouteMetadata(string method, string path)\r\n        {\r\n            this.Method = method;\r\n            this.Path = path;\r\n            this.Description = \"Lorem ipsum\";\r\n            this.ValidStatusCodes = new[] { HttpStatusCode.Accepted, HttpStatusCode.OK, HttpStatusCode.Processing };\r\n            this.CodeSample = \"Get['/'] = x => {\\n\" +\r\n                            \"\\treturn View['routes', routeCacheProvider.GetCache()];\\n\" +\r\n                            \"};\";\r\n        }\r\n\r\n        public string Path { get; set; }\r\n\r\n        public string Method { get; set; }\r\n\r\n        public string Description { get; set; }\r\n\r\n        public IEnumerable<HttpStatusCode> ValidStatusCodes { get; set; }\r\n\r\n        public string CodeSample { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/DemoBootstrapper.cs",
    "content": "﻿namespace Nancy.Demo.Hosting.Aspnet\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Reflection;\r\n\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Configuration;\r\n    using Nancy.Conventions;\r\n    using Nancy.Cryptography;\r\n    using Nancy.Diagnostics;\r\n    using Nancy.Security;\r\n    using Nancy.Session;\r\n    using Nancy.TinyIoc;\r\n    using Nancy.ViewEngines.Razor;\r\n\r\n    public class DemoBootstrapper : DefaultNancyBootstrapper\r\n    {\r\n        // Overriding this just to show how it works, not actually necessary as autoregister\r\n        // takes care of it all.\r\n        protected override void ConfigureApplicationContainer(TinyIoCContainer existingContainer)\r\n        {\r\n            // We don't call base because we don't want autoregister\r\n            // we just register our one known dependency as an application level singleton\r\n            existingContainer.Register<IApplicationDependency, ApplicationDependencyClass>().AsSingleton();\r\n        }\r\n\r\n        // Override with a valid password (albeit a really really bad one!)\r\n        // to enable the diagnostics dashboard\r\n        public override void Configure(INancyEnvironment environment)\r\n        {\r\n            environment.Diagnostics(\r\n                enabled: true,\r\n                password: \"password\",\r\n                path: \"/_Nancy\",\r\n                cookieName: \"__custom_cookie\",\r\n                slidingTimeout: 30,\r\n                cryptographyConfiguration: CryptographyConfiguration.NoEncryption);\r\n\r\n            environment.Tracing(\r\n                enabled: true,\r\n                displayErrorTraces: true);\r\n\r\n            environment.MyConfig(\"Hello World\");\r\n        }\r\n\r\n        protected override Func<ITypeCatalog, NancyInternalConfiguration> InternalConfiguration\r\n        {\r\n            get\r\n            {\r\n                return NancyInternalConfiguration.WithOverrides(x => x.ResourceAssemblyProvider = typeof(CustomResourceAssemblyProvider));\r\n            }\r\n        }\r\n\r\n        protected override void ConfigureRequestContainer(TinyIoCContainer existingContainer, NancyContext context)\r\n        {\r\n            base.ConfigureRequestContainer(existingContainer, context);\r\n\r\n            existingContainer.Register<IRequestDependency, RequestDependencyClass>().AsSingleton();\r\n        }\r\n\r\n        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)\r\n        {\r\n            base.ApplicationStartup(container, pipelines);\r\n\r\n            Csrf.Enable(pipelines);\r\n\r\n            this.Conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory(\"moo\", \"Content\"));\r\n\r\n            CookieBasedSessions.Enable(pipelines);\r\n\r\n            pipelines.AfterRequest += (ctx) =>\r\n            {\r\n                var username = ctx.Request.Query.pirate;\r\n\r\n                if (username.HasValue)\r\n                {\r\n                    ctx.Response = new HereBeAResponseYouScurvyDog(ctx.Response);\r\n                }\r\n            };\r\n        }\r\n    }\r\n\r\n    public class MyRazorConfiguration : IRazorConfiguration\r\n    {\r\n        public bool AutoIncludeModelNamespace\r\n        {\r\n            get\r\n            {\r\n                return false;\r\n            }\r\n        }\r\n\r\n        public IEnumerable<string> GetAssemblyNames()\r\n        {\r\n            return new string[] { };\r\n        }\r\n\r\n        public IEnumerable<string> GetDefaultNamespaces()\r\n        {\r\n            return new string[] { };\r\n        }\r\n    }\r\n\r\n    public class CustomResourceAssemblyProvider : IResourceAssemblyProvider\r\n    {\r\n        private readonly IAssemblyCatalog assemblyCatalog;\r\n        private IEnumerable<Assembly> filteredAssemblies;\r\n\r\n        public CustomResourceAssemblyProvider(IAssemblyCatalog assemblyCatalog)\r\n        {\r\n            this.assemblyCatalog = assemblyCatalog;\r\n        }\r\n\r\n        public IEnumerable<Assembly> GetAssembliesToScan()\r\n        {\r\n            return (this.filteredAssemblies ?? (this.filteredAssemblies = this.assemblyCatalog.GetAssemblies()));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/DependencyModule.cs",
    "content": "﻿namespace Nancy.Demo.Hosting.Aspnet\r\n{\r\n    using Nancy.Demo.Hosting.Aspnet.Models;\r\n\r\n    public class DependencyModule : NancyModule\r\n    {\r\n        private readonly IApplicationDependency applicationDependency;\r\n        private readonly IRequestDependency requestDependency;\r\n\r\n        public DependencyModule(IApplicationDependency applicationDependency, IRequestDependency requestDependency)\r\n        {\r\n            this.applicationDependency = applicationDependency;\r\n            this.requestDependency = requestDependency;\r\n\r\n            Get(\"/dependency\", args => {\r\n                var model =\r\n                    new RatPackWithDependencyText\r\n                    {\r\n                        FirstName = \"Bob\",\r\n                        ApplicationDependencyText = this.applicationDependency.GetContent(),\r\n                        RequestDependencyText = this.requestDependency.GetContent()\r\n                    };\r\n\r\n                return View[\"razor-dependency.cshtml\", model];\r\n            });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/HereBeAResponseYouScurvyDog.cs",
    "content": "﻿namespace Nancy.Demo.Hosting.Aspnet\r\n{\r\n    using System;\r\n    using System.IO;\r\n    using System.Text;\r\n\r\n    using Yarrrr;\r\n\r\n    public class HereBeAResponseYouScurvyDog : Response\r\n    {\r\n        private readonly string oldResponseOutput;\r\n\r\n        public HereBeAResponseYouScurvyDog(Response response)\r\n        {\r\n            this.ContentType = response.ContentType;\r\n            this.Headers = response.Headers;\r\n            this.StatusCode = response.StatusCode;\r\n\r\n            using (var memoryStream = new MemoryStream())\r\n            {\r\n                response.Contents.Invoke(memoryStream);\r\n                this.oldResponseOutput = Encoding.ASCII.GetString(memoryStream.GetBuffer());\r\n            }\r\n\r\n            this.Contents = GetContents(this.oldResponseOutput);\r\n        }\r\n\r\n        protected static Action<Stream> GetContents(string contents)\r\n        {\r\n            return stream =>\r\n            {\r\n                var writer = new StreamWriter(stream) { AutoFlush = true };\r\n                writer.Write(contents.Piratize());\r\n            };\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/IApplicationDependency.cs",
    "content": "namespace Nancy.Demo.Hosting.Aspnet\r\n{\r\n    public interface IApplicationDependency\r\n    {\r\n        string GetContent();\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/IRequestDependency.cs",
    "content": "namespace Nancy.Demo.Hosting.Aspnet\r\n{\r\n    public interface IRequestDependency\r\n    {\r\n        string GetContent();\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/MainModule.cs",
    "content": "namespace Nancy.Demo.Hosting.Aspnet\r\n{\r\n    using System;\r\n    using System.Linq;\r\n    using Nancy.Configuration;\r\n    using Nancy.Demo.Hosting.Aspnet.Metadata;\r\n    using Nancy.Demo.Hosting.Aspnet.Models;\r\n    using Nancy.Routing;\r\n    using Nancy.Security;\r\n\r\n    public class MainModule : NancyModule\r\n    {\r\n        public MainModule(IRouteCacheProvider routeCacheProvider, INancyEnvironment environment)\r\n        {\r\n            Get(\"/\", args =>\r\n            {\r\n                return View[\"routes\", routeCacheProvider.GetCache()];\r\n            });\r\n\r\n            Get(\"/texts\", args =>\r\n            {\r\n                return (string)this.Context.Text.Menu.Home;\r\n            });\r\n\r\n            Get(\"/env\", args =>\r\n            {\r\n                return \"From nancy environment: \" + environment.GetValue<MyConfig>().Value;\r\n            });\r\n\r\n            Get(\"/meta\", args =>\r\n            {\r\n                return Negotiate\r\n                    .WithModel(routeCacheProvider.GetCache().RetrieveMetadata<MyRouteMetadata>())\r\n                    .WithView(\"meta\");\r\n            });\r\n\r\n            Get(\"/uber-meta\", args =>\r\n            {\r\n                return Negotiate\r\n                    .WithModel(routeCacheProvider.GetCache().RetrieveMetadata<MyUberRouteMetadata>().OfType<MyUberRouteMetadata>())\r\n                    .WithView(\"uber-meta\");\r\n            });\r\n\r\n            Get(\"/text\", args =>\r\n            {\r\n                var value = (string)this.Context.Text.Menu.Home;\r\n                return string.Concat(\"Value of 'Home' resource key in the Menu resource file: \", value);\r\n            });\r\n\r\n            Get(\"/negotiated\", args =>\r\n            {\r\n                return Negotiate\r\n                    .WithModel(new RatPack { FirstName = \"Nancy \" })\r\n                    .WithMediaRangeModel(\"text/html\", new RatPack { FirstName = \"Nancy fancy pants\" })\r\n                    .WithView(\"negotiatedview\")\r\n                    .WithHeader(\"X-Custom\", \"SomeValue\");\r\n            });\r\n\r\n            Get(\"/user/{name}\", args =>\r\n            {\r\n                return (string)args.name;\r\n            });\r\n\r\n            Get(\"/filtered\",\r\n                condition: r => true,\r\n                action: args =>\r\n                {\r\n                    return \"This is a route with a filter that always returns true.\";\r\n                }\r\n            );\r\n\r\n            Get(\"/filtered\",\r\n                condition: r => false,\r\n                action: args =>\r\n                {\r\n                    return \"This is also a route, but filtered out so should never be hit.\";\r\n                }\r\n            );\r\n\r\n            Get(@\"/(?<foo>\\d{2,4})/{bar}\", args =>\r\n            {\r\n                return string.Format(\"foo: {0}<br/>bar: {1}\", args.foo, args.bar);\r\n            });\r\n\r\n            Get(\"/test\", args =>\r\n            {\r\n                return \"Test\";\r\n            });\r\n\r\n            Get(\"/nustache\", args =>\r\n            {\r\n                return View[\"nustache\", new { name = \"Nancy\", value = 1000000 }];\r\n            });\r\n\r\n            Get(\"/dotliquid\", args =>\r\n            {\r\n                return View[\"dot\", new { name = \"dot\" }];\r\n            });\r\n\r\n            Get(\"/javascript\", args =>\r\n            {\r\n                return View[\"javascript.html\"];\r\n            });\r\n\r\n            Get(\"/static\", args =>\r\n            {\r\n                return View[\"static\"];\r\n            });\r\n\r\n            Get(\"/razor\", args =>\r\n            {\r\n                var model = new RatPack { FirstName = \"Frank\" };\r\n                return View[\"razor.cshtml\", model];\r\n            });\r\n\r\n            Get(\"/razor-divzero\", args =>\r\n            {\r\n                var model = new { FirstName = \"Frank\", Number = 22 };\r\n                return View[\"razor-divzero.cshtml\", model];\r\n            });\r\n\r\n            Get(\"/razorError\", args =>\r\n            {\r\n                var model = new RatPack { FirstName = \"Frank\" };\r\n                return View[\"razor-error.cshtml\", model];\r\n            });\r\n\r\n            Get(\"/razor-simple\", args =>\r\n            {\r\n                var model = new RatPack { FirstName = \"Frank\" };\r\n                return View[\"razor-simple.cshtml\", model];\r\n            });\r\n\r\n            Get(\"/razor-dynamic\", args =>\r\n            {\r\n                return View[\"razor.cshtml\", new { FirstName = \"Frank\" }];\r\n            });\r\n\r\n            Get(\"/razor-cs-strong\", args =>\r\n            {\r\n                return View[\"razor-strong.cshtml\", new RatPack { FirstName = \"Frank\" }];\r\n            });\r\n\r\n            Get(\"/razor-vb-strong\", args =>\r\n            {\r\n                return View[\"razor-strong.vbhtml\", new RatPack { FirstName = \"Frank\" }];\r\n            });\r\n\r\n            Get(\"/razor2\", args =>\r\n            {\r\n                return new Razor2();\r\n            });\r\n\r\n            Get(\"/ssve\", args =>\r\n            {\r\n                var model = new RatPack { FirstName = \"You\" };\r\n                return View[\"ssve.sshtml\", model];\r\n            });\r\n\r\n            Get(\"/viewmodelconvention\", args =>\r\n            {\r\n                return View[new SomeViewModel()];\r\n            });\r\n\r\n            Get(\"/spark\", args =>\r\n            {\r\n                var model = new RatPack { FirstName = \"Bright\" };\r\n                return View[\"spark.spark\", model];\r\n            });\r\n\r\n            Get(\"/spark-anon\", args =>\r\n            {\r\n                var model = new { FirstName = \"Anonymous\" };\r\n                return View[\"anon.spark\", model];\r\n            });\r\n\r\n            Get(\"/json\", args =>\r\n            {\r\n                var model = new RatPack { FirstName = \"Andy\" };\r\n                return this.Response.AsJson(model);\r\n            });\r\n\r\n            Get(\"/xml\", args =>\r\n            {\r\n                var model = new RatPack { FirstName = \"Andy\" };\r\n                return this.Response.AsXml(model);\r\n            });\r\n\r\n            Get(\"/session\", args =>\r\n            {\r\n                var value = Session[\"moo\"] ?? \"\";\r\n\r\n                var output = \"Current session value is: \" + value;\r\n\r\n                if (string.IsNullOrEmpty(value.ToString()))\r\n                {\r\n                    Session[\"moo\"] = \"I've created a session!\";\r\n                }\r\n\r\n                return output;\r\n            });\r\n\r\n            Get(\"/sessionObject\", args =>\r\n            {\r\n                var value = Session[\"baa\"] ?? \"null\";\r\n\r\n                var output = \"Current session value is: \" + value;\r\n\r\n                if (value.ToString() == \"null\")\r\n                {\r\n                    Session[\"baa\"] = new Payload(27, true, \"some random string value\");\r\n                }\r\n\r\n                return output;\r\n            });\r\n\r\n            Get(\"/error\", args =>\r\n            {\r\n                throw new NotSupportedException(\"This is an exception thrown in a route.\");\r\n                return 500;\r\n            });\r\n\r\n            Get(\"/customErrorHandler\", args =>\r\n            {\r\n                return HttpStatusCode.ImATeapot;\r\n            });\r\n\r\n            Get(\"/csrf\", args =>\r\n            {\r\n                return this.View[\"csrf\", new { Blurb = \"CSRF without an expiry using the 'session' token\" }];\r\n            });\r\n\r\n            Post(\"/csrf\", args =>\r\n            {\r\n                this.ValidateCsrfToken();\r\n\r\n                return string.Format(\"Hello {0}!\", this.Request.Form.Name);\r\n            });\r\n\r\n            Get(\"/csrfWithExpiry\", args =>\r\n            {\r\n                // Create a new one because we have an expiry to check\r\n                this.CreateNewCsrfToken();\r\n\r\n                return this.View[\"csrf\", new { Blurb = \"You have 20 seconds to submit the page.. TICK TOCK :-)\" }];\r\n            });\r\n\r\n            Post(\"/csrfWithExpiry\", args =>\r\n            {\r\n                this.ValidateCsrfToken(TimeSpan.FromSeconds(20));\r\n\r\n                return string.Format(\"Hello {0}!\", this.Request.Form.Name);\r\n            });\r\n\r\n            Get(\"/viewNotFound\", args => {\r\n                return View[\"I-do-not-exist\"];\r\n            });\r\n\r\n            Get(\"/fileupload\", args =>\r\n            {\r\n                return View[\"FileUpload\", new { Posted = \"Nothing\" }];\r\n            });\r\n\r\n            Post(\"/fileupload\", args =>\r\n            {\r\n                var file = this.Request.Files.FirstOrDefault();\r\n\r\n                string fileDetails = \"Nothing\";\r\n\r\n                if (file != null)\r\n                {\r\n                    fileDetails = string.Format(\"{3} - {0} ({1}) {2}bytes\", file.Name, file.ContentType, file.Value.Length, file.Key);\r\n                }\r\n\r\n                return View[\"FileUpload\", new { Posted = fileDetails }];\r\n            });\r\n\r\n            Get(\r\n                name: \"NamedRoute\",\r\n                path: \"/namedRoute\",\r\n                action: args =>\r\n                {\r\n                    return \"I am a named route!\";\r\n                });\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Metadata/MainMetadataModule.cs",
    "content": "﻿namespace Nancy.Demo.Hosting.Aspnet.Metadata\r\n{\r\n    using Nancy.Metadata.Modules;\r\n\r\n    public class MainMetadataModule : MetadataModule<MyUberRouteMetadata>\r\n    {\r\n        public MainMetadataModule()\r\n        {\r\n            Describe[\"NamedRoute\"] = desc =>\r\n                {\r\n                    return new MyUberRouteMetadata(desc.Method, desc.Path)\r\n                        {\r\n                            SuperDescription = \"Returns the string \\\"I am a named route!\\\"\",\r\n                            CodeSample = \"Get[\\\"NamedRoute\\\", \\\"/namedRoute\\\"] = _ => \\\"I am a named route!\\\";\"\r\n                        };\r\n                };\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Metadata/MyUberRouteMetadata.cs",
    "content": "﻿namespace Nancy.Demo.Hosting.Aspnet.Metadata\r\n{\r\n    public class MyUberRouteMetadata : MyRouteMetadata\r\n    {\r\n        public MyUberRouteMetadata(string method, string path)\r\n            : base(method, path)\r\n        {\r\n        }\r\n\r\n        public string SuperDescription { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Models/Payload.cs",
    "content": "namespace Nancy.Demo.Hosting.Aspnet.Models\r\n{\r\n    using System;\r\n\r\n    [Serializable]\r\n    public class Payload : IEquatable<Payload>\r\n    {\r\n        public int IntValue { get; private set; }\r\n\r\n        public bool BoolValue { get; private set; }\r\n\r\n        public string StringValue { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"T:System.Object\"/> class.\r\n        /// </summary>\r\n        public Payload(int intValue, bool boolValue, string stringValue)\r\n        {\r\n            this.IntValue = intValue;\r\n            this.BoolValue = boolValue;\r\n            this.StringValue = stringValue;\r\n        }\r\n\r\n        public bool Equals(Payload other)\r\n        {\r\n            if (ReferenceEquals(null, other))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            if (ReferenceEquals(this, other))\r\n            {\r\n                return true;\r\n            }\r\n\r\n            return other.IntValue == this.IntValue && other.BoolValue.Equals(this.BoolValue) && Equals(other.StringValue, this.StringValue);\r\n        }\r\n\r\n        public override bool Equals(object obj)\r\n        {\r\n            if (ReferenceEquals(null, obj))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            if (ReferenceEquals(this, obj))\r\n            {\r\n                return true;\r\n            }\r\n\r\n            return obj.GetType() == typeof(Payload) && this.Equals((Payload)obj);\r\n        }\r\n\r\n        public override int GetHashCode()\r\n        {\r\n            unchecked\r\n            {\r\n                var result = this.IntValue;\r\n                result = (result * 397) ^ this.BoolValue.GetHashCode();\r\n                result = (result * 397) ^ (this.StringValue != null ? this.StringValue.GetHashCode() : 0);\r\n                return result;\r\n            }\r\n        }\r\n\r\n        public static bool operator ==(Payload left, Payload right)\r\n        {\r\n            return Equals(left, right);\r\n        }\r\n\r\n        public static bool operator !=(Payload left, Payload right)\r\n        {\r\n            return !Equals(left, right);\r\n        }\r\n\r\n        public override string ToString()\r\n        {\r\n            return string.Format(\"{0},{1},{2}\", this.StringValue, this.IntValue, this.BoolValue);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Models/RatPack.cs",
    "content": "﻿namespace Nancy.Demo.Hosting.Aspnet.Models\r\n{\r\n    public class RatPack\r\n    {\r\n        public string FirstName { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Models/RatPackWithDependencyText.cs",
    "content": "﻿namespace Nancy.Demo.Hosting.Aspnet.Models\r\n{\r\n    public class RatPackWithDependencyText : RatPack\r\n    {\r\n        public string ApplicationDependencyText { get; set; }\r\n\r\n        public string RequestDependencyText { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Models/Razor2.cs",
    "content": "﻿namespace Nancy.Demo.Hosting.Aspnet.Models\r\n{\r\n    public class Razor2\r\n    {\r\n        public string FirstName { get; set; }\r\n\r\n        public string NotNullOne { get; set; }\r\n\r\n        public string NotNullTwo { get; set; }\r\n\r\n        public string NullOne { get; set; }\r\n\r\n        public string NullTwo { get; set; }\r\n\r\n        public bool FalseBool { get; set; }\r\n\r\n        public bool TrueBool { get; set; }\r\n\r\n        public Razor2()\r\n        {\r\n            this.FirstName = \"Razor2\";\r\n            this.NotNullOne = \"NotNullOne\";\r\n            this.NotNullTwo = \"NotNullTwo\";\r\n            this.TrueBool = true;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Models/SomeViewModel.cs",
    "content": "namespace Nancy.Demo.Hosting.Aspnet.Models\r\n{\r\n    public class SomeViewModel\r\n    {\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/MyConfig.cs",
    "content": "namespace Nancy.Demo.Hosting.Aspnet\r\n{\r\n    /// <summary>\r\n    /// Sample custom configuration type. It is good practise (but not required)\r\n    /// to make your config objects immutable.\r\n    /// </summary>\r\n    public class MyConfig\r\n    { \r\n        public MyConfig(string value)\r\n        {\r\n            this.Value = value;\r\n        }\r\n\r\n        public string Value { get; private set; }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/MyConfigExtensions.cs",
    "content": "﻿namespace Nancy.Demo.Hosting.Aspnet\r\n{\r\n    using Nancy.Configuration;\r\n\r\n    /// <summary>\r\n    /// Illustrates how you can create custom environment configurations by hanging\r\n    /// extension methods on INancyEnvironment and sticking custom configuration\r\n    /// objects into environment.\r\n    /// </summary>\r\n    public static class MyConfigExtensions\r\n    {\r\n        public static void MyConfig(this INancyEnvironment environment, string value)\r\n        {\r\n            environment.AddValue(\r\n                typeof(MyConfig).FullName, // Using the full type name of the type to avoid collisions\r\n                new MyConfig(value));\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Nancy.Demo.Hosting.Aspnet.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\r\n  <PropertyGroup>\r\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\r\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\r\n    <SchemaVersion>2.0</SchemaVersion>\r\n    <ProjectGuid>{E127FED3-01C0-41BA-BF83-D8DCDD827D6A}</ProjectGuid>\r\n    <ProjectTypeGuids>{349C5851-65DF-11DA-9384-00065B846F21};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>\r\n    <OutputType>Library</OutputType>\r\n    <AppDesignerFolder>Properties</AppDesignerFolder>\r\n    <RootNamespace>Nancy.Demo.Hosting.Aspnet</RootNamespace>\r\n    <AssemblyName>Nancy.Demo.Hosting.Aspnet</AssemblyName>\r\n    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\r\n    <UseIISExpress>true</UseIISExpress>\r\n    <OldToolsVersion>4.0</OldToolsVersion>\r\n    <IISExpressAnonymousAuthentication>enabled</IISExpressAnonymousAuthentication>\r\n    <IISExpressWindowsAuthentication>enabled</IISExpressWindowsAuthentication>\r\n    <IISExpressUseClassicPipelineMode>false</IISExpressUseClassicPipelineMode>\r\n    <IISExpressSSLPort />\r\n    <UseGlobalApplicationHostFile />\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <DebugType>full</DebugType>\r\n    <Optimize>false</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\r\n    <DebugType>pdbonly</DebugType>\r\n    <Optimize>true</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoDebug|AnyCPU'\">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <DebugType>full</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.Hosting.Aspnet.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Optimize>false</Optimize>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoRelease|AnyCPU'\">\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <Optimize>true</Optimize>\r\n    <DebugType>pdbonly</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.Hosting.Aspnet.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <ItemGroup>\r\n    <Reference Include=\"Microsoft.CodeAnalysis, Version=1.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL\">\r\n      <HintPath>..\\..\\packages\\Microsoft.CodeAnalysis.Common.1.1.1\\lib\\net45\\Microsoft.CodeAnalysis.dll</HintPath>\r\n      <Private>True</Private>\r\n    </Reference>\r\n    <Reference Include=\"Microsoft.CodeAnalysis.CSharp, Version=1.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL\">\r\n      <HintPath>..\\..\\packages\\Microsoft.CodeAnalysis.CSharp.1.1.1\\lib\\net45\\Microsoft.CodeAnalysis.CSharp.dll</HintPath>\r\n      <Private>True</Private>\r\n    </Reference>\r\n    <Reference Include=\"Microsoft.CSharp\" />\r\n    <Reference Include=\"System\" />\r\n    <Reference Include=\"System.Collections.Immutable, Version=1.1.37.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL\">\r\n      <HintPath>..\\..\\packages\\System.Collections.Immutable.1.1.37\\lib\\dotnet\\System.Collections.Immutable.dll</HintPath>\r\n      <Private>True</Private>\r\n    </Reference>\r\n    <Reference Include=\"System.Data\" />\r\n    <Reference Include=\"System.Drawing\" />\r\n    <Reference Include=\"System.Reflection.Metadata, Version=1.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL\">\r\n      <HintPath>..\\..\\packages\\System.Reflection.Metadata.1.1.0\\lib\\dotnet5.2\\System.Reflection.Metadata.dll</HintPath>\r\n      <Private>True</Private>\r\n    </Reference>\r\n    <Reference Include=\"System.Web\" />\r\n    <Reference Include=\"System.Xml\" />\r\n    <Reference Include=\"System.Configuration\" />\r\n    <Reference Include=\"System.Xml.Linq\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Content\\face.png\" />\r\n    <Content Include=\"Content\\main.css\" />\r\n    <Content Include=\"Content\\scripts.js\" />\r\n    <Content Include=\"Views\\razor-error.cshtml\" />\r\n    <Content Include=\"Views\\razor-layout-error.cshtml\" />\r\n    <Content Include=\"Views\\negotiatedview.cshtml\" />\r\n    <Content Include=\"Views\\razor2.cshtml\" />\r\n    <Content Include=\"Views\\nustachePartial.nustache\" />\r\n    <Content Include=\"Views\\uber-meta.cshtml\" />\r\n    <Content Include=\"packages.config\" />\r\n    <None Include=\"Views\\FileUpload.sshtml\">\r\n      <SubType>Designer</SubType>\r\n    </None>\r\n    <None Include=\"Views\\interactive-diags-results.sshtml\" />\r\n    <None Include=\"Views\\interactive-diags-methods.sshtml\" />\r\n    <None Include=\"Views\\interactive-diags.sshtml\" />\r\n    <Content Include=\"Views\\javascript.html\" />\r\n    <Content Include=\"Views\\static.html\" />\r\n    <Content Include=\"Web.config\">\r\n      <SubType>Designer</SubType>\r\n    </Content>\r\n    <Content Include=\"Web.Debug.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n    <Content Include=\"Web.Release.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Compile Include=\"..\\..\\SharedAssemblyInfo.cs\">\r\n      <Link>Properties\\SharedAssemblyInfo.cs</Link>\r\n    </Compile>\r\n    <Compile Include=\"ApplicationDependencyClass.cs\" />\r\n    <Compile Include=\"CustomStatusHandler.cs\" />\r\n    <Compile Include=\"DefaultRouteMetadataProvider.cs\" />\r\n    <Compile Include=\"HereBeAResponseYouScurvyDog.cs\" />\r\n    <Compile Include=\"DemoBootstrapper.cs\" />\r\n    <Compile Include=\"DependencyModule.cs\" />\r\n    <Compile Include=\"IApplicationDependency.cs\" />\r\n    <Compile Include=\"IRequestDependency.cs\" />\r\n    <Compile Include=\"MainModule.cs\" />\r\n    <Compile Include=\"Metadata\\MainMetadataModule.cs\" />\r\n    <Compile Include=\"Metadata\\MyUberRouteMetadata.cs\" />\r\n    <Compile Include=\"Models\\Payload.cs\" />\r\n    <Compile Include=\"Models\\RatPack.cs\" />\r\n    <Compile Include=\"Models\\RatPackWithDependencyText.cs\" />\r\n    <Compile Include=\"Models\\Razor2.cs\" />\r\n    <Compile Include=\"Models\\SomeViewModel.cs\" />\r\n    <Compile Include=\"MyConfig.cs\" />\r\n    <Compile Include=\"MyConfigExtensions.cs\" />\r\n    <Compile Include=\"Piratizer4000.cs\" />\r\n    <Compile Include=\"PngSerializer.cs\" />\r\n    <Compile Include=\"RequestDependencyClass.cs\" />\r\n    <Compile Include=\"Resources\\Menu.Designer.cs\">\r\n      <AutoGen>True</AutoGen>\r\n      <DesignTime>True</DesignTime>\r\n      <DependentUpon>Menu.resx</DependentUpon>\r\n    </Compile>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Views\\razor.cshtml\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.Hosting.Aspnet.MSBuild\\Nancy.Hosting.Aspnet.csproj\">\r\n      <Project>{15B7F794-0BB2-4B66-AD78-4A951F1209B2}</Project>\r\n      <Name>Nancy.Hosting.Aspnet</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.Metadata.Modules.MSBuild\\Nancy.Metadata.Modules.csproj\">\r\n      <Project>{DC8AAA8B-7FD0-47C4-9413-3CC94088BCC4}</Project>\r\n      <Name>Nancy.Metadata.Modules</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.ViewEngines.DotLiquid.MSBuild\\Nancy.ViewEngines.DotLiquid.csproj\">\r\n      <Project>{B795886D-9D70-45B1-BFB5-AD54CBC9A447}</Project>\r\n      <Name>Nancy.ViewEngines.DotLiquid</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.ViewEngines.Nustache.MSBuild\\Nancy.ViewEngines.Nustache.csproj\">\r\n      <Project>{A1A9E636-A37C-4170-B2E4-99D4F69B415D}</Project>\r\n      <Name>Nancy.ViewEngines.Nustache</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.ViewEngines.Razor.MSBuild\\Nancy.ViewEngines.Razor.csproj\">\r\n      <Project>{2c6f51df-015c-4db6-b44c-0e5e4f25e2a9}</Project>\r\n      <Name>Nancy.ViewEngines.Razor</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.ViewEngines.Spark.MSBuild\\Nancy.ViewEngines.Spark.csproj\">\r\n      <Project>{4B7E35DF-1569-4346-B180-A09615723095}</Project>\r\n      <Name>Nancy.ViewEngines.Spark</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.MSBuild\\Nancy.csproj\">\r\n      <Project>{34576216-0DCA-4B0F-A0DC-9075E75A676F}</Project>\r\n      <Name>Nancy</Name>\r\n    </ProjectReference>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Views\\someview.cshtml\" />\r\n    <Content Include=\"Views\\razor-layout.cshtml\" />\r\n    <None Include=\"Views\\anon.spark\" />\r\n    <Content Include=\"Views\\csrf.cshtml\" />\r\n    <Content Include=\"Views\\razor-strong.cshtml\" />\r\n    <Content Include=\"Views\\razor-divzero.cshtml\" />\r\n    <None Include=\"Views\\razor-strong.vbhtml\" />\r\n    <None Include=\"Views\\dot.liquid\" />\r\n    <Content Include=\"Views\\razor-dependency.cshtml\" />\r\n    <Content Include=\"Views\\razor-simple.cshtml\" />\r\n    <None Include=\"Views\\nustache.nustache\" />\r\n    <Content Include=\"Views\\meta.cshtml\" />\r\n    <None Include=\"Views\\routes.cshtml\" />\r\n    <None Include=\"Views\\spark.spark\" />\r\n    <None Include=\"Views\\ssve.sshtml\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <EmbeddedResource Include=\"Resources\\Menu.resx\">\r\n      <Generator>ResXFileCodeGenerator</Generator>\r\n      <LastGenOutput>Menu.Designer.cs</LastGenOutput>\r\n    </EmbeddedResource>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Analyzer Include=\"..\\..\\packages\\Microsoft.CodeAnalysis.Analyzers.1.1.0\\analyzers\\dotnet\\cs\\Microsoft.CodeAnalysis.Analyzers.dll\" />\r\n    <Analyzer Include=\"..\\..\\packages\\Microsoft.CodeAnalysis.Analyzers.1.1.0\\analyzers\\dotnet\\cs\\Microsoft.CodeAnalysis.CSharp.Analyzers.dll\" />\r\n  </ItemGroup>\r\n  <PropertyGroup>\r\n    <VisualStudioVersion Condition=\"'$(VisualStudioVersion)' == ''\">10.0</VisualStudioVersion>\r\n    <VSToolsPath Condition=\"'$(VSToolsPath)' == ''\">$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)</VSToolsPath>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\r\n  <Import Project=\"$(VSToolsPath)\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"'$(VSToolsPath)' != ''\" />\r\n  <Import Project=\"$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v10.0\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"false\" />\r\n  <ProjectExtensions>\r\n    <VisualStudio>\r\n      <FlavorProperties GUID=\"{349C5851-65DF-11DA-9384-00065B846F21}\">\r\n        <WebProjectProperties>\r\n          <UseIIS>True</UseIIS>\r\n          <AutoAssignPort>False</AutoAssignPort>\r\n          <DevelopmentServerPort>40965</DevelopmentServerPort>\r\n          <DevelopmentServerVPath>/NancyTest/</DevelopmentServerVPath>\r\n          <IISUrl>http://localhost:59017/</IISUrl>\r\n          <NTLMAuthentication>False</NTLMAuthentication>\r\n          <UseCustomServer>False</UseCustomServer>\r\n          <CustomServerUrl>\r\n          </CustomServerUrl>\r\n          <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>\r\n        </WebProjectProperties>\r\n      </FlavorProperties>\r\n    </VisualStudio>\r\n    <MonoDevelop>\r\n      <Properties VerifyCodeBehindFields=\"true\" VerifyCodeBehindEvents=\"true\">\r\n        <XspParameters Port=\"8080\" Address=\"127.0.0.1\" SslMode=\"None\" SslProtocol=\"Default\" KeyType=\"None\" CertFile=\"\" KeyFile=\"\" PasswordOptions=\"None\" Password=\"\" Verbose=\"true\" />\r\n      </Properties>\r\n    </MonoDevelop>\r\n  </ProjectExtensions>\r\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r\n       Other similar extension points exist, see Microsoft.Common.targets.\r\n  <Target Name=\"BeforeBuild\">\r\n  </Target>\r\n  <Target Name=\"AfterBuild\">\r\n  </Target>\r\n  -->\r\n</Project>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Piratizer4000.cs",
    "content": "namespace Yarrrr\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Pirate dictionary be plundered from Davie Reed ( http://nifty.stanford.edu/2004/TalkLikeAPirate/pirate3.html )\r\n    /// Yarrr!\r\n    /// </summary>\r\n    public static class HereBePiratesYarrr\r\n    {\r\n        public static string ToSentenceCase(this string input)\r\n        {\r\n            return String.Format(\"{0}{1}\", input.Substring(0, 1).ToUpper(), input.Substring(1));\r\n        }\r\n\r\n        private static readonly Dictionary<string, string> lowerSubstitutions;\r\n        private static readonly Dictionary<string, string> sentenceCaseSubstitutions;\r\n\r\n        static HereBePiratesYarrr()\r\n        {\r\n            lowerSubstitutions =\r\n                new Dictionary<string, string>\r\n                {\r\n                    { \"hello\", \"ahoy\" },\r\n                    { \"hi\", \"yo-ho-ho\" },\r\n                    { \"pardon me\", \"avast\" },\r\n                    { \"excuse me\", \"arrr\" },\r\n                    { \"yes\", \"aye\" },\r\n                    { \"my\", \"me\" },\r\n                    { \"friend\", \"me bucko\" },\r\n                    { \"sir\", \"matey\" },\r\n                    { \"madam\", \"proud beauty\" },\r\n                    { \"miss\", \"comely wench\" },\r\n                    { \"stranger\", \"scurvy dog\" },\r\n                    { \"officer\", \"foul blaggart\" },\r\n                    { \"where\", \"whar\" },\r\n                    { \"is\", \"be\" },\r\n                    { \"are\", \"be\" },\r\n                    { \"am\", \"be\" },\r\n                    { \"the\", \"th'\" },\r\n                    { \"you\", \"ye\" },\r\n                    { \"your\", \"yer\" },\r\n                    { \"tell\", \"be tellin'\" },\r\n                    { \"know\", \"be knowin'\" },\r\n                    { \"how far\", \"how many leagues\" },\r\n                    { \"old\", \"barnacle-covered\" },\r\n                    { \"attractive\", \"comely\" },\r\n                    { \"happy\", \"grog-filled\" },\r\n                    { \"quickly\", \"smartly\" },\r\n                    { \"nearby\", \"broadside\" },\r\n                    { \"restroom\", \"head\" },\r\n                    { \"restaurant\", \"galley\" },\r\n                    { \"hotel\", \"fleabag inn\" },\r\n                    { \"pub\", \"Skull & Scuppers\" },\r\n                    { \"mall\", \"market\" },\r\n                    { \"bank\", \"buried treasure\" },\r\n                    { \"die\", \"visit Davey Jones' Locker\" },\r\n                    { \"died\", \"visited Davey Jones' Locker\" },\r\n                    { \"kill\", \"keel-haul\" },\r\n                    { \"killed\", \"keel-hauled\" },\r\n                    { \"sleep\", \"take a caulk\" },\r\n                    { \"stupid\", \"addled\" },\r\n                    { \"after\", \"aft\" },\r\n                    { \"stop\", \"belay\" },\r\n                    { \"nonsense\", \"bilge\" },\r\n                    { \"ocean\", \"briny deep\" },\r\n                    { \"song\", \"shanty\" },\r\n                    { \"money\", \"doubloons\" },\r\n                    { \"food\", \"grub\" },\r\n                    { \"nose\", \"prow\" },\r\n                    { \"leave\", \"weigh anchor\" },\r\n                    { \"cheat\", \"hornswaggle\" },\r\n                    { \"forward\", \"fore\" },\r\n                    { \"child\", \"sprog\" },\r\n                    { \"children\", \"sprogs\" },\r\n                    { \"sailor\", \"swab\" },\r\n                    { \"lean\", \"careen\" },\r\n                    { \"find\", \"come across\" },\r\n                    { \"mother\", \"dear ol' mum, bless her black soul\" },\r\n                    { \"drink\", \"barrel o' rum\" },\r\n                    { \"of\", \"o'\" },\r\n                    { \"!\", \"YARRR!\" },\r\n                };\r\n\r\n            sentenceCaseSubstitutions = new Dictionary<string, string>(lowerSubstitutions.Count);\r\n            foreach (var substitution in lowerSubstitutions)\r\n            {\r\n                sentenceCaseSubstitutions.Add(substitution.Key.ToSentenceCase(), substitution.Key.ToSentenceCase());\r\n            }\r\n        }\r\n\r\n        public static string Piratize(this string boringEnglishString)\r\n        {\r\n            // TODO - turn this into a non-horrible regex ;-)\r\n            return lowerSubstitutions.Aggregate(boringEnglishString, (current, substitution) => current.Replace(substitution.Key, substitution.Value));\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/PngSerializer.cs",
    "content": "﻿namespace Nancy.Demo.Hosting.Aspnet\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Drawing;\r\n    using System.Drawing.Imaging;\r\n    using System.IO;\r\n    using Nancy.Responses.Negotiation;\r\n\r\n    /// <summary>\r\n    /// If you request /negotiated with an accept header with the value image/png you will get an image back\r\n    /// </summary>\r\n    public class PngSerializer : ISerializer\r\n    {\r\n        private readonly IRootPathProvider rootPathProvider;\r\n\r\n        public PngSerializer(IRootPathProvider rootPathProvider)\r\n        {\r\n            this.rootPathProvider = rootPathProvider;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Whether the serializer can serialize the content type\r\n        /// </summary>\r\n        /// <param name=\"mediaRange\">Content type to serialise</param>\r\n        /// <returns>True if supported, false otherwise</returns>\r\n        public bool CanSerialize(MediaRange mediaRange)\r\n        {\r\n            return mediaRange.Matches(\"image/png\");\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the list of extensions that the serializer can handle.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> of extensions if any are available, otherwise an empty enumerable.</value>\r\n        public IEnumerable<string> Extensions\r\n        {\r\n            get { yield return \"png\"; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Serialize the given model with the given contentType\r\n        /// </summary>\r\n        /// <param name=\"mediaRange\">Content type to serialize into</param>\r\n        /// <param name=\"model\">Model to serialize</param>\r\n        /// <param name=\"outputStream\">Output stream to serialize to</param>\r\n        /// <returns>Serialised object</returns>\r\n        public void Serialize<TModel>(MediaRange mediaRange, TModel model, Stream outputStream)\r\n        {\r\n            var path =\r\n                Path.Combine(this.rootPathProvider.GetRootPath(), \"content/face.png\");\r\n\r\n            var face =\r\n                Image.FromFile(path);\r\n\r\n            face.Save(outputStream, ImageFormat.Png);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/README.txt",
    "content": "﻿"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/RequestDependencyClass.cs",
    "content": "namespace Nancy.Demo.Hosting.Aspnet\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// A module dependency that will have a per-request lifetime scope.\r\n    /// </summary>\r\n    public class RequestDependencyClass : IRequestDependency\r\n    {\r\n        private readonly DateTime currentDateTime;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the RequestDependencyClass class.\r\n        /// </summary>\r\n        public RequestDependencyClass()\r\n        {\r\n            this.currentDateTime = DateTime.Now;\r\n        }\r\n\r\n        public string GetContent()\r\n\t\t{\r\n            return \"This is a per-request dependency, constructed on: \" + this.currentDateTime.ToLongTimeString();\r\n\t\t}\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Resources/Menu.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\r\n// <auto-generated>\r\n//     This code was generated by a tool.\r\n//     Runtime Version:4.0.30319.0\r\n//\r\n//     Changes to this file may cause incorrect behavior and will be lost if\r\n//     the code is regenerated.\r\n// </auto-generated>\r\n//------------------------------------------------------------------------------\r\n\r\nnamespace Nancy.Demo.Hosting.Aspnet.Resources {\r\n    using System.CodeDom.Compiler;\r\n    using System.ComponentModel;\r\n    using System.Diagnostics;\r\n    using System.Diagnostics.CodeAnalysis;\r\n    using System.Globalization;\r\n    using System.Resources;\r\n    using System.Runtime.CompilerServices;\r\n\r\n    /// <summary>\r\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\r\n    /// </summary>\r\n    // This class was auto-generated by the StronglyTypedResourceBuilder\r\n    // class via a tool like ResGen or Visual Studio.\r\n    // To add or remove a member, edit your .ResX file then rerun ResGen\r\n    // with the /str option, or rebuild your VS project.\r\n    [GeneratedCode(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\r\n    [DebuggerNonUserCode()]\r\n    [CompilerGenerated()]\r\n    internal class Menu {\r\n        \r\n        private static ResourceManager resourceMan;\r\n        \r\n        private static CultureInfo resourceCulture;\r\n        \r\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\r\n        internal Menu() {\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Returns the cached ResourceManager instance used by this class.\r\n        /// </summary>\r\n        [EditorBrowsable(EditorBrowsableState.Advanced)]\r\n        internal static ResourceManager ResourceManager {\r\n            get {\r\n                if (ReferenceEquals(resourceMan, null)) {\r\n                    ResourceManager temp = new ResourceManager(\"Nancy.Demo.Hosting.Aspnet.Resources.Menu\", typeof(Menu).Assembly);\r\n                    resourceMan = temp;\r\n                }\r\n                return resourceMan;\r\n            }\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Overrides the current thread's CurrentUICulture property for all\r\n        ///   resource lookups using this strongly typed resource class.\r\n        /// </summary>\r\n        [EditorBrowsable(EditorBrowsableState.Advanced)]\r\n        internal static CultureInfo Culture {\r\n            get {\r\n                return resourceCulture;\r\n            }\r\n            set {\r\n                resourceCulture = value;\r\n            }\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Looks up a localized string similar to This is the home link.\r\n        /// </summary>\r\n        internal static string Home {\r\n            get {\r\n                return ResourceManager.GetString(\"Home\", resourceCulture);\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Resources/Menu.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<root>\r\n  <!-- \r\n    Microsoft ResX Schema \r\n    \r\n    Version 2.0\r\n    \r\n    The primary goals of this format is to allow a simple XML format \r\n    that is mostly human readable. The generation and parsing of the \r\n    various data types are done through the TypeConverter classes \r\n    associated with the data types.\r\n    \r\n    Example:\r\n    \r\n    ... ado.net/XML headers & schema ...\r\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\r\n    <resheader name=\"version\">2.0</resheader>\r\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\r\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\r\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\r\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\r\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\r\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\r\n    </data>\r\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\r\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\r\n        <comment>This is a comment</comment>\r\n    </data>\r\n                \r\n    There are any number of \"resheader\" rows that contain simple \r\n    name/value pairs.\r\n    \r\n    Each data row contains a name, and value. The row also contains a \r\n    type or mimetype. Type corresponds to a .NET class that support \r\n    text/value conversion through the TypeConverter architecture. \r\n    Classes that don't support this are serialized and stored with the \r\n    mimetype set.\r\n    \r\n    The mimetype is used for serialized objects, and tells the \r\n    ResXResourceReader how to depersist the object. This is currently not \r\n    extensible. For a given mimetype the value must be set accordingly:\r\n    \r\n    Note - application/x-microsoft.net.object.binary.base64 is the format \r\n    that the ResXResourceWriter will generate, however the reader can \r\n    read any of the formats listed below.\r\n    \r\n    mimetype: application/x-microsoft.net.object.binary.base64\r\n    value   : The object must be serialized with \r\n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\r\n            : and then encoded with base64 encoding.\r\n    \r\n    mimetype: application/x-microsoft.net.object.soap.base64\r\n    value   : The object must be serialized with \r\n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\r\n            : and then encoded with base64 encoding.\r\n\r\n    mimetype: application/x-microsoft.net.object.bytearray.base64\r\n    value   : The object must be serialized into a byte array \r\n            : using a System.ComponentModel.TypeConverter\r\n            : and then encoded with base64 encoding.\r\n    -->\r\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\r\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\r\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\r\n      <xsd:complexType>\r\n        <xsd:choice maxOccurs=\"unbounded\">\r\n          <xsd:element name=\"metadata\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\r\n              <xsd:attribute ref=\"xml:space\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"assembly\">\r\n            <xsd:complexType>\r\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"data\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\r\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\r\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\r\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\r\n              <xsd:attribute ref=\"xml:space\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"resheader\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n        </xsd:choice>\r\n      </xsd:complexType>\r\n    </xsd:element>\r\n  </xsd:schema>\r\n  <resheader name=\"resmimetype\">\r\n    <value>text/microsoft-resx</value>\r\n  </resheader>\r\n  <resheader name=\"version\">\r\n    <value>2.0</value>\r\n  </resheader>\r\n  <resheader name=\"reader\">\r\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\r\n  </resheader>\r\n  <resheader name=\"writer\">\r\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\r\n  </resheader>\r\n  <data name=\"Home\" xml:space=\"preserve\">\r\n    <value>This is the home link</value>\r\n  </data>\r\n</root>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/FileUpload.sshtml",
    "content": "﻿<html>\r\n  <head>\r\n    <title>Nancy File Posting Demo</title>\r\n  </head>\r\n  <body>\r\n    <p>You uploaded: @Model.Posted</p>\r\n    <p>\r\n      <form action=\"@Path['~/fileupload']\" method=\"POST\" enctype=\"multipart/form-data\">\r\n        <input name=\"upload\" type=\"file\" size=\"40\"/>\r\n        <input type=\"submit\" value=\"Post!\"/>\r\n      </form>\r\n    </p>\r\n  </body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/anon.spark",
    "content": "﻿<viewdata model=\"dynamic\" />\r\n<html>\r\n<head>\r\n    <title>Spark View Engine Demo</title>\r\n</head>\r\n<body>\r\n    <h1>The name's Spark, ${Model.FirstName} Spark</h1>\r\n    <p>This is a sample Spark view!</p>\r\n</body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/csrf.cshtml",
    "content": "﻿<html>\r\n<head>\r\n    <title>CSRF Demo</title>\r\n</head>\r\n<body>\r\n    <form method=\"POST\">\r\n        <h1>CSRF Test</h1>\r\n        <p>@Model.Blurb</p>\r\n        <input type=\"text\" name=\"Name\"/>\r\n        @Html.AntiForgeryToken();\r\n        <input type=\"submit\"/>\r\n    </form>\r\n</body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/dot.liquid",
    "content": "﻿<html>\r\n<head>\r\n    <title>DotLiquid View Engine Demo</title>\r\n</head>\r\n<body>\r\n    <h1>The name's Liquid, {{ model.name | upcase }} Liquid</h1>\r\n    <p>This is a sample DotLiquid view!</p>\r\n</body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/interactive-diags-methods.sshtml",
    "content": "﻿<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n    <title>Interactive Diagnostics</title>\r\n</head>\r\n<body>\r\n    @Each.Methods\r\n\t\t<form method=\"post\" action=\"@Path['~/diags/interactive/@Model.Name/@Current.MethodName']\">\r\n\t\t\t@Current.ReturnType : @Current.MethodName<br/>\r\n\t\t\t<!-- need recursive each (probably with partials) to get method params in -->\r\n\t\t\t<input type=\"submit\" value=\"Execute\">\r\n\t\t\t<hr/>\r\n\t\t</form>\r\n    @EndEach\r\n</body>\r\n</html>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/interactive-diags-results.sshtml",
    "content": "﻿<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n    <title>Interactive Diagnostics</title>\r\n\r\n\t<script language=\"javascript\" type=\"text/javascript\">\r\n\t\t/**\r\n\t\t * Created by demis.bellot@gmail.com\r\n\t\t * Open Source under the New BSD Licence: https://github.com/AjaxStack/AjaxStack/blob/master/LICENSE\r\n\t\t */\r\n\r\n\t\t//for non-modern browsers i.e: <=IE8\r\n\t\t!window.JSON && document.write(unescape('%3Cscript src=\"\"http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js\"\"%3E%3C/script%3E'));\r\n\r\n\t\tvar cssText =\r\n\t\t  \".jsonreport TABLE { border-collapse:collapse; border: solid 1px #ccc; clear: left; }\\r\\n\" +\r\n\t\t  \".jsonreport TH { text-align: left; padding: 4px 8px; text-shadow: #fff 1px 1px -1px; background: #f1f1f1; white-space:nowrap; cursor:pointer; font-weight: bold; }\\r\\n\" +\r\n\t\t  \".jsonreport TH, .jsonreport TD, .jsonreport TD DT, .jsonreport TD DD { font-size: 13px; font-family: Arial; }\\r\\n\" +\r\n\t\t  \".jsonreport TD { padding: 8px 8px 0 8px; vertical-align: top; }\\r\\n\" +\r\n\t\t  \".jsonreport DL { clear: left; }\\r\\n\" +\r\n\t\t  \".jsonreport DT { margin: 10px 0 5px 0; font: bold 18px Helvetica, Verdana, Arial; width: 200px; clear: left; float: left; display:block; white-space:nowrap; }\\r\\n\" +\r\n\t\t  \".jsonreport DD { margin: 5px 10px; font: 18px Arial; padding: 2px; display: block; float: left; }\\r\\n\" +\r\n\t\t  \".jsonreport DL DL DT { font: bold 16px Arial; }\\r\\n\" +\r\n\t\t  \".jsonreport DL DL DD { font: 16px Arial; }\\r\\n\" +\r\n\t\t  \".jsonreport HR { display:none; }\\r\\n\" +\r\n\t\t  \".jsonreport TD DL HR { display:block; padding: 0; clear: left; border: none; }\\r\\n\" +\r\n\t\t  \".jsonreport TD DL { padding: 4px; margin: 0; height:100%; max-width: 700px; }\\r\\n\" +\r\n\t\t  \".jsonreport DL TD DL DT { padding: 2px; margin: 0 10px 0 0; font-weight: bold; font-size: 13px; width: 120px; overflow: hidden; clear: left; float: left; display:block; }\\r\\n\" +\r\n\t\t  \".jsonreport DL TD DL DD { margin: 0; padding: 2px; font-size: 13px; display: block; float: left; }\\r\\n\" +\r\n\t\t  \".jsonreport TBODY>TR:last-child>TD { padding: 8px; }\\r\\n\" +\r\n\t\t  \".jsonreport THEAD { -webkit-user-select:none; -moz-user-select:none; }\\r\\n\" +\r\n\t\t  \".jsonreport .desc, .jsonreport .asc { background-color: #FAFAD2; }\\r\\n\" +\r\n\t\t  \".jsonreport .desc { background-color: #D4EDC9; }\\r\\n\" +\r\n\t\t  \".jsonreport TH B { display:block; float:right; margin: 0 0 0 5px; width: 0; height: 0; border-left: 5px solid transparent; border-right: 5px solid transparent; border-top: 5px solid #ccc; border-bottom: none; }\\r\\n\" +\r\n\t\t  \".jsonreport .asc B { border-left: 5px solid transparent; border-right: 5px solid transparent; border-top: 5px solid #333; border-bottom: none; }\\r\\n\" +\r\n\t\t  \".jsonreport .desc B { border-left: 5px solid transparent; border-right: 5px solid transparent; border-bottom: 5px solid #333; border-top: none; }\\r\\n\" +\r\n\t\t  \".jsonreport H3 { font-size: 18px; margin: 0 0 10px 0; }\";\r\n\r\n\t\tdocument.write('<style type=\"text/css\">' + cssText + '</style>\\r\\n');\r\n\r\n\t\tif (!_) var _ = {};\r\n\t\t_.jsonreport = (function(){\r\n\t\t\tvar root = this, doc = document,\r\n\t\t\t\t$ = function(id) { return doc.getElementById(id); },\r\n\t\t\t\t$$ = function(sel) { return doc.getElementsByTagName(sel); },\r\n\t\t\t\t$each = function(fn) { for (var i=0,len=this.length; i<len; i++) fn(i, this[i], this); },\r\n\t\t\t\tisIE = /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);\r\n\r\n\t\t\t$.each = function(arr, fn) { $each.call(arr, fn); };\r\n\r\n\t\t\tvar splitCase = function(t) { return typeof t != 'string' ? t : t.replace(/([A-Z]|[0-9]+)/g, ' $1').replace(/_/g,' '); },\r\n\t\t\t\tuniqueKeys = function(m){ var h={}; for (var i=0,len=m.length; i<len; i++) for (var k in m[i]) h[k] = k; return h; },\r\n\t\t\t\tkeys = function(o){ var a=[]; for (var k in o) a.push(k); return a; }\r\n\t\t\tvar tbls = [];\r\n\r\n\t\t\tfunction val(m) {\r\n\t\t\t  if (m == null) return '';\r\n\t\t\t  if (typeof m == 'number') return num(m);\r\n\t\t\t  if (typeof m == 'string') return str(m);\r\n\t\t\t  if (typeof m == 'boolean') return m ? 'true' : 'false';\r\n\t\t\t  return m.length ? arr(m) : obj(m);\r\n\t\t\t}\r\n\t\t\tfunction num(m) { return m; }\r\n\t\t\tfunction str(m) {\r\n\t\t\t  return m.substr(0,6) == '/Date(' ? dfmt(date(m)) : m;\r\n\t\t\t}\r\n\t\t\tfunction date(s) { return new Date(parseFloat(/Date\\(([^)]+)\\)/.exec(s)[1])); }\r\n\t\t\tfunction pad(d) { return d < 10 ? '0'+d : d; }\r\n\t\t\tfunction dfmt(d) { return d.getFullYear() + '/' + pad(d.getMonth() + 1) + '/' + pad(d.getDate()); }\r\n\t\t\tfunction obj(m) {\r\n\t\t\t  var sb = '<dl>';\r\n\t\t\t  for (var k in m) sb += '<dt class=\"ib\">' + splitCase(k) + '</dt><dd>' + val(m[k]) + '</dd>';\r\n\t\t\t  sb += '</dl>';\r\n\t\t\t  return sb;\r\n\t\t\t}\r\n\t\t\tfunction arr(m) {\r\n\t\t\t  if (typeof m[0] == 'string' || typeof m[0] == 'number') return m.join(', ');\r\n\t\t\t  var id=tbls.length, h=uniqueKeys(m);\r\n\t\t\t  var sb = '<table id=\"tbl-' + id + '\"><caption></caption><thead><tr>';\r\n\t\t\t  tbls.push(m);\r\n\t\t\t  var i=0;\r\n\t\t\t  for (var k in h) sb += '<th id=\"h-' + id + '-' + (i++) + '\"><b></b>' + splitCase(k) + '</th>';\r\n\t\t\t  sb += '</tr></thead><tbody>' + makeRows(h,m) + '</tbody></table>';\r\n\t\t\t  return sb;\r\n\t\t\t}\r\n\r\n\t\t\tfunction makeRows(h,m) {\r\n\t\t\t  var sb = '';\r\n\t\t\t  for (var r=0,len=m.length; r<len; r++) {\r\n\t\t\t\tsb += '<tr>';\r\n\t\t\t\tvar row = m[r];\r\n\t\t\t\tfor (var k in h) sb += '<td>' + val(row[k]) + '</td>';\r\n\t\t\t\tsb += '</tr>';\r\n\t\t\t  }\r\n\t\t\t  return sb;\r\n\t\t\t}\r\n\r\n\t\t\tfunction setTableBody(tbody, html) {\r\n\t\t\t  if (!isIE) { tbody.innerHTML = html; return; }\r\n\t\t\t  var temp = tbody.ownerDocument.createElement('div');\r\n\t\t\t  temp.innerHTML = '<table>' + html + '</table>';\r\n\t\t\t  tbody.parentNode.replaceChild(temp.firstChild.firstChild, tbody);\r\n\t\t\t}\r\n\r\n\t\t\tfunction clearSel() {\r\n\t\t\t  if (doc.selection && doc.selection.empty) doc.selection.empty();\r\n\t\t\t  else if(root.getSelection) {\r\n\t\t\t\tvar sel=root.getSelection();\r\n\t\t\t\tif (sel && sel.removeAllRanges) sel.removeAllRanges();\r\n\t\t\t  }\r\n\t\t\t}\r\n\r\n\t\t\tfunction cmp(v1, v2){\r\n\t\t\t  var f1, f2, f1=parseFloat(v1), f2=parseFloat(v2);\r\n\t\t\t  if (!isNaN(f1) && !isNaN(f2)) v1=f1, v2=f2;\r\n\t\t\t  if (typeof v1 == 'string' && v1.substr(0,6) == '/Date(') v1=date(v1), v2=date(v2);\r\n\t\t\t  if (v1 == v2) return 0;\r\n\t\t\t  return v1 > v2 ? 1 : -1;\r\n\t\t\t}\r\n\r\n\t\t\tfunction enc(html) {\r\n\t\t\t  if (typeof html != 'string') return html;\r\n\t\t\t  return html.replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/\"/g,'&quot;');\r\n\t\t\t}\r\n\r\n\t\t\tfunction addEvent(obj, type, fn) {\r\n\t\t\t  if ( obj.attachEvent ) {\r\n\t\t\t\tobj['e'+type+fn] = fn;\r\n\t\t\t\tobj[type+fn] = function(){obj['e'+type+fn]( root.event );}\r\n\t\t\t\tobj.attachEvent( 'on'+type, obj[type+fn] );\r\n\t\t\t  } else\r\n\t\t\t\tobj.addEventListener( type, fn, false );\r\n\t\t\t}\r\n\r\n\t\t\taddEvent(doc, 'click', function (e) {\r\n\t\t\t\tvar e = e || root.event, el = e.target || e.srcElement, cls = el.className;\r\n\t\t\t\tif (el.tagName == 'B') el = el.parentNode;\r\n\t\t\t\tif (el.tagName != 'TH') return;\r\n\t\t\t\tel.className = cls == 'asc' ? 'desc' : (cls == 'desc' ? null : 'asc');\r\n\t\t\t\t$.each($$('TH'), function(i,th){ if (th == el) return; th.className = null; });\r\n\t\t\t\tclearSel();\r\n\t\t\t\tvar ids=el.id.split('-'), tId=ids[1], cId=ids[2];\r\n\t\t\t\tvar tbl=tbls[tId].slice(0), h=uniqueKeys(tbl), col=keys(h)[cId], tbody=el.parentNode.parentNode.nextSibling;\r\n\t\t\t\tif (!el.className){ setTableBody(tbody, makeRows(h,tbls[tId])); return; }\r\n\t\t\t\tvar d=el.className=='asc'?1:-1;\r\n\t\t\t\ttbl.sort(function(a,b){ return cmp(a[col],b[col]) * d; });\r\n\t\t\t\tsetTableBody(tbody, makeRows(h,tbl));\r\n\t\t\t});\r\n\r\n\t\t\treturn function(json) {\r\n\t\t\t\tvar model = JSON.parse(json);\r\n\t\t\t\treturn val(model);\r\n\t\t\t};\r\n\t\t})();\r\n\r\n\t</script>\r\n</head>\r\n<body>\r\n\t<div class=\"jsonreport\">@Model.Json<div>\r\n\r\n\t<input type=\"hidden\" id=\"json\" value='@Model.Json'/>\r\n\r\n\t<script language=\"javascript\">\r\n\t\tdocument.getElementsByClassName('jsonreport')[0].innerHTML = _.jsonreport(document.getElementById('json').value);\r\n\t</script>\r\n</body>\r\n</html>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/interactive-diags.sshtml",
    "content": "﻿<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n    <title>Interactive Diagnostics</title>\r\n</head>\r\n<body>\r\n    @Each\r\n        <a href=\"@Path['~/diags/interactive/@Current.Name']\">@Current.Name</a>\r\n    @EndEach\r\n</body>\r\n</html>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/javascript.html",
    "content": "﻿<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n    <title>Nancy - Loading Javascripts</title>\r\n    <script src=\"@Path['~/Content/scripts.js'];\" type=\"text/javascript\"></script>\r\n</head>\r\n<body>\r\n    The script on this page was loaded using Nancy.\r\n</body>\r\n</html>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/meta.cshtml",
    "content": "﻿@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<System.Collections.Generic.IEnumerable<Nancy.Demo.Hosting.Aspnet.MyRouteMetadata>>\r\n\r\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n    <title>Route metadata</title>\r\n    <link rel=\"stylesheet\" href='@Url.Content(\"~/content/main.css\")' type=\"text/css\" media=\"screen\"/>\r\n    <link rel=\"stylesheet\" href=\"http://highlightjs.org/static/styles/default.css\" />\r\n\r\n    <script src=\"http://highlightjs.org/static/highlight.pack.js\"></script>\r\n\r\n    <style type=\"text/css\">\r\n\r\n        div.meta>div {\r\n            border: 1px solid #000;\r\n            padding: 8px;\r\n            margin-bottom: 20px;\r\n            width: 800px;\r\n        }\r\n\r\n    </style>\r\n</head>\r\n<body>\r\n\r\n    <h1>Route metadata</h1>\r\n    <p>Below is a list of route metadata that was generated from a custom <strong>IRouteMetadataProvider</strong> implementation</p>\r\n\r\n    <div class=\"meta\">\r\n        @foreach (var meta in @Model)\r\n        {\r\n            <div>\r\n                <h1>(@meta.Method) @meta.Path</h1>\r\n\r\n                <strong>Description:</strong>\r\n                <p>@meta.Description</p>\r\n\r\n                <strong>Valid return status codes:</strong>\r\n                <p>\r\n                    @string.Join(\", \", @meta.ValidStatusCodes)\r\n                </p>\r\n\r\n                <strong>Code sample:</strong>\r\n<pre><code class=\"csharp\">@meta.CodeSample</code></pre>\r\n            </div>\r\n        }\r\n    </div>\r\n    <script>hljs.initHighlightingOnLoad();</script>\r\n</body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/negotiatedview.cshtml",
    "content": "﻿<html>\r\n<head>\r\n    <title>Negotiation Demo</title>\r\n</head>\r\n<body>\r\n    <h1>Hello @Model.FirstName</h1>\r\n\r\n    <p>\r\n        This is a text/html representation of a RatPack model, \r\n        you should be seeing this because you requested text/html either manually or\r\n        via your browser. Try using Fiddler to hit this url and request JSON, or add .json to\r\n        the end of this url.\r\n    </p>\r\n</body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/nustache.nustache",
    "content": "﻿{{>nustachePartial}}\r\nYou have just won ${{value}}!"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/nustachePartial.nustache",
    "content": "﻿Hello {{name}} "
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/razor-dependency.cshtml",
    "content": "﻿<html>\r\n<head>\r\n    <title>Razor View Engine Demo</title>\r\n</head>\r\n<body>\r\n    <h1>Hello @Model.FirstName</h1>\r\n    <p>This is a Razor view..</p>\r\n    <p>@Model.ApplicationDependencyText</p>\r\n    <p>@Model.RequestDependencyText</p>\r\n</body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/razor-divzero.cshtml",
    "content": "﻿@{\r\n    Layout = \"razor-layout.cshtml\";\r\n}\r\n@section Header\r\n{\r\n    <!-- This comment should appear in the header -->\r\n}\r\n<h1>Hello @Model.FirstName</h1>\r\n<p>This is a sample Razor view! @(Model.Number / 0)</p>\r\n@section Footer\r\n{\r\n<p>This is footer content!</p>\r\n    <img src='@Url.Content(\"~/content/face.png\")' alt=\"Face\"/>\r\n}\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/razor-error.cshtml",
    "content": "﻿@{\r\n    Layout = \"razor-layout-error.cshtml\";\r\n}\r\n@section Header\r\n{\r\n    <!-- This comment should appear in the header -->\r\n}\r\n<h1>Hello @Model.FirstName</h1>\r\n<p>This is a sample Razor view!</p>\r\n@section Footer\r\n{\r\n    <p>This is footer content!</p>\r\n<img src='@Url.Content(\"~/content/face.png\")' alt=\"Face\"/>\r\n}\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/razor-layout-error.cshtml",
    "content": "﻿<html>\r\n<head>\r\n    <title>Razor View Engine Demo - @Model.FirstName</title>\r\n    @RenderSection(\"Header\")\r\n</head>\r\n<body>\r\n    <div id=\"body\">@RenderBody()</div>\r\n    <div id=\"Error\">@ThisDoesntExist()</div>\r\n    <div id=\"footer\">@RenderSection(\"Footer\")</div>\r\n    <div id=\"optional\">@RenderSection(\"Optional\", false)</div>\r\n</body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/razor-layout.cshtml",
    "content": "﻿<html>\r\n<head>\r\n    <title>Razor View Engine Demo - @Model.FirstName</title>\r\n    @RenderSection(\"Header\")\r\n</head>\r\n<body>\r\n    <div id=\"body\">@RenderBody()</div>\r\n    <div id=\"footer\">@RenderSection(\"Footer\")</div>\r\n    <div id=\"optional\">@RenderSection(\"Optional\", false)</div>\r\n</body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/razor-simple.cshtml",
    "content": "﻿<html>\r\n<head>\r\n    <title>Razor View Engine Demo</title>\r\n</head>\r\n<body>\r\n    <h1>Hello @Model.FirstName</h1>\r\n    <p>This is a sample Razor view!</p>\r\n    <img src='@Url.Content(\"~/content/face.png\")' alt=\"Face\"/>\r\n</body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/razor-strong.cshtml",
    "content": "﻿@model Nancy.Demo.Hosting.Aspnet.Models.RatPack\r\n<html>\r\n<head>\r\n    <title>Razor View Engine Demo</title>\r\n</head>\r\n<body>\r\n    <h1>Hello @Model.FirstName</h1>\r\n    <p>This is a strongly typed csharp razor view!</p>\r\n    <img src='@Url.Content(\"~/content/face.png\")' alt=\"Face\"/>\r\n</body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/razor-strong.vbhtml",
    "content": "﻿@ModelType Nancy.Demo.Hosting.Aspnet.Models.RatPack\r\n<html>\r\n<head>\r\n    <title>Razor View Engine Demo</title>\r\n</head>\r\n<body>\r\n    <h1>Hello @Model.FirstName</h1>\r\n    <p>This is a strongly typed vb razor view!</p>\r\n    <img src='@Url.Content(\"~/content/face.png\")' alt=\"Face\"/>\r\n</body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/razor.cshtml",
    "content": "﻿@{\r\n    Layout = \"razor-layout.cshtml\";\r\n}\r\n@section Header\r\n{\r\n    <!-- This comment should appear in the header -->\r\n}\r\n<h1>Hello @Model.FirstName</h1>\r\n<p>This is a sample Razor view!</p>\r\n@section Footer\r\n{\r\n<p>This is footer content!</p>\r\n    <img src='@Url.Content(\"~/content/face.png\")' alt=\"Face\"/>\r\n}\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/razor2.cshtml",
    "content": "﻿@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<Nancy.Demo.Hosting.Aspnet.Models.Razor2>\r\n<html>\r\n<head>\r\n    <title>Razor View Engine Demo</title>\r\n</head>\r\n<body>\r\n    <h1>Hello @Model.FirstName</h1>\r\n    <p>This is a sample Razor2 view!</p>\r\n\r\n    <a href=\"/@Model.FirstName\">Test link to @Model.FirstName</a>\r\n    <a href=\"~/@Model.FirstName\">Test link to @Model.FirstName</a>\r\n\r\n    <!-- Auto expanded ~ safepaths -->\r\n    <img src='~/content/face.png' alt=\"Face\"/>\r\n\r\n    <!-- Two null properties should collapse the whole class attribute -->\r\n    <div class=\"@Model.NullOne @Model.NullTwo\"/>\r\n\r\n    <!-- One null property and one non-null should just show the one -->\r\n    <div class=\"@Model.NotNullOne @Model.NullTwo\"/>\r\n\r\n    <!--Two non-null should show both -->\r\n    <div class=\"@Model.NotNullOne @Model.NotNullTwo\"/>\r\n\r\n    <!-- A single bool value of false should collapse the attribute -->\r\n    <input type=\"checkbox\" checked=\"@Model.FalseBool\"/>\r\n\r\n    <!-- A single bool value of true should show the attribute -->\r\n    <input type=\"checkbox\" checked=\"@Model.TrueBool\"/>\r\n</body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/routes.cshtml",
    "content": "﻿<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n    <title>Routes</title>\r\n    <link rel=\"stylesheet\" href='@Url.Content(\"~/content/main.css\")' type=\"text/css\" media=\"screen\"/>\r\n</head>\r\n<body>\r\n\r\n    <h1>Routes</h1>\r\n    <p>Below is a list of all of the currently registered routes in this application</p>\r\n    <ul>\r\n        @foreach (var module in @Model) {\r\n            @foreach (var route in @module.Value) {\r\n                <li><a href='@Url.Content(\"~\" + route.Item2.Path)'>@route.Item2.Path</a></li>\r\n            }\r\n        }\r\n        <li><a href='thiswillgivea404'>404</a></li>\r\n        <li><a href='@Url.Content(\"~/content/face.png\")'>An image</a></li>\r\n        <li><a href='@Url.Content(\"~/moo/face.png\")'>An image using alternative content convention</a></li>\r\n        <li><a href='@Url.Content(\"~/content/main.css\")'>CSS</a></li>\r\n        <li><a href='@Url.Content(\"~/content/scripts.js\")'>Some javascript</a></li>\r\n    </ul>\r\n\r\n</body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/someview.cshtml",
    "content": "﻿<html>\r\n<head>\r\n    <title>Razor View Engine Demo</title>\r\n</head>\r\n<body>\r\n    <h1>Model: @Model.GetType().Name</h1>\r\n    <h1>View: SomeView</h1>\r\n    <p>This is a sample of using the name of the model type to locate the view to render!</p>\r\n</body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/spark.spark",
    "content": "﻿<viewdata model=\"Nancy.Demo.Hosting.Aspnet.Models.RatPack\" />\r\n<html>\r\n<head>\r\n    <title>Spark View Engine Demo</title>\r\n</head>\r\n<body>\r\n    <h1>The name's Spark, ${Model.FirstName} Spark</h1>\r\n    <p>This is a sample Spark view!</p>\r\n    <img src=\"~/content/face.png\" alt=\"Face\" />\r\n</body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/ssve.sshtml",
    "content": "﻿<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n    <title>Super Simple View Engine Demo</title>\r\n</head>\r\n<body>\r\n    <h1>SSVE - so simple, even @Model.FirstName can do it.</h1>\r\n    <p>This is a sample SSVE view!</p>\r\n    <img src=\"@Path['~/Content/face.png'];\" alt=\"Face\"/>\r\n</body>\r\n</html>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/static.html",
    "content": "﻿<html>\r\n<head>\r\n    <title>Static View Engine Demo</title>\r\n</head>\r\n<body>\r\n    <h1>Hello Tina</h1>\r\n    <p>This is a sample static view!</p>\r\n</body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Views/uber-meta.cshtml",
    "content": "﻿@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<System.Collections.Generic.IEnumerable<Nancy.Demo.Hosting.Aspnet.Metadata.MyUberRouteMetadata>>\r\n\r\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n    <title>Route metadata</title>\r\n    <link rel=\"stylesheet\" href='@Url.Content(\"~/content/main.css\")' type=\"text/css\" media=\"screen\"/>\r\n\r\n    <style type=\"text/css\">\r\n\r\n        div.meta>div {\r\n            border: 1px solid #000;\r\n            padding: 8px;\r\n            margin-bottom: 20px;\r\n            width: 800px;\r\n        }\r\n\r\n    </style>\r\n</head>\r\n<body>\r\n    <h1>Route metadata</h1>\r\n    <p>Below is a list of route metadata that was declared within a metadata module.</p>\r\n\r\n    <div class=\"meta\">\r\n        @foreach (var meta in @Model)\r\n        {\r\n            <div>\r\n                <h1>(@meta.Method) @meta.Path</h1>\r\n\r\n                <strong>Super Description:</strong>\r\n                <p>@meta.SuperDescription</p>\r\n\r\n                <strong>Description:</strong>\r\n                <p>@meta.Description</p>\r\n\r\n                <strong>Valid return status codes:</strong>\r\n                <p>\r\n                    @string.Join(\", \", @meta.ValidStatusCodes)\r\n                </p>\r\n\r\n                <strong>Code sample:</strong>\r\n<pre><code class=\"csharp\">@meta.CodeSample</code></pre>\r\n            </div>\r\n        }\r\n    </div>\r\n</body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Web.Debug.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Web.Release.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n    <compilation xdt:Transform=\"RemoveAttributes(debug)\" />\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/Web.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n\r\n<configuration>\r\n  <configSections>\r\n    <section name=\"nancyFx\" type=\"Nancy.Hosting.Aspnet.NancyFxSection\" />\r\n    <section name=\"razor\" type=\"Nancy.ViewEngines.Razor.RazorConfigurationSection\" />\r\n  </configSections>\r\n\r\n  <nancyFx>\r\n    <!-- We can override the bootstrapper inside the config if we don't want to rely on the bootstrapper locator. -->\r\n    <disableoutputbuffer value=\"false\" />\r\n    <bootstrapper assembly=\"Nancy.Demo.Hosting.Aspnet\" type=\"Nancy.Demo.Hosting.Aspnet.DemoBootstrapper\" />\r\n  </nancyFx>\r\n\r\n  <razor disableAutoIncludeModelNamespace=\"false\">\r\n    <assemblies>\r\n      <add assembly=\"System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" />\r\n    </assemblies>\r\n    <namespaces>\r\n      <add namespace=\"System.Xml\" />\r\n    </namespaces>\r\n  </razor>\r\n\r\n  <system.web>\r\n    <compilation debug=\"true\" targetFramework=\"4.0\" />\r\n    <httpHandlers>\r\n      <add verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </httpHandlers>\r\n  </system.web>\r\n\r\n  <system.webServer>\r\n    <modules runAllManagedModulesForAllRequests=\"true\" />\r\n    <validation validateIntegratedModeConfiguration=\"false\" />\r\n    <handlers>\r\n      <add name=\"Nancy\" verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </handlers>\r\n  </system.webServer>\r\n\r\n  <runtime>\r\n    <assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\">\r\n      <dependentAssembly>\r\n        <assemblyIdentity name=\"FSharp.Core\" publicKeyToken=\"b03f5f7f11d50a3a\" culture=\"neutral\" />\r\n        <bindingRedirect oldVersion=\"0.0.0.0-2.0.0.0\" newVersion=\"2.0.0.0\" />\r\n      </dependentAssembly>\r\n    </assemblyBinding>\r\n  </runtime>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Aspnet/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<packages>\r\n  <package id=\"Microsoft.CodeAnalysis.Analyzers\" version=\"1.1.0\" targetFramework=\"net45\" />\r\n  <package id=\"Microsoft.CodeAnalysis.Common\" version=\"1.1.1\" targetFramework=\"net45\" />\r\n  <package id=\"Microsoft.CodeAnalysis.CSharp\" version=\"1.1.1\" targetFramework=\"net45\" />\r\n  <package id=\"System.Collections\" version=\"4.0.0\" targetFramework=\"net45\" />\r\n  <package id=\"System.Collections.Immutable\" version=\"1.1.37\" targetFramework=\"net45\" />\r\n  <package id=\"System.Diagnostics.Debug\" version=\"4.0.0\" targetFramework=\"net45\" />\r\n  <package id=\"System.Globalization\" version=\"4.0.0\" targetFramework=\"net45\" />\r\n  <package id=\"System.IO\" version=\"4.0.0\" targetFramework=\"net45\" />\r\n  <package id=\"System.Linq\" version=\"4.0.0\" targetFramework=\"net45\" />\r\n  <package id=\"System.Reflection\" version=\"4.0.0\" targetFramework=\"net45\" />\r\n  <package id=\"System.Reflection.Extensions\" version=\"4.0.0\" targetFramework=\"net45\" />\r\n  <package id=\"System.Reflection.Metadata\" version=\"1.1.0\" targetFramework=\"net45\" />\r\n  <package id=\"System.Reflection.Primitives\" version=\"4.0.0\" targetFramework=\"net45\" />\r\n  <package id=\"System.Resources.ResourceManager\" version=\"4.0.0\" targetFramework=\"net45\" />\r\n  <package id=\"System.Runtime\" version=\"4.0.0\" targetFramework=\"net45\" />\r\n  <package id=\"System.Runtime.Extensions\" version=\"4.0.0\" targetFramework=\"net45\" />\r\n  <package id=\"System.Runtime.InteropServices\" version=\"4.0.0\" targetFramework=\"net45\" />\r\n  <package id=\"System.Text.Encoding\" version=\"4.0.0\" targetFramework=\"net45\" />\r\n  <package id=\"System.Text.Encoding.Extensions\" version=\"4.0.0\" targetFramework=\"net45\" />\r\n  <package id=\"System.Threading\" version=\"4.0.0\" targetFramework=\"net45\" />\r\n</packages>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Kestrel/AppConfiguration.cs",
    "content": "namespace Nancy.Demo.Hosting.Kestrel\n{\n    public class AppConfiguration : IAppConfiguration\n    {\n        public Logging Logging { get; set; }\n        public Smtp Smtp { get; set; }\n    }\n    \n    public class LogLevel\n    {\n        public string Default { get; set; }\n        public string System { get; set; }\n        public string Microsoft { get; set; }\n    }\n\n    public class Logging\n    {\n        public bool IncludeScopes { get; set; }\n        public LogLevel LogLevel { get; set; }\n    }\n\n    public class Smtp\n    {\n        public string Server { get; set; }\n        public string User { get; set; }\n        public string Pass { get; set; }\n        public string Port { get; set; }\n    }\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Kestrel/DemoBootstrapper.cs",
    "content": "namespace Nancy.Demo.Hosting.Kestrel\n{\n    using Nancy;\n    using Nancy.TinyIoc;\n    \n    public class DemoBootstrapper : DefaultNancyBootstrapper\n    {\n        private readonly IAppConfiguration appConfig;\n\n        public DemoBootstrapper()\n        {\n        }\n        \n        public DemoBootstrapper(IAppConfiguration appConfig)\n        {\n            this.appConfig = appConfig;\n        }\n\n        protected override void ConfigureApplicationContainer(TinyIoCContainer container)\n        {\n            base.ConfigureApplicationContainer(container);\n\n            container.Register<IAppConfiguration>(appConfig);\n        }\n    }   \n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Kestrel/HomeModule.cs",
    "content": "﻿namespace Nancy.Demo.Hosting.Kestrel\r\n{\r\n    using ModelBinding;\r\n\r\n    public class HomeModule : NancyModule\r\n    {\r\n        public HomeModule(IAppConfiguration appConfig)\r\n        {\r\n            Get(\"/\", args => \"Hello from Nancy running on CoreCLR\");\r\n\r\n            Get(\"/conneg/{name}\", args => new Person() { Name = args.name });\r\n\r\n            Get(\"/smtp\", args => \r\n            {\r\n                return new\r\n                {\r\n                    appConfig.Smtp.Server,\r\n                    appConfig.Smtp.User,\r\n                    appConfig.Smtp.Pass,\r\n                    appConfig.Smtp.Port\r\n                };\r\n            });\r\n\r\n            Post(\"/\", args =>\r\n            {\r\n                var person = this.BindAndValidate<Person>();\r\n\r\n                if (!this.ModelValidationResult.IsValid)\r\n                {\r\n                    return 422;\r\n                }\r\n\r\n                return person;\r\n            });\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Kestrel/IAppConfiguration.cs",
    "content": "namespace Nancy.Demo.Hosting.Kestrel\r\n{\r\n    public interface IAppConfiguration\r\n    {\r\n        Logging Logging { get; }\r\n        Smtp Smtp { get; }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Kestrel/Nancy.Demo.Hosting.Kestrel.csproj",
    "content": "<Project Sdk=\"Microsoft.NET.Sdk.Web\">\n\n  <PropertyGroup>\n    <TargetFramework>netcoreapp2.0</TargetFramework>\n    <DebugType>portable</DebugType>\n    <AssemblyName>Nancy.Demo.Hosting.Kestrel</AssemblyName>\n    <OutputType>Exe</OutputType>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <ProjectReference Include=\"../../src/Nancy/Nancy.csproj\" />\n    <ProjectReference Include=\"../../src/Nancy.Validation.FluentValidation/Nancy.Validation.FluentValidation.csproj\" />\n  </ItemGroup>\n\n  <ItemGroup Condition=\" '$(TargetFramework)' == 'netcoreapp2.0' \">\n    <PackageReference Include=\"Microsoft.AspNetCore.Hosting\" Version=\"1.0.2\" />\n    <PackageReference Include=\"Microsoft.AspNetCore.Server.Kestrel\" Version=\"1.0.3\" />\n    <PackageReference Include=\"Microsoft.AspNetCore.Owin\" Version=\"1.0.2\" />\n    <PackageReference Include=\"Microsoft.Extensions.Configuration.Binder\" Version=\"1.0.2\" />\n    <PackageReference Include=\"Microsoft.Extensions.Configuration.Json\" Version=\"1.0.2\" />\n  </ItemGroup>\n\n</Project>\n"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Kestrel/Person.cs",
    "content": "namespace Nancy.Demo.Hosting.Kestrel\r\n{\r\n    public class Person\r\n    {\r\n        public string Name { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Kestrel/PersonValidator.cs",
    "content": "﻿namespace Nancy.Demo.Hosting.Kestrel\r\n{\r\n    using FluentValidation;\r\n    \r\n    public class PersonValidator : AbstractValidator<Person>\r\n    {\r\n        public PersonValidator()\r\n        {\r\n            this.RuleFor(x => x.Name).NotEmpty();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Kestrel/Program.cs",
    "content": "namespace Nancy.Demo.Hosting.Kestrel\r\n{\r\n    using System.IO;\r\n    using Microsoft.AspNetCore.Hosting;\r\n    \r\n    public class Program\r\n    {\r\n        public static void Main(string[] args)\r\n        {\r\n            var host = new WebHostBuilder()\r\n                .UseContentRoot(Directory.GetCurrentDirectory())\r\n                .UseKestrel()\r\n                .UseStartup<Startup>()\r\n                .Build();\r\n\r\n            host.Run();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Kestrel/Properties/launchSettings.json",
    "content": "{\r\n  \"iisSettings\": {\r\n    \"windowsAuthentication\": false,\r\n    \"anonymousAuthentication\": true,\r\n    \"iisExpress\": {\r\n      \"applicationUrl\": \"http://localhost:59916/\",\r\n      \"sslPort\": 0\r\n    }\r\n  },\r\n  \"profiles\": {\r\n    \"IIS Express\": {\r\n      \"commandName\": \"IISExpress\",\r\n      \"launchBrowser\": true,\r\n      \"environmentVariables\": {\r\n        \"ASPNETCORE_ENVIRONMENT\": \"Development\"\r\n      }\r\n    }\r\n  }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Kestrel/Startup.cs",
    "content": "namespace Nancy.Demo.Hosting.Kestrel\n{\n    using Microsoft.AspNetCore.Builder;\n    using Microsoft.AspNetCore.Hosting;\n    using Microsoft.Extensions.Configuration;\n    using Nancy.Owin;\n    \n    public class Startup\n    {\n        private readonly IConfiguration config;\n        \n        public Startup(IHostingEnvironment env)\n        {\n            var builder = new ConfigurationBuilder()\n                              .AddJsonFile(\"appsettings.json\")\n                              .SetBasePath(env.ContentRootPath);\n\n            config = builder.Build();\n        }\n        \n        public void Configure(IApplicationBuilder app)\n        {\n            var appConfig = new AppConfiguration();\n            ConfigurationBinder.Bind(config, appConfig);\n\n            app.UseOwin(x => x.UseNancy(opt => opt.Bootstrapper = new DemoBootstrapper(appConfig)));\n        }\n    }\n}\n"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Kestrel/appsettings.json",
    "content": "{\n  \"Logging\": {\n    \"IncludeScopes\": false,\n    \"LogLevel\": {\n      \"Default\": \"Verbose\",\n      \"System\": \"Information\",\n      \"Microsoft\": \"Information\"\n    }\n  },\n  \"Smtp\": {\n    \"Server\": \"0.0.0.1\",\n    \"User\": \"user@company.com\",\n    \"Pass\": \"123456789\",\n    \"Port\": \"25\"\n  }\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Owin/MainModule.cs",
    "content": "﻿namespace Nancy.Demo.Hosting.Owin\r\n{\r\n    using System.Collections.Generic;\r\n    using Nancy.Owin;\r\n\r\n    public class MainModule : NancyModule\r\n    {\r\n        public MainModule()\r\n        {\r\n            Get(\"\", args => Root(args));\r\n        }\r\n\r\n        private object Root(dynamic o)\r\n        {\r\n            var env = GetOwinEnvironmentValue<IDictionary<string, object>>(this.Context.Items, NancyMiddleware.RequestEnvironmentKey);\r\n\r\n            if (env == null)\r\n            {\r\n                return \"Not running on owin host\";\r\n            }\r\n\r\n            var requestMethod = GetOwinEnvironmentValue<string>(env, \"owin.RequestMethod\");\r\n            var requestPath = GetOwinEnvironmentValue<string>(env, \"owin.RequestPath\");\r\n            var owinVersion = GetOwinEnvironmentValue<string>(env, \"owin.Version\");\r\n            var statusMessage = string.Format(\"You made a {0} request to {1} which runs on OWIN {2}.\", requestMethod, requestPath, owinVersion);\r\n\r\n            return View[\"Root\", new Models.Index {StatusMessage = statusMessage}];\r\n        }\r\n\r\n        private static T GetOwinEnvironmentValue<T>(IDictionary<string, object> env, string name, T defaultValue = default(T))\r\n        {\r\n            object value;\r\n            return env.TryGetValue(name, out value) && value is T ? (T)value : defaultValue;\r\n        }\r\n\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Owin/Models/Index.cs",
    "content": "namespace Nancy.Demo.Hosting.Owin.Models\r\n{\r\n    public class Index\r\n    {\r\n        public string StatusMessage { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Owin/Nancy.Demo.Hosting.Owin.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\r\n  <PropertyGroup>\r\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\r\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\r\n    <SchemaVersion>2.0</SchemaVersion>\r\n    <ProjectGuid>{7959D79C-9E2B-4871-9470-6A6B527ABE5E}</ProjectGuid>\r\n    <ProjectTypeGuids>{349C5851-65DF-11DA-9384-00065B846F21};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>\r\n    <OutputType>Library</OutputType>\r\n    <AppDesignerFolder>Properties</AppDesignerFolder>\r\n    <RootNamespace>Nancy.Demo.Hosting.Owin</RootNamespace>\r\n    <AssemblyName>Nancy.Demo.Hosting.Owin</AssemblyName>\r\n    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\r\n    <UseIISExpress>false</UseIISExpress>\r\n    <OldToolsVersion>4.0</OldToolsVersion>\r\n    <IISExpressAnonymousAuthentication>enabled</IISExpressAnonymousAuthentication>\r\n    <IISExpressWindowsAuthentication>enabled</IISExpressWindowsAuthentication>\r\n    <IISExpressUseClassicPipelineMode>false</IISExpressUseClassicPipelineMode>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <DebugType>full</DebugType>\r\n    <Optimize>false</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE;DEBUG</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\r\n    <DebugType>pdbonly</DebugType>\r\n    <Optimize>true</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoDebug|AnyCPU'\">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <DebugType>full</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.Hosting.Owin.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Optimize>false</Optimize>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoRelease|AnyCPU'\">\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <Optimize>true</Optimize>\r\n    <DebugType>pdbonly</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.Hosting.Owin.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <ItemGroup>\r\n    <Reference Include=\"Microsoft.CSharp\" />\r\n    <Reference Include=\"Microsoft.Owin, Version=3.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL\">\r\n      <HintPath>..\\..\\packages\\Microsoft.Owin.3.0.1\\lib\\net45\\Microsoft.Owin.dll</HintPath>\r\n      <Private>True</Private>\r\n    </Reference>\r\n    <Reference Include=\"Microsoft.Owin.Host.SystemWeb, Version=3.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL\">\r\n      <HintPath>..\\..\\packages\\Microsoft.Owin.Host.SystemWeb.3.0.1\\lib\\net45\\Microsoft.Owin.Host.SystemWeb.dll</HintPath>\r\n      <Private>True</Private>\r\n    </Reference>\r\n    <Reference Include=\"Owin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f0ebd12fd5e55cc5, processorArchitecture=MSIL\">\r\n      <HintPath>..\\..\\packages\\Owin.1.0\\lib\\net40\\Owin.dll</HintPath>\r\n      <Private>True</Private>\r\n    </Reference>\r\n    <Reference Include=\"System.Net.Http\" />\r\n    <Reference Include=\"System\" />\r\n    <Reference Include=\"System.Data\" />\r\n    <Reference Include=\"System.Drawing\" />\r\n    <Reference Include=\"System.Web\" />\r\n    <Reference Include=\"System.Xml\" />\r\n    <Reference Include=\"System.Configuration\" />\r\n    <Reference Include=\"Spark, Version=1.5.0.0, Culture=neutral, PublicKeyToken=7f8549eed921a12c\">\r\n      <SpecificVersion>False</SpecificVersion>\r\n      <HintPath>..\\..\\packages\\Spark.1.7.0.0\\lib\\NET40\\Spark.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"System.Xml.Linq\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <None Include=\"Views\\Root.spark\" />\r\n    <Content Include=\"Web.config\">\r\n      <SubType>Designer</SubType>\r\n    </Content>\r\n    <Content Include=\"Web.Debug.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n    <Content Include=\"Web.Release.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Compile Include=\"..\\..\\SharedAssemblyInfo.cs\">\r\n      <Link>Properties\\SharedAssemblyInfo.cs</Link>\r\n    </Compile>\r\n    <Compile Include=\"MainModule.cs\" />\r\n    <Compile Include=\"Models\\Index.cs\" />\r\n    <Compile Include=\"Startup.cs\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.Owin.MSBuild\\Nancy.Owin.csproj\">\r\n      <Project>{d6b2480c-2a52-4d02-9477-d387d7a486e5}</Project>\r\n      <Name>Nancy.Owin</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.ViewEngines.Spark.MSBuild\\Nancy.ViewEngines.Spark.csproj\">\r\n      <Project>{4B7E35DF-1569-4346-B180-A09615723095}</Project>\r\n      <Name>Nancy.ViewEngines.Spark</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.MSBuild\\Nancy.csproj\">\r\n      <Project>{34576216-0DCA-4B0F-A0DC-9075E75A676F}</Project>\r\n      <Name>Nancy</Name>\r\n    </ProjectReference>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"packages.config\" />\r\n  </ItemGroup>\r\n  <PropertyGroup>\r\n    <VisualStudioVersion Condition=\"'$(VisualStudioVersion)' == ''\">10.0</VisualStudioVersion>\r\n    <VSToolsPath Condition=\"'$(VSToolsPath)' == ''\">$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)</VSToolsPath>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\r\n  <Import Project=\"$(VSToolsPath)\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"'$(VSToolsPath)' != ''\" />\r\n  <Import Project=\"$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v10.0\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"false\" />\r\n  <ProjectExtensions>\r\n    <VisualStudio>\r\n      <FlavorProperties GUID=\"{349C5851-65DF-11DA-9384-00065B846F21}\">\r\n        <WebProjectProperties>\r\n          <SaveServerSettingsInUserFile>True</SaveServerSettingsInUserFile>\r\n        </WebProjectProperties>\r\n      </FlavorProperties>\r\n    </VisualStudio>\r\n    <MonoDevelop>\r\n      <Properties VerifyCodeBehindFields=\"true\" VerifyCodeBehindEvents=\"true\">\r\n        <XspParameters Port=\"8080\" Address=\"127.0.0.1\" SslMode=\"None\" SslProtocol=\"Default\" KeyType=\"None\" CertFile=\"\" KeyFile=\"\" PasswordOptions=\"None\" Password=\"\" Verbose=\"true\" />\r\n      </Properties>\r\n    </MonoDevelop>\r\n  </ProjectExtensions>\r\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r\n       Other similar extension points exist, see Microsoft.Common.targets.\r\n  <Target Name=\"BeforeBuild\">\r\n  </Target>\r\n  <Target Name=\"AfterBuild\">\r\n  </Target>\r\n  -->\r\n</Project>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Owin/Startup.cs",
    "content": "﻿namespace Nancy.Demo.Hosting.Owin\r\n{\r\n    using global::Owin;\r\n\r\n    public class Startup\r\n    {\r\n        public void Configuration(IAppBuilder app)\r\n        {\r\n            app.UseNancy();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Owin/Views/Root.spark",
    "content": "﻿<viewdata model=\"Nancy.Demo.Hosting.Owin.Models.Index\" />\r\n\r\n<!DOCTYPE html>\r\n\r\n<html>\r\n  <head>\r\n    <title>Nancy OWIN Host Demo</title>\r\n  </head>\r\n  <body>\r\n    <h1>Nancy OWIN Host Demo</h1>\r\n    <p>This is a Spark view rendered via the OWIN hosting. ${Model.StatusMessage}</p>\r\n  </body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Owin/Web.Debug.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<!-- For more information on using web.config transformation visit http://go.microsoft.com/fwlink/?LinkId=125889 -->\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <!--\r\n    In the example below, the \"SetAttributes\" transform will change the value of \r\n    \"connectionString\" to use \"ReleaseSQLServer\" only when the \"Match\" locator \r\n    finds an atrribute \"name\" that has a value of \"MyDB\".\r\n    \r\n    <connectionStrings>\r\n      <add name=\"MyDB\" \r\n        connectionString=\"Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True\" \r\n        xdt:Transform=\"SetAttributes\" xdt:Locator=\"Match(name)\"/>\r\n    </connectionStrings>\r\n  -->\r\n  <system.web>\r\n    <!--\r\n      In the example below, the \"Replace\" transform will replace the entire \r\n      <customErrors> section of your web.config file.\r\n      Note that because there is only one customErrors section under the \r\n      <system.web> node, there is no need to use the \"xdt:Locator\" attribute.\r\n      \r\n      <customErrors defaultRedirect=\"GenericError.htm\"\r\n        mode=\"RemoteOnly\" xdt:Transform=\"Replace\">\r\n        <error statusCode=\"500\" redirect=\"InternalError.htm\"/>\r\n      </customErrors>\r\n    -->\r\n  </system.web>\r\n</configuration>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Owin/Web.Release.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<!-- For more information on using web.config transformation visit http://go.microsoft.com/fwlink/?LinkId=125889 -->\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <!--\r\n    In the example below, the \"SetAttributes\" transform will change the value of \r\n    \"connectionString\" to use \"ReleaseSQLServer\" only when the \"Match\" locator \r\n    finds an atrribute \"name\" that has a value of \"MyDB\".\r\n    \r\n    <connectionStrings>\r\n      <add name=\"MyDB\" \r\n        connectionString=\"Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True\" \r\n        xdt:Transform=\"SetAttributes\" xdt:Locator=\"Match(name)\"/>\r\n    </connectionStrings>\r\n  -->\r\n  <system.web>\r\n    <compilation xdt:Transform=\"RemoveAttributes(debug)\" />\r\n    <!--\r\n      In the example below, the \"Replace\" transform will replace the entire \r\n      <customErrors> section of your web.config file.\r\n      Note that because there is only one customErrors section under the \r\n      <system.web> node, there is no need to use the \"xdt:Locator\" attribute.\r\n      \r\n      <customErrors defaultRedirect=\"GenericError.htm\"\r\n        mode=\"RemoteOnly\" xdt:Transform=\"Replace\">\r\n        <error statusCode=\"500\" redirect=\"InternalError.htm\"/>\r\n      </customErrors>\r\n    -->\r\n  </system.web>\r\n</configuration>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Owin/Web.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n<!--\r\n  For more information on how to configure your ASP.NET application, please visit\r\n  http://go.microsoft.com/fwlink/?LinkId=169433\r\n  -->\r\n<configuration>\r\n  <appSettings>\r\n    <add key=\"owin:HandleAllRequests\" value=\"true\"/>\r\n  </appSettings>\r\n  <!--\r\n    For a description of web.config changes see http://go.microsoft.com/fwlink/?LinkId=235367.\r\n\r\n    The following attributes can be set on the <httpRuntime> tag.\r\n      <system.Web>\r\n        <httpRuntime targetFramework=\"4.5\" />\r\n      </system.Web>\r\n  -->\r\n  <system.web>\r\n    <compilation debug=\"true\" targetFramework=\"4.5\"/>\r\n    <httpRuntime maxRequestLength=\"1048576\"/>\r\n    <pages controlRenderingCompatibilityVersion=\"4.0\"/>\r\n  </system.web>\r\n  <system.webServer>\r\n    <security>\r\n      <requestFiltering>\r\n        <requestLimits maxAllowedContentLength=\"1048576000\"/>\r\n      </requestFiltering>\r\n    </security>\r\n  </system.webServer>\r\n</configuration>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Owin/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<packages>\r\n  <package id=\"Microsoft.Owin\" version=\"3.0.1\" targetFramework=\"net45\" />\r\n  <package id=\"Microsoft.Owin.Host.SystemWeb\" version=\"3.0.1\" targetFramework=\"net45\" />\r\n  <package id=\"Owin\" version=\"1.0\" targetFramework=\"net45\" />\r\n</packages>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Self/DemoBootstrapper.cs",
    "content": "﻿namespace Nancy.Demo.Hosting.Self\r\n{\r\n    using Nancy;\r\n    using Nancy.Diagnostics;\r\n\r\n    public class DemoBootstrapper : DefaultNancyBootstrapper\r\n    {\r\n        public override void Configure(Nancy.Configuration.INancyEnvironment environment)\r\n        {\r\n            environment.Diagnostics(\r\n                enabled: true,\r\n                password: \"password\");\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Self/Models/Index.cs",
    "content": "namespace Nancy.Demo.Hosting.Self.Models\r\n{\r\n    public class Index\r\n    {\r\n        public string Name { get; set; }\r\n\r\n        public string Posted { get; set; }\r\n\r\n        public Index()\r\n        {\r\n            this.Posted = \"Nothing :-(\";\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Self/Nancy.Demo.Hosting.Self.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <PropertyGroup>\r\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\r\n    <Platform Condition=\" '$(Platform)' == '' \">x86</Platform>\r\n    <ProjectGuid>{0B3EA40E-F7D8-4E14-A30F-1536F41B62D1}</ProjectGuid>\r\n    <OutputType>Exe</OutputType>\r\n    <AppDesignerFolder>Properties</AppDesignerFolder>\r\n    <RootNamespace>Nancy.Demo.Hosting.Self</RootNamespace>\r\n    <AssemblyName>Nancy.Demo.Hosting.Self</AssemblyName>\r\n    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\r\n    <FileAlignment>512</FileAlignment>\r\n    <PublishUrl>publish\\</PublishUrl>\r\n    <Install>true</Install>\r\n    <InstallFrom>Disk</InstallFrom>\r\n    <UpdateEnabled>false</UpdateEnabled>\r\n    <UpdateMode>Foreground</UpdateMode>\r\n    <UpdateInterval>7</UpdateInterval>\r\n    <UpdateIntervalUnits>Days</UpdateIntervalUnits>\r\n    <UpdatePeriodically>false</UpdatePeriodically>\r\n    <UpdateRequired>false</UpdateRequired>\r\n    <MapFileExtensions>true</MapFileExtensions>\r\n    <ApplicationRevision>0</ApplicationRevision>\r\n    <ApplicationVersion>1.0.0.%2a</ApplicationVersion>\r\n    <IsWebBootstrapper>false</IsWebBootstrapper>\r\n    <UseApplicationTrust>false</UseApplicationTrust>\r\n    <BootstrapperEnabled>true</BootstrapperEnabled>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|x86' \">\r\n    <PlatformTarget>x86</PlatformTarget>\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <DebugType>full</DebugType>\r\n    <Optimize>false</Optimize>\r\n    <OutputPath>bin\\Debug\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n    <Externalconsole>true</Externalconsole>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|x86' \">\r\n    <PlatformTarget>x86</PlatformTarget>\r\n    <DebugType>pdbonly</DebugType>\r\n    <Optimize>true</Optimize>\r\n    <OutputPath>bin\\Release\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup>\r\n    <StartupObject>Nancy.Demo.Hosting.Self.Program</StartupObject>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoDebug|x86'\">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <OutputPath>bin\\x86\\MonoDebug\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <DebugType>full</DebugType>\r\n    <PlatformTarget>x86</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Debug\\Nancy.Demo.Hosting.Self.exe.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRules>false</CodeAnalysisIgnoreBuiltInRules>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Optimize>false</Optimize>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoRelease|x86'\">\r\n    <OutputPath>bin\\x86\\MonoRelease\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <Optimize>true</Optimize>\r\n    <DebugType>pdbonly</DebugType>\r\n    <PlatformTarget>x86</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Release\\Nancy.Demo.Hosting.Self.exe.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRules>false</CodeAnalysisIgnoreBuiltInRules>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <ItemGroup>\r\n    <Reference Include=\"System\" />\r\n    <Reference Include=\"System.Core\" />\r\n    <Reference Include=\"System.Xml.Linq\" />\r\n    <Reference Include=\"Microsoft.CSharp\" />\r\n    <Reference Include=\"System.Data\" />\r\n    <Reference Include=\"System.Xml\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Compile Include=\"..\\..\\SharedAssemblyInfo.cs\">\r\n      <Link>Properties\\SharedAssemblyInfo.cs</Link>\r\n    </Compile>\r\n    <Compile Include=\"Models\\Index.cs\" />\r\n    <Compile Include=\"Program.cs\" />\r\n    <Compile Include=\"TestModule.cs\" />\r\n    <Compile Include=\"DemoBootstrapper.cs\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.Hosting.Self.MSBuild\\Nancy.Hosting.Self.csproj\">\r\n      <Project>{AA7F66EB-EC2C-47DE-855F-30B3E6EF2134}</Project>\r\n      <Name>Nancy.Hosting.Self</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.ViewEngines.Spark.MSBuild\\Nancy.ViewEngines.Spark.csproj\">\r\n      <Project>{4B7E35DF-1569-4346-B180-A09615723095}</Project>\r\n      <Name>Nancy.ViewEngines.Spark</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.MSBuild\\Nancy.csproj\">\r\n      <Project>{34576216-0DCA-4B0F-A0DC-9075E75A676F}</Project>\r\n      <Name>Nancy</Name>\r\n    </ProjectReference>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <None Include=\"app.config\">\r\n      <SubType>Designer</SubType>\r\n    </None>\r\n    <Content Include=\"Views\\FileUpload.spark\">\r\n      <SubType>Designer</SubType>\r\n      <CopyToOutputDirectory>Always</CopyToOutputDirectory>\r\n    </Content>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Views\\staticview.html\">\r\n      <CopyToOutputDirectory>Always</CopyToOutputDirectory>\r\n    </Content>\r\n  </ItemGroup>\r\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\r\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r\n       Other similar extension points exist, see Microsoft.Common.targets.\r\n  <Target Name=\"BeforeBuild\">\r\n  </Target>\r\n  <Target Name=\"AfterBuild\">\r\n  </Target>\r\n  -->\r\n</Project>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Self/Program.cs",
    "content": "﻿namespace Nancy.Demo.Hosting.Self\r\n{\r\n    using System;\r\n    using System.Diagnostics;\r\n\r\n    using Nancy.Hosting.Self;\r\n\r\n    class Program\r\n    {\r\n        static void Main()\r\n        {\r\n            using (var nancyHost = new NancyHost(new Uri(\"http://localhost:8888/nancy/\"), new Uri(\"http://127.0.0.1:8898/nancy/\"), new Uri(\"http://localhost:8889/nancytoo/\")))\r\n            {\r\n                nancyHost.Start();\r\n\r\n                Console.WriteLine(\"Nancy now listening - navigating to http://localhost:8888/nancy/. Press enter to stop\");\r\n                try\r\n                {\r\n                    Process.Start(\"http://localhost:8888/nancy/\");\r\n                }\r\n                catch (Exception)\r\n                {\r\n                }\r\n                Console.ReadKey();\r\n            }\r\n\r\n            Console.WriteLine(\"Stopped. Good bye!\");\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Self/README.txt",
    "content": "﻿"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Self/TestModule.cs",
    "content": "namespace Nancy.Demo.Hosting.Self\r\n{\r\n    using System.Linq;\r\n    using Nancy.Demo.Hosting.Self.Models;\r\n\r\n    public class TestModule : NancyModule\r\n    {\r\n        public TestModule()\r\n        {\r\n            Get(\"/\", args => {\r\n                return View[\"staticview\", this.Request.Url];\r\n            });\r\n\r\n            Get(\"/testing\", args =>\r\n            {\r\n                return View[\"staticview\", this.Request.Url];\r\n            });\r\n\r\n            Get(\"/fileupload\", args =>\r\n            {\r\n                var model = new Index() { Name = \"Boss Hawg\" };\r\n\r\n                return View[\"FileUpload\", model];\r\n            });\r\n\r\n            Post(\"/fileupload\", args =>\r\n            {\r\n                var model = new Index() { Name = \"Boss Hawg\" };\r\n\r\n                var file = this.Request.Files.FirstOrDefault();\r\n                string fileDetails = \"None\";\r\n\r\n                if (file != null)\r\n                {\r\n                    fileDetails = string.Format(\"{3} - {0} ({1}) {2}bytes\", file.Name, file.ContentType, file.Value.Length, file.Key);\r\n                }\r\n\r\n                model.Posted = fileDetails;\r\n\r\n                return View[\"FileUpload\", model];\r\n            });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Self/Views/FileUpload.spark",
    "content": "﻿<viewdata model=\"Nancy.Demo.Hosting.Self.Models.Index\" />\r\n<html>\r\n  <head>\r\n    <title>Nancy Self Host Demo</title>\r\n  </head>\r\n  <body>\r\n    <h1>Hello ${Model.Name}!</h1>\r\n    <p>This is a Spark view rendered via the self hosting.</p>\r\n    <p>You uploaded: ${Model.Posted}</p>\r\n    <p>\r\n      <form action=\"~/fileupload\" method=\"POST\" enctype=\"multipart/form-data\">\r\n        <input name=\"upload\" type=\"file\" size=\"40\"/>\r\n        <input type=\"submit\" value=\"Post!\"/>\r\n      </form>\r\n    </p>\r\n  </body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Self/Views/staticview.html",
    "content": "﻿<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\r\n<html>\r\n    <head>\r\n        <title>Nancy - Static view served by self-host</title>\r\n    </head>\r\n    <body>\r\n        <h1>Static view served by self-host</h1>\r\n        <p>\r\n            This view was served by the Nancy self-host.\r\n        </p>\r\n        <ul>\r\n            <li>Scheme: @Model.Scheme</li>\r\n            <li>HostName: @Model.HostName</li>\r\n            <li>Port: @Model.Port</li>\r\n            <li>BasePath: @Model.BasePath</li>\r\n            <li>Path: @Model.Path</li>\r\n        </ul>\r\n        <a href=\"http://localhost:8888/nancy/\">http://localhost:8888/nancy/</a><br/>\r\n        <a href=\"http://localhost:8888/nancy/testing\">http://localhost:8888/nancy/testing</a><br/>\r\n        <a href=\"http://127.0.0.1:8898/nancy/\">http://127.0.0.1:8898/nancy/</a><br/>\r\n        <a href=\"http://127.0.0.1:8898/nancy/testing\">http://127.0.0.1:8898/nancy/testing</a><br/>\r\n        <a href=\"http://localhost:8889/nancytoo/\">http://localhost:8889/nancytoo/</a><br/>\r\n        <a href=\"http://localhost:8889/nancytoo/testing\">http://localhost:8889/nancytoo/testing</a><br/>\r\n    </body>\r\n</html>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Hosting.Self/app.config",
    "content": "<?xml version=\"1.0\"?>\r\n\r\n<configuration>\r\n  <startup>\r\n    <supportedRuntime version=\"v4.0\" sku=\".NETFramework,Version=v4.0\" />\r\n  </startup>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.MarkdownViewEngine/Content/blog.css",
    "content": "﻿body {\r\n    background: #f2f2f2 url('/content/images/body.png') repeat scroll top center /* Credit: Pixel Oplosan (http://www.pixeloplosan.com) */;\r\n    margin: 0;\r\n    color: #777777;\r\n}\r\n\r\na:link, a:visited, a:hover {\r\n    color: #6c83ad;\r\n    text-decoration: none;\r\n}\r\n\r\na:hover {\r\n    color: #45597f;\r\n    text-decoration: underline;\r\n}\r\n\r\na img {\r\n    border-width: 0;\r\n}\r\n\r\n#navbar-iframe,\r\n#LinkList1 h2,\r\n.feed-links {\r\n    display: none;\r\n}\r\n\r\n.firstline {\r\n    text-transform: uppercase;\r\n    font-size: 11px;\r\n}\r\n\r\nh1, h2, h3, h4, h5, h6 {\r\n    font-family: Arial, Helvetica, sans-serif;\r\n    font-weight: normal;\r\n    clear: both;\r\n}\r\n\r\nh1 {\r\n    font-size: 28px;\r\n}\r\n\r\nh2 {\r\n    font-size: 24px;\r\n}\r\n\r\nh3 {\r\n    font-size: 20px;\r\n}\r\n\r\nh4 {\r\n    font-size: 12px;\r\n}\r\n\r\nh5 {\r\n    font-size: 10px;\r\n}\r\n\r\nh6 {\r\n    font-size: 8px;\r\n}\r\n\r\nhr {\r\n    background-color: #777777;\r\n    border: 0;\r\n    height: 1px;\r\n    margin-bottom: 2px;\r\n    clear: both;\r\n}\r\n\r\npre {\r\n    overflow: auto;\r\n    padding: 10px;\r\n    background: #635c5c;\r\n    color: #fff;\r\n    margin-bottom: 0;\r\n}\r\n/* ===================\r\nHeader\r\n=================== */\r\n#header-wrapper {\r\n    width: 100%;\r\n    overflow: hidden;\r\n    padding: 0;\r\n}\r\n\r\n#header {\r\n    padding-bottom: 50px;\r\n}\r\n\r\n    #header .caption {\r\n        font-size: 16px;\r\n        font-family: Garamond, Georgia, 'Times New Roman', serif;\r\n        font-style: italic;\r\n    }\r\n\r\n    #header h1 {\r\n        margin: 0;\r\n        padding: 10px 0 0 0;\r\n        font: normal normal 36px Lobster;\r\n        color: #666;\r\n    }\r\n\r\n    #header .description {\r\n        margin: 0;\r\n        padding: 0;\r\n        font: normal normal 10px Verdana, Geneva, sans-serif;\r\n    }\r\n\r\n    #header a {\r\n        color: #666;\r\n        text-decoration: none;\r\n    }\r\n\r\n        #header a:hover {\r\n            color: #111;\r\n        }\r\n/* ===================\r\nOuter-Wrapper\r\n=================== */\r\n#outer-wrapper {\r\n    width: 1074px;\r\n    margin: 0 auto;\r\n    padding: 0;\r\n    text-align: left;\r\n    font: normal normal 12px Helvetica, Arial, Sans;\r\n}\r\n\r\n#content-wrapper {\r\n    width: 100%;\r\n}\r\n/* ===================\r\nSet cloud\r\n=================== */\r\n#mountain {\r\n    background: url('/content/images/mountain.png') no-repeat 205px bottom;\r\n    height: 200px;\r\n    width: 100%;\r\n    margin: 0 auto -1px auto;\r\n}\r\n\r\n#cover-cloud {\r\n    width: 100%;\r\n    min-width: 1074px;\r\n    height: 200px;\r\n    position: absolute;\r\n    z-index: 100;\r\n    left: 0;\r\n}\r\n\r\n#cloud {\r\n    background: url('/content/images/cloud1.png') repeat-x 0 0;\r\n    position: absolute;\r\n    width: 100%;\r\n    height: 188px;\r\n    z-index: 200;\r\n}\r\n\r\n#cloud2 {\r\n    background: url('/content/images/cloud2.png') repeat-x 0 0;\r\n    position: absolute;\r\n    width: 100%;\r\n    height: 125px;\r\n    z-index: 300;\r\n}\r\n\r\n#cloud3 {\r\n    background: url('/content/images/cloud3.png') repeat-x 0 0;\r\n    position: absolute;\r\n    width: 100%;\r\n    height: 46px;\r\n    z-index: 400;\r\n}\r\n/* ===================\r\nNavigation\r\n=================== */\r\n.PageList h2 {\r\n    display: none;\r\n}\r\n\r\n.PageList ul {\r\n    list-style: none;\r\n    margin: 10px 0 0 0;\r\n    line-height: 2.3em;\r\n}\r\n\r\n    .PageList ul li {\r\n        padding: 5px 0;\r\n        color: #666;\r\n        background: none;\r\n        border: none;\r\n    }\r\n\r\n        .PageList ul li a {\r\n            font: normal normal 18px 'Questrial';\r\n        }\r\n\r\n.PageList .selected a {\r\n    color: #111;\r\n    font-weight: normal!important;\r\n}\r\n/* ===================\r\nPrimary Content\r\n=================== */\r\n#main-wrapper {\r\n    float: left;\r\n    width: 604px;\r\n    background: url('/content/images/post-head.png') no-repeat center top;\r\n}\r\n\r\n#main {\r\n    background: url('/content/images/post-midd.png') repeat-y center top;\r\n    .background-position:left top;\r\n}\r\n\r\n    #main .widget {\r\n        background: url('/content/images/post-foot.png') no-repeat center bottom;\r\n        background-position: left bottom;\r\n        margin: 30px 0;\r\n        padding: 0 20px 20px 20px;\r\n    }\r\n\r\n.main .Blog {\r\n    border-bottom-width: 0;\r\n}\r\n\r\n.post-header-line-1 {\r\n    clear: both;\r\n    font-size: 11px;\r\n    text-align: left;\r\n    line-height: 1.6em;\r\n}\r\n\r\n.hentry-top {\r\n    font-size: 8px;\r\n    text-transform: uppercase;\r\n    text-align: left;\r\n}\r\n\r\n.post {\r\n    margin: 0 0 50px 0;\r\n}\r\n\r\n    .post h3 {\r\n        margin: 0;\r\n        padding: 0;\r\n    }\r\n\r\n        .post h3 a, .post h3 a:visited, .post h3 strong {\r\n            width: 100%;\r\n            font: normal normal 35px 'questrial';\r\n            float: left;\r\n            text-decoration: none;\r\n            color: #6c83ad;\r\n            text-align: left;\r\n            padding: 5px 0 0 0;\r\n            margin-bottom: 20px;\r\n        }\r\n\r\n            .post h3 strong, .post h3 a:hover {\r\n                color: $titlecolor;\r\n            }\r\n\r\n.post-body {\r\n    margin: 0 0 .75em;\r\n    line-height: 1.8em;\r\n}\r\n\r\n    .post-body p {\r\n        padding-top: 0;\r\n        margin-top: 0;\r\n    }\r\n\r\n    .post-body blockquote {\r\n        line-height: 1.8em;\r\n        border-left: 1px solid #ddd;\r\n        padding: 10px;\r\n        color: #828282;\r\n    }\r\n\r\n.post blockquote {\r\n    margin: 0 20px;\r\n}\r\n\r\n    .post blockquote p {\r\n        margin: .75em 0;\r\n    }\r\n\r\n.post-footer {\r\n    margin: 30px 0 0;\r\n    font-size: 11px;\r\n    padding: 0;\r\n    color: #b0b0b0!important;\r\n}\r\n\r\n    .post-footer a {\r\n        color: #b0b0b0;\r\n    }\r\n\r\n.post-footer-line-2 {\r\n    margin-top: 5px;\r\n}\r\n\r\n.comment-link {\r\n    margin-left: .6em;\r\n}\r\n\r\n.post img, table.tr-caption-container {\r\n    max-width: 520px;\r\n    height: auto;\r\n    margin: 0;\r\n    overflow: hidden;\r\n}\r\n\r\n.tr-caption-container img {\r\n    border: none;\r\n    padding: 0;\r\n}\r\n\r\n.jump-link a {\r\n    font-size: 11px;\r\n    border-bottom: 1px dotted #cc2610;\r\n}\r\n\r\n.jump-link {\r\n    margin-top: 20px;\r\n}\r\n/* =======================\r\nComments Content\r\n======================= */\r\n#comments h4 {\r\n    font: normal normal 35px 'questrial';\r\n    font-size: 16px !important;\r\n    color: #6c83ad;\r\n    clear: both;\r\n}\r\n\r\n#comments {\r\n    margin: 0;\r\n    padding: 0;\r\n    float: left;\r\n    clear: left;\r\n    .width:565px;\r\n}\r\n\r\n.comment-header .user {\r\n    font-size: 14px;\r\n    font-weight: bold;\r\n}\r\n\r\n.comment-header .datetime {\r\n    font-size: 11px;\r\n}\r\n\r\n.comment-thread li .comment-block {\r\n    border-bottom: 1px dotted #e2e2e2;\r\n    padding-bottom: 10px;\r\n    .margin-left:10px;\r\n}\r\n\r\n.comment-content {\r\n    margin: 0;\r\n    padding: 0;\r\n    line-height: 1.8em!important;\r\n}\r\n\r\n.comments blockquote {\r\n    margin-bottom: 20px;\r\n    padding: 10px 0;\r\n}\r\n\r\n#comment-holder .comment-block .comment-actions a {\r\n    font-size: 11px;\r\n    margin-right: 20px;\r\n}\r\n\r\n#comment-holder .avatar-image-container {\r\n    background: transparent;\r\n    overflow: hidden;\r\n    .margin-left:-35px;\r\n}\r\n\r\n    #comment-holder .avatar-image-container img {\r\n        border: medium none;\r\n    }\r\n\r\n#comments-block.avatar-comment-indent {\r\n    position: relative;\r\n    margin: 0 auto;\r\n}\r\n/* ===================\r\nPage Navigation\r\n=================== */\r\n#blog-pager-newer-link {\r\n    float: right;\r\n}\r\n\r\n#blog-pager-older-link {\r\n    float: left;\r\n    margin-right: 10px;\r\n}\r\n\r\n#blog-pager {\r\n    font: normal normal 18px 'Questrial';\r\n    border-top: 3px double #e2e2e2;\r\n    padding-top: 20px;\r\n    clear: both;\r\n}\r\n/* ===================\r\nSecondary Content\r\n=================== */\r\n#left-content {\r\n    float: left;\r\n    width: 200px;\r\n    padding-top: 20px;\r\n}\r\n\r\n#sidebar-wrapper {\r\n    float: right;\r\n    width: 270px;\r\n    padding-top: 20px;\r\n}\r\n\r\n.sidebar, .header {\r\n    color: $sidebartextcolor;\r\n    line-height: 1.8em;\r\n    padding: 0 20px;\r\n}\r\n\r\n    .sidebar h2 {\r\n        font: normal normal 20px Lobster;\r\n        margin: 0 0 20px 0;\r\n        padding: 4px 0;\r\n        color: #555;\r\n    }\r\n\r\n    .sidebar ul {\r\n        list-style: none;\r\n        margin: 0 0 0;\r\n        padding: 0 0 0;\r\n        line-height: 1.8em;\r\n    }\r\n\r\n    .sidebar li {\r\n        margin: 0;\r\n    }\r\n\r\n    .sidebar .widget {\r\n        margin: 0 0 20px 0;\r\n        padding: 0 0 15px 0;\r\n        clear: both;\r\n    }\r\n\r\n    .sidebar .Label li {\r\n        float: left;\r\n        width: 45%;\r\n        margin-right: 5%;\r\n    }\r\n\r\n    .sidebar blockquote {\r\n        margin: 0;\r\n        padding: 15px 0;\r\n        font-size: 14px;\r\n        font-style: italic;\r\n        border-top: 1px solid #e2e2e2;\r\n        border-bottom: 1px solid #e2e2e2;\r\n        font-family: georgia, 'times new roman', serif;\r\n    }\r\n\r\n    .sidebar .PopularPosts .item-snippet {\r\n        font-size: 11px;\r\n    }\r\n\r\n    .sidebar .PopularPosts .item-title {\r\n        font-weight: bold;\r\n    }\r\n\r\n    .sidebar .Attribution .widget-content {\r\n        text-align: left!important;\r\n        color: #bbb;\r\n        text-shadow: 1px 1px 0 #fff;\r\n    }\r\n\r\n        .sidebar .Attribution .widget-content a {\r\n            text-transform: uppercase;\r\n            font-weight: bold;\r\n            font-size: 11px;\r\n            color: #aaa;\r\n        }\r\n\r\n            .sidebar .Attribution .widget-content a:hover {\r\n                color: #000;\r\n            }\r\n/* ===================\r\nFooter\r\n=================== */\r\n#credit-wrapper {\r\n    margin: 0 auto;\r\n    padding: 30px 0 0 20px;\r\n    clear: both;\r\n    color: #bbb;\r\n    line-height: 1.6em;\r\n    text-shadow: 1px 1px 0 #fff;\r\n}\r\n\r\n.credit span {\r\n    text-transform: uppercase;\r\n    font-weight: bold;\r\n    font-size: 11px;\r\n}\r\n\r\n    .credit span em {\r\n        font-weight: normal;\r\n        text-transform: lowercase;\r\n        font-style: italic;\r\n        font-family: georgia, 'times new roman', serif;\r\n    }\r\n\r\n.credit a, .footer a:visited {\r\n    color: #aaa;\r\n}\r\n\r\n    .credit a:hover {\r\n        color: #000;\r\n        text-decoration: underline;\r\n    }\r\n"
  },
  {
    "path": "samples/Nancy.Demo.MarkdownViewEngine/Content/js/jquery.spritely-0.6.js",
    "content": "/*\n * jQuery spritely 0.6\n * http://spritely.net/\n *\n * Documentation:\n * http://spritely.net/documentation/\n *\n * Copyright 2010-2011, Peter Chater, Artlogic Media Ltd, http://www.artlogic.net/\n * Dual licensed under the MIT or GPL Version 2 licenses.\n *\n * Change history:\n * Version 0.6\n *   - added events to the .sprite() method: on_first_frame, on_last_frame, on_frame:\n *     $('#sprite').sprite({\n *         fps: 9, \n *         no_of_frames: 24, \n *         on_first_frame: function(obj) {\n *             obj.spState(1); // change to state 1 (first row) on frame 1\n *         }, \n *         on_last_frame: function(obj) {\n *             obj.spStop(); // stop the animation on the last frame\n *         },\n *         on_frame: {\n *             8: function(obj) {\n *                 obj.spState(2); // change to state 2 (row 2) on frame 8\n *             },\n *             16: function(obj) {\n *                 obj.spState(3); // change to state 3 (row 3) on frame 16\n *             }\n *         }\n *     });\n *   - added start_at_frame: $('#sprite').sprite({fps: 9, no_of_frames: 24, start_at_frame: 8});\n * Version 0.5\n *   - added a 'destroy()' method which will stop the element's sprite behaviour, without actually removing the element. Example: $('#my_sprite').destroy()\n * Version 0.4\n *   - add up/down for 'pan' method. <ricky.hewitt@artlogic.net>\n *   - added 'dir' option for Sprites. This means a Sprite can be played in reverse.\n *   - removed alert message regarding jQuery.draggable (now uses console.log, if available) <ricky.hewitt@artlogic.net>\n * Version 0.3b\n *   - added lockTo method for locking sprites to background images. $('#sprite').lockTo('#background, {'left': 380, 'top': -60, 'bg_img_width': 1110});\n * Version 0.2.1\n *   - animate function will stop cycling after play_frames has completed\n * Version 0.2 beta\n *   - added isDraggable method (requires jquery-ui) $('#sprite').sprite().isDraggable({start: null, stop: function() {alert('Ouch! You dropped me!')});\n *   - sprites may be set to play a limited number of frames when instantiated, e.g. $('#sprite').sprite({fps: 9, no_of_frames: 3, play_frames: 30})\n *   - sprite speed may be controlled at any point by setting the frames-per-second $('#sprite').fps(20);\n *   - sprites with multiple rows of frames may have there 'state' changed, e.g. to make the second row of frames\n *     active, use: $('#sprite').spState(2); - to return to the first row, use $('#sprite').spState(1);\n *   - background element speed may be controlled at any point with .spSpeed(), e.g. $('#bg1').spSpeed(10)\n *   - background elements may be set to a depth where 100 is the viewer (up close) and 0 is the horizon, e.g.:\n *     $('#bg1').pan({fps: 30, speed: 2, dir: 'left', depth: 30});\n *     $('#bg2').pan({fps: 30, speed: 3, dir: 'left', depth: 70});\n *     relative speed of backgrounds may now be set in a single action with $('#bg1, #bg2').spRelSpeed(20);\n *     which will make elements closer to the horizon (lower depths) move slower than closer elements (higher depths)\n */\n\n(function($) {\n    $._spritely = {\n        // shared methods and variables used by spritely plugin\n        animate: function(options) {\n            var el = $(options.el);\n            var el_id = el.attr('id');\n            if (!$._spritely.instances[el_id]) {\n                return this;\n            }\n            options = $.extend(options, $._spritely.instances[el_id] || {});\n            if (options.play_frames && !$._spritely.instances[el_id]['remaining_frames']) {\n                $._spritely.instances[el_id]['remaining_frames'] = options.play_frames + 1;\n            }\n            if (options.type == 'sprite' && options.fps) {\n                var frames;\n                var animate = function(el) {\n                    var w = options.width, h = options.height;\n                    if (!frames) {\n                        frames = [];\n                        total = 0\n                        for (var i = 0; i < options.no_of_frames; i ++) {\n                            frames[frames.length] = (0 - total);\n                            total += w;\n                        }\n                    }\n                    if ($._spritely.instances[el_id]['current_frame'] == 0) {\n                        if (options.on_first_frame) {\n                            options.on_first_frame(el);\n                        }\n                    } else if ($._spritely.instances[el_id]['current_frame'] == frames.length - 1) {\n                        if (options.on_last_frame) {\n                            options.on_last_frame(el);\n                        }\n                    }\n                    if (options.on_frame && options.on_frame[$._spritely.instances[el_id]['current_frame']]) {\n                        options.on_frame[$._spritely.instances[el_id]['current_frame']](el);\n                    }\n                    if (options.rewind == true) {\n                        if ($._spritely.instances[el_id]['current_frame'] <= 0) {\n                            $._spritely.instances[el_id]['current_frame'] = frames.length - 1;\n                        } else {\n                            $._spritely.instances[el_id]['current_frame'] = $._spritely.instances[el_id]['current_frame'] - 1;\n                        };\n                    } else {\n                        if ($._spritely.instances[el_id]['current_frame'] >= frames.length - 1) {\n                            $._spritely.instances[el_id]['current_frame'] = 0;\n                        } else {\n                            $._spritely.instances[el_id]['current_frame'] = $._spritely.instances[el_id]['current_frame'] + 1;\n                        }\n                    }\n\n                    var yPos = $._spritely.getBgY(el);\n                    el.css('background-position', frames[$._spritely.instances[el_id]['current_frame']] + 'px ' + yPos);\n                    if (options.bounce && options.bounce[0] > 0 && options.bounce[1] > 0) {\n                        var ud = options.bounce[0]; // up-down\n                        var lr = options.bounce[1]; // left-right\n                        var ms = options.bounce[2]; // milliseconds\n                        el\n                            .animate({top: '+=' + ud + 'px', left: '-=' + lr + 'px'}, ms)\n                            .animate({top: '-=' + ud + 'px', left: '+=' + lr + 'px'}, ms);\n                    }\n                }\n                if ($._spritely.instances[el_id]['remaining_frames'] && $._spritely.instances[el_id]['remaining_frames'] > 0) {\n                    $._spritely.instances[el_id]['remaining_frames'] --;\n                    if ($._spritely.instances[el_id]['remaining_frames'] == 0) {\n                        $._spritely.instances[el_id]['remaining_frames'] = -1;\n                        delete $._spritely.instances[el_id]['remaining_frames'];\n                        return;\n                    } else {\n                        animate(el);\n                    }\n                } else if ($._spritely.instances[el_id]['remaining_frames'] != -1) {\n                    animate(el);\n                }\n            } else if (options.type == 'pan') {\n                if (!$._spritely.instances[el_id]['_stopped']) {\n                                        if (options.dir == 'up') {\n                                            $._spritely.instances[el_id]['l'] = $._spritely.getBgX(el).replace('px', '');\n                                            $._spritely.instances[el_id]['t'] = ($._spritely.instances[el_id]['t'] - (options.speed || 1)) || 0;\n                                        }\n                                        else if (options.dir == 'down') {\n                                            $._spritely.instances[el_id]['l'] = $._spritely.getBgX(el).replace('px', '');\n                                            $._spritely.instances[el_id]['t'] = ($._spritely.instances[el_id]['t'] + (options.speed || 1)) || 0;\n                                        }\n                    else if (options.dir == 'left') {\n                        $._spritely.instances[el_id]['l'] = ($._spritely.instances[el_id]['l'] - (options.speed || 1)) || 0;\n                                                $._spritely.instances[el_id]['t'] = $._spritely.getBgY(el).replace('px', '');\n                    } else {\n                        $._spritely.instances[el_id]['l'] = ($._spritely.instances[el_id]['l'] + (options.speed || 1)) || 0;\n                                                $._spritely.instances[el_id]['t'] = $._spritely.getBgY(el).replace('px', '');\n                    }\n\n                                        // When assembling the background-position string, care must be taken\n                                        // to ensure correct formatting.. <ricky.hewitt@artlogic.net>\n                                        var bg_left = $._spritely.instances[el_id]['l'].toString();\n                                        if (bg_left.indexOf('%') == -1) {\n                                            bg_left += 'px ';\n                                        } else { bg_left += ' '; }\n\n                                        var bg_top = $._spritely.instances[el_id]['t'].toString();\n                                        if (bg_top.indexOf('%') == -1) {\n                                            bg_top += 'px ';\n                                        } else { bg_top += ' '; }\n\n                    $(el).css('background-position', bg_left + bg_top);\n                }\n            }\n            $._spritely.instances[el_id]['options'] = options;\n            window.setTimeout(function() {\n                $._spritely.animate(options);\n            }, parseInt(1000 / options.fps));\n        },\n        randomIntBetween: function(lower, higher) {\n            return parseInt(rand_no = Math.floor((higher - (lower - 1)) * Math.random()) + lower);\n        },\n        getBgY: function(el) {\n            if ($.browser.msie) {\n                // fixme - the background-position property does not work\n                // correctly in IE so we have to hack it here... Not ideal\n                // especially as $.browser is depricated\n                var bgY = $(el).css('background-position-y') || '0';\n            } else {\n                var bgY = ($(el).css('background-position') || ' ').split(' ')[1];\n            }\n            return bgY;\n        },\n        getBgX: function(el) {\n            if ($.browser.msie) {\n                // see note, above\n                var bgX = $(el).css('background-position-x') || '0';\n            } else {\n                var bgX = ($(el).css('background-position') || ' ').split(' ')[0];\n            }\n            return bgX;\n        },\n        get_rel_pos: function(pos, w) {\n            // return the position of an item relative to a background\n            // image of width given by w\n            var r = pos;\n            if (pos < 0) {\n                while (r < 0) {\n                    r += w;\n                }\n            } else {\n                while (r > w) {\n                    r -= w;\n                }\n            }\n            return r;\n        }\n    };\n    $.fn.extend({\n        spritely: function(options) {\n            var options = $.extend({\n                type: 'sprite',\n                do_once: false,\n                width: null,\n                height: null,\n                fps: 12,\n                no_of_frames: 2,\n                stop_after: null\n            }, options || {});\n            var el_id = $(this).attr('id');\n            if (!$._spritely.instances) {\n                $._spritely.instances = {};\n            }\n            if (!$._spritely.instances[el_id]) {\n                if (options.start_at_frame) {\n                    $._spritely.instances[el_id] = {current_frame: options.start_at_frame - 1};\n                } else {\n                    $._spritely.instances[el_id] = {current_frame: -1};\n                }\n            }\n            $._spritely.instances[el_id]['type'] = options.type;\n            $._spritely.instances[el_id]['depth'] = options.depth;\n            options.el = this;\n            options.width = options.width || $(this).width() || 100;\n            options.height = options.height || $(this).height() || 100;\n            var get_rate = function() {\n                return parseInt(1000 / options.fps);\n            }\n            if (!options.do_once) {\n                window.setTimeout(function() {\n                    $._spritely.animate(options);\n                }, get_rate(options.fps));\n            } else {\n                $._spritely.animate(options);\n            }\n            return this; // so we can chain events\n        },\n        sprite: function(options) {\n            var options = $.extend({\n                type: 'sprite',\n                bounce: [0, 0, 1000] // up-down, left-right, milliseconds\n            }, options || {});\n            return $(this).spritely(options);\n        },\n        pan: function(options) {\n            var options = $.extend({\n                type: 'pan',\n                dir: 'left',\n                continuous: true,\n                speed: 1 // 1 pixel per frame\n            }, options || {});\n            return $(this).spritely(options);\n        },\n        flyToTap: function(options) {\n            var options = $.extend({\n                el_to_move: null,\n                type: 'moveToTap',\n                ms: 1000, // milliseconds\n                do_once: true\n            }, options || {});\n            if (options.el_to_move) {\n                $(options.el_to_move).active();\n            }\n            if ($._spritely.activeSprite) {\n                if (window.Touch) { // iphone method see http://cubiq.org/remove-onclick-delay-on-webkit-for-iphone/9 or http://www.nimblekit.com/tutorials.html for clues...\n                    $(this)[0].ontouchstart = function(e) {\n                        var el_to_move = $._spritely.activeSprite;\n                        var touch = e.touches[0];\n                        var t = touch.pageY - (el_to_move.height() / 2);\n                        var l = touch.pageX - (el_to_move.width() / 2);\n                        el_to_move.animate({\n                            top: t + 'px',\n                            left: l + 'px'\n                        }, 1000);\n                    };\n                } else {\n                    $(this).click(function(e) {\n                        var el_to_move = $._spritely.activeSprite;\n                        $(el_to_move).stop(true);\n                        var w = el_to_move.width();\n                        var h = el_to_move.height();\n                        var l = e.pageX - (w / 2);\n                        var t = e.pageY - (h / 2);\n                        el_to_move.animate({\n                            top: t + 'px',\n                            left: l + 'px'\n                        }, 1000);\n                    });\n                }\n            }\n            return this;\n        },\n        // isDraggable requires jQuery ui\n        isDraggable: function(options) {\n            if ((!$(this).draggable)) {\n                //console.log('To use the isDraggable method you need to load jquery-ui.js');\n                return this;\n            }\n            var options = $.extend({\n                type: 'isDraggable',\n                start: null,\n                stop: null,\n                drag: null\n            }, options || {});\n            var el_id = $(this).attr('id');\n            if (!$._spritely.instances[el_id]) {\n                return this;\n            }\n            $._spritely.instances[el_id].isDraggableOptions = options;\n            $(this).draggable({\n                start: function() {\n                    var el_id = $(this).attr('id');\n                    $._spritely.instances[el_id].stop_random = true;\n                    $(this).stop(true);\n                    if ($._spritely.instances[el_id].isDraggableOptions.start) {\n                        $._spritely.instances[el_id].isDraggableOptions.start(this);\n                    }\n                },\n                drag: options.drag,\n                stop: function() {\n                    var el_id = $(this).attr('id');\n                    $._spritely.instances[el_id].stop_random = false;\n                    if ($._spritely.instances[el_id].isDraggableOptions.stop) {\n                        $._spritely.instances[el_id].isDraggableOptions.stop(this);\n                    }\n                }\n            });\n            return this;\n        },\n        active: function() {\n            // the active sprite\n            $._spritely.activeSprite = this;\n            return this;\n        },\n        activeOnClick: function() {\n            // make this the active script if clicked...\n            var el = $(this);\n            if (window.Touch) { // iphone method see http://cubiq.org/remove-onclick-delay-on-webkit-for-iphone/9 or http://www.nimblekit.com/tutorials.html for clues...\n                el[0].ontouchstart = function(e) {\n                    $._spritely.activeSprite = el;\n                };\n            } else {\n                el.click(function(e) {\n                    $._spritely.activeSprite = el;\n                });\n            }\n            return this;\n        },\n        spRandom: function(options) {\n            var options = $.extend({\n                top: 50,\n                left: 50,\n                right: 290,\n                bottom: 320,\n                speed: 4000,\n                pause: 0\n            }, options || {});\n            var el_id = $(this).attr('id');\n            if (!$._spritely.instances[el_id]) {\n                return this;\n            }\n            if (!$._spritely.instances[el_id].stop_random) {\n                var r = $._spritely.randomIntBetween;\n                var t = r(options.top, options.bottom);\n                var l = r(options.left, options.right);\n                $('#' + el_id).animate({\n                    top: t + 'px',\n                    left: l + 'px'\n                }, options.speed)\n            }\n            window.setTimeout(function() {\n                $('#' + el_id).spRandom(options);\n            }, options.speed + options.pause)\n            return this;\n        },\n        makeAbsolute: function() {\n            // remove an element from its current position in the DOM and\n            // position it absolutely, appended to the body tag.\n            return this.each(function() {\n                var el = $(this);\n                var pos = el.position();\n                el.css({position: \"absolute\", marginLeft: 0, marginTop: 0, top: pos.top, left: pos.left })\n                    .remove()\n                    .appendTo(\"body\");\n            });\n\n        },\n        spSet: function(prop_name, prop_value) {\n            var el_id = $(this).attr('id');\n            $._spritely.instances[el_id][prop_name] = prop_value;\n            return this;\n        },\n        spGet: function(prop_name, prop_value) {\n            var el_id = $(this).attr('id');\n            return $._spritely.instances[el_id][prop_name];\n        },\n        spStop: function(bool) {\n            $(this).each(function() {\n                var el_id = $(this).attr('id');\n                $._spritely.instances[el_id]['_last_fps'] = $(this).spGet('fps');\n                $._spritely.instances[el_id]['_stopped'] = true;\n                $._spritely.instances[el_id]['_stopped_f1'] = bool;\n                if ($._spritely.instances[el_id]['type'] == 'sprite') {\n                    $(this).spSet('fps', 0);\n                }\n                if (bool) {\n                    // set background image position to 0\n                    var bp_top = $._spritely.getBgY($(this));\n                    $(this).css('background-position', '0 ' + bp_top);\n                }\n            });\n            return this;\n        },\n        spStart: function() {\n            $(this).each(function() {\n                var el_id = $(this).attr('id');\n                var fps = $._spritely.instances[el_id]['_last_fps'] || 12;\n                $._spritely.instances[el_id]['_stopped'] = false;\n                if ($._spritely.instances[el_id]['type'] == 'sprite') {\n                    $(this).spSet('fps', fps);\n                }\n            });\n            return this;\n        },\n        spToggle: function() {\n            var el_id = $(this).attr('id');\n            var stopped = $._spritely.instances[el_id]['_stopped'] || false;\n            var stopped_f1 = $._spritely.instances[el_id]['_stopped_f1'] || false;\n            if (stopped) {\n                $(this).spStart();\n            } else {\n                $(this).spStop(stopped_f1);\n            }\n            return this;\n        },\n        fps: function(fps) {\n            $(this).each(function() {\n                $(this).spSet('fps', fps);\n            });\n            return this;\n        },\n        spSpeed: function(speed) {\n            $(this).each(function() {\n                $(this).spSet('speed', speed);\n            });\n            return this;\n        },\n        spRelSpeed: function(speed) {\n            $(this).each(function() {\n                var rel_depth = $(this).spGet('depth') / 100;\n                $(this).spSet('speed', speed * rel_depth);\n            });\n            return this;\n        },\n        spChangeDir: function(dir) {\n            $(this).each(function() {\n                $(this).spSet('dir', dir);\n            });\n            return this;\n        },\n        spState: function(n) {\n            $(this).each(function() {\n                // change state of a sprite, where state is the vertical\n                // position of the background image (e.g. frames row)\n                var yPos = ((n - 1) * $(this).height()) + 'px';\n                var xPos = $._spritely.getBgX($(this));\n                var bp = xPos + ' -' + yPos;\n                $(this).css('background-position', bp);\n            });\n            return this;\n        },\n        lockTo: function(el, options) {\n            $(this).each(function() {\n                var el_id = $(this).attr('id');\n                if (!$._spritely.instances[el_id]) {\n                    return this;\n                }\n                $._spritely.instances[el_id]['locked_el'] = $(this);\n                $._spritely.instances[el_id]['lock_to'] = $(el);\n                $._spritely.instances[el_id]['lock_to_options'] = options;\n                window.setInterval(function() {\n                    if ($._spritely.instances[el_id]['lock_to']) {\n                        var locked_el = $._spritely.instances[el_id]['locked_el'];\n                        var locked_to_el = $._spritely.instances[el_id]['lock_to'];\n                        var locked_to_options = $._spritely.instances[el_id]['lock_to_options'];\n                        var locked_to_el_w = locked_to_options.bg_img_width;\n                        var locked_to_el_h = locked_to_el.height();\n                        var locked_to_el_y = $._spritely.getBgY(locked_to_el);\n                        var locked_to_el_x = $._spritely.getBgX(locked_to_el);\n                        var el_l = (parseInt(locked_to_el_x) + parseInt(locked_to_options['left']));\n                        var el_t = (parseInt(locked_to_el_y) + parseInt(locked_to_options['top']));\n                        el_l = $._spritely.get_rel_pos(el_l, locked_to_el_w);\n                        $(locked_el).css({\n                            'top': el_t + 'px',\n                            'left': el_l + 'px'\n                        });\n                    }\n                }, options.interval || 20);\n            });\n            return this;\n        },\n        destroy: function() {\n            var el = $(this);\n            var el_id = $(this).attr('id');\n            delete $._spritely.instances[el_id]\n            return this;\n        }\n    })\n})(jQuery);\n// Stop IE6 re-loading background images continuously\ntry {\n  document.execCommand(\"BackgroundImageCache\", false, true);\n} catch(err) {} "
  },
  {
    "path": "samples/Nancy.Demo.MarkdownViewEngine/Model/BlogModel.cs",
    "content": "﻿namespace Nancy.Demo.MarkdownViewEngine\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Globalization;\r\n    using System.Linq;\r\n    using System.Text;\r\n    using System.Text.RegularExpressions;\r\n\r\n    using MarkdownSharp;\r\n\r\n    [Serializable]\r\n    public class BlogModel\r\n    {\r\n        private static readonly Regex SSVESubstitution = new Regex(\"^@[^$]*?$\",\r\n                                                                   RegexOptions.Compiled | RegexOptions.IgnoreCase |\r\n                                                                   RegexOptions.Multiline);\r\n\r\n        private readonly Markdown parser = new Markdown();\r\n\r\n        private readonly Dictionary<string, string> metaData = new Dictionary<string, string>();\r\n\r\n        public string Title { get; private set; }\r\n\r\n        public string Abstract { get; private set; }\r\n\r\n        public DateTime BlogDate { get; private set; }\r\n\r\n        public string FriendlyDate\r\n        {\r\n            get { return BlogDate.ToString(\"dddd,MMMM dd, yyyy\"); }\r\n        }\r\n\r\n        public IEnumerable<string> Tags { get; private set; }\r\n\r\n        public string Slug { get; private set; }\r\n\r\n        public BlogModel(string markdown)\r\n        {\r\n            string metadata = markdown.Contains(\"@Tags\")\r\n                           ? markdown.Substring(markdown.IndexOf(\"@Tags\", StringComparison.Ordinal) + 5,\r\n                                                markdown.IndexOf(\"@EndTags\", StringComparison.Ordinal) - 7)\r\n                           : string.Empty;\r\n\r\n            var metadataSplit = metadata.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);\r\n\r\n            foreach (var item in metadataSplit)\r\n            {\r\n                var itemdata = item.Split(new string[] { \":\" }, StringSplitOptions.RemoveEmptyEntries);\r\n                if (itemdata.Length < 2)\r\n                    continue;\r\n                metaData.Add(itemdata[0].Trim(), itemdata[1].Trim());\r\n            }\r\n\r\n            BlogDate = GetBlogDate();\r\n            Title = GetTitle();\r\n            Slug = GenerateSlug();\r\n            Abstract = GetAbstract(markdown);\r\n            Tags = GetTags();\r\n        }\r\n\r\n        private IEnumerable<string> GetTags()\r\n        {\r\n            if (!metaData.Any(x => x.Key == \"Tags\"))\r\n                return Enumerable.Empty<string>();\r\n\r\n            var csv = metaData.FirstOrDefault(x => x.Key == \"Tags\").Value;\r\n\r\n            return csv.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim());\r\n        }\r\n\r\n        private DateTime GetBlogDate()\r\n        {\r\n            if (!metaData.Any(x => x.Key == \"Date\"))\r\n                return DateTime.MinValue;\r\n\r\n            var kvp = metaData.FirstOrDefault(x => x.Key == \"Date\");\r\n\r\n            DateTime blogDateTime = DateTime.ParseExact(kvp.Value, \"dd/MM/yyyy\", CultureInfo.InvariantCulture);\r\n\r\n            return blogDateTime;\r\n        }\r\n\r\n        private string GetTitle()\r\n        {\r\n            if (!metaData.Any(x => x.Key == \"Title\"))\r\n                return string.Empty;\r\n\r\n            return metaData.FirstOrDefault(x => x.Key == \"Title\").Value;\r\n        }\r\n\r\n        private string GetAbstract(string content)\r\n        {\r\n            if (string.IsNullOrWhiteSpace(content))\r\n                return string.Empty;\r\n\r\n            if (content.Contains(\"@Tags\"))\r\n            {\r\n                content = content.Substring(content.IndexOf(\"@EndTags\", StringComparison.Ordinal) + 8);\r\n            }\r\n\r\n            string ssveRemoved = SSVESubstitution.Replace(content, \"\").Trim();\r\n            var abstractpost = ssveRemoved.Substring(0, 175).Trim();\r\n            var html = parser.Transform(abstractpost);\r\n            html = html + \"<p><a href='\" + this.Slug + \"'>Read More...</a>\";\r\n            return html.Substring(html.IndexOf(\"<p>\", StringComparison.Ordinal));\r\n        }\r\n\r\n        private string GenerateSlug(char spacer = '-', bool removeStopWords = false)\r\n        {\r\n            string str = RemoveAccent(Title).ToLower();\r\n            str = str.Replace(\"-\", \" \");\r\n            str = Regex.Replace(str, @\"[^a-z0-9\\s-]\", \"\"); // invalid chars\r\n            str = Regex.Replace(str, @\"\\s+\", \" \").Trim(); // convert multiple spaces into one space   \r\n            str = str.Substring(0, str.Length <= 100 ? str.Length : 100).Trim(); // cut and trim it   \r\n            str = Regex.Replace(str, @\"\\s\", spacer.ToString(CultureInfo.InvariantCulture)); // hyphens   \r\n\r\n            if (removeStopWords)\r\n            {\r\n                var stopWords = \"a,all,also,am,an,and,as,at,be,but,by,can,could,did,do,does,for,from,get,got,had,has,have,he,how,i,if,in,into,is,it,its,me,my,no,nor,not,of,off,on,or,other,our,so,some,than,that,the,their,them,then,there,these,they,this,tis,to,too,us,was,we,were,yet,you,your\".Split(',');\r\n                str = string.Join(spacer.ToString(CultureInfo.InvariantCulture), str.Split(spacer).Where(o => !stopWords.Contains(o)));\r\n            }\r\n\r\n            return str;\r\n        }\r\n\r\n        public string RemoveAccent(string txt)\r\n        {\r\n            byte[] bytes = Encoding.GetEncoding(\"Cyrillic\").GetBytes(txt);\r\n            return Encoding.ASCII.GetString(bytes);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.MarkdownViewEngine/Modules/HomeModule.cs",
    "content": "namespace Nancy.Demo.MarkdownViewEngine.Modules\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Dynamic;\r\n    using System.Linq;\r\n\r\n    using Nancy.ViewEngines;\r\n\r\n    public class HomeModule : NancyModule\r\n    {\r\n        private readonly IViewLocationProvider viewLocationProvider;\r\n\r\n        public HomeModule(IViewLocationProvider viewLocationProvider)\r\n        {\r\n            this.viewLocationProvider = viewLocationProvider;\r\n\r\n            Get(\"/\", args =>\r\n            {\r\n                var popularposts = GetModel();\r\n\r\n                dynamic postModel = new ExpandoObject();\r\n                postModel.PopularPosts = popularposts;\r\n                postModel.MetaData = popularposts;\r\n\r\n                return View[\"blogindex\", postModel];\r\n            });\r\n\r\n            Get(\"/{viewname}\", args =>\r\n            {\r\n                var popularposts = GetModel();\r\n\r\n                dynamic postModel = new ExpandoObject();\r\n                postModel.PopularPosts = popularposts;\r\n                postModel.MetaData =\r\n                popularposts.FirstOrDefault(x => x.Slug == args.viewname);\r\n\r\n                return View[\"Posts/\" + args.viewname, postModel];\r\n            });\r\n        }\r\n\r\n        private IEnumerable<BlogModel> GetModel()\r\n        {\r\n            var views = this.viewLocationProvider.GetLocatedViews(new[] { \"md\", \"markdown\" });\r\n            var model = views.Select(x =>\r\n            {\r\n                using (var reader = x.Contents())\r\n                {\r\n                    var markdown = reader.ReadToEnd();\r\n                    return new BlogModel(markdown);\r\n                }\r\n            })\r\n            .Where(x => x.BlogDate.Date <= DateTime.Today) //Allow for future posts to be lined up but don't show\r\n            .OrderByDescending(x => x.BlogDate)\r\n            .ToList();\r\n\r\n            return model;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "samples/Nancy.Demo.MarkdownViewEngine/Nancy.Demo.MarkdownViewEngine.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project DefaultTargets=\"Build\" ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\r\n  <PropertyGroup>\r\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\r\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\r\n    <ProductVersion>10.0.0</ProductVersion>\r\n    <SchemaVersion>2.0</SchemaVersion>\r\n    <ProjectGuid>{B6929D0B-5104-4C7E-979D-F4914E813FA6}</ProjectGuid>\r\n    <ProjectTypeGuids>{349C5851-65DF-11DA-9384-00065B846F21};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>\r\n    <OutputType>Library</OutputType>\r\n    <RootNamespace>Nancy.Demo.MarkdownViewEngine</RootNamespace>\r\n    <AssemblyName>Nancy.Demo.MarkdownViewEngine</AssemblyName>\r\n    <OldToolsVersion>4.0</OldToolsVersion>\r\n    <UseIISExpress>false</UseIISExpress>\r\n    <SolutionDir Condition=\"$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'\">..\\..\\</SolutionDir>\r\n    <RestorePackages>true</RestorePackages>\r\n    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\r\n    <IISExpressSSLPort />\r\n    <IISExpressAnonymousAuthentication />\r\n    <IISExpressWindowsAuthentication />\r\n    <IISExpressUseClassicPipelineMode />\r\n    <UseGlobalApplicationHostFile />\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\r\n    <DebugSymbols>True</DebugSymbols>\r\n    <DebugType>full</DebugType>\r\n    <Optimize>False</Optimize>\r\n    <OutputPath>bin</OutputPath>\r\n    <DefineConstants>DEBUG;</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <ConsolePause>False</ConsolePause>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\r\n    <DebugType>none</DebugType>\r\n    <Optimize>True</Optimize>\r\n    <OutputPath>bin</OutputPath>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <ConsolePause>False</ConsolePause>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <ItemGroup>\r\n    <Reference Include=\"MarkdownSharp, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL\">\r\n      <SpecificVersion>False</SpecificVersion>\r\n      <HintPath>..\\..\\packages\\MarkdownSharp.1.13.0.0\\lib\\35\\MarkdownSharp.dll</HintPath>\r\n    </Reference>\r\n    <Reference Include=\"Microsoft.CSharp\" />\r\n    <Reference Include=\"System\" />\r\n    <Reference Include=\"System.Web\" />\r\n    <Reference Include=\"System.Xml\" />\r\n    <Reference Include=\"System.Xml.Linq\" />\r\n  </ItemGroup>\r\n  <PropertyGroup>\r\n    <VisualStudioVersion Condition=\"'$(VisualStudioVersion)' == ''\">10.0</VisualStudioVersion>\r\n    <VSToolsPath Condition=\"'$(VSToolsPath)' == ''\">$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)</VSToolsPath>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoDevelop|AnyCPU'\">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;</DefineConstants>\r\n    <DebugType>full</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoRelease|AnyCPU'\">\r\n    <OutputPath>bin\\</OutputPath>\r\n    <Optimize>true</Optimize>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\r\n  <Import Project=\"$(VSToolsPath)\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"'$(VSToolsPath)' != ''\" />\r\n  <Import Project=\"$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v10.0\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"false\" />\r\n  <ProjectExtensions>\r\n    <MonoDevelop>\r\n      <Properties VerifyCodeBehindFields=\"True\" VerifyCodeBehindEvents=\"True\">\r\n        <XspParameters Port=\"8080\" Address=\"127.0.0.1\" SslMode=\"None\" SslProtocol=\"Default\" KeyType=\"None\" CertFile=\"\" KeyFile=\"\" PasswordOptions=\"None\" Password=\"\" Verbose=\"True\" />\r\n      </Properties>\r\n    </MonoDevelop>\r\n    <VisualStudio>\r\n      <FlavorProperties GUID=\"{349C5851-65DF-11DA-9384-00065B846F21}\">\r\n        <WebProjectProperties>\r\n          <UseIIS>False</UseIIS>\r\n          <AutoAssignPort>True</AutoAssignPort>\r\n          <DevelopmentServerPort>52805</DevelopmentServerPort>\r\n          <DevelopmentServerVPath>/</DevelopmentServerVPath>\r\n          <IISUrl>\r\n          </IISUrl>\r\n          <NTLMAuthentication>False</NTLMAuthentication>\r\n          <UseCustomServer>False</UseCustomServer>\r\n          <CustomServerUrl>\r\n          </CustomServerUrl>\r\n          <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>\r\n        </WebProjectProperties>\r\n      </FlavorProperties>\r\n    </VisualStudio>\r\n  </ProjectExtensions>\r\n  <ItemGroup>\r\n    <Content Include=\"Content\\blog.css\" />\r\n    <Content Include=\"Content\\images\\body.png\" />\r\n    <Content Include=\"Content\\images\\cloud1.png\" />\r\n    <Content Include=\"Content\\images\\cloud2.png\" />\r\n    <Content Include=\"Content\\images\\cloud3.png\" />\r\n    <Content Include=\"Content\\images\\logo.png\" />\r\n    <Content Include=\"Content\\images\\mountain.png\" />\r\n    <Content Include=\"Content\\images\\nancy-nuget.png\" />\r\n    <Content Include=\"Content\\images\\post-foot.png\" />\r\n    <Content Include=\"Content\\images\\post-head.png\" />\r\n    <Content Include=\"Content\\images\\post-midd.png\" />\r\n    <Content Include=\"Content\\js\\jquery.spritely-0.6.js\" />\r\n    <Content Include=\"Views\\blogfooter.html\" />\r\n    <Content Include=\"Views\\blogheader.html\" />\r\n    <Content Include=\"Views\\blogindex.html\" />\r\n    <Content Include=\"Views\\master.html\" />\r\n    <Content Include=\"Views\\popularposts.html\" />\r\n    <Content Include=\"Views\\Posts\\why-use-nancy.md\" />\r\n    <Content Include=\"Views\\Posts\\my-first-blog-post.md\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Compile Include=\"Model\\BlogModel.cs\" />\r\n    <Compile Include=\"Modules\\HomeModule.cs\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"web.config\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.Hosting.Aspnet.MSBuild\\Nancy.Hosting.Aspnet.csproj\">\r\n      <Project>{15b7f794-0bb2-4b66-ad78-4a951f1209b2}</Project>\r\n      <Name>Nancy.Hosting.Aspnet</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.ViewEngines.Markdown.MSBuild\\Nancy.ViewEngines.Markdown.csproj\">\r\n      <Project>{864af449-0902-44fc-beee-06ba9a6f4a8f}</Project>\r\n      <Name>Nancy.ViewEngines.Markdown</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.MSBuild\\Nancy.csproj\">\r\n      <Project>{34576216-0dca-4b0f-a0dc-9075e75a676f}</Project>\r\n      <Name>Nancy</Name>\r\n    </ProjectReference>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Views\\Posts\\readme.md\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Views\\Posts\\future-post.md\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"packages.config\" />\r\n  </ItemGroup>\r\n</Project>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.MarkdownViewEngine/Views/Posts/future-post.md",
    "content": "﻿@Master['master']\r\n\r\n@Tags\r\nDate: 21/02/2099\r\nTitle: Future Post\r\nTags: Blogging,Internet\r\n@EndTags\r\n\r\n@Section['Content']\r\n\r\n@Partial['blogheader', Model.MetaData];\r\n\r\n# Future post!\r\n\r\nNow that we know who you are, I know who I am. I'm not a mistake! It all makes sense! In a comic, you know how you can tell who the arch-villain's going to be? He's the exact opposite of the hero. And most times they're friends, like you and me! I should've known way back when... You know why, David? Because of the kids. They called me Mr Glass.\r\n\r\n@Partial['blogfooter', Model.MetaData];\r\n\r\n@EndSection"
  },
  {
    "path": "samples/Nancy.Demo.MarkdownViewEngine/Views/Posts/my-first-blog-post.md",
    "content": "﻿@Master['master']\r\n\r\n@Tags\r\nDate: 21/02/2012\r\nTitle: My First Blog Post\r\nTags: Blogging,Internet\r\n@EndTags\r\n\r\n@Section['Content']\r\n\r\n@Partial['blogheader', Model.MetaData];\r\n\r\n# First post!\r\n\r\nBacon ipsum dolor sit amet strip steak frankfurter bacon corned beef tenderloin chuck, prosciutto beef turkey tri-tip. Prosciutto spare ribs strip steak pork loin bresaola, pork chop sausage. Tri-tip salami ham hock pork pork belly fatback bresaola prosciutto turducken sirloin pork loin andouille sausage. Drumstick sausage tri-tip filet mignon doner corned beef kielbasa, chuck swine shank salami. Prosciutto pork chop biltong cow, leberkas ham hock ground round swine sausage ball tip tenderloin. Turducken pork chop ball tip, short loin frankfurter jowl pig. Prosciutto tail tri-tip, pancetta meatloaf doner ham flank venison pork loin filet mignon sausage.\r\n\r\n@Partial['blogfooter', Model.MetaData];\r\n\r\n@EndSection"
  },
  {
    "path": "samples/Nancy.Demo.MarkdownViewEngine/Views/Posts/readme.md",
    "content": "﻿@Master['master']\r\n\r\n@Tags\r\nDate: 15/03/2013\r\nTitle: Readme\r\nTags: Nancy,Runtime\r\n@EndTags\r\n\r\n@Section['Content']\r\n\r\n@Partial['blogheader', Model.MetaData];\r\n\r\n# Readme!\r\n\r\n## Markdown Viewengine\r\n\r\nThis Markdown Viewengine allows views to be written in Markdown.\r\n\r\n* Full Model support\r\n* Master page support\r\n* Supports HTML within any MD content\r\n* Simple call `return View[\"Home\"]` for Nancy to render your MD file\r\n\r\n## Markdown Blog Demo\r\n\r\n* Allows for dropping in Markdown files into a directory\r\n* Allows for future post scheduling\r\n* Generates slug automatically\r\n* Uses meta data for date, tags, title\r\n* Allows for custom HTML design\r\n\r\n@Partial['blogfooter', Model.MetaData];\r\n\r\n@EndSection"
  },
  {
    "path": "samples/Nancy.Demo.MarkdownViewEngine/Views/Posts/why-use-nancy.md",
    "content": "﻿@Master['master']\r\n\r\n@Tags\r\nDate: 19/12/2012\r\nTitle: Why use Nancy\r\nTags: Nancy,.Net,C#\r\n@EndTags\r\n\r\n@Section['Content']\r\n\r\n@Partial['blogheader', Model.MetaData];\r\n\r\n# Why use Nancy?\r\n\r\nWhen a new project comes along why should you automatically choose ASP.NET MVC?  Yes, its Microsoft based so you may have more of your peers fluent already in that architecture but is there an alternative, a better alternative?\r\n\r\nI believe so and its called [NancyFX][1].  Your first reaction, what is so special about Nancy?  I also believe you’ll ask what is wrong with ASP.NET MVC but maybe you should look at it differently and ask what is right with Nancy?\r\n\r\n## What is Nancy?\r\nNancy is a lightweight framework for building websites / services without getting in your way. It’s heavily inspired by a Ruby project called Sinatra, which happens to identify itself as not being a framework, since it doesn’t include all the plumbing of things such as an ORM, lots of configuration, etc. \r\n\r\n##Does it implement MVC?\r\nNancy does not force you to adhere to the model-view-controller pattern, or any other pattern. It’s nothing more than a service endpoint responding to HTTP verbs. Making it ideal for building Websites, Web Services and APIs.\r\n\r\nThat doesn’t mean you can’t apply the MVC pattern to Nancy. You can define Views and put them in a Views folder, create Models to return from your endpoints, and map requests to Models, just like you currently do with ASP.NET MVC. \r\n\r\n##Key Considerations\r\n\r\n__Easier Testing__ - Nancy provides a testing library that allows you to test the full request/response cycle so not only can you test that your request returns the model you expect you can test that when you pass in accept headers the response is in the format you expect. For example:\r\n\r\n    [Fact]\r\n    public void GetData_WhenRequested_ShouldReturnOKStatusCode()\r\n    {\r\n        var browser = new Browser();\r\n        var response = await browser.Get(\"/GetData\", (with) =>\r\n        {\r\n            with.Header(\"Authorization\", \"Bearer johnsmith\");\r\n            with.Header(\"Accept\", \"application/json\");\r\n            with.HttpRequest();\r\n        });\r\n    \r\n        Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);\r\n    }\r\n\r\nI am unaware of how you would be able to test this in MVC without it being a full integration test whereas Nancy has no dependencies on System.Web or MVC so it can provide us with a Response without hitting a server.\r\n\r\n__Automatic Dependency Resolution__ - Nancy provides an in built IOC container called [TinyIOC][2] which will find all your dependencies automatically for you or if you want/need to configure something you can do so at various points in your application.  This is done in a Bootstrapper class that exposes various methods and properties to allow you to configure Nancy.\r\n\r\n\r\n    protected override void ConfigureApplicationContainer(TinyIoCContainer container)\r\n    {\r\n        base.ConfigureApplicationContainer(container);\r\n    \r\n        var store = new EmbeddableDocumentStore()\r\n        {\r\n            ConnectionStringName = \"RavenDB\"\r\n        };\r\n    \r\n        store.Initialize();\r\n    \r\n        container.Register<IDocumentStore>(store);\r\n    }\r\n    \r\n    protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)\r\n    {\r\n        base.ConfigureRequestContainer(container, context);\r\n    \r\n        var store = container.Resolve<IDocumentStore>();\r\n        var documentSession = store.OpenSession();\r\n    \r\n        container.Register<IDocumentSession>(documentSession);\r\n    }\r\n\r\n\r\nHere the IOC container is used in different places within an application's lifecycle. Once at the startup and once per request.  It registers a DocumentStore which should be done only once in an application and then on every request it finds the DocumentStore and uses it to open a session and registers it with the IOC.  If you have a service that has a IDocumentSession dependency then it will come via this.\r\n\r\nIf for some reason you're being stubborn and want to use your preferred IOC container, Nancy supports all the main IOC players allowing you to register your dependencies with them instead.\r\n\r\n__Completely Customisable, Conventions & Better Extension Points__ - One of Nancy's core features is its extensibility.  It it designed to allow you to replace any part you want.  You can have custom model binders, view renderers, serializers in fact you can implement your own INancyEngine and completely change how Nancy handles requests etc.  There are also a set of pre-defined conventions that you can swap in/out if you want Nancy to do something different than what comes as standard.  Everything is complete customisable and very easy to modify Nancy's behaviour which offers great extensibility points if you wanted to create a 3rd party library for example.\r\n\r\n__Terse Syntax & Less Ceremony__ - Nancy provides a nice terse syntax that does not get in the way of your application and leaves you to write your code. What I have found is that due to the terse syntax it encourages you to make your application code nice and neat too.  One example of less ceremony and terseness is that you can get a full Nancy application running inside a 140 character tweet!\r\n\r\n\r\n    public class HelloModule : NancyModule\r\n    {\r\n        public HelloModule()\r\n        {\r\n            Get[\"/\"] = parameters => \"Hello World\";\r\n        }\r\n    }\r\n\r\n\r\n__Runs on Mono__ - Nancy does not tie itself down to Windows it works just as well on OSX and Linux under [Mono][3] which allows your team to work on multiple platforms. In fact Nancy can even run on a [Raspberry Pi][4] I would like to see ASP.NET MVC do that!\r\n\r\n__Content Negotiation__ - Content Negotiation is built into Nancy and runs out of the box.  This means Nancy can be used in an API type application as well as a website application.  In fact if you wanted you could have it do both very easily.\r\n\r\n\r\n    Get[\"/\"] = parameters => {\r\n        return Negotiate\r\n            .WithModel(new RatPack {FirstName = \"Nancy \"})\r\n            .WithMediaRangeModel(\"text/html\", new RatPack {FirstName = \"Nancy fancy pants\"})\r\n            .WithView(\"negotiatedview\")\r\n            .WithHeader(\"X-Custom\", \"SomeValue\");\r\n    };\r\n\r\n\r\nThis demo highlights that if you made a request to \"/\" in your application by a web browser it will return a specific model with a property name of \"Nancy fancy pants\", return a view called \"negotiatedview\" and return a custom header. However, if your API client made a request to \"/\" it would return a model with \"Nancy\" and a custom header.  The resulting model would then be serialized into JSON, JSONP, XML or any other variation specified in the Accept header from your client.  This example is possibly contrived somewhat but Nancy supplies conneg from all routes so something like the below would be serialized based on the headers.\r\n\r\n\r\n    Get[\"/\"] = parameters => {\r\n        var model = MyModel();\r\n        return model;\r\n    };\r\n\r\n\r\n__No Config__ - To get Nancy up and running there is no config required, no nasty XML files to modify, nothing.  As its host agnostic you don't have to modify anything in web.config to have it running via IIS for example.\r\n\r\n__Runs Anywhere__ - As I just mentioned Nancy is host agnostic which means you can run it in IIS, WCF, embedded within a EXE, as a windows service or within a self hosted application. Pretty much everywhere!\r\n\r\n__Pipeline Hooks__ - Nancy allows you to modify the pipeline ie.the request and response before and after they are invoked.  One simple example is saving your data at the end of a request.\r\n\r\n\r\n    protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)\r\n    {\r\n        base.RequestStartup(container, pipelines, context);\r\n    \r\n        pipelines.AfterRequest.AddItemToEndOfPipeline(\r\n            (ctx) =>\r\n            {\r\n                var documentSession = container.Resolve<IDocumentSession>();\r\n    \r\n                if (ctx.Response.StatusCode != HttpStatusCode.InternalServerError)\r\n                {\r\n                    documentSession.SaveChanges();\r\n                }\r\n    \r\n                documentSession.Dispose();\r\n            });\r\n    }\r\n\r\n\r\nHere we configure the AfterRequest delegate to find the IDocumentSession used in the request, save the changes to the database and then dispose of the IDocumentSession (although TinyIOC would actually dispose of this for you).\r\n\r\nA more complex example could be that you modify the way the Request.Form is populated on a HTTP POST, it is that extensible and configurable you could do that quite easily.\r\n\r\n__No ties to System.Web and a Freely Designed Framework__ - System.Web is the core DLL based in ASP.Net. It contains the whole kitchen sink of the framework so you get everything bundled into your application even if you only use 25% of the possibilities.  Nancy is architected the other way in that there are [numerous plugins][5] that supply additional and alternative functionality.  Nancy is also not bound to any specific implementation or framework and all requests and responses are built from the ground up allowing it to be loosely coupled and free.  This also means that Nancy can run in the .Net client profile environments without the added requirement for .Net full profile that ASP.NET MVC does require.\r\n\r\n__Support & Community__ - One of the great things about Nancy is its community and support.  They have a very active [Google group][6] and you'll find loads of help in [Jabbr][7] to get your questions answered ASAP.  There is a real feeling of community and support because people want to spread the good word about Nancy.  It has over 100 contributors to the project but keep in mind the vision, impetus and most of the work is done by 2 guys, [@TheCodeJunkie][8] and [@GrumpyDev][9] not a huge team sitting in Redmond.  One final thing the [swag][10] is a lot more stylish than Microsoft t-shirts :)\r\n\r\n##Conclusion\r\nIn one of my last [blog posts][11] I described how you could test the full pipeline in ASP.NET Web API because Microsoft don't supply a nice way to do it.  This blog post got the attention of Microsoft and at the time of writing this blog post it has had over 3150 hits and appeared on the home page of ASP.NET.  The core of the code in that post was taken out of Nancy.  So please if you liked what you saw there, give Nancy a try I think you'll find there many benefits described above as well as others I've not mentioned.  It is your duty as software developers to try new things and investigate tools.\r\n\r\nSo when your next project comes about and your manager says \"Ok lets write our new app in ASP.NET MVC\" your reactions should be reflected by these animated GIFs.\r\n\r\n__Should we really use ASP.NET MVC?__\r\n![Should we use ASP.NET MVC?](http://i.minus.com/imM6lHNgto38I.gif)\r\n\r\n__The boss says we can use Nancy!__\r\n![All systems go](http://i.minus.com/i3nPmdfBC2VaH.gif)\r\n\r\n__We have our new Nancy app up and running in no time!__\r\n![Up and Running](http://i.minus.com/ie4Om0y5NXhS1.gif)\r\n\r\nFor more infomation on Nancy checkout the [website][12] and [documentation][13].\r\n\r\n\r\n  [1]: http://nancyfx.org/\r\n  [2]: https://github.com/grumpydev/TinyIoC\r\n  [3]: http://www.mono-project.com/Main_Page\r\n  [4]: http://www.raspberrypi.org/quick-start-guide\r\n  [5]: http://nuget.org/packages?q=nancy\r\n  [6]: https://groups.google.com/forum/?fromgroups#!forum/nancy-web-framework\r\n  [7]: http://jabbr.net/#/rooms/nancyfx\r\n  [8]: http://twitter.com/TheCodeJunkie\r\n  [9]: http://twitter.com/GrumpyDev\r\n  [10]: http://nancyfx.spreadshirt.net\r\n  [11]: http://blog.jonathanchannon.com/2012/11/29/asp-net-web-api-testing\r\n  [12]: http://nancyfx.org/\r\n  [13]: https://github.com/NancyFx/Nancy/wiki/Documentation\r\n\r\n@Partial['blogfooter', Model.MetaData];\r\n\r\n@EndSection"
  },
  {
    "path": "samples/Nancy.Demo.MarkdownViewEngine/Views/blogfooter.html",
    "content": "﻿   <div style='clear: both;'></div>\r\n                    </div>\r\n                    <div class='post-footer'>\r\n                        <div class='post-footer-line post-footer-line-1'></div>\r\n                        <div class='post-footer-line post-footer-line-2'>\r\n                            <div>\r\n                                <strong>Tags:\r\n                                @Each.Tags\r\n                                @Current\r\n                                @EndEach\r\n                                </strong>\r\n                            </div>\r\n                            <div class='post-share-buttons'>\r\n                                <a class='goog-inline-block share-button sb-email' href='#' target='_blank' title='Email This'><span class='share-button-link-text'>Email This</span>\r\n\r\n                                </a>\r\n                                <a class='goog-inline-block share-button sb-blog' href='#' target='_blank'\r\n                                   title='BlogThis!'><span class='share-button-link-text'>BlogThis!</span>\r\n\r\n                                </a>\r\n                                <a class='goog-inline-block share-button sb-twitter' href='#' target='_blank' title='Share to Twitter'><span class='share-button-link-text'>Share to Twitter</span>\r\n\r\n                                </a>\r\n                                <a class='goog-inline-block share-button sb-facebook' href='#' target='_blank'\r\n                                   title='Share to Facebook'><span class='share-button-link-text'>Share to Facebook</span>\r\n\r\n                                </a>\r\n                                <div class='goog-inline-block dummy-container'>\r\n                                    <g:plusone annotation='none' size='medium'></g:plusone>\r\n                                </div>\r\n                            </div>\r\n                        </div>\r\n                        <div class='post-footer-line post-footer-line-3'>\r\n                            <span class='post-location'></span>\r\n\r\n                        </div>\r\n                    </div>\r\n                </div>\r\n            </div>\r\n        </div>\r\n    </div>\r\n</div>"
  },
  {
    "path": "samples/Nancy.Demo.MarkdownViewEngine/Views/blogheader.html",
    "content": "﻿<div class='widget Blog'>\r\n    <div class='blog-posts hfeed'>\r\n        <div class=\"date-posts\">\r\n            <div class='post-outer'>\r\n                <div class='post hentry'>\r\n                    <div class='hentry-top'>\r\n                        <span>@Model.FriendlyDate</span>\r\n\r\n                    </div>\r\n                    <h3 class='post-title entry-title'>\r\n\r\n                    </h3>\r\n\r\n                    <div class='post-header'>\r\n                        <div class='post-header-line-1'></div>\r\n                    </div>\r\n                    <div class='post-body entry-content'>"
  },
  {
    "path": "samples/Nancy.Demo.MarkdownViewEngine/Views/blogindex.html",
    "content": "﻿@Master['master']\r\n\r\n@Section['Content']\r\n\r\n@Each.MetaData\r\n   <div class='widget Blog'>\r\n    <div class='blog-posts hfeed'>\r\n        <div class=\"date-posts\">\r\n            <div class='post-outer'>\r\n                <div class='post hentry'>\r\n                    <div class='hentry-top'>\r\n                        <span>@Current.FriendlyDate</span>\r\n\r\n                    </div>\r\n                    <h3 class='post-title entry-title'>\r\n                        <a href=\"@Current.Slug\">@Current.Title</a>\r\n                    </h3>\r\n\r\n                    <div class='post-header'>\r\n                        <div class='post-header-line-1'></div>\r\n                    </div>\r\n                    <div class='post-body entry-content'>\r\n\r\n                        @Current.Abstract\r\n\r\n                         <div style='clear: both;'></div>\r\n                    </div>\r\n                    <div class='post-footer'>\r\n                        <div class='post-footer-line post-footer-line-1'></div>\r\n                        <div class='post-footer-line post-footer-line-2'>\r\n                            <div class='post-share-buttons'>\r\n                                <a class='goog-inline-block share-button sb-email' href='#' target='_blank' title='Email This'><span class='share-button-link-text'>Email This</span>\r\n\r\n                                </a>\r\n                                <a class='goog-inline-block share-button sb-blog' href='#' target='_blank'\r\n                                   title='BlogThis!'><span class='share-button-link-text'>BlogThis!</span>\r\n\r\n                                </a>\r\n                                <a class='goog-inline-block share-button sb-twitter' href='#' target='_blank' title='Share to Twitter'><span class='share-button-link-text'>Share to Twitter</span>\r\n\r\n                                </a>\r\n                                <a class='goog-inline-block share-button sb-facebook' href='#' target='_blank'\r\n                                   title='Share to Facebook'><span class='share-button-link-text'>Share to Facebook</span>\r\n\r\n                                </a>\r\n                                <div class='goog-inline-block dummy-container'>\r\n                                    <g:plusone annotation='none' size='medium'></g:plusone>\r\n                                </div>\r\n                            </div>\r\n                        </div>\r\n                        <div class='post-footer-line post-footer-line-3'>\r\n                            <span class='post-location'></span>\r\n\r\n                        </div>\r\n                    </div>\r\n                </div>\r\n            </div>\r\n        </div>\r\n    </div>\r\n</div>\r\n\r\n@EndEach\r\n\r\n@EndSection"
  },
  {
    "path": "samples/Nancy.Demo.MarkdownViewEngine/Views/master.html",
    "content": "﻿<!DOCTYPE html>\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />\r\n    <title>Nancy.Demo.MarkdownViewEngine</title>\r\n    <link href=\"../../Content/blog.css\" rel=\"stylesheet\" />\r\n    <link href='http://fonts.googleapis.com/css?family=Goudy+Lobster+Bookletter+1911|Questrial' rel='stylesheet' type='text/css' />\r\n    <script type=\"text/javascript\" src=\"https://apis.google.com/js/plusone.js\"></script>\r\n    <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js' type='text/javascript'></script>\r\n    <script src=\"../Content/js/jquery.spritely-0.6.js\"></script>\r\n    <script type='text/javascript'>\r\n        (function ($) {\r\n            $(document).ready(function () {\r\n                $('#cloud').pan({ fps: 30, speed: 1, dir: 'right' });\r\n                $('#cloud2').pan({ fps: 30, speed: 2, dir: 'right' });\r\n                $('#cloud3').pan({ fps: 30, speed: 0.5, dir: 'right' });\r\n            });\r\n        })(jQuery);\r\n    </script>\r\n</head>\r\n<body>\r\n    <div id='cover-cloud'>\r\n        <div id='cloud'>&#160;</div>\r\n        <div id='cloud2'>&#160;</div>\r\n        <div id='cloud3'>&#160;</div>\r\n    </div>\r\n    <div id='outer-wrapper'>\r\n        <div id='wrap2'>\r\n            <div id='content-wrapper'>\r\n                <div id='mountain'></div>\r\n                <div id='left-content'>\r\n                    <div id='header-wrapper'>\r\n                        <div id='header'>\r\n                            <div class='widget'>\r\n                                <div id='header-inner'>\r\n                                    <a href='/' style='display: block'>\r\n                                        <img alt='Legit' src='../../Content/images/logo.png' />\r\n                                    </a>\r\n                                </div>\r\n                            </div>\r\n                        </div>\r\n                    </div>\r\n                    <div id='sidebar2-wrapper'>\r\n                        <div class='sidebar' id='leftsidebar'>\r\n                            <div class='widget PageList'>\r\n                                <h2>Pages</h2>\r\n                                <div class='widget-content'>\r\n                                    <ul>\r\n                                        <li class='selected'><a href='/'>Home</a></li>\r\n                                        <li><a href='/'>About Me</a></li>\r\n                                        <li><a href='/'>Contact Us</a></li>\r\n                                        <li><a href='/'>Portfolio</a></li>\r\n                                        <li><a href='/'>Premium</a></li>\r\n                                    </ul>\r\n                                    <div class='clear'></div>\r\n                                </div>\r\n                            </div>\r\n                        </div>\r\n                    </div>\r\n                    <div id='credit-wrapper'>\r\n                        <div class='credit'>\r\n                            Copyright &#169; <a href='http://legit-dzignine.blogspot.ie/'>Legit</a><br />\r\n                            <span>Design <em>by</em>\r\n                                <a href='http://dzignine.com'>Dzignine</a></span>\r\n                        </div>\r\n                    </div>\r\n                </div>\r\n                <div id='main-wrapper'>\r\n                    <div class='main' id='main'>\r\n\r\n                        @Section['Content']\r\n\r\n                    </div>\r\n                </div>\r\n                <div id='sidebar-wrapper'>\r\n                    <div class='sidebar' id='rightsidebar'>\r\n                        @Partial['popularposts', Model.PopularPosts];\r\n                    </div>\r\n                </div>\r\n                <div class='clear'>&#160;</div>\r\n            </div>\r\n        </div>\r\n    </div>\r\n</body>\r\n</html>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.MarkdownViewEngine/Views/popularposts.html",
    "content": "﻿<div class='widget PopularPosts'>\r\n    <h2>Popular Posts</h2>\r\n    <div class='widget-content'>\r\n        <ul>\r\n            @Each\r\n            <li>\r\n                <div class='item-content'>\r\n                    <div class='item-thumbnail'>\r\n                        <a href='/' target='_blank'>\r\n                            <img alt='' border='0' src='/Content/images/nancy-nuget.png'  />\r\n                        </a>\r\n                    </div>\r\n                    <div class='item-title'><a href=\"@Current.Slug\">@Current.Title</a></div>\r\n                    <div class='item-snippet'>@Current.Abstract...</div>\r\n                </div>\r\n                <div style='clear: both;'></div>\r\n            </li>\r\n            @EndEach\r\n        </ul>\r\n        <div class='clear'></div>\r\n    </div>\r\n</div>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.MarkdownViewEngine/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n\r\n<packages>\r\n  <package id=\"MarkdownSharp\" version=\"1.13.0.0\" targetFramework=\"net45\" />\r\n</packages>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.MarkdownViewEngine/web.config",
    "content": "<?xml version=\"1.0\"?>\r\n\r\n<configuration>\r\n  <system.web>\r\n    <compilation debug=\"true\" targetFramework=\"4.0\">\r\n      <assemblies>\r\n        <add assembly=\"System.Data.DataSetExtensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" />\r\n        <add assembly=\"System.Web.ApplicationServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" />\r\n        <add assembly=\"System.Web.DynamicData, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" />\r\n        <add assembly=\"System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" />\r\n        <add assembly=\"System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" />\r\n      </assemblies>\r\n    </compilation>\r\n    <httpHandlers>\r\n      <add verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </httpHandlers>\r\n    <pages controlRenderingCompatibilityVersion=\"3.5\" clientIDMode=\"AutoID\" />\r\n  </system.web>\r\n\r\n  <appSettings>\r\n    <add key=\"webPages:Enabled\" value=\"false\" />\r\n  </appSettings>\r\n\r\n  <system.webServer>\r\n    <validation validateIntegratedModeConfiguration=\"false\" />\r\n    <handlers>\r\n      <add name=\"Nancy\" verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </handlers>\r\n  </system.webServer>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.ModelBinding/CustomersModule.cs",
    "content": "namespace Nancy.BindingDemo\r\n{\r\n    using System.Linq;\r\n\r\n    using Nancy.Demo.ModelBinding.Database;\r\n    using Nancy.Demo.ModelBinding.Models;\r\n    using Nancy.ModelBinding;\r\n\r\n    public class CustomersModule : NancyModule\r\n    {\r\n        public CustomersModule()\r\n            : base(\"/customers\")\r\n        {\r\n            Get(\"/\", args =>\r\n            {\r\n                var model = DB.Customers.OrderBy(e => e.RenewalDate).ToArray();\r\n\r\n                return View[\"Customers\", model];\r\n            });\r\n\r\n            Post(\"/\", args =>\r\n            {\r\n                Customer model = this.Bind();\r\n                var model2 = this.Bind<Customer>();\r\n\r\n                DB.Customers.Add(model);\r\n                DB.Customers.Add(model2);\r\n\r\n                return this.Response.AsRedirect(\"/Customers\");\r\n            });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.ModelBinding/Database/DB.cs",
    "content": "namespace Nancy.Demo.ModelBinding.Database\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using Nancy.Demo.ModelBinding.Models;\r\n\r\n    public static class DB\r\n    {\r\n        public static List<Event> Events { get; private set; }\r\n\r\n        public static List<Customer> Customers { get; private set; }\r\n\r\n        static DB()\r\n        {\r\n            Events = new List<Event>();\r\n            Customers = new List<Customer>();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.ModelBinding/EventsModule.cs",
    "content": "namespace Nancy.Demo.ModelBinding\r\n{\r\n    using System.Linq;\r\n\r\n    using Nancy.Demo.ModelBinding.Database;\r\n    using Nancy.Demo.ModelBinding.Models;\r\n    using Nancy.ModelBinding;\r\n\r\n    public class EventsModule : NancyModule\r\n    {\r\n        public EventsModule()\r\n            : base(\"/events\")\r\n        {\r\n            Get(\"/\", args =>\r\n            {\r\n                var model = DB.Events.OrderBy(e => e.Time).ToArray();\r\n\r\n                return View[\"Events\", model];\r\n            });\r\n\r\n            Post(\"/\", args =>\r\n            {\r\n                Event model = this.Bind();\r\n                var model2 = this.Bind<Event>(\"Location\"); // Blacklist location\r\n\r\n                DB.Events.Add(model);\r\n                DB.Events.Add(model2);\r\n\r\n                return this.Response.AsRedirect(\"/Events\");\r\n            });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.ModelBinding/JsonModule.cs",
    "content": "namespace Nancy.Demo.ModelBinding\r\n{\r\n    using System.Text;\r\n    using Nancy.Demo.ModelBinding.Models;\r\n    using Nancy.ModelBinding;\r\n\r\n    public class JsonModule : NancyModule\r\n    {\r\n        public JsonModule()\r\n        {\r\n            Get(\"/bindjson\", args =>\r\n            {\r\n                return View[\"PostJson\"];\r\n            });\r\n\r\n            Post(\"/bindjson\", args =>\r\n            {\r\n                User model = this.Bind();\r\n\r\n                var sb = new StringBuilder();\r\n\r\n                sb.AppendLine(\"Bound Model:\");\r\n                sb.Append(\"Type: \");\r\n                sb.AppendLine(model.GetType().FullName);\r\n                sb.Append(\"Name: \");\r\n                sb.AppendLine(model.Name);\r\n                sb.Append(\"Address: \");\r\n                sb.AppendLine(model.Address);\r\n\r\n                return sb.ToString();\r\n            });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.ModelBinding/MainModule.cs",
    "content": "namespace Nancy.Demo.ModelBinding\r\n{\r\n    public class MainModule : NancyModule\r\n    {\r\n        public MainModule()\r\n        {\r\n            Get(\"/\", args =>\r\n            {\r\n                return \"<a href='/events'>Events (default model binder)</a><br><a href='/customers'>Customers (custom model binder)</a><br><a href='/bindjson'>Users (JSON)</a></a><br><a href='/bindxml'>Users (XML)</a><br>\";\r\n            });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.ModelBinding/ModelBinders/CustomerModelBinder.cs",
    "content": "namespace Nancy.Demo.ModelBinding.ModelBinders\r\n{\r\n    using System;\r\n\r\n    using Nancy.Demo.ModelBinding.Models;\r\n    using Nancy.ModelBinding;\r\n\r\n    /// <summary>\r\n    /// Sample model binder that manually binds customer models\r\n    /// </summary>\r\n    public class CustomerModelBinder : IModelBinder\r\n    {\r\n        /// <summary>\r\n        /// Whether the binder can bind to the given model type\r\n        /// </summary>\r\n        /// <param name=\"modelType\">Required model type</param>\r\n        /// <returns>True if binding is possible, false otherwise</returns>\r\n        public bool CanBind(Type modelType)\r\n        {\r\n            return modelType == typeof(Customer);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind to the given model type\r\n        /// </summary>\r\n        /// <param name=\"context\">Current context</param>\r\n        /// <param name=\"modelType\">Model type to bind to</param>\r\n        /// <param name=\"instance\">Optional existing instance</param>\r\n        /// <param name=\"configuration\">The <see cref=\"BindingConfig\"/> that should be applied during binding.</param>\r\n        /// <param name=\"blackList\">Blacklisted property names</param>\r\n        /// <returns>Bound model</returns>\r\n        public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList)\r\n        {\r\n            var customer = (instance as Customer) ?? new Customer();\r\n\r\n            customer.Name = customer.Name ?? context.Request.Form[\"Name\"];\r\n            customer.RenewalDate = customer.RenewalDate == default(DateTime) ? context.Request.Form[\"RenewalDate\"] : customer.RenewalDate;\r\n\r\n            return customer;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.ModelBinding/ModelBindingBootstrapper.cs",
    "content": "namespace Nancy.Demo.ModelBinding\r\n{\r\n    public class ModelBindingBootstrapper : DefaultNancyBootstrapper\r\n    {\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.ModelBinding/Models/Customer.cs",
    "content": "namespace Nancy.Demo.ModelBinding.Models\r\n{\r\n    using System;\r\n\r\n    public class Customer\r\n    {\r\n        public int Id { get; set; }\r\n\r\n        public string Name { get; set; }\r\n\r\n        public DateTime RenewalDate { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.ModelBinding/Models/Event.cs",
    "content": "namespace Nancy.Demo.ModelBinding.Models\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    public class Event\r\n    {\r\n        public int Id { get; set; }\r\n\r\n        public string Title { get; set; }\r\n\r\n        public string Location { get; set; }\r\n\r\n        public IEnumerable<int> Venues { get; set; }\r\n\r\n        public DateTime Time { get; set; }\r\n\r\n        public Event()\r\n        {\r\n            this.Title = \"Default\";\r\n            this.Location = \"Default\";\r\n            this.Time = DateTime.Now;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.ModelBinding/Models/User.cs",
    "content": "namespace Nancy.Demo.ModelBinding.Models\r\n{\r\n    public class User\r\n    {\r\n        public string Name { get; set; }\r\n\r\n        public string Address { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.ModelBinding/Nancy.Demo.ModelBinding.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\r\n  <PropertyGroup>\r\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\r\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\r\n    <SchemaVersion>2.0</SchemaVersion>\r\n    <ProjectGuid>{1258BFCD-3BAD-4373-B786-4D698EC3C157}</ProjectGuid>\r\n    <ProjectTypeGuids>{349C5851-65DF-11DA-9384-00065B846F21};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>\r\n    <OutputType>Library</OutputType>\r\n    <AppDesignerFolder>Properties</AppDesignerFolder>\r\n    <RootNamespace>Nancy.Demo.ModelBinding</RootNamespace>\r\n    <AssemblyName>Nancy.Demo.ModelBinding</AssemblyName>\r\n    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\r\n    <UseIISExpress>false</UseIISExpress>\r\n    <OldToolsVersion>4.0</OldToolsVersion>\r\n    <IISExpressSSLPort />\r\n    <IISExpressAnonymousAuthentication />\r\n    <IISExpressWindowsAuthentication />\r\n    <IISExpressUseClassicPipelineMode />\r\n    <UseGlobalApplicationHostFile />\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <DebugType>full</DebugType>\r\n    <Optimize>false</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\r\n    <DebugType>pdbonly</DebugType>\r\n    <Optimize>true</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoDebug|AnyCPU'\">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <DebugType>full</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.ModelBinding.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Optimize>false</Optimize>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoRelease|AnyCPU'\">\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <Optimize>true</Optimize>\r\n    <DebugType>pdbonly</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.ModelBinding.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <ItemGroup>\r\n    <Reference Include=\"Microsoft.CSharp\" />\r\n    <Reference Include=\"System\" />\r\n    <Reference Include=\"System.Data\" />\r\n    <Reference Include=\"System.Drawing\" />\r\n    <Reference Include=\"System.Web\" />\r\n    <Reference Include=\"System.Xml\" />\r\n    <Reference Include=\"System.Configuration\" />\r\n    <Reference Include=\"System.Xml.Linq\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Views\\PostXml.html\" />\r\n    <Content Include=\"Views\\PostJson.html\" />\r\n    <Content Include=\"Web.config\" />\r\n    <Content Include=\"Web.Debug.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n    <Content Include=\"Web.Release.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Compile Include=\"..\\..\\SharedAssemblyInfo.cs\">\r\n      <Link>Properties\\SharedAssemblyInfo.cs</Link>\r\n    </Compile>\r\n    <Compile Include=\"CustomersModule.cs\" />\r\n    <Compile Include=\"Database\\DB.cs\" />\r\n    <Compile Include=\"EventsModule.cs\" />\r\n    <Compile Include=\"JsonModule.cs\" />\r\n    <Compile Include=\"MainModule.cs\" />\r\n    <Compile Include=\"ModelBinders\\CustomerModelBinder.cs\" />\r\n    <Compile Include=\"ModelBindingBootstrapper.cs\" />\r\n    <Compile Include=\"Models\\Customer.cs\" />\r\n    <Compile Include=\"Models\\Event.cs\" />\r\n    <Compile Include=\"Models\\User.cs\" />\r\n    <Compile Include=\"XmlModule.cs\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <None Include=\"Views\\Customers.spark\" />\r\n    <None Include=\"Views\\Events.spark\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.Hosting.Aspnet.MSBuild\\Nancy.Hosting.Aspnet.csproj\">\r\n      <Project>{15B7F794-0BB2-4B66-AD78-4A951F1209B2}</Project>\r\n      <Name>Nancy.Hosting.Aspnet</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.ViewEngines.Spark.MSBuild\\Nancy.ViewEngines.Spark.csproj\">\r\n      <Project>{4B7E35DF-1569-4346-B180-A09615723095}</Project>\r\n      <Name>Nancy.ViewEngines.Spark</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.MSBuild\\Nancy.csproj\">\r\n      <Project>{34576216-0DCA-4B0F-A0DC-9075E75A676F}</Project>\r\n      <Name>Nancy</Name>\r\n    </ProjectReference>\r\n  </ItemGroup>\r\n  <PropertyGroup>\r\n    <VisualStudioVersion Condition=\"'$(VisualStudioVersion)' == ''\">10.0</VisualStudioVersion>\r\n    <VSToolsPath Condition=\"'$(VSToolsPath)' == ''\">$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)</VSToolsPath>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\r\n  <Import Project=\"$(VSToolsPath)\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"'$(VSToolsPath)' != ''\" />\r\n  <Import Project=\"$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v10.0\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"false\" />\r\n  <ProjectExtensions>\r\n    <VisualStudio>\r\n      <FlavorProperties GUID=\"{349C5851-65DF-11DA-9384-00065B846F21}\">\r\n        <WebProjectProperties>\r\n          <UseIIS>False</UseIIS>\r\n          <AutoAssignPort>True</AutoAssignPort>\r\n          <DevelopmentServerPort>1953</DevelopmentServerPort>\r\n          <DevelopmentServerVPath>/</DevelopmentServerVPath>\r\n          <IISUrl>\r\n          </IISUrl>\r\n          <NTLMAuthentication>False</NTLMAuthentication>\r\n          <UseCustomServer>False</UseCustomServer>\r\n          <CustomServerUrl>\r\n          </CustomServerUrl>\r\n          <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>\r\n        </WebProjectProperties>\r\n      </FlavorProperties>\r\n    </VisualStudio>\r\n    <MonoDevelop>\r\n      <Properties VerifyCodeBehindFields=\"true\" VerifyCodeBehindEvents=\"true\">\r\n        <XspParameters Port=\"8080\" Address=\"127.0.0.1\" SslMode=\"None\" SslProtocol=\"Default\" KeyType=\"None\" CertFile=\"\" KeyFile=\"\" PasswordOptions=\"None\" Password=\"\" Verbose=\"true\" />\r\n      </Properties>\r\n    </MonoDevelop>\r\n  </ProjectExtensions>\r\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r\n       Other similar extension points exist, see Microsoft.Common.targets.\r\n  <Target Name=\"BeforeBuild\">\r\n  </Target>\r\n  <Target Name=\"AfterBuild\">\r\n  </Target>\r\n  -->\r\n</Project>"
  },
  {
    "path": "samples/Nancy.Demo.ModelBinding/Views/Customers.spark",
    "content": "﻿<viewdata model=\"Nancy.Demo.ModelBinding.Models.Customer[]\"/>\r\n<html>\r\n  <head>\r\n    <title>Customers</title>\r\n  </head>\r\n  <body>\r\n    <h1>Customers</h1>\r\n    <p>Customer is added twice, one using the dynamic binder adapter, the other using the generic one.</p>\r\n    <p>Current customers:</p>\r\n    <ul>\r\n      <li each=\"var v in Model\">\r\n        <a href=\"customer/${v.Id}\"> ${v.Name} - ${v.RenewalDate.ToShortDateString()} </a>\r\n      </li>\r\n    </ul>\r\n\r\n    <h2>Add another</h2>\r\n    <form method=\"POST\" action=\"/customers\">\r\n      <label for=\"Name\">Name</label>\r\n      <input type=\"text\" name=\"Name\" />\r\n      <label for=\"Location\">Renewal Date</label>\r\n      <input type=\"text\" name=\"RenewalDate\" />\r\n      <input type=\"submit\"/>\r\n    </form>\r\n  </body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.ModelBinding/Views/Events.spark",
    "content": "﻿<viewdata model=\"Nancy.Demo.ModelBinding.Models.Event[]\"/>\r\n<html>\r\n  <head>\r\n    <title>Events</title>\r\n  </head>\r\n  <body>\r\n    <h1>Events</h1>\r\n    <p>Event is added twice, one using the dynamic binder adapter, the other using the generic one.</p>\r\n    <p>The second one has 'Location' marked as blacklisted so should appear as 'Default'</p>\r\n    <p>Current events:</p>\r\n    <ul>\r\n      <li each=\"var v in Model\">\r\n        <a href=\"event/${v.Id}\"> ${v.Title} - ${v.Location} </a> ${v.Time}\r\n      </li>\r\n    </ul>\r\n\r\n    <h2>Add another</h2>\r\n    <form method=\"POST\" action=\"/events\">\r\n      <label for=\"Name\">Title</label>\r\n      <input type=\"text\" name=\"Title\" />\r\n      <label for=\"Location\">Location</label>\r\n      <input type=\"text\" name=\"Location\" />\r\n\r\n      <input type=\"checkbox\" name=\"Venues\" value=\"1\">Venue 1</input>\r\n      <input type=\"checkbox\" name=\"Venues\" value=\"2\">Venue 2</input>\r\n      <input type=\"checkbox\" name=\"Venues\" value=\"3\">Venue 3</input>\r\n      <input type=\"checkbox\" name=\"Venues\" value=\"4\">Venue 4</input>\r\n\r\n      <label for=\"EventDate\">Time</label>\r\n      <input type=\"text\" name=\"Time\" value=\"${System.DateTime.Now}\"/>\r\n      <input type=\"submit\"/>\r\n    </form>\r\n  </body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.ModelBinding/Views/PostJson.html",
    "content": "<html>\r\n  <head>\r\n     <title>JSON Post Test</title>\r\n     <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js\"></script>\r\n     <script type=\"text/javascript\">\r\n         $(function () {\r\n             var dat = \"{\\\"Name\\\":\\\"This is the name\\\", \\\"Address\\\":\\\"This is the address\\\"}\";\r\n\r\n             alert(\"POSTing the following data to /bindjson:\\n\\n\" + dat);\r\n\r\n             $.ajax({\r\n                 type: \"POST\",\r\n                 url: \"/bindjson\",\r\n                 contentType: \"application/json\",\r\n                 data: dat,\r\n                 success: function (data) {\r\n                     alert(\"Response:\\n\" + data);\r\n                 }\r\n             });\r\n         });\r\n     </script>\r\n  </head>\r\n  <body>\r\n    JSON Post\r\n  </body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.ModelBinding/Views/PostXml.html",
    "content": "<html>\r\n  <head>\r\n     <title>XML Post Test</title>\r\n     <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js\"></script>\r\n     <script type=\"text/javascript\">\r\n         $(function () {\r\n             var dat = \"<User><Name>This is the name</Name><Address>This is the address</Address></User>\";\r\n\r\n             alert(\"POSTing the following data to /bindxml:\\n\\n\" + dat);\r\n\r\n             $.ajax({\r\n                 type: \"POST\",\r\n                 url: \"/bindxml\",\r\n                 contentType: \"application/xml\",\r\n                 data: dat,\r\n                 success: function (data) {\r\n                     alert(\"Response:\\n\" + data);\r\n                 }\r\n             });\r\n         });\r\n     </script>\r\n  </head>\r\n  <body>\r\n    XML Post\r\n  </body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.ModelBinding/Web.Debug.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.ModelBinding/Web.Release.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n    <compilation xdt:Transform=\"RemoveAttributes(debug)\" />\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.ModelBinding/Web.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration>\r\n  <system.web>\r\n    <compilation debug=\"true\" targetFramework=\"4.0\" />\r\n    <httpHandlers>\r\n      <add verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </httpHandlers>\r\n  </system.web>\r\n\r\n  <system.webServer>\r\n    <modules runAllManagedModulesForAllRequests=\"true\" />\r\n    <validation validateIntegratedModeConfiguration=\"false\" />\r\n    <handlers>\r\n      <add name=\"Nancy\" verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </handlers>\r\n  </system.webServer>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.ModelBinding/XmlModule.cs",
    "content": "namespace Nancy.Demo.ModelBinding\r\n{\r\n    using System.Text;\r\n\r\n    using Nancy.Demo.ModelBinding.Models;\r\n    using Nancy.ModelBinding;\r\n\r\n    public class XmlModule : NancyModule\r\n    {\r\n        public XmlModule()\r\n        {\r\n            Get(\"/bindxml\", args =>\r\n            {\r\n                return View[\"PostXml\"];\r\n            });\r\n\r\n            Post(\"/bindxml\", args =>\r\n            {\r\n                var model = this.Bind<User>(u => u.Name);\r\n\r\n                var sb = new StringBuilder();\r\n\r\n                sb.AppendLine(\"Bound Model:\");\r\n                sb.Append(\"Type: \");\r\n                sb.AppendLine(model.GetType().FullName);\r\n                sb.Append(\"Name: (which will be empty because it's ignored)\");\r\n                sb.AppendLine(model.Name);\r\n                sb.Append(\"Address: \");\r\n                sb.AppendLine(model.Address);\r\n\r\n                return sb.ToString();\r\n            });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Razor.Localization/CustomResourceAssemblyProvider.cs",
    "content": "﻿namespace Nancy.Demo.Razor.Localization\r\n{\r\n    using System.Collections.Generic;\r\n    using System.Reflection;\r\n\r\n    /// <summary>\r\n    /// Use a custom <see cref=\"IResourceAssemblyProvider\"/> because the default one ignores any\r\n    /// assembly that starts with Nancy*. For normal applications this is not required to\r\n    /// implement.\r\n    /// </summary>\r\n    public class CustomResourceAssemblyProvider : IResourceAssemblyProvider\r\n    {\r\n        private readonly IAssemblyCatalog assemblyCatalog;\r\n        private IEnumerable<Assembly> filteredAssemblies;\r\n\r\n        public CustomResourceAssemblyProvider(IAssemblyCatalog assemblyCatalog)\r\n        {\r\n            this.assemblyCatalog = assemblyCatalog;\r\n        }\r\n\r\n        public IEnumerable<Assembly> GetAssembliesToScan()\r\n        {\r\n            return (this.filteredAssemblies ?? (this.filteredAssemblies = this.assemblyCatalog.GetAssemblies()));\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Razor.Localization/DemoBootstrapper.cs",
    "content": "﻿namespace Nancy.Demo.Razor.Localization\r\n{\r\n    using System;\r\n    using Nancy.Bootstrapper;\r\n\r\n    public class DemoBootstrapper : DefaultNancyBootstrapper\r\n    {\r\n        protected override Func<ITypeCatalog, NancyInternalConfiguration> InternalConfiguration\r\n        {\r\n            get\r\n            {\r\n                return NancyInternalConfiguration.WithOverrides(x => x.ResourceAssemblyProvider = typeof(CustomResourceAssemblyProvider));\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Razor.Localization/Modules/HomeModule.cs",
    "content": "﻿namespace Nancy.Demo.Razor.Localization.Modules\r\n{\r\n    using System.Globalization;\r\n\r\n    public class HomeModule : NancyModule\r\n    {\r\n        public HomeModule()\r\n        {\r\n            Get(\"/\", args => View[\"Index\"]);\r\n\r\n            Get(\"/cultureview\", args => View[\"CultureView\"]);\r\n\r\n            Get(\"/cultureviewgerman\", args =>\r\n            {\r\n                this.Context.Culture = new CultureInfo(\"de-DE\");\r\n                return View[\"CultureView\"];\r\n            });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Razor.Localization/Nancy.Demo.Razor.Localization.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoDebug|AnyCPU'\">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <DebugType>full</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoRelease|AnyCPU'\">\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <Optimize>true</Optimize>\r\n    <DebugType>pdbonly</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisIgnoreBuiltInRuleSets>true</CodeAnalysisIgnoreBuiltInRuleSets>\r\n    <CodeAnalysisIgnoreBuiltInRules>true</CodeAnalysisIgnoreBuiltInRules>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\r\n  <PropertyGroup>\r\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\r\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\r\n    <SchemaVersion>2.0</SchemaVersion>\r\n    <ProjectGuid>{396F0BCE-5B51-4B6A-931E-312880C24725}</ProjectGuid>\r\n    <ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>\r\n    <OutputType>Library</OutputType>\r\n    <AppDesignerFolder>Properties</AppDesignerFolder>\r\n    <RootNamespace>Nancy.Demo.Razor.Localization</RootNamespace>\r\n    <AssemblyName>Nancy.Demo.Razor.Localization</AssemblyName>\r\n    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\r\n    <UseIISExpress>true</UseIISExpress>\r\n    <IISExpressSSLPort />\r\n    <IISExpressAnonymousAuthentication />\r\n    <IISExpressWindowsAuthentication />\r\n    <IISExpressUseClassicPipelineMode />\r\n    <UseGlobalApplicationHostFile />\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <DebugType>full</DebugType>\r\n    <Optimize>false</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\r\n    <DebugType>pdbonly</DebugType>\r\n    <Optimize>true</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <ItemGroup>\r\n    <Reference Include=\"Microsoft.CSharp\" />\r\n    <Reference Include=\"System.ComponentModel.DataAnnotations\" />\r\n    <Reference Include=\"System\" />\r\n    <Reference Include=\"System.Data\" />\r\n    <Reference Include=\"System.Drawing\" />\r\n    <Reference Include=\"System.Web\" />\r\n    <Reference Include=\"System.Xml\" />\r\n    <Reference Include=\"System.Configuration\" />\r\n    <Reference Include=\"System.Xml.Linq\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Web.config\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Compile Include=\"CustomResourceAssemblyProvider.cs\" />\r\n    <Compile Include=\"DemoBootstrapper.cs\" />\r\n    <Compile Include=\"Modules\\HomeModule.cs\" />\r\n    <Compile Include=\"Resources\\Text.Designer.cs\">\r\n      <AutoGen>True</AutoGen>\r\n      <DesignTime>True</DesignTime>\r\n      <DependentUpon>Text.resx</DependentUpon>\r\n    </Compile>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Views\\Index.cshtml\" />\r\n    <Content Include=\"Views\\razor-layout.cshtml\" />\r\n    <Content Include=\"Views\\CultureView.cshtml\" />\r\n    <Content Include=\"Views\\CultureView-de-DE.cshtml\" />\r\n    <None Include=\"Web.Debug.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </None>\r\n    <None Include=\"Web.Release.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </None>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <EmbeddedResource Include=\"Resources\\Text.de-DE.resx\" />\r\n    <EmbeddedResource Include=\"Resources\\Text.en-US.resx\" />\r\n    <EmbeddedResource Include=\"Resources\\Text.resx\">\r\n      <Generator>PublicResXFileCodeGenerator</Generator>\r\n      <LastGenOutput>Text.Designer.cs</LastGenOutput>\r\n    </EmbeddedResource>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.Hosting.Aspnet.MSBuild\\Nancy.Hosting.Aspnet.csproj\">\r\n      <Project>{15b7f794-0bb2-4b66-ad78-4a951f1209b2}</Project>\r\n      <Name>Nancy.Hosting.Aspnet</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.ViewEngines.Razor.MSBuild\\Nancy.ViewEngines.Razor.csproj\">\r\n      <Project>{2c6f51df-015c-4db6-b44c-0e5e4f25e2a9}</Project>\r\n      <Name>Nancy.ViewEngines.Razor</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.MSBuild\\Nancy.csproj\">\r\n      <Project>{34576216-0dca-4b0f-a0dc-9075e75a676f}</Project>\r\n      <Name>Nancy</Name>\r\n    </ProjectReference>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Folder Include=\"Properties\\\" />\r\n  </ItemGroup>\r\n  <PropertyGroup>\r\n    <VisualStudioVersion Condition=\"'$(VisualStudioVersion)' == ''\">10.0</VisualStudioVersion>\r\n    <VSToolsPath Condition=\"'$(VSToolsPath)' == ''\">$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)</VSToolsPath>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\r\n  <Import Project=\"$(VSToolsPath)\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"'$(VSToolsPath)' != ''\" />\r\n  <Import Project=\"$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v10.0\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"false\" />\r\n  <ProjectExtensions>\r\n    <VisualStudio>\r\n      <FlavorProperties GUID=\"{349c5851-65df-11da-9384-00065b846f21}\">\r\n        <WebProjectProperties>\r\n          <UseIIS>False</UseIIS>\r\n          <AutoAssignPort>True</AutoAssignPort>\r\n          <DevelopmentServerPort>56029</DevelopmentServerPort>\r\n          <DevelopmentServerVPath>/</DevelopmentServerVPath>\r\n          <IISUrl>http://localhost:61703/</IISUrl>\r\n          <NTLMAuthentication>False</NTLMAuthentication>\r\n          <UseCustomServer>False</UseCustomServer>\r\n          <CustomServerUrl>\r\n          </CustomServerUrl>\r\n          <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>\r\n        </WebProjectProperties>\r\n      </FlavorProperties>\r\n    </VisualStudio>\r\n  </ProjectExtensions>\r\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r\n       Other similar extension points exist, see Microsoft.Common.targets.\r\n  <Target Name=\"BeforeBuild\">\r\n  </Target>\r\n  <Target Name=\"AfterBuild\">\r\n  </Target>\r\n  -->\r\n</Project>"
  },
  {
    "path": "samples/Nancy.Demo.Razor.Localization/Resources/Text.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\r\n// <auto-generated>\r\n//     This code was generated by a tool.\r\n//     Runtime Version:4.0.30319.0\r\n//\r\n//     Changes to this file may cause incorrect behavior and will be lost if\r\n//     the code is regenerated.\r\n// </auto-generated>\r\n//------------------------------------------------------------------------------\r\n\r\nnamespace Nancy.Demo.Razor.Localization.Resources {\r\n    using System.CodeDom.Compiler;\r\n    using System.ComponentModel;\r\n    using System.Diagnostics;\r\n    using System.Diagnostics.CodeAnalysis;\r\n    using System.Globalization;\r\n    using System.Resources;\r\n    using System.Runtime.CompilerServices;\r\n\r\n    /// <summary>\r\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\r\n    /// </summary>\r\n    // This class was auto-generated by the StronglyTypedResourceBuilder\r\n    // class via a tool like ResGen or Visual Studio.\r\n    // To add or remove a member, edit your .ResX file then rerun ResGen\r\n    // with the /str option, or rebuild your VS project.\r\n    [GeneratedCode(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\r\n    [DebuggerNonUserCode()]\r\n    [CompilerGenerated()]\r\n    public class Text {\r\n        \r\n        private static ResourceManager resourceMan;\r\n        \r\n        private static CultureInfo resourceCulture;\r\n        \r\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\r\n        internal Text() {\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Returns the cached ResourceManager instance used by this class.\r\n        /// </summary>\r\n        [EditorBrowsable(EditorBrowsableState.Advanced)]\r\n        public static ResourceManager ResourceManager {\r\n            get {\r\n                if (ReferenceEquals(resourceMan, null)) {\r\n                    ResourceManager temp = new ResourceManager(\"Nancy.Demo.Razor.Localization.Resources.Text\", typeof(Text).Assembly);\r\n                    resourceMan = temp;\r\n                }\r\n                return resourceMan;\r\n            }\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Overrides the current thread's CurrentUICulture property for all\r\n        ///   resource lookups using this strongly typed resource class.\r\n        /// </summary>\r\n        [EditorBrowsable(EditorBrowsableState.Advanced)]\r\n        public static CultureInfo Culture {\r\n            get {\r\n                return resourceCulture;\r\n            }\r\n            set {\r\n                resourceCulture = value;\r\n            }\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Looks up a localized string similar to Hello Sir.\r\n        /// </summary>\r\n        public static string Greeting {\r\n            get {\r\n                return ResourceManager.GetString(\"Greeting\", resourceCulture);\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Razor.Localization/Resources/Text.de-DE.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<root>\r\n  <!-- \r\n    Microsoft ResX Schema \r\n    \r\n    Version 2.0\r\n    \r\n    The primary goals of this format is to allow a simple XML format \r\n    that is mostly human readable. The generation and parsing of the \r\n    various data types are done through the TypeConverter classes \r\n    associated with the data types.\r\n    \r\n    Example:\r\n    \r\n    ... ado.net/XML headers & schema ...\r\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\r\n    <resheader name=\"version\">2.0</resheader>\r\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\r\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\r\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\r\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\r\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\r\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\r\n    </data>\r\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\r\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\r\n        <comment>This is a comment</comment>\r\n    </data>\r\n                \r\n    There are any number of \"resheader\" rows that contain simple \r\n    name/value pairs.\r\n    \r\n    Each data row contains a name, and value. The row also contains a \r\n    type or mimetype. Type corresponds to a .NET class that support \r\n    text/value conversion through the TypeConverter architecture. \r\n    Classes that don't support this are serialized and stored with the \r\n    mimetype set.\r\n    \r\n    The mimetype is used for serialized objects, and tells the \r\n    ResXResourceReader how to depersist the object. This is currently not \r\n    extensible. For a given mimetype the value must be set accordingly:\r\n    \r\n    Note - application/x-microsoft.net.object.binary.base64 is the format \r\n    that the ResXResourceWriter will generate, however the reader can \r\n    read any of the formats listed below.\r\n    \r\n    mimetype: application/x-microsoft.net.object.binary.base64\r\n    value   : The object must be serialized with \r\n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\r\n            : and then encoded with base64 encoding.\r\n    \r\n    mimetype: application/x-microsoft.net.object.soap.base64\r\n    value   : The object must be serialized with \r\n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\r\n            : and then encoded with base64 encoding.\r\n\r\n    mimetype: application/x-microsoft.net.object.bytearray.base64\r\n    value   : The object must be serialized into a byte array \r\n            : using a System.ComponentModel.TypeConverter\r\n            : and then encoded with base64 encoding.\r\n    -->\r\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\r\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\r\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\r\n      <xsd:complexType>\r\n        <xsd:choice maxOccurs=\"unbounded\">\r\n          <xsd:element name=\"metadata\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\r\n              <xsd:attribute ref=\"xml:space\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"assembly\">\r\n            <xsd:complexType>\r\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"data\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\r\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\r\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\r\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\r\n              <xsd:attribute ref=\"xml:space\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"resheader\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n        </xsd:choice>\r\n      </xsd:complexType>\r\n    </xsd:element>\r\n  </xsd:schema>\r\n  <resheader name=\"resmimetype\">\r\n    <value>text/microsoft-resx</value>\r\n  </resheader>\r\n  <resheader name=\"version\">\r\n    <value>2.0</value>\r\n  </resheader>\r\n  <resheader name=\"reader\">\r\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\r\n  </resheader>\r\n  <resheader name=\"writer\">\r\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\r\n  </resheader>\r\n  <data name=\"Greeting\" xml:space=\"preserve\">\r\n    <value>Guten Tag</value>\r\n  </data>\r\n</root>"
  },
  {
    "path": "samples/Nancy.Demo.Razor.Localization/Resources/Text.en-US.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<root>\r\n  <!-- \r\n    Microsoft ResX Schema \r\n    \r\n    Version 2.0\r\n    \r\n    The primary goals of this format is to allow a simple XML format \r\n    that is mostly human readable. The generation and parsing of the \r\n    various data types are done through the TypeConverter classes \r\n    associated with the data types.\r\n    \r\n    Example:\r\n    \r\n    ... ado.net/XML headers & schema ...\r\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\r\n    <resheader name=\"version\">2.0</resheader>\r\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\r\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\r\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\r\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\r\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\r\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\r\n    </data>\r\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\r\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\r\n        <comment>This is a comment</comment>\r\n    </data>\r\n                \r\n    There are any number of \"resheader\" rows that contain simple \r\n    name/value pairs.\r\n    \r\n    Each data row contains a name, and value. The row also contains a \r\n    type or mimetype. Type corresponds to a .NET class that support \r\n    text/value conversion through the TypeConverter architecture. \r\n    Classes that don't support this are serialized and stored with the \r\n    mimetype set.\r\n    \r\n    The mimetype is used for serialized objects, and tells the \r\n    ResXResourceReader how to depersist the object. This is currently not \r\n    extensible. For a given mimetype the value must be set accordingly:\r\n    \r\n    Note - application/x-microsoft.net.object.binary.base64 is the format \r\n    that the ResXResourceWriter will generate, however the reader can \r\n    read any of the formats listed below.\r\n    \r\n    mimetype: application/x-microsoft.net.object.binary.base64\r\n    value   : The object must be serialized with \r\n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\r\n            : and then encoded with base64 encoding.\r\n    \r\n    mimetype: application/x-microsoft.net.object.soap.base64\r\n    value   : The object must be serialized with \r\n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\r\n            : and then encoded with base64 encoding.\r\n\r\n    mimetype: application/x-microsoft.net.object.bytearray.base64\r\n    value   : The object must be serialized into a byte array \r\n            : using a System.ComponentModel.TypeConverter\r\n            : and then encoded with base64 encoding.\r\n    -->\r\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\r\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\r\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\r\n      <xsd:complexType>\r\n        <xsd:choice maxOccurs=\"unbounded\">\r\n          <xsd:element name=\"metadata\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\r\n              <xsd:attribute ref=\"xml:space\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"assembly\">\r\n            <xsd:complexType>\r\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"data\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\r\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\r\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\r\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\r\n              <xsd:attribute ref=\"xml:space\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"resheader\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n        </xsd:choice>\r\n      </xsd:complexType>\r\n    </xsd:element>\r\n  </xsd:schema>\r\n  <resheader name=\"resmimetype\">\r\n    <value>text/microsoft-resx</value>\r\n  </resheader>\r\n  <resheader name=\"version\">\r\n    <value>2.0</value>\r\n  </resheader>\r\n  <resheader name=\"reader\">\r\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\r\n  </resheader>\r\n  <resheader name=\"writer\">\r\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\r\n  </resheader>\r\n  <data name=\"Greeting\" xml:space=\"preserve\">\r\n    <value>Howdy Partner</value>\r\n  </data>\r\n</root>"
  },
  {
    "path": "samples/Nancy.Demo.Razor.Localization/Resources/Text.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<root>\r\n  <!-- \r\n    Microsoft ResX Schema \r\n    \r\n    Version 2.0\r\n    \r\n    The primary goals of this format is to allow a simple XML format \r\n    that is mostly human readable. The generation and parsing of the \r\n    various data types are done through the TypeConverter classes \r\n    associated with the data types.\r\n    \r\n    Example:\r\n    \r\n    ... ado.net/XML headers & schema ...\r\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\r\n    <resheader name=\"version\">2.0</resheader>\r\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\r\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\r\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\r\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\r\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\r\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\r\n    </data>\r\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\r\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\r\n        <comment>This is a comment</comment>\r\n    </data>\r\n                \r\n    There are any number of \"resheader\" rows that contain simple \r\n    name/value pairs.\r\n    \r\n    Each data row contains a name, and value. The row also contains a \r\n    type or mimetype. Type corresponds to a .NET class that support \r\n    text/value conversion through the TypeConverter architecture. \r\n    Classes that don't support this are serialized and stored with the \r\n    mimetype set.\r\n    \r\n    The mimetype is used for serialized objects, and tells the \r\n    ResXResourceReader how to depersist the object. This is currently not \r\n    extensible. For a given mimetype the value must be set accordingly:\r\n    \r\n    Note - application/x-microsoft.net.object.binary.base64 is the format \r\n    that the ResXResourceWriter will generate, however the reader can \r\n    read any of the formats listed below.\r\n    \r\n    mimetype: application/x-microsoft.net.object.binary.base64\r\n    value   : The object must be serialized with \r\n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\r\n            : and then encoded with base64 encoding.\r\n    \r\n    mimetype: application/x-microsoft.net.object.soap.base64\r\n    value   : The object must be serialized with \r\n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\r\n            : and then encoded with base64 encoding.\r\n\r\n    mimetype: application/x-microsoft.net.object.bytearray.base64\r\n    value   : The object must be serialized into a byte array \r\n            : using a System.ComponentModel.TypeConverter\r\n            : and then encoded with base64 encoding.\r\n    -->\r\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\r\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\r\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\r\n      <xsd:complexType>\r\n        <xsd:choice maxOccurs=\"unbounded\">\r\n          <xsd:element name=\"metadata\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\r\n              <xsd:attribute ref=\"xml:space\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"assembly\">\r\n            <xsd:complexType>\r\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"data\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\r\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\r\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\r\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\r\n              <xsd:attribute ref=\"xml:space\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"resheader\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n        </xsd:choice>\r\n      </xsd:complexType>\r\n    </xsd:element>\r\n  </xsd:schema>\r\n  <resheader name=\"resmimetype\">\r\n    <value>text/microsoft-resx</value>\r\n  </resheader>\r\n  <resheader name=\"version\">\r\n    <value>2.0</value>\r\n  </resheader>\r\n  <resheader name=\"reader\">\r\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\r\n  </resheader>\r\n  <resheader name=\"writer\">\r\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\r\n  </resheader>\r\n  <data name=\"Greeting\" xml:space=\"preserve\">\r\n    <value>Hello Sir</value>\r\n  </data>\r\n</root>"
  },
  {
    "path": "samples/Nancy.Demo.Razor.Localization/Views/CultureView-de-DE.cshtml",
    "content": "﻿@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic>\r\n\r\n@{\r\n    Layout = \"razor-layout.cshtml\";\r\n}\r\n\r\n<h1>You're here based on the German culture set in HomeModule however the HomeModule only calls return View[\"CultureView\"]. It uses View Location Conventions therefore there must be a file called CultureView-de-DE.cshtml</h1>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Razor.Localization/Views/CultureView.cshtml",
    "content": "﻿@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic>\r\n\r\n@{\r\n    Layout = \"razor-layout.cshtml\";\r\n}\r\n\r\n<h1>You're here based on your default culture which is @Html.CurrentLocale </h1>\r\n\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Razor.Localization/Views/Index.cshtml",
    "content": "﻿@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic>\r\n@{\r\n    Layout = \"razor-layout.cshtml\";\r\n}\r\n\r\n<h1>The below greeting should be based on your culture:</h1>\r\n\r\n<h3>\"@Text.Text.Greeting\"</h3>\r\n\r\n<p>\r\n    You will see:\r\n    <br />\r\n    { \"en-GB\", \"Hello Sir\" }\r\n     <br />\r\n    { \"de-DE\", \"Guten Tag\" }\r\n     <br />\r\n    { \"en-US\", \"Howdy Partner\" }\r\n</p>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Razor.Localization/Views/razor-layout.cshtml",
    "content": "﻿@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic>\r\n<html>\r\n<head>\r\n    <title>Razor Localization Demo</title>\r\n</head>\r\n<body>\r\n    <div id=\"container\">\r\n        @RenderBody()\r\n        <br/>\r\n        <a href=\"/\">Text Resource Example</a>\r\n        <br/>\r\n        <a href=\"/cultureview\">Default Culture View Example</a>\r\n        <br/>\r\n        <a href=\"/cultureviewgerman\">German Culture View Example</a>\r\n    </div>\r\n</body>\r\n</html>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Razor.Localization/Web.Debug.config",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Razor.Localization/Web.Release.config",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n    <compilation xdt:Transform=\"RemoveAttributes(debug)\" />\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Razor.Localization/Web.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n\r\n<configuration>\r\n  <configSections>\r\n    <section name=\"razor\" type=\"Nancy.ViewEngines.Razor.RazorConfigurationSection\" />\r\n  </configSections>\r\n\r\n  <razor disableAutoIncludeModelNamespace=\"false\">\r\n    <assemblies>\r\n      <add assembly=\"System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" />\r\n      <add assembly=\"Nancy.Hosting.Aspnet\" />\r\n    </assemblies>\r\n    <namespaces>\r\n      <add namespace=\"System.Xml\" />\r\n    </namespaces>\r\n  </razor>\r\n\r\n  <system.web>\r\n    <compilation debug=\"true\" targetFramework=\"4.0\" />\r\n    <httpHandlers>\r\n      <add verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </httpHandlers>\r\n  </system.web>\r\n\r\n  <system.webServer>\r\n    <modules runAllManagedModulesForAllRequests=\"true\" />\r\n    <validation validateIntegratedModeConfiguration=\"false\" />\r\n    <handlers>\r\n      <add name=\"Nancy\" verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </handlers>\r\n  </system.webServer>\r\n\r\n  <runtime>\r\n    <assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\">\r\n      <dependentAssembly>\r\n        <assemblyIdentity name=\"FSharp.Core\" publicKeyToken=\"b03f5f7f11d50a3a\" culture=\"neutral\" />\r\n        <bindingRedirect oldVersion=\"0.0.0.0-2.0.0.0\" newVersion=\"2.0.0.0\" />\r\n      </dependentAssembly>\r\n    </assemblyBinding>\r\n  </runtime>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.SparkViewEngine/FifthElement/Fifth.spark",
    "content": "﻿<html>\r\n<head>\r\n    <title>Is she hot or not</title>\r\n</head>\r\n<body>\r\n    <p>This is the fifth element maaaaan! Like whoaaa...</p>\r\n</body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.SparkViewEngine/FifthElement/FifthElementModule.cs",
    "content": "namespace Nancy.Demo.SparkViewEngine.FifthElement\r\n{\r\n    public class FifthElementModule : NancyModule\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"INancyModule\"/> class.\r\n        /// </summary>\r\n        public FifthElementModule()\r\n        {\r\n            Get(\"/5\", args =>\r\n            {\r\n                return View[\"Fifth.spark\"];\r\n            });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.SparkViewEngine/MainModule.cs",
    "content": "namespace Nancy.Demo.SparkViewEngine\r\n{\r\n    public class MainModule : NancyModule\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"INancyModule\"/> class.\r\n        /// </summary>\r\n        public MainModule()\r\n        {\r\n            Get(\"/\", args =>\r\n            {\r\n                return View[\"Index.spark\"];\r\n            });\r\n\r\n           Get(\"/test\", args => View[\"test\"]);\r\n\r\n           Get(\"/test2\", args => View[\"test2\"]);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.SparkViewEngine/Nancy.Demo.SparkViewEngine.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\r\n  <PropertyGroup>\r\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\r\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\r\n    <SchemaVersion>2.0</SchemaVersion>\r\n    <ProjectGuid>{DE91D085-70DF-4892-B0E3-B849E9BF6AF5}</ProjectGuid>\r\n    <ProjectTypeGuids>{349C5851-65DF-11DA-9384-00065B846F21};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>\r\n    <OutputType>Library</OutputType>\r\n    <AppDesignerFolder>Properties</AppDesignerFolder>\r\n    <RootNamespace>Nancy.Demo.SparkViewEngine</RootNamespace>\r\n    <AssemblyName>Nancy.Demo.SparkViewEngine</AssemblyName>\r\n    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\r\n    <UseIISExpress>false</UseIISExpress>\r\n    <OldToolsVersion>4.0</OldToolsVersion>\r\n    <IISExpressSSLPort />\r\n    <IISExpressAnonymousAuthentication />\r\n    <IISExpressWindowsAuthentication />\r\n    <IISExpressUseClassicPipelineMode />\r\n    <UseGlobalApplicationHostFile />\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <DebugType>full</DebugType>\r\n    <Optimize>false</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\r\n    <DebugType>pdbonly</DebugType>\r\n    <Optimize>true</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoDebug|AnyCPU'\">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <DebugType>full</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.SparkViewEngine.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRules>false</CodeAnalysisIgnoreBuiltInRules>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Optimize>false</Optimize>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoRelease|AnyCPU'\">\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <Optimize>true</Optimize>\r\n    <DebugType>pdbonly</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.SparkViewEngine.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRules>false</CodeAnalysisIgnoreBuiltInRules>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <ItemGroup>\r\n    <Reference Include=\"Microsoft.CSharp\" />\r\n    <Reference Include=\"System\" />\r\n    <Reference Include=\"System.Data\" />\r\n    <Reference Include=\"System.Drawing\" />\r\n    <Reference Include=\"System.Web\" />\r\n    <Reference Include=\"System.Xml\" />\r\n    <Reference Include=\"System.Configuration\" />\r\n    <Reference Include=\"System.Xml.Linq\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Web.config\" />\r\n    <Content Include=\"Web.Debug.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n    <Content Include=\"Web.Release.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Compile Include=\"..\\..\\SharedAssemblyInfo.cs\">\r\n      <Link>Properties\\SharedAssemblyInfo.cs</Link>\r\n    </Compile>\r\n    <Compile Include=\"FifthElement\\FifthElementModule.cs\" />\r\n    <Compile Include=\"MainModule.cs\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.Hosting.Aspnet.MSBuild\\Nancy.Hosting.Aspnet.csproj\">\r\n      <Project>{15B7F794-0BB2-4B66-AD78-4A951F1209B2}</Project>\r\n      <Name>Nancy.Hosting.Aspnet</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.ViewEngines.Spark.MSBuild\\Nancy.ViewEngines.Spark.csproj\">\r\n      <Project>{4B7E35DF-1569-4346-B180-A09615723095}</Project>\r\n      <Name>Nancy.ViewEngines.Spark</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.MSBuild\\Nancy.csproj\">\r\n      <Project>{34576216-0DCA-4B0F-A0DC-9075E75A676F}</Project>\r\n      <Name>Nancy</Name>\r\n    </ProjectReference>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Folder Include=\"Models\\\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Views\\Index.spark\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Views\\_SmallBit.spark\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"FifthElement\\Fifth.spark\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <None Include=\"Views\\Main\\test.spark\" />\r\n    <None Include=\"Views\\Main\\test2.spark\" />\r\n    <None Include=\"Views\\Shared\\application.spark\" />\r\n    <None Include=\"Views\\Shared\\html5.spark\" />\r\n  </ItemGroup>\r\n  <PropertyGroup>\r\n    <VisualStudioVersion Condition=\"'$(VisualStudioVersion)' == ''\">10.0</VisualStudioVersion>\r\n    <VSToolsPath Condition=\"'$(VSToolsPath)' == ''\">$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)</VSToolsPath>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\r\n  <Import Project=\"$(VSToolsPath)\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"'$(VSToolsPath)' != ''\" />\r\n  <Import Project=\"$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v10.0\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"false\" />\r\n  <ProjectExtensions>\r\n    <VisualStudio>\r\n      <FlavorProperties GUID=\"{349C5851-65DF-11DA-9384-00065B846F21}\">\r\n        <WebProjectProperties>\r\n          <UseIIS>False</UseIIS>\r\n          <AutoAssignPort>True</AutoAssignPort>\r\n          <DevelopmentServerPort>6459</DevelopmentServerPort>\r\n          <DevelopmentServerVPath>/</DevelopmentServerVPath>\r\n          <IISUrl>\r\n          </IISUrl>\r\n          <NTLMAuthentication>False</NTLMAuthentication>\r\n          <UseCustomServer>False</UseCustomServer>\r\n          <CustomServerUrl>\r\n          </CustomServerUrl>\r\n          <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>\r\n        </WebProjectProperties>\r\n      </FlavorProperties>\r\n    </VisualStudio>\r\n    <MonoDevelop>\r\n      <Properties VerifyCodeBehindFields=\"true\" VerifyCodeBehindEvents=\"true\">\r\n        <XspParameters Port=\"8080\" Address=\"127.0.0.1\" SslMode=\"None\" SslProtocol=\"Default\" KeyType=\"None\" CertFile=\"\" KeyFile=\"\" PasswordOptions=\"None\" Password=\"\" Verbose=\"true\" />\r\n      </Properties>\r\n    </MonoDevelop>\r\n  </ProjectExtensions>\r\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r\n       Other similar extension points exist, see Microsoft.Common.targets.\r\n  <Target Name=\"BeforeBuild\">\r\n  </Target>\r\n  <Target Name=\"AfterBuild\">\r\n  </Target>\r\n  -->\r\n</Project>"
  },
  {
    "path": "samples/Nancy.Demo.SparkViewEngine/Views/Index.spark",
    "content": "﻿<html>\r\n<head>\r\n    <title>Spark View Engine Demo</title>\r\n</head>\r\n<body>\r\n    <p>This is a sample Spark view!</p>\r\n</body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.SparkViewEngine/Views/Main/test.spark",
    "content": "﻿<use master=\"html5\" />\r\n\r\n<content name=\"main\">\r\n   <p>This is the content!</p>\r\n</content>"
  },
  {
    "path": "samples/Nancy.Demo.SparkViewEngine/Views/Main/test2.spark",
    "content": "﻿<content name=\"main\">\r\n   <p>This is the content for the page which doesn't explicitly define its own master template.</p>\r\n</content>"
  },
  {
    "path": "samples/Nancy.Demo.SparkViewEngine/Views/Shared/application.spark",
    "content": "﻿<!DOCTYPE html>\r\n<html>\r\n   <head>\r\n       <title>HTML 5 Template</title>\r\n   </head>\r\n   <body>\r\n      <use content=\"main\" />\r\n\r\n      <p>... It's using the application.spark template!</p>\r\n   </body>\r\n</html>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.SparkViewEngine/Views/Shared/html5.spark",
    "content": "﻿<!DOCTYPE html>\r\n<html>\r\n   <head>\r\n       <title>HTML 5 Template</title>\r\n   </head>\r\n   <body>\r\n      <use content=\"main\" />\r\n   </body>\r\n</html>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.SparkViewEngine/Views/_SmallBit.spark",
    "content": "﻿<p>This is a small bit</p>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.SparkViewEngine/Web.Debug.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.SparkViewEngine/Web.Release.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n    <compilation xdt:Transform=\"RemoveAttributes(debug)\" />\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.SparkViewEngine/Web.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration>\r\n  <system.web>\r\n    <compilation debug=\"true\" targetFramework=\"4.0\" />\r\n    <httpHandlers>\r\n      <add verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </httpHandlers>\r\n  </system.web>\r\n\r\n  <system.webServer>\r\n    <modules runAllManagedModulesForAllRequests=\"true\" />\r\n    <validation validateIntegratedModeConfiguration=\"false\" />\r\n    <handlers>\r\n      <add name=\"Nancy\" verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </handlers>\r\n  </system.webServer>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.SuperSimpleViewEngine/MainModule.cs",
    "content": "namespace Nancy.Demo.SuperSimpleViewEngine\r\n{\r\n    using Nancy.Demo.SuperSimpleViewEngine.Models;\r\n\r\n    public class MainModule : NancyModule\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"INancyModule\"/> class.\r\n        /// </summary>\r\n        public MainModule()\r\n        {\r\n            Get(\"/\", args =>\r\n            {\r\n                ViewBag.Test = \"Test ViewBag\";\r\n                var model = new MainModel(\r\n                    \"Jimbo\",\r\n                    new[] {new User(\"Bob\", \"Smith\"), new User(\"Jimbo\", \"Jones\"), new User(\"Bill\", \"Bobs\"),},\r\n                    \"<script type=\\\"text/javascript\\\">alert('Naughty JavaScript!');</script>\");\r\n\r\n                return View[\"Index\", model];\r\n            });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.SuperSimpleViewEngine/Models/MainModel.cs",
    "content": "namespace Nancy.Demo.SuperSimpleViewEngine.Models\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    public class MainModel\r\n    {\r\n        public string Name { get; set; }\r\n\r\n        public IEnumerable<User> Users { get; set; }\r\n\r\n        public string NaughtyStuff { get; set; }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"T:System.Object\"/> class.\r\n        /// </summary>\r\n        public MainModel(string name, IEnumerable<User> users, string naughtyStuff)\r\n        {\r\n            this.Name = name;\r\n            this.Users = users;\r\n            this.NaughtyStuff = naughtyStuff;\r\n        }\r\n    }\r\n\r\n    public class User\r\n    {\r\n        public string FirstName { get; private set; }\r\n\r\n        public string LastName { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"T:System.Object\"/> class.\r\n        /// </summary>\r\n        public User(string firstName, string lastName)\r\n        {\r\n            this.FirstName = firstName;\r\n            this.LastName = lastName;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.SuperSimpleViewEngine/Nancy.Demo.SuperSimpleViewEngine.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\r\n  <PropertyGroup>\r\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\r\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\r\n    <SchemaVersion>2.0</SchemaVersion>\r\n    <ProjectGuid>{4885B9DF-D99C-4A1C-8606-259D32A58C33}</ProjectGuid>\r\n    <ProjectTypeGuids>{349C5851-65DF-11DA-9384-00065B846F21};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>\r\n    <OutputType>Library</OutputType>\r\n    <AppDesignerFolder>Properties</AppDesignerFolder>\r\n    <RootNamespace>Nancy.Demo.SuperSimpleViewEngine</RootNamespace>\r\n    <AssemblyName>Nancy.Demo.SuperSimpleViewEngine</AssemblyName>\r\n    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\r\n    <UseIISExpress>true</UseIISExpress>\r\n    <OldToolsVersion>4.0</OldToolsVersion>\r\n    <IISExpressSSLPort />\r\n    <IISExpressAnonymousAuthentication />\r\n    <IISExpressWindowsAuthentication />\r\n    <IISExpressUseClassicPipelineMode />\r\n    <UseGlobalApplicationHostFile />\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <DebugType>full</DebugType>\r\n    <Optimize>false</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\r\n    <DebugType>pdbonly</DebugType>\r\n    <Optimize>true</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoDebug|AnyCPU'\">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <DebugType>full</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.SuperSimpleViewEngine.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRules>false</CodeAnalysisIgnoreBuiltInRules>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Optimize>false</Optimize>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoRelease|AnyCPU'\">\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <Optimize>true</Optimize>\r\n    <DebugType>pdbonly</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.SuperSimpleViewEngine.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRules>false</CodeAnalysisIgnoreBuiltInRules>\r\n    <WarningLevel>4</WarningLevel>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <ItemGroup>\r\n    <Reference Include=\"Microsoft.CSharp\" />\r\n    <Reference Include=\"System\" />\r\n    <Reference Include=\"System.Data\" />\r\n    <Reference Include=\"System.Drawing\" />\r\n    <Reference Include=\"System.Web\" />\r\n    <Reference Include=\"System.Xml\" />\r\n    <Reference Include=\"System.Configuration\" />\r\n    <Reference Include=\"System.Xml.Linq\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Web.config\" />\r\n    <Content Include=\"Web.Debug.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n    <Content Include=\"Web.Release.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Compile Include=\"..\\..\\SharedAssemblyInfo.cs\">\r\n      <Link>Properties\\SharedAssemblyInfo.cs</Link>\r\n    </Compile>\r\n    <Compile Include=\"MainModule.cs\" />\r\n    <Compile Include=\"Models\\MainModel.cs\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.Hosting.Aspnet.MSBuild\\Nancy.Hosting.Aspnet.csproj\">\r\n      <Project>{15B7F794-0BB2-4B66-AD78-4A951F1209B2}</Project>\r\n      <Name>Nancy.Hosting.Aspnet</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.MSBuild\\Nancy.csproj\">\r\n      <Project>{34576216-0DCA-4B0F-A0DC-9075E75A676F}</Project>\r\n      <Name>Nancy</Name>\r\n    </ProjectReference>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <None Include=\"Views\\Index.sshtml\" />\r\n    <None Include=\"Views\\Login.sshtml\" />\r\n    <None Include=\"Views\\MasterPage.sshtml\" />\r\n    <None Include=\"Views\\User.sshtml\" />\r\n  </ItemGroup>\r\n  <PropertyGroup>\r\n    <VisualStudioVersion Condition=\"'$(VisualStudioVersion)' == ''\">10.0</VisualStudioVersion>\r\n    <VSToolsPath Condition=\"'$(VSToolsPath)' == ''\">$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)</VSToolsPath>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\r\n  <Import Project=\"$(VSToolsPath)\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"'$(VSToolsPath)' != ''\" />\r\n  <Import Project=\"$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v10.0\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"false\" />\r\n  <ProjectExtensions>\r\n    <VisualStudio>\r\n      <FlavorProperties GUID=\"{349C5851-65DF-11DA-9384-00065B846F21}\">\r\n        <WebProjectProperties>\r\n          <UseIIS>False</UseIIS>\r\n          <AutoAssignPort>True</AutoAssignPort>\r\n          <DevelopmentServerPort>57861</DevelopmentServerPort>\r\n          <DevelopmentServerVPath>/</DevelopmentServerVPath>\r\n          <IISUrl>http://localhost:57861/</IISUrl>\r\n          <NTLMAuthentication>False</NTLMAuthentication>\r\n          <UseCustomServer>False</UseCustomServer>\r\n          <CustomServerUrl>\r\n          </CustomServerUrl>\r\n          <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>\r\n        </WebProjectProperties>\r\n      </FlavorProperties>\r\n    </VisualStudio>\r\n    <MonoDevelop>\r\n      <Properties VerifyCodeBehindFields=\"true\" VerifyCodeBehindEvents=\"true\">\r\n        <XspParameters Port=\"8080\" Address=\"127.0.0.1\" SslMode=\"None\" SslProtocol=\"Default\" KeyType=\"None\" CertFile=\"\" KeyFile=\"\" PasswordOptions=\"None\" Password=\"\" Verbose=\"true\" />\r\n      </Properties>\r\n    </MonoDevelop>\r\n  </ProjectExtensions>\r\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r\n       Other similar extension points exist, see Microsoft.Common.targets.\r\n  <Target Name=\"BeforeBuild\">\r\n  </Target>\r\n  <Target Name=\"AfterBuild\">\r\n  </Target>\r\n  -->\r\n</Project>"
  },
  {
    "path": "samples/Nancy.Demo.SuperSimpleViewEngine/Views/Index.sshtml",
    "content": "﻿@Master['MasterPage']\r\n\r\n@Section['Content']\r\n\r\n    <h3>ViewBag</h3>\r\n    @ViewBag.Test\r\n    <p>This content from the index page<p>\r\n    <h3>Partials</h3>\r\n    <p>Login box below rendered via a partial view with no model.</p>\r\n    <div id=\"login\">\r\n        @Partial['login'];\r\n    </div>\r\n    <p>Box below is rendered via a partial with a sub-model passed in.</p>\r\n    <p>The submodel is a list which the partial iterates over with Each</p>\r\n    <div id=\"users\">\r\n        @Partial['user', Model.Users];\r\n    </div>\r\n    <h3>Encoding</h3>\r\n    <p>Model output can also be encoded:</p>\r\n    <p>@!Model.NaughtyStuff</p>\r\n    <p>\r\n        <h2>The context stuff</h2>\r\n        The requested path: @Context.Request.Path\r\n    </p>\r\n@EndSection"
  },
  {
    "path": "samples/Nancy.Demo.SuperSimpleViewEngine/Views/Login.sshtml",
    "content": "﻿<form>\r\n    Username: <input/><br/>\r\n    Password: <input/><br/>\r\n    <input type=\"submit\" value=\"Login\"/>\r\n</form>"
  },
  {
    "path": "samples/Nancy.Demo.SuperSimpleViewEngine/Views/MasterPage.sshtml",
    "content": "﻿<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n    <title>Super Simple View Engine</title>\r\n</head>\r\n<body>\r\n<h1>Super Simple View Engine</h1>\r\n<p>This text is in the master page, it has access to the model:</p>\r\n<p>Hello @Model.Name!<p>\r\n@Section['Content']\r\n</body>\r\n</html>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.SuperSimpleViewEngine/Views/User.sshtml",
    "content": "﻿@Each\r\nFirst name: @Current.FirstName <br/>\r\nSurname: @Current.LastName <br/>\r\n<br/>\r\n@EndEach"
  },
  {
    "path": "samples/Nancy.Demo.SuperSimpleViewEngine/Web.Debug.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.SuperSimpleViewEngine/Web.Release.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n    <compilation xdt:Transform=\"RemoveAttributes(debug)\" />\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.SuperSimpleViewEngine/Web.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration>\r\n  <system.web>\r\n    <compilation debug=\"true\" targetFramework=\"4.0\" />\r\n    <httpHandlers>\r\n      <add verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </httpHandlers>\r\n  </system.web>\r\n\r\n  <system.webServer>\r\n    <modules runAllManagedModulesForAllRequests=\"true\" />\r\n    <validation validateIntegratedModeConfiguration=\"false\" />\r\n    <handlers>\r\n      <add name=\"Nancy\" verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </handlers>\r\n  </system.webServer>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Validation/CustomersModule.cs",
    "content": "namespace Nancy.Demo.Validation\r\n{\r\n    using System.Linq;\r\n    using Nancy.Demo.Validation.Database;\r\n    using Nancy.Demo.Validation.Models;\r\n    using Nancy.ModelBinding;\r\n    using Nancy.Validation;\r\n\r\n    public class CustomersModule : NancyModule\r\n    {\r\n        public CustomersModule() : base(\"/customers\")\r\n        {\r\n            Get(\"/\", args =>\r\n            {\r\n                var model = DB.Customers.OrderBy(e => e.RenewalDate).ToArray();\r\n\r\n                return View[\"Customers\", model];\r\n            });\r\n\r\n            Get(\"/poke\", args =>\r\n            {\r\n                var validator =\r\n                    this.ValidatorLocator.GetValidatorForType(typeof(Customer));\r\n\r\n                return this.Response.AsJson(validator.Description);\r\n            });\r\n\r\n            Post<dynamic>(\"/\", args =>\r\n            {\r\n                Customer model = this.Bind();\r\n                var result = this.Validate(model);\r\n\r\n                if (!result.IsValid)\r\n                {\r\n                    return View[\"CustomerError\", result];\r\n                }\r\n\r\n                DB.Customers.Add(model);\r\n\r\n                return this.Response.AsRedirect(\"/Customers\");\r\n            });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Validation/Database/DB.cs",
    "content": "namespace Nancy.Demo.Validation.Database\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using Nancy.Demo.Validation.Models;\r\n\r\n    public static class DB\r\n    {\r\n        public static List<Customer> Customers { get; private set; }\r\n\r\n        static DB()\r\n        {\r\n            Customers = new List<Customer>();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Validation/MainModule.cs",
    "content": "﻿namespace Nancy.Demo.Validation\r\n{\r\n    public class MainModule : NancyModule\r\n    {\r\n        public MainModule()\r\n        {\r\n            Get(\"/\", args =>\r\n            {\r\n                return \"<a href='/customers'>Customers</a><br><a href='/products'>Products</a>\";\r\n            });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Validation/Models/Customer.cs",
    "content": "﻿namespace Nancy.Demo.Validation.Models\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.ComponentModel.DataAnnotations;\r\n\r\n    public class Customer : IValidatableObject\r\n    {\r\n        public int Id { get; set; }\r\n\r\n        [Required, OddLengthString]\r\n        public string Name { get; set; }\r\n\r\n        [Range(typeof(DateTime), \"1/1/2000\", \"1/1/3000\", ErrorMessage = \"Value for {0} must be between {1} and {2}\")]\r\n        public DateTime RenewalDate { get; set; }\r\n\r\n        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)\r\n        {\r\n            if (this.Id > 100)\r\n            {\r\n                yield return new ValidationResult(\"The Id cannot be greater than 100\", new[] { \"Id\" });\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Validation/Models/OddLengthStringAttribute.cs",
    "content": "﻿namespace Nancy.Demo.Validation.Models\r\n{\r\n    using System.ComponentModel.DataAnnotations;\r\n\r\n    public class OddLengthStringAttribute : ValidationAttribute\r\n    {\r\n        protected override ValidationResult IsValid(object value, ValidationContext validationContext)\r\n        {\r\n            if (value != null && ((string)value).Length % 2 != 0)\r\n            {\r\n                return ValidationResult.Success;\r\n            }\r\n\r\n            return new ValidationResult(\r\n                this.ErrorMessage = string.Format(\"The value of {0} was not an odd length\", validationContext.MemberName),\r\n                new[] { validationContext.MemberName }\r\n                );\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Validation/Models/OddLengthStringAttributeAdapter.cs",
    "content": "﻿namespace Nancy.Demo.Validation.Models\r\n{\r\n    using System.ComponentModel.DataAnnotations;\r\n\r\n    using Nancy.Validation.DataAnnotations;\r\n\r\n    public class OddLengthStringAttributeAdapter : DataAnnotationsValidatorAdapter\r\n    {\r\n        public OddLengthStringAttributeAdapter() : base(\"Compare\")\r\n        {\r\n        }\r\n\r\n        public override bool CanHandle(ValidationAttribute attribute)\r\n        {\r\n            return attribute.GetType() == typeof(OddLengthStringAttribute);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Validation/Models/Product.cs",
    "content": "﻿namespace Nancy.Demo.Validation.Models\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    using FluentValidation;\r\n    using FluentValidation.Internal;\r\n    using FluentValidation.Validators;\r\n\r\n    using Nancy.Validation;\r\n    using Nancy.Validation.FluentValidation;\r\n\r\n    public class Product\r\n    {\r\n        public string Name { get; set; }\r\n\r\n        public int Price { get; set; }\r\n    }\r\n\r\n    public class ProductValidator : AbstractValidator<Product>\r\n    {\r\n        public ProductValidator()\r\n        {\r\n            RuleFor(product => product.Name).NotEmpty();\r\n            RuleFor(product => product.Name).Length(1, 10).OddLength();\r\n            RuleFor(product => product.Name).Matches(\"[A-Z]*\");\r\n            RuleFor(product => product.Name).EmailAddress();\r\n\r\n            RuleFor(product => product.Price).ExclusiveBetween(10, 15);\r\n            RuleFor(product => product.Price).InclusiveBetween(10, 15);\r\n            RuleFor(product => product.Price).Equal(5);\r\n        }\r\n    }\r\n\r\n    public class OddLengthStringValidator : PropertyValidator\r\n    {\r\n        public OddLengthStringValidator()\r\n            : base(\"'{PropertyName}' has to be of odd length.\")\r\n        {\r\n        }\r\n\r\n        protected override bool IsValid(PropertyValidatorContext context)\r\n        {\r\n            var value =\r\n                context.PropertyValue as string;\r\n\r\n            if (value == null)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            return (value.Length % 2 != 0);\r\n        }\r\n    }\r\n\r\n    public static class FluentValidationExtensions\r\n    {\r\n        public static IRuleBuilderOptions<T, string> OddLength<T>(this IRuleBuilder<T, string> ruleBuilder)\r\n        {\r\n            return ruleBuilder.SetValidator(new OddLengthStringValidator());\r\n        }\r\n    }\r\n\r\n    public class OddLengthStringValidatorAdapter : AdapterBase\r\n    {\r\n        public override bool CanHandle(IPropertyValidator validator)\r\n        {\r\n            return validator is OddLengthStringValidator;\r\n        }\r\n\r\n        public override IEnumerable<ModelValidationRule> GetRules(PropertyRule rule, IPropertyValidator validator)\r\n        {\r\n            yield return new OddLengthStringRule(\r\n                base.FormatMessage(rule, validator),\r\n                base.GetMemberNames(rule));\r\n        }\r\n    }\r\n\r\n    public class OddLengthStringRule : ModelValidationRule\r\n    {\r\n        public OddLengthStringRule(Func<string, string> errorMessageFormatter, IEnumerable<string> memberNames)\r\n            : base(\"OddLengthString\", errorMessageFormatter, memberNames)\r\n        {\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Validation/Nancy.Demo.Validation.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <Import Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\" Condition=\"Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\" />\r\n  <PropertyGroup>\r\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\r\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\r\n    <SchemaVersion>2.0</SchemaVersion>\r\n    <ProjectGuid>{F417B81C-B914-4BFD-8299-6BBD11072B01}</ProjectGuid>\r\n    <ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>\r\n    <OutputType>Library</OutputType>\r\n    <AppDesignerFolder>Properties</AppDesignerFolder>\r\n    <RootNamespace>Nancy.Demo.Validation</RootNamespace>\r\n    <AssemblyName>Nancy.Demo.Validation</AssemblyName>\r\n    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>\r\n    <UseIISExpress>false</UseIISExpress>\r\n    <OldToolsVersion>4.0</OldToolsVersion>\r\n    <IISExpressSSLPort />\r\n    <IISExpressAnonymousAuthentication />\r\n    <IISExpressWindowsAuthentication />\r\n    <IISExpressUseClassicPipelineMode />\r\n    <UseGlobalApplicationHostFile />\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <DebugType>full</DebugType>\r\n    <Optimize>false</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\r\n    <DebugType>pdbonly</DebugType>\r\n    <Optimize>true</Optimize>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <WarningLevel>4</WarningLevel>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoDebug|AnyCPU'\">\r\n    <DebugSymbols>true</DebugSymbols>\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\r\n    <DebugType>full</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.Validation.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRules>false</CodeAnalysisIgnoreBuiltInRules>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'MonoRelease|AnyCPU'\">\r\n    <OutputPath>bin\\</OutputPath>\r\n    <DefineConstants>TRACE</DefineConstants>\r\n    <Optimize>true</Optimize>\r\n    <DebugType>pdbonly</DebugType>\r\n    <PlatformTarget>AnyCPU</PlatformTarget>\r\n    <CodeAnalysisLogFile>bin\\Nancy.Demo.Validation.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>\r\n    <CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>\r\n    <CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>\r\n    <ErrorReport>prompt</ErrorReport>\r\n    <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>\r\n    <CodeAnalysisRuleSetDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\\\Rule Sets</CodeAnalysisRuleSetDirectories>\r\n    <CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>\r\n    <CodeAnalysisRuleDirectories>;C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Team Tools\\Static Analysis Tools\\FxCop\\\\Rules</CodeAnalysisRuleDirectories>\r\n    <Prefer32Bit>false</Prefer32Bit>\r\n  </PropertyGroup>\r\n  <ItemGroup>\r\n    <Reference Include=\"FluentValidation, Version=6.3.4.0, Culture=neutral, processorArchitecture=MSIL\">\r\n      <HintPath>..\\..\\packages\\FluentValidation.6.3.4-alpha\\lib\\Net45\\FluentValidation.dll</HintPath>\r\n      <Private>True</Private>\r\n    </Reference>\r\n    <Reference Include=\"Microsoft.CSharp\" />\r\n    <Reference Include=\"System.ComponentModel.DataAnnotations\" />\r\n    <Reference Include=\"System\" />\r\n    <Reference Include=\"System.Data\" />\r\n    <Reference Include=\"System.Drawing\" />\r\n    <Reference Include=\"System.Web\" />\r\n    <Reference Include=\"System.Xml\" />\r\n    <Reference Include=\"System.Configuration\" />\r\n    <Reference Include=\"System.Xml.Linq\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"Web.config\" />\r\n    <Content Include=\"Web.Debug.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n    <Content Include=\"Web.Release.config\">\r\n      <DependentUpon>Web.config</DependentUpon>\r\n    </Content>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Compile Include=\"..\\..\\SharedAssemblyInfo.cs\">\r\n      <Link>Properties\\SharedAssemblyInfo.cs</Link>\r\n    </Compile>\r\n    <Compile Include=\"CustomersModule.cs\" />\r\n    <Compile Include=\"Database\\DB.cs\" />\r\n    <Compile Include=\"MainModule.cs\" />\r\n    <Compile Include=\"Models\\Customer.cs\" />\r\n    <Compile Include=\"Models\\OddLengthStringAttribute.cs\" />\r\n    <Compile Include=\"Models\\OddLengthStringAttributeAdapter.cs\" />\r\n    <Compile Include=\"Models\\Product.cs\" />\r\n    <Compile Include=\"ProductsModule.cs\" />\r\n    <Compile Include=\"ValidationBootstrapper.cs\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.Hosting.Aspnet.MSBuild\\Nancy.Hosting.Aspnet.csproj\">\r\n      <Project>{15B7F794-0BB2-4B66-AD78-4A951F1209B2}</Project>\r\n      <Name>Nancy.Hosting.Aspnet</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.Validation.DataAnnotations.MSBuild\\Nancy.Validation.DataAnnotations.csproj\">\r\n      <Project>{701765DC-F4F2-4943-A37F-6ED253198158}</Project>\r\n      <Name>Nancy.Validation.DataAnnotations</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.Validation.FluentValidation.MSBuild\\Nancy.Validation.FluentValidation.csproj\">\r\n      <Project>{01230F2A-D108-480C-B834-8CE0569FD3B3}</Project>\r\n      <Name>Nancy.Validation.FluentValidation</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.ViewEngines.Spark.MSBuild\\Nancy.ViewEngines.Spark.csproj\">\r\n      <Project>{4B7E35DF-1569-4346-B180-A09615723095}</Project>\r\n      <Name>Nancy.ViewEngines.Spark</Name>\r\n    </ProjectReference>\r\n    <ProjectReference Include=\"..\\..\\src\\Nancy.MSBuild\\Nancy.csproj\">\r\n      <Project>{34576216-0DCA-4B0F-A0DC-9075E75A676F}</Project>\r\n      <Name>Nancy</Name>\r\n    </ProjectReference>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <Content Include=\"packages.config\" />\r\n    <None Include=\"Views\\CustomerError.spark\">\r\n      <SubType>Designer</SubType>\r\n    </None>\r\n    <None Include=\"Views\\Customers.spark\" />\r\n  </ItemGroup>\r\n  <PropertyGroup>\r\n    <VisualStudioVersion Condition=\"'$(VisualStudioVersion)' == ''\">10.0</VisualStudioVersion>\r\n    <VSToolsPath Condition=\"'$(VSToolsPath)' == ''\">$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v$(VisualStudioVersion)</VSToolsPath>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\r\n  <Import Project=\"$(VSToolsPath)\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"'$(VSToolsPath)' != ''\" />\r\n  <Import Project=\"$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v10.0\\WebApplications\\Microsoft.WebApplication.targets\" Condition=\"false\" />\r\n  <ProjectExtensions>\r\n    <VisualStudio>\r\n      <FlavorProperties GUID=\"{349c5851-65df-11da-9384-00065b846f21}\">\r\n        <WebProjectProperties>\r\n          <UseIIS>False</UseIIS>\r\n          <AutoAssignPort>True</AutoAssignPort>\r\n          <DevelopmentServerPort>3382</DevelopmentServerPort>\r\n          <DevelopmentServerVPath>/</DevelopmentServerVPath>\r\n          <IISUrl>\r\n          </IISUrl>\r\n          <NTLMAuthentication>False</NTLMAuthentication>\r\n          <UseCustomServer>False</UseCustomServer>\r\n          <CustomServerUrl>\r\n          </CustomServerUrl>\r\n          <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>\r\n        </WebProjectProperties>\r\n      </FlavorProperties>\r\n    </VisualStudio>\r\n  </ProjectExtensions>\r\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r\n       Other similar extension points exist, see Microsoft.Common.targets.\r\n  <Target Name=\"BeforeBuild\">\r\n  </Target>\r\n  <Target Name=\"AfterBuild\">\r\n  </Target>\r\n  -->\r\n</Project>"
  },
  {
    "path": "samples/Nancy.Demo.Validation/ProductsModule.cs",
    "content": "﻿namespace Nancy.Demo.Validation\r\n{\r\n    using Nancy.Demo.Validation.Models;\r\n    using Nancy.ModelBinding;\r\n    using Nancy.Validation;\r\n\r\n    public class ProductsModule : NancyModule\r\n    {\r\n        public ProductsModule() : base(\"/products\")\r\n        {\r\n            Get(\"/\", args =>\r\n            {\r\n                return \"Products module\";\r\n            });\r\n\r\n            Get(\"/poke\", args =>\r\n            {\r\n                var validator =\r\n                    this.ValidatorLocator.GetValidatorForType(typeof(Product));\r\n\r\n                return this.Response.AsJson(validator.Description);\r\n            });\r\n\r\n            Post<dynamic>(\"/\", args =>\r\n            {\r\n                Product model = this.Bind();\r\n                var result = this.Validate(model);\r\n\r\n                if (!result.IsValid)\r\n                {\r\n                    return View[\"CustomerError\", result];\r\n                }\r\n\r\n                return 200;\r\n            });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Validation/ValidationBootstrapper.cs",
    "content": "﻿namespace Nancy.Demo.Validation\r\n{\r\n    using Nancy.TinyIoc;\r\n\r\n    public class ValidationBootstrapper : DefaultNancyBootstrapper\r\n    {\r\n        protected override void ConfigureApplicationContainer(TinyIoCContainer container)\r\n        {\r\n            // Disable auto-registration so that we can make sure that the\r\n            // application registrations are preformed correctly by each of\r\n            // the validation projects. This is for testing purposes only\r\n            // and is not required to perform in your own project.\r\n\r\n            //base.ConfigureApplicationContainer(container);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "samples/Nancy.Demo.Validation/Views/CustomerError.spark",
    "content": "﻿<viewdata model=\"Nancy.Validation.ModelValidationResult\"/>\r\n<html>\r\n  <head>\r\n    <title>Customers</title>\r\n  </head>\r\n  <body>\r\n    <h1>Error submitting customer.</h1>\r\n      <for each=\"var k in Model.Errors.Keys\">\r\n        <h2>${k}</h2>\r\n        <ul>\r\n          <for each=\"var e in Model.Errors[k]\">\r\n            <li>${e}</li>\r\n          </for>\r\n        </ul>\r\n      </for>\r\n  </body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Validation/Views/Customers.spark",
    "content": "﻿<viewdata model=\"Nancy.Demo.Validation.Models.Customer[]\"/>\r\n<html>\r\n  <head>\r\n    <title>Customers</title>\r\n  </head>\r\n  <body>\r\n    <h1>Customers</h1>\r\n    <p>Customer is added twice, one using the dynamic binder adapter, the other using the generic one.</p>\r\n    <p>Current customers:</p>\r\n    <ul>\r\n      <li each=\"var v in Model\">\r\n        <a href=\"customer/${v.Id}\"> ${v.Name} - ${v.RenewalDate.ToShortDateString()} </a>\r\n      </li>\r\n    </ul>\r\n\r\n    <h2>Add another</h2>\r\n    <form method=\"POST\" action=\"/customers\">\r\n      <label for=\"Name\">Name</label>\r\n      <input type=\"text\" name=\"Name\" />\r\n      <label for=\"Location\">Renewal Date</label>\r\n      <input type=\"text\" name=\"RenewalDate\" />\r\n      <input type=\"submit\"/>\r\n    </form>\r\n  </body>\r\n</html>"
  },
  {
    "path": "samples/Nancy.Demo.Validation/Web.Debug.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Validation/Web.Release.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\">\r\n  <system.web>\r\n    <compilation xdt:Transform=\"RemoveAttributes(debug)\" />\r\n  </system.web>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Validation/Web.config",
    "content": "﻿<?xml version=\"1.0\"?>\r\n\r\n<configuration>\r\n  <system.web>\r\n    <compilation debug=\"true\" targetFramework=\"4.0\" />\r\n    <httpHandlers>\r\n      <add verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </httpHandlers>\r\n  </system.web>\r\n\r\n  <system.webServer>\r\n    <modules runAllManagedModulesForAllRequests=\"true\" />\r\n    <validation validateIntegratedModeConfiguration=\"false\" />\r\n    <handlers>\r\n      <add name=\"Nancy\" verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\" />\r\n    </handlers>\r\n  </system.webServer>\r\n</configuration>\r\n"
  },
  {
    "path": "samples/Nancy.Demo.Validation/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<packages>\r\n  <package id=\"FluentValidation\" version=\"6.3.4-alpha\" targetFramework=\"net45\" />\r\n</packages>"
  },
  {
    "path": "src/Directory.Build.props",
    "content": "﻿<Project>\r\n  <PropertyGroup>\r\n    <Authors>Andreas Håkansson, Steven Robbins and contributors</Authors>\r\n    <CodeAnalysisRuleSet>..\\..\\Nancy.ruleset</CodeAnalysisRuleSet>\r\n    <Configurations>Debug;Release</Configurations>\r\n    <DisableImplicitFrameworkReferences Condition=\" '$(TargetFramework)' == 'net452' \">true</DisableImplicitFrameworkReferences>\r\n    <GenerateDocumentationFile>true</GenerateDocumentationFile>\r\n    <PackageIconUrl>http://nancyfx.org/nancy-nuget.png</PackageIconUrl>\r\n    <PackageLicenseUrl>https://github.com/NancyFx/Nancy/blob/master/license.txt</PackageLicenseUrl>\r\n    <PackageProjectUrl>http://nancyfx.org</PackageProjectUrl>\r\n    <PackageTags>Nancy</PackageTags>\r\n    <Platforms>AnyCPU</Platforms>\r\n    <Version>2.0.0-clinteastwood</Version>\r\n  </PropertyGroup>\r\n\r\n  <ItemGroup Condition=\" '$(MSBuildProjectName)' != 'Nancy' \">\r\n    <ProjectReference Include=\"../Nancy/Nancy.csproj\" />\r\n  </ItemGroup>\r\n\r\n  <ItemGroup>\r\n    <PackageReference Include=\"AsyncUsageAnalyzers\" Version=\"1.0.0-alpha003\">\r\n      <PrivateAssets>All</PrivateAssets>\r\n    </PackageReference>\r\n  </ItemGroup>\r\n\r\n  <PropertyGroup Condition=\" '$(TargetFramework)' == 'netstandard2.0' \">\r\n    <DefineConstants>$(DefineConstants);CORE</DefineConstants>\r\n  </PropertyGroup>\r\n\r\n  <ItemGroup Condition=\" '$(TargetFramework)' == 'net452' \">\r\n    <Reference Include=\"Microsoft.CSharp\" />\r\n    <Reference Include=\"System.Core\" />\r\n    <Reference Include=\"System\" />\r\n  </ItemGroup>\r\n</Project>\r\n"
  },
  {
    "path": "src/Nancy/AfterPipeline.cs",
    "content": "namespace Nancy\r\n{\r\n    using System;\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Helpers;\r\n\r\n    /// <summary>\r\n    /// Intercepts the request after the appropriate route handler has completed its operation.\r\n    /// The After hooks does not have any return value because one has already been produced by the appropriate route.\r\n    /// Instead you get the option to modify (or completely replace) the existing response by accessing the Response property of the NancyContext that is passed in.\r\n    /// </summary>\r\n    /// <seealso cref=\"AsyncNamedPipelineBase{TAsyncDelegate,TSyncDelegate}\" />\r\n    public class AfterPipeline : AsyncNamedPipelineBase<Func<NancyContext, CancellationToken, Task>, Action<NancyContext>>\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"AfterPipeline\"/> class.\r\n        /// </summary>\r\n        public AfterPipeline()\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"AfterPipeline\"/> class, with\r\n        /// the provided <paramref name= \"capacity\" />.\r\n        /// </summary>\r\n        /// <param name=\"capacity\">Number of delegates in pipeline</param>\r\n        public AfterPipeline(int capacity)\r\n            : base(capacity)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"AfterPipeline\"/> to <see cref=\"Func{NancyContext, CancellationToken, Task}\"/>.\r\n        /// </summary>\r\n        /// <param name=\"pipeline\">The <see cref=\"AfterPipeline\"/> instance.</param>\r\n        /// <returns>The result of the conversion.</returns>\r\n        public static implicit operator Func<NancyContext, CancellationToken, Task>(AfterPipeline pipeline)\r\n        {\r\n            return pipeline.Invoke;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"Func{NancyContext, CancellationToken, Task}\"/> to <see cref=\"AfterPipeline\"/>.\r\n        /// </summary>\r\n        /// <param name=\"func\">The function.</param>\r\n        /// <returns>\r\n        /// A new <see cref=\"AfterPipeline\"/> instance with <paramref name=\"func\"/>\r\n        /// </returns>\r\n        public static implicit operator AfterPipeline(Func<NancyContext, CancellationToken, Task> func)\r\n        {\r\n            var pipeline = new AfterPipeline();\r\n            pipeline.AddItemToEndOfPipeline(func);\r\n            return pipeline;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Appends a new func to the AfterPipeline\r\n        /// </summary>\r\n        /// <param name=\"pipeline\">The pipeline.</param>\r\n        /// <param name=\"func\">The function.</param>\r\n        /// <returns>\r\n        /// <paramref name=\"pipeline\"/>\r\n        /// </returns>\r\n        public static AfterPipeline operator +(AfterPipeline pipeline, Func<NancyContext, CancellationToken, Task> func)\r\n        {\r\n            pipeline.AddItemToEndOfPipeline(func);\r\n            return pipeline;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Appends a new action to the AfterPipeline\r\n        /// </summary>\r\n        /// <param name=\"pipeline\">The <see cref=\"AfterPipeline\"/> instance.</param>\r\n        /// <param name=\"action\">The action.</param>\r\n        /// <returns>\r\n        /// <paramref name=\"pipeline\"/>\r\n        /// </returns>\r\n        public static AfterPipeline operator +(AfterPipeline pipeline, Action<NancyContext> action)\r\n        {\r\n            pipeline.AddItemToEndOfPipeline(action);\r\n            return pipeline;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Appends the items of an <see cref=\"AfterPipeline\"/> to the other.\r\n        /// </summary>\r\n        /// <param name=\"pipelineToAddTo\">The <see cref=\"AfterPipeline\"/> to add to.</param>\r\n        /// <param name=\"pipelineToAdd\">The <see cref=\"AfterPipeline\"/> to add.</param>\r\n        /// <returns>\r\n        /// <paramref name=\"pipelineToAddTo\"/>\r\n        /// </returns>\r\n        public static AfterPipeline operator +(AfterPipeline pipelineToAddTo, AfterPipeline pipelineToAdd)\r\n        {\r\n            foreach (var pipelineItem in pipelineToAdd.PipelineItems)\r\n            {\r\n                pipelineToAddTo.AddItemToEndOfPipeline(pipelineItem);\r\n            }\r\n\r\n            return pipelineToAddTo;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Invokes the pipeline items in Nancy context.\r\n        /// </summary>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> instance.</param>\r\n        /// <param name=\"cancellationToken\">The <see cref=\"CancellationToken\"/> instance</param>\r\n        public async Task Invoke(NancyContext context, CancellationToken cancellationToken)\r\n        {\r\n            foreach (var pipelineDelegate in this.PipelineDelegates)\r\n            {\r\n                await pipelineDelegate.Invoke(context, cancellationToken).ConfigureAwait(false);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Wraps the specified <see cref=\"PipelineItem{T}\"/> instance into its async form.\r\n        /// </summary>\r\n        /// <param name=\"pipelineItem\">The <see cref=\"PipelineItem{T}\"/> instance.</param>\r\n        /// <returns>Async <see cref=\"PipelineItem{T}\"/> instance</returns>\r\n        protected override PipelineItem<Func<NancyContext, CancellationToken, Task>> Wrap(PipelineItem<Action<NancyContext>> pipelineItem)\r\n        {\r\n            return new PipelineItem<Func<NancyContext, CancellationToken, Task>>(pipelineItem.Name, (ctx, ct) =>\r\n            {\r\n                pipelineItem.Delegate(ctx);\r\n                return TaskHelpers.CompletedTask;\r\n            });\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/AppDomainAssemblyCatalog.cs",
    "content": "#if !CORE\r\nnamespace Nancy\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using Nancy.Extensions;\r\n    using Nancy.Helpers;\r\n\r\n    /// <summary>\r\n    /// Default implementation of the <see cref=\"IAssemblyCatalog\"/> interface, based on\r\n    /// retrieving <see cref=\"Assembly\"/> information from <see cref=\"AppDomain.CurrentDomain\"/>.\r\n    /// </summary>\r\n    public class AppDomainAssemblyCatalog : IAssemblyCatalog\r\n    {\r\n        private static readonly AssemblyName NancyAssemblyName = typeof(INancyEngine).GetTypeInfo().Assembly.GetName();\r\n        private readonly Lazy<IReadOnlyCollection<Assembly>> assemblies = new Lazy<IReadOnlyCollection<Assembly>>(GetAvailableAssemblies);\r\n\r\n        /// <summary>\r\n        /// Gets all <see cref=\"Assembly\"/> instances in the catalog.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IReadOnlyCollection{T}\"/> of <see cref=\"Assembly\"/> instances.</returns>\r\n        public virtual IReadOnlyCollection<Assembly> GetAssemblies()\r\n        {\r\n            return this.assemblies.Value;\r\n        }\r\n\r\n        private static IReadOnlyCollection<Assembly> GetAvailableAssemblies()\r\n        {\r\n            var assemblies = GetLoadedNancyReferencingAssemblies();\r\n\r\n            var loaded = LoadNancyReferencingAssemblies(assemblies);\r\n\r\n            return assemblies.Union(loaded).ToArray();\r\n        }\r\n\r\n        private static List<Assembly> GetLoadedNancyReferencingAssemblies()\r\n        {\r\n            var assemblies = new List<Assembly>();\r\n\r\n            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())\r\n            {\r\n                if (!assembly.IsDynamic && !assembly.ReflectionOnly && assembly.IsReferencing(NancyAssemblyName))\r\n                {\r\n                    assemblies.Add(assembly);\r\n                }\r\n            }\r\n\r\n            return assemblies;\r\n        }\r\n\r\n        private static IEnumerable<Assembly> LoadNancyReferencingAssemblies(IEnumerable<Assembly> loadedAssemblies)\r\n        {\r\n            var assemblies = new HashSet<Assembly>();\r\n            var inspectionAppDomain = CreateInspectionAppDomain();\r\n            var inspectionProber = CreateRemoteReferenceProber(inspectionAppDomain);\r\n            var loadedNancyReferencingAssemblyNames = loadedAssemblies.Select(assembly => assembly.GetName()).ToArray();\r\n\r\n            foreach (var directory in GetAssemblyDirectories())\r\n            {\r\n                foreach (var assemblyPath in Directory.EnumerateFiles(directory, \"*.dll\"))\r\n                {\r\n                    var unloadedAssemblyName = SafeGetAssemblyName(assemblyPath);\r\n\r\n                    if (unloadedAssemblyName == null)\r\n                    {\r\n                        continue;\r\n                    }\r\n\r\n                    if (!loadedNancyReferencingAssemblyNames.Any(loadedNancyReferencingAssemblyName => AssemblyName.ReferenceMatchesDefinition(loadedNancyReferencingAssemblyName, unloadedAssemblyName)))\r\n                    {\r\n                        if (inspectionProber.HasReference(unloadedAssemblyName, NancyAssemblyName))\r\n                        {\r\n                            var assembly = SafeLoadAssembly(AppDomain.CurrentDomain, unloadedAssemblyName);\r\n\r\n                            if (assembly != null)\r\n                            {\r\n                                assemblies.Add(assembly);\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n\r\n            AppDomain.Unload(inspectionAppDomain);\r\n\r\n            return assemblies.ToArray();\r\n        }\r\n\r\n        private static AppDomain CreateInspectionAppDomain()\r\n        {\r\n            var currentAppDomain = AppDomain.CurrentDomain;\r\n\r\n            return AppDomain.CreateDomain(\"AppDomainAssemblyCatalog\", currentAppDomain.Evidence,\r\n                currentAppDomain.SetupInformation);\r\n        }\r\n\r\n        private static ProxyNancyReferenceProber CreateRemoteReferenceProber(AppDomain appDomain)\r\n        {\r\n            return (ProxyNancyReferenceProber)appDomain.CreateInstanceAndUnwrap(\r\n                typeof(ProxyNancyReferenceProber).Assembly.FullName,\r\n                typeof(ProxyNancyReferenceProber).FullName);\r\n        }\r\n\r\n        private static IEnumerable<string> GetAssemblyDirectories()\r\n        {\r\n            var directories = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath != null\r\n                ? AppDomain.CurrentDomain.SetupInformation.PrivateBinPath.Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries)\r\n                : new string[] { };\r\n\r\n            foreach (var directory in directories.Where(directory => !string.IsNullOrWhiteSpace(directory)))\r\n            {\r\n                yield return directory;\r\n            }\r\n\r\n            if (AppDomain.CurrentDomain.SetupInformation.PrivateBinPathProbe == null)\r\n            {\r\n                yield return AppDomain.CurrentDomain.SetupInformation.ApplicationBase;\r\n            }\r\n        }\r\n\r\n        private static AssemblyName SafeGetAssemblyName(string assemblyPath)\r\n        {\r\n            try\r\n            {\r\n                return AssemblyName.GetAssemblyName(assemblyPath);\r\n            }\r\n            catch\r\n            {\r\n                return null;\r\n            }\r\n        }\r\n\r\n        private static Assembly SafeLoadAssembly(AppDomain domain, AssemblyName assemblyName)\r\n        {\r\n            try\r\n            {\r\n                return domain.Load(assemblyName);\r\n            }\r\n            catch\r\n            {\r\n                return null;\r\n            }\r\n        }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "src/Nancy/ArrayCache.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    /// <summary>\r\n    /// A cache for empty arrays.\r\n    /// </summary>\r\n    public class ArrayCache\r\n    {\r\n        /// <summary>\r\n        /// Gets a cached, empty array of the specified type.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">the type of array to get.</typeparam>\r\n        public static T[] Empty<T>()\r\n        {\r\n            return EmptyArray<T>.Value;\r\n        }\r\n\r\n        private static class EmptyArray<T>\r\n        {\r\n            public static readonly T[] Value = new T[0];\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/AsyncNamedPipelineBase.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Abstract base class for request pipelines with async support\r\n    /// </summary>\r\n    /// <typeparam name=\"TAsyncDelegate\">The type of the asynchronous delegate.</typeparam>\r\n    /// <typeparam name=\"TSyncDelegate\">The type of the synchronus delegate.</typeparam>\r\n    public abstract class AsyncNamedPipelineBase<TAsyncDelegate, TSyncDelegate>\r\n    {\r\n        /// <summary>\r\n        /// Pipeline items to execute\r\n        /// </summary>\r\n        protected readonly List<PipelineItem<TAsyncDelegate>> pipelineItems;\r\n\r\n        /// <summary>\r\n        /// Creates a new instance of <see cref=\"AsyncNamedPipelineBase{TAsyncDelegate,TSyncDelegate}\"/>\r\n        /// </summary>\r\n        protected AsyncNamedPipelineBase()\r\n        {\r\n            this.pipelineItems = new List<PipelineItem<TAsyncDelegate>>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a new instance of <see cref=\"AsyncNamedPipelineBase{TAsyncDelegate,TSyncDelegate}\"/> with size\r\n        /// </summary>\r\n        /// <param name=\"capacity\">Number of delegates in pipeline</param>\r\n        protected AsyncNamedPipelineBase(int capacity)\r\n        {\r\n            this.pipelineItems = new List<PipelineItem<TAsyncDelegate>>(capacity);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the current pipeline items\r\n        /// </summary>\r\n        public IEnumerable<PipelineItem<TAsyncDelegate>> PipelineItems\r\n        {\r\n            get { return this.pipelineItems.AsReadOnly(); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the current pipeline item delegates\r\n        /// </summary>\r\n        public IEnumerable<TAsyncDelegate> PipelineDelegates\r\n        {\r\n            get { return this.pipelineItems.Select(pipelineItem => pipelineItem.Delegate); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Add an item to the start of the pipeline\r\n        /// </summary>\r\n        /// <param name=\"item\">Item to add</param>\r\n        public virtual void AddItemToStartOfPipeline(TAsyncDelegate item)\r\n        {\r\n            this.AddItemToStartOfPipeline((PipelineItem<TAsyncDelegate>)item);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Add an item to the start of the pipeline\r\n        /// </summary>\r\n        /// <param name=\"item\">Item to add</param>\r\n        public virtual void AddItemToStartOfPipeline(TSyncDelegate item)\r\n        {\r\n            this.AddItemToStartOfPipeline(this.Wrap(item));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Add an item to the start of the pipeline\r\n        /// </summary>\r\n        /// <param name=\"item\">Item to add</param>\r\n        /// <param name=\"replaceInPlace\">\r\n        /// Whether to replace an existing item with the same name in its current place,\r\n        /// rather than at the position requested. Defaults to false.\r\n        /// </param>\r\n        public virtual void AddItemToStartOfPipeline(PipelineItem<TAsyncDelegate> item, bool replaceInPlace = false)\r\n        {\r\n            this.InsertItemAtPipelineIndex(0, item, replaceInPlace);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Add an item to the start of the pipeline\r\n        /// </summary>\r\n        /// <param name=\"item\">Item to add</param>\r\n        /// <param name=\"replaceInPlace\">\r\n        /// Whether to replace an existing item with the same name in its current place,\r\n        /// rather than at the position requested. Defaults to false.\r\n        /// </param>\r\n        public virtual void AddItemToStartOfPipeline(PipelineItem<TSyncDelegate> item, bool replaceInPlace = false)\r\n        {\r\n            this.AddItemToStartOfPipeline(this.Wrap(item), replaceInPlace);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Add an item to the end of the pipeline\r\n        /// </summary>\r\n        /// <param name=\"item\">Item to add</param>\r\n        public virtual void AddItemToEndOfPipeline(TAsyncDelegate item)\r\n        {\r\n            this.AddItemToEndOfPipeline((PipelineItem<TAsyncDelegate>)item);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Add an item to the end of the pipeline\r\n        /// </summary>\r\n        /// <param name=\"item\">Item to add</param>\r\n        public virtual void AddItemToEndOfPipeline(TSyncDelegate item)\r\n        {\r\n            this.AddItemToEndOfPipeline(this.Wrap(item));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Add an item to the end of the pipeline\r\n        /// </summary>\r\n        /// <param name=\"item\">Item to add</param>\r\n        /// <param name=\"replaceInPlace\">\r\n        /// Whether to replace an existing item with the same name in its current place,\r\n        /// rather than at the position requested. Defaults to false.\r\n        /// </param>\r\n        public virtual void AddItemToEndOfPipeline(PipelineItem<TAsyncDelegate> item, bool replaceInPlace = false)\r\n        {\r\n            var existingIndex = this.RemoveByName(item.Name);\r\n\r\n            if (replaceInPlace && existingIndex != -1)\r\n            {\r\n                this.InsertItemAtPipelineIndex(existingIndex, item);\r\n            }\r\n            else\r\n            {\r\n                this.pipelineItems.Add(item);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Add an item to the end of the pipeline\r\n        /// </summary>\r\n        /// <param name=\"item\">Item to add</param>\r\n        /// <param name=\"replaceInPlace\">\r\n        /// Whether to replace an existing item with the same name in its current place,\r\n        /// rather than at the position requested. Defaults to false.\r\n        /// </param>\r\n        public virtual void AddItemToEndOfPipeline(PipelineItem<TSyncDelegate> item, bool replaceInPlace = false)\r\n        {\r\n            this.AddItemToEndOfPipeline(this.Wrap(item), replaceInPlace);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Add an item to a specific place in the pipeline.\r\n        /// </summary>\r\n        /// <param name=\"index\">Index to add at</param>\r\n        /// <param name=\"item\">Item to add</param>\r\n        public virtual void InsertItemAtPipelineIndex(int index, TAsyncDelegate item)\r\n        {\r\n            this.InsertItemAtPipelineIndex(index, (PipelineItem<TAsyncDelegate>)item);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Add an item to a specific place in the pipeline.\r\n        /// </summary>\r\n        /// <param name=\"index\">Index to add at</param>\r\n        /// <param name=\"item\">Item to add</param>\r\n        public virtual void InsertItemAtPipelineIndex(int index, TSyncDelegate item)\r\n        {\r\n            this.InsertItemAtPipelineIndex(index, this.Wrap(item));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Add an item to a specific place in the pipeline.\r\n        /// </summary>\r\n        /// <param name=\"index\">Index to add at</param>\r\n        /// <param name=\"item\">Item to add</param>\r\n        /// <param name=\"replaceInPlace\">\r\n        /// Whether to replace an existing item with the same name in its current place,\r\n        /// rather than at the position requested. Defaults to false.\r\n        /// </param>\r\n        public virtual void InsertItemAtPipelineIndex(int index, PipelineItem<TAsyncDelegate> item, bool replaceInPlace = false)\r\n        {\r\n            var existingIndex = this.RemoveByName(item.Name);\r\n\r\n            var newIndex = (replaceInPlace && existingIndex != -1) ? existingIndex : index;\r\n\r\n            this.pipelineItems.Insert(newIndex, item);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Add an item to a specific place in the pipeline.\r\n        /// </summary>\r\n        /// <param name=\"index\">Index to add at</param>\r\n        /// <param name=\"item\">Item to add</param>\r\n        /// <param name=\"replaceInPlace\">\r\n        /// Whether to replace an existing item with the same name in its current place,\r\n        /// rather than at the position requested. Defaults to false.\r\n        /// </param>\r\n        public virtual void InsertItemAtPipelineIndex(int index, PipelineItem<TSyncDelegate> item, bool replaceInPlace = false)\r\n        {\r\n            this.InsertItemAtPipelineIndex(index, this.Wrap(item), replaceInPlace);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Insert an item before a named item.\r\n        /// If the named item does not exist the item is inserted at the start of the pipeline.\r\n        /// </summary>\r\n        /// <param name=\"name\">Name of the item to insert before</param>\r\n        /// <param name=\"item\">Item to insert</param>\r\n        public virtual void InsertBefore(string name, TAsyncDelegate item)\r\n        {\r\n            this.InsertBefore(name, (PipelineItem<TAsyncDelegate>)item);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Insert an item before a named item.\r\n        /// If the named item does not exist the item is inserted at the start of the pipeline.\r\n        /// </summary>\r\n        /// <param name=\"name\">Name of the item to insert before</param>\r\n        /// <param name=\"item\">Item to insert</param>\r\n        public virtual void InsertBefore(string name, TSyncDelegate item)\r\n        {\r\n            this.InsertBefore(name, this.Wrap(item));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Insert an item before a named item.\r\n        /// If the named item does not exist the item is inserted at the start of the pipeline.\r\n        /// </summary>\r\n        /// <param name=\"name\">Name of the item to insert before</param>\r\n        /// <param name=\"item\">Item to insert</param>\r\n        public virtual void InsertBefore(string name, PipelineItem<TAsyncDelegate> item)\r\n        {\r\n            var existingIndex =\r\n                this.pipelineItems.FindIndex(i => string.Equals(name, i.Name, StringComparison.Ordinal));\r\n\r\n            if (existingIndex == -1)\r\n            {\r\n                existingIndex = 0;\r\n            }\r\n\r\n            this.InsertItemAtPipelineIndex(existingIndex, item);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Insert an item before a named item.\r\n        /// If the named item does not exist the item is inserted at the start of the pipeline.\r\n        /// </summary>\r\n        /// <param name=\"name\">Name of the item to insert before</param>\r\n        /// <param name=\"item\">Item to insert</param>\r\n        public virtual void InsertBefore(string name, PipelineItem<TSyncDelegate> item)\r\n        {\r\n            this.InsertBefore(name, this.Wrap(item));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Insert an item after a named item.\r\n        /// If the named item does not exist the item is inserted at the end of the pipeline.\r\n        /// </summary>\r\n        /// <param name=\"name\">Name of the item to insert after</param>\r\n        /// <param name=\"item\">Item to insert</param>\r\n        public virtual void InsertAfter(string name, TAsyncDelegate item)\r\n        {\r\n            this.InsertAfter(name, (PipelineItem<TAsyncDelegate>)item);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Insert an item after a named item.\r\n        /// If the named item does not exist the item is inserted at the end of the pipeline.\r\n        /// </summary>\r\n        /// <param name=\"name\">Name of the item to insert after</param>\r\n        /// <param name=\"item\">Item to insert</param>\r\n        public virtual void InsertAfter(string name, TSyncDelegate item)\r\n        {\r\n            this.InsertAfter(name, this.Wrap(item));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Insert an item after a named item.\r\n        /// If the named item does not exist the item is inserted at the end of the pipeline.\r\n        /// </summary>\r\n        /// <param name=\"name\">Name of the item to insert after</param>\r\n        /// <param name=\"item\">Item to insert</param>\r\n        public virtual void InsertAfter(string name, PipelineItem<TAsyncDelegate> item)\r\n        {\r\n            var existingIndex =\r\n                this.pipelineItems.FindIndex(i => string.Equals(name, i.Name, StringComparison.Ordinal));\r\n\r\n            if (existingIndex == -1)\r\n            {\r\n                existingIndex = this.pipelineItems.Count;\r\n            }\r\n\r\n            existingIndex++;\r\n\r\n            if (existingIndex > this.pipelineItems.Count)\r\n            {\r\n                this.AddItemToEndOfPipeline(item);\r\n            }\r\n            else\r\n            {\r\n                this.InsertItemAtPipelineIndex(existingIndex, item);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Insert an item after a named item.\r\n        /// If the named item does not exist the item is inserted at the end of the pipeline.\r\n        /// </summary>\r\n        /// <param name=\"name\">Name of the item to insert after</param>\r\n        /// <param name=\"item\">Item to insert</param>\r\n        public virtual void InsertAfter(string name, PipelineItem<TSyncDelegate> item)\r\n        {\r\n            this.InsertAfter(name, this.Wrap(item));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Remove a named pipeline item\r\n        /// </summary>\r\n        /// <param name=\"name\">Name</param>\r\n        /// <returns>Index of item that was removed or -1 if nothing removed</returns>\r\n        public virtual int RemoveByName(string name)\r\n        {\r\n            if (string.IsNullOrEmpty(name))\r\n            {\r\n                return -1;\r\n            }\r\n\r\n            var existingIndex =\r\n                this.pipelineItems.FindIndex(i => string.Equals(name, i.Name, StringComparison.Ordinal));\r\n\r\n            if (existingIndex != -1)\r\n            {\r\n                this.pipelineItems.RemoveAt(existingIndex);\r\n            }\r\n\r\n            return existingIndex;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Wraps a sync delegate into its async form\r\n        /// </summary>\r\n        /// <param name=\"syncDelegate\">Sync pipeline instance</param>\r\n        /// <returns>Async pipeline instance</returns>\r\n        protected abstract PipelineItem<TAsyncDelegate> Wrap(PipelineItem<TSyncDelegate> syncDelegate);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/BeforePipeline.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using System;\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n\r\n\r\n    /// <summary>\r\n    /// Intercepts the request before it is passed to the appropriate route handler.\r\n    /// This gives you a couple of possibilities such as modifying parts of the request\r\n    /// or even prematurely aborting the request by returning a response that will be sent back to the caller.\r\n    /// </summary>\r\n    /// <seealso cref=\"AsyncNamedPipelineBase{TAsyncDelegate,TSyncDelegate}\" />\r\n    public class BeforePipeline : AsyncNamedPipelineBase<Func<NancyContext, CancellationToken, Task<Response>>, Func<NancyContext, Response>>\r\n    {\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"BeforePipeline\"/> class.\r\n        /// </summary>\r\n        public BeforePipeline()\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"BeforePipeline\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"capacity\">Number of delegates in pipeline</param>\r\n        public BeforePipeline(int capacity)\r\n            : base(capacity)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"BeforePipeline\"/> to <see cref=\"Func{TNancyContext, TCancellationToken, TTaskResponse}\"/>.\r\n        /// </summary>\r\n        /// <param name=\"pipeline\">The <see cref=\"BeforePipeline\"/>.</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator Func<NancyContext, CancellationToken, Task<Response>>(BeforePipeline pipeline)\r\n        {\r\n            return pipeline.Invoke;\r\n        }\r\n\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"Func{TNancyContext, TCancellationToken, TTaskResponse}\"/> to <see cref=\"BeforePipeline\"/>.\r\n        /// </summary>\r\n        /// <param name=\"func\">A <see cref=\"Func{TNancyContext, TCancellationToken, TTaskResponse}\"/>.</param>\r\n        /// <returns>\r\n        /// A new <see cref=\"BeforePipeline\"/> instance with <paramref name=\"func\"/>.\r\n        /// </returns>\r\n        public static implicit operator BeforePipeline(Func<NancyContext, CancellationToken, Task<Response>> func)\r\n        {\r\n            var pipeline = new BeforePipeline();\r\n            pipeline.AddItemToEndOfPipeline(func);\r\n            return pipeline;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Appends a new function to the <see cref=\"BeforePipeline\"/>.\r\n        /// </summary>\r\n        /// <param name=\"pipeline\">The <see cref=\"BeforePipeline\"/> instance.</param>\r\n        /// <param name=\"func\">A <see cref=\"Func{TNancyContext, TCancellationToken, TTaskResponse}\"/></param>\r\n        /// <returns>\r\n        /// <paramref name=\"pipeline\"/> with <paramref name=\"func\"/> added\r\n        /// </returns>\r\n        public static BeforePipeline operator +(BeforePipeline pipeline, Func<NancyContext, CancellationToken, Task<Response>> func)\r\n        {\r\n            pipeline.AddItemToEndOfPipeline(func);\r\n            return pipeline;\r\n        }\r\n\r\n\r\n        /// <summary>\r\n        /// Appends a new action to the <see cref=\"BeforePipeline\"/>.\r\n        /// </summary>\r\n        /// <param name=\"pipeline\">The <see cref=\"BeforePipeline\"/> instance.</param>\r\n        /// <param name=\"action\">The <see cref=\"Action\"/> for appending to the <see cref=\"BeforePipeline\"/> instance.</param>\r\n        /// <returns>\r\n        /// <paramref name=\"pipeline\"/> with <paramref name=\"action\"/> added\r\n        /// </returns>\r\n        public static BeforePipeline operator +(BeforePipeline pipeline, Func<NancyContext, Response> action)\r\n        {\r\n            pipeline.AddItemToEndOfPipeline(action);\r\n            return pipeline;\r\n        }\r\n\r\n\r\n        /// <summary>\r\n        /// Appends the items of an <see cref=\"BeforePipeline\"/> to the other.\r\n        /// </summary>\r\n        /// <param name=\"pipelineToAddTo\">The <see cref=\"BeforePipeline\"/> to add to.</param>\r\n        /// <param name=\"pipelineToAdd\">The <see cref=\"BeforePipeline\"/> to add.</param>\r\n        /// <returns>\r\n        /// <paramref name=\"pipelineToAddTo\"/>\r\n        /// </returns>\r\n        public static BeforePipeline operator +(BeforePipeline pipelineToAddTo, BeforePipeline pipelineToAdd)\r\n        {\r\n            foreach (var pipelineItem in pipelineToAdd.PipelineItems)\r\n            {\r\n                pipelineToAddTo.AddItemToEndOfPipeline(pipelineItem);\r\n            }\r\n\r\n            return pipelineToAddTo;\r\n        }\r\n\r\n\r\n        /// <summary>\r\n        /// Invokes the specified <see cref=\"NancyContext\"/>.\r\n        /// </summary>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> instance.</param>\r\n        /// <param name=\"cancellationToken\">The <see cref=\"CancellationToken\"/> instance.</param>\r\n        /// <returns>\r\n        /// A <see cref=\"Response\"/> instance or <see langword=\"null\" />\r\n        /// </returns>\r\n        public async Task<Response> Invoke(NancyContext context, CancellationToken cancellationToken)\r\n        {\r\n            foreach (var pipelineDelegate in this.PipelineDelegates)\r\n            {\r\n                var response = await pipelineDelegate.Invoke(context, cancellationToken).ConfigureAwait(false);\r\n                if (response != null)\r\n                {\r\n                    return response;\r\n                }\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Wraps the specified <see cref=\"PipelineItem{T}\"/> into its async form.\r\n        /// </summary>\r\n        /// <param name=\"pipelineItem\">The <see cref=\"PipelineItem{T}\"/>.</param>\r\n        /// <returns>Async <see cref=\"PipelineItem{T}\"/> instance</returns>\r\n        protected override PipelineItem<Func<NancyContext, CancellationToken, Task<Response>>> Wrap(PipelineItem<Func<NancyContext, Response>> pipelineItem)\r\n        {\r\n            return new PipelineItem<Func<NancyContext, CancellationToken, Task<Response>>>(pipelineItem.Name, (ctx, ct) => Task.FromResult(pipelineItem.Delegate(ctx)));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Bootstrapper/BootstrapperException.cs",
    "content": "﻿namespace Nancy.Bootstrapper\r\n{\r\n    using System;\r\n    using System.Runtime.Serialization;\r\n\r\n    /// <summary>\r\n    /// Exception that is raised from inside the <see cref=\"NancyBootstrapperBase{T}\"/> type or one of\r\n    /// the inheriting types.\r\n    /// </summary>\r\n    public class BootstrapperException : Exception\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"BootstrapperException\"/> class, with\r\n        /// the provided <paramref name=\"message\"/>.\r\n        /// </summary>\r\n        /// <param name=\"message\">The message that describes the error.</param>\r\n        public BootstrapperException(string message) : base(message)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"BootstrapperException\"/> class, with\r\n        /// the provided <paramref name=\"message\"/> and <paramref name=\"innerException\"/>.\r\n        /// </summary>\r\n        /// <param name=\"message\">The error message that explains the reason for the exception.</param>\r\n        /// <param name=\"innerException\">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param>\r\n        public BootstrapperException(string message, Exception innerException) : base(message, innerException)\r\n        {\r\n        }\r\n\r\n#if !NETSTANDARD1_6\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"MultipleRootPathProvidersLocatedException\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"info\">The <see cref=\"T:System.Runtime.Serialization.SerializationInfo\" /> that holds the serialized object data about the exception being thrown.</param>\r\n        /// <param name=\"context\">The <see cref=\"T:System.Runtime.Serialization.StreamingContext\" /> that contains contextual information about the source or destination.</param>\r\n        protected BootstrapperException(SerializationInfo info, StreamingContext context)\r\n            : base(info, context)\r\n        {\r\n        }\r\n#endif\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Bootstrapper/CollectionTypeRegistration.cs",
    "content": "namespace Nancy.Bootstrapper\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Represents a type to be registered multiple times into the\r\n    /// container to later be resolved using an IEnumerable{RegistrationType}\r\n    /// constructor dependency.\r\n    /// </summary>\r\n    public class CollectionTypeRegistration : ContainerRegistration\r\n    {\r\n        /// <summary>\r\n        /// Represents a type to be registered multiple times into the\r\n        /// container to later be resolved using an IEnumerable{RegistrationType}\r\n        /// constructor dependency.\r\n        /// </summary>\r\n        /// <param name=\"registrationType\">Registration type i.e. IMyInterface</param>\r\n        /// <param name=\"implementationTypes\">Collection of implementation type i.e. MyClassThatImplementsIMyInterface</param>\r\n        /// <param name=\"lifetime\">Lifetime to register the type as</param>\r\n        public CollectionTypeRegistration(Type registrationType, IEnumerable<Type> implementationTypes, Lifetime lifetime = Lifetime.Singleton)\r\n        {\r\n            if (registrationType == null)\r\n            {\r\n                throw new ArgumentNullException(\"registrationType\");\r\n            }\r\n\r\n            if (implementationTypes == null)\r\n            {\r\n                throw new ArgumentNullException(\"implementationTypes\");\r\n            }\r\n\r\n            this.RegistrationType = registrationType;\r\n            this.ImplementationTypes = implementationTypes;\r\n            this.Lifetime = lifetime;\r\n\r\n            this.ValidateTypeCompatibility(implementationTypes.ToArray());\r\n        }\r\n\r\n        /// <summary>\r\n        /// Collection of implementation type i.e. MyClassThatImplementsIMyInterface\r\n        /// </summary>\r\n        public IEnumerable<Type> ImplementationTypes { get; private set; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Bootstrapper/ContainerRegistration.cs",
    "content": "namespace Nancy.Bootstrapper\r\n{\r\n    using System;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using Nancy.Extensions;\r\n\r\n    /// <summary>\r\n    /// Base class for container registrations\r\n    /// </summary>\r\n    public abstract class ContainerRegistration\r\n    {\r\n        /// <summary>\r\n        /// Gets the lifetime of the registration\r\n        /// </summary>\r\n        public Lifetime Lifetime { get; protected set; }\r\n\r\n        /// <summary>\r\n        /// Registration type i.e. IMyInterface\r\n        /// </summary>\r\n        public Type RegistrationType { get; protected set; }\r\n\r\n        /// <summary>\r\n        /// Checks if all implementation types are assignable from the registration type, otherwise throws an exception.\r\n        /// </summary>\r\n        /// <param name=\"types\">The implementation types.</param>\r\n        /// <exception cref=\"ArgumentException\">One or more of the implementation types is not assignable from the registration type.</exception>\r\n        /// <exception cref=\"InvalidOperationException\">The <see cref=\"RegistrationType\"/> property must be assigned before the method is invoked.</exception>\r\n        protected void ValidateTypeCompatibility(params Type[] types)\r\n        {\r\n            if (this.RegistrationType == null)\r\n            {\r\n                throw new InvalidOperationException(\"The RegistrationType must be set first.\");\r\n            }\r\n\r\n            var incompatibleTypes =\r\n                types.Where(type => !this.RegistrationType.IsAssignableFrom(type) && !type.IsAssignableToGenericType(this.RegistrationType)).ToArray();\r\n\r\n            if (incompatibleTypes.Any())\r\n            {\r\n                var incompatibleTypeNames =\r\n                    string.Join(\", \", incompatibleTypes.Select(type => type.FullName));\r\n\r\n                var errorMessage =\r\n                    string.Format(\"{0} must implement {1} inorder to be registered by {2}\", incompatibleTypeNames, this.RegistrationType.FullName, this.GetType().Name);\r\n\r\n                throw new ArgumentException(errorMessage);\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Bootstrapper/FavIconApplicationStartup.cs",
    "content": "﻿namespace Nancy.Bootstrapper\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using Nancy.Configuration;\r\n    using System.Reflection;\r\n    \r\n    /// <summary>\r\n    /// Application startup task that attempts to locate a favicon. The startup will first scan all\r\n    /// folders in the path defined by the provided <see cref=\"IRootPathProvider\"/> and if it cannot\r\n    /// find one, it will fall back and use the default favicon that is embedded in the Nancy.dll file.\r\n    /// </summary>\r\n    public class FavIconApplicationStartup : IApplicationStartup\r\n    {\r\n        private static TraceConfiguration traceConfiguration;\r\n        private static IRootPathProvider rootPathProvider;\r\n        private static byte[] favIcon;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"FavIconApplicationStartup\"/> class, with the\r\n        /// provided <see cref=\"IRootPathProvider\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"rootPathProvider\">The <see cref=\"IRootPathProvider\"/> that should be used to scan for a favicon.</param>\r\n        /// <param name=\"environment\">An <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        public FavIconApplicationStartup(IRootPathProvider rootPathProvider, INancyEnvironment environment)\r\n        {\r\n            FavIconApplicationStartup.rootPathProvider = rootPathProvider;\r\n            FavIconApplicationStartup.traceConfiguration = environment.GetValue<TraceConfiguration>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the default favicon\r\n        /// </summary>\r\n        /// <value>A byte array, containing a favicon.ico file.</value>\r\n        public static byte[] FavIcon\r\n        {\r\n            get { return favIcon ?? (favIcon = ScanForFavIcon()); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Perform any initialisation tasks\r\n        /// </summary>\r\n        /// <param name=\"pipelines\">Application pipelines</param>\r\n        public void Initialize(IPipelines pipelines)\r\n        {\r\n        }\r\n\r\n        private static byte[] ExtractDefaultIcon()\r\n        {\r\n            var resourceStream =\r\n                typeof(INancyEngine).GetTypeInfo().Assembly.GetManifestResourceStream(\"Nancy.favicon.ico\");\r\n\r\n\r\n            if (resourceStream == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            var result =\r\n                new byte[resourceStream.Length];\r\n\r\n            resourceStream.Read(result, 0, (int)resourceStream.Length);\r\n\r\n            return result;\r\n        }\r\n\r\n        private static byte[] LocateIconOnFileSystem()\r\n        {\r\n            if (rootPathProvider == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            var extensions = new[] { \"ico\", \"png\" };\r\n\r\n            var locatedFavIcon = extensions.SelectMany(EnumerateFiles).FirstOrDefault();\r\n            if (locatedFavIcon == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            try\r\n            {\r\n                return File.ReadAllBytes(locatedFavIcon);\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                if (!traceConfiguration.Enabled)\r\n                {\r\n                    throw new InvalidDataException(\"Unable to load favicon\", e);\r\n                }\r\n\r\n                return null;\r\n            }\r\n        }\r\n\r\n        private static IEnumerable<string> EnumerateFiles(string extension)\r\n        {\r\n            var rootPath = rootPathProvider.GetRootPath();\r\n            var fileName = string.Concat(\"favicon.\", extension);\r\n\r\n            return Directory.EnumerateFiles(rootPath, fileName, SearchOption.AllDirectories);\r\n        }\r\n\r\n        private static byte[] ScanForFavIcon()\r\n        {\r\n            byte[] locatedIcon = null;\r\n\r\n            try\r\n            {\r\n                locatedIcon = LocateIconOnFileSystem();\r\n            }\r\n            catch (Exception)\r\n            {\r\n            }\r\n\r\n            return locatedIcon ?? ExtractDefaultIcon();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Bootstrapper/IApplicationStartup.cs",
    "content": "namespace Nancy.Bootstrapper\r\n{\r\n    /// <summary>\r\n    /// Provides a hook to execute code during application startup.\r\n    /// </summary>\r\n    public interface IApplicationStartup\r\n    {\r\n        /// <summary>\r\n        /// Perform any initialisation tasks\r\n        /// </summary>\r\n        /// <param name=\"pipelines\">Application pipelines</param>\r\n        void Initialize(IPipelines pipelines);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Bootstrapper/INancyBootstrapper.cs",
    "content": "﻿namespace Nancy.Bootstrapper\r\n{\r\n    using System;\r\n    using Nancy.Configuration;\r\n\r\n    /// <summary>\r\n    /// Bootstrapper for the Nancy Engine\r\n    /// </summary>\r\n    public interface INancyBootstrapper : IDisposable\r\n    {\r\n        /// <summary>\r\n        /// Initialise the bootstrapper.\r\n        /// </summary>\r\n        /// <remarks>Must be called prior to <see cref=\"GetEngine\"/> and <see cref=\"GetEnvironment\"/>.</remarks>\r\n        void Initialise();\r\n\r\n        /// <summary>\r\n        /// Gets the configured <see cref=\"INancyEngine\"/>.\r\n        /// </summary>\r\n        /// <returns>An configured <see cref=\"INancyEngine\"/> instance.</returns>\r\n        /// <remarks>The boostrapper must be initialised (<see cref=\"Initialise\"/>) prior to calling this.</remarks>\r\n        INancyEngine GetEngine();\r\n\r\n        /// <summary>\r\n        /// Get the <see cref=\"INancyEnvironment\"/> instance.\r\n        /// </summary>\r\n        /// <returns>An configured <see cref=\"INancyEnvironment\"/> instance.</returns>\r\n        /// <remarks>The boostrapper must be initialised (<see cref=\"Initialise\"/>) prior to calling this.</remarks>\r\n        INancyEnvironment GetEnvironment();\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Bootstrapper/IPipelines.cs",
    "content": "namespace Nancy.Bootstrapper\r\n{\r\n    /// <summary>\r\n    /// Defines the functionality of a Nancy pipeline.\r\n    /// </summary>\r\n    public interface IPipelines\r\n    {\r\n        /// <summary>\r\n        /// <para>\r\n        /// The pre-request hook\r\n        /// </para>\r\n        /// <para>\r\n        /// The PreRequest hook is called prior to processing a request. If a hook returns\r\n        /// a non-null response then processing is aborted and the response provided is\r\n        /// returned.\r\n        /// </para>\r\n        /// </summary>\r\n        BeforePipeline BeforeRequest { get; set; }\r\n\r\n        /// <summary>\r\n        /// <para>\r\n        /// The post-request hook\r\n        /// </para>\r\n        /// <para>\r\n        /// The post-request hook is called after the response is created. It can be used\r\n        /// to rewrite the response or add/remove items from the context.\r\n        /// </para>\r\n        /// </summary>\r\n        AfterPipeline AfterRequest { get; set; }\r\n\r\n        /// <summary>\r\n        /// <para>\r\n        /// The error hook\r\n        /// </para>\r\n        /// <para>\r\n        /// The error hook is called if an exception is thrown at any time during the pipeline.\r\n        /// If no error hook exists a standard InternalServerError response is returned\r\n        /// </para>\r\n        /// </summary>\r\n        ErrorPipeline OnError { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Bootstrapper/IRegistrations.cs",
    "content": "﻿namespace Nancy.Bootstrapper\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Provides a hook to perform registrations during application startup.\r\n    /// </summary>\r\n    public interface IRegistrations\r\n    {\r\n        /// <summary>\r\n        /// Gets the type registrations to register for this startup task\r\n        /// </summary>\r\n        IEnumerable<TypeRegistration> TypeRegistrations { get; }\r\n\r\n        /// <summary>\r\n        /// Gets the collection registrations to register for this startup task\r\n        /// </summary>\r\n        IEnumerable<CollectionTypeRegistration> CollectionTypeRegistrations { get; }\r\n\r\n        /// <summary>\r\n        /// Gets the instance registrations to register for this startup task\r\n        /// </summary>\r\n        IEnumerable<InstanceRegistration> InstanceRegistrations { get; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Bootstrapper/IRequestStartup.cs",
    "content": "﻿namespace Nancy.Bootstrapper\r\n{\r\n    /// <summary>\r\n    /// Provides a hook to execute code during request startup.\r\n    /// </summary>\r\n    public interface IRequestStartup\r\n    {\r\n        /// <summary>\r\n        /// Perform any initialisation tasks\r\n        /// </summary>\r\n        /// <param name=\"pipelines\">Application pipelines</param>\r\n        /// <param name=\"context\">The current context</param>\r\n        void Initialize(IPipelines pipelines, NancyContext context);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Bootstrapper/InstanceRegistration.cs",
    "content": "namespace Nancy.Bootstrapper\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Represents an instance to be registered into the container\r\n    /// </summary>\r\n    public class InstanceRegistration : ContainerRegistration\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"InstanceRegistration\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"registrationType\">The registration type.</param>\r\n        /// <param name=\"implementation\">The implementation.</param>\r\n        public InstanceRegistration(Type registrationType, object implementation)\r\n        {\r\n            if (registrationType == null)\r\n            {\r\n                throw new ArgumentNullException(\"registrationType\");\r\n            }\r\n\r\n            if (implementation == null)\r\n            {\r\n                throw new ArgumentNullException(\"implementation\");\r\n            }\r\n\r\n            this.RegistrationType = registrationType;\r\n            this.Implementation = implementation;\r\n            this.Lifetime = Lifetime.Singleton;\r\n\r\n            this.ValidateTypeCompatibility(implementation.GetType());\r\n        }\r\n\r\n        /// <summary>\r\n        /// Implementation object instance i.e. instance of MyClassThatImplementsIMyInterface\r\n        /// </summary>\r\n        public object Implementation { get; private set; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Bootstrapper/Lifetime.cs",
    "content": "namespace Nancy.Bootstrapper\r\n{\r\n    /// <summary>\r\n    /// Represents the lifetime of a container registration\r\n    /// </summary>\r\n    public enum Lifetime\r\n    {\r\n        /// <summary>\r\n        /// Transient lifetime - each request to the container for\r\n        /// the type will result in a new version being returned.\r\n        /// </summary>\r\n        Transient,\r\n\r\n        /// <summary>\r\n        /// Singleton - each request to the container for the type\r\n        /// will result in the same instance being returned.\r\n        /// </summary>\r\n        Singleton,\r\n\r\n        /// <summary>\r\n        /// PerRequest - within the context of each request each request\r\n        /// for the type will result in the same instance being returned.\r\n        /// Different requests will have different versions.\r\n        /// </summary>\r\n        PerRequest\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Bootstrapper/ModuleRegistrationType.cs",
    "content": "namespace Nancy.Bootstrapper\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Holds module type for registration into a container.\r\n    /// </summary>\r\n    public sealed class ModuleRegistration\r\n    {\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ModuleRegistration\"/> class, with\r\n        /// the provided <paramref name= \"moduleType\" />\r\n        /// </summary>\r\n        /// <param name=\"moduleType\">Type of the module.</param>\r\n        public ModuleRegistration(Type moduleType)\r\n        {\r\n            ModuleType = moduleType;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the type of the module.\r\n        /// </summary>\r\n        /// <value> The type of the module.</value>\r\n        public Type ModuleType { get; private set; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Bootstrapper/MultipleRootPathProvidersLocatedException.cs",
    "content": "﻿namespace Nancy.Bootstrapper\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Runtime.Serialization;\r\n    using System.Text;\r\n\r\n    /// <summary>\r\n    /// Exception raised when the <see cref=\"NancyBootstrapperBase{T}\"/> discovers more than one\r\n    /// <see cref=\"IRootPathProvider\"/> implementation in the loaded assemblies.\r\n    /// </summary>\r\n    public class MultipleRootPathProvidersLocatedException : BootstrapperException\r\n    {\r\n        private const string DefaultMessageIntroduction = @\"More than one IRootPathProvider was found\";\r\n        private const string DefaultMessageConclusion = @\"and since we do not know which one you want to use, you need to override the RootPathProvider property on your bootstrapper and specify which one to use. Sorry for the inconvenience.\";\r\n        private const string DefaultMessage = DefaultMessageIntroduction + \", \" + DefaultMessageConclusion;\r\n        private string errorMessage;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"MultipleRootPathProvidersLocatedException\"/> class.\r\n        /// </summary>\r\n        public MultipleRootPathProvidersLocatedException()\r\n            : base(DefaultMessage)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"MultipleRootPathProvidersLocatedException\"/> class, with\r\n        /// the provided <paramref name= \"message\" />\r\n        /// </summary>\r\n        /// <param name=\"message\">The message that describes the error.</param>\r\n        public MultipleRootPathProvidersLocatedException(string message) : base(message)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"MultipleRootPathProvidersLocatedException\"/> class, with\r\n        /// the provided <paramref name= \"message\" /> and  <paramref name= \"innerException\" />\r\n        /// </summary>\r\n        /// <param name=\"message\">The error message that explains the reason for the exception.</param>\r\n        /// <param name=\"innerException\">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param>\r\n        public MultipleRootPathProvidersLocatedException(string message, Exception innerException) : base(message, innerException)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"MultipleRootPathProvidersLocatedException\"/> class, with\r\n        /// the provided <paramref name= \"providerTypes\" />\r\n        /// </summary>\r\n        /// <param name=\"providerTypes\">The provider types.</param>\r\n        public MultipleRootPathProvidersLocatedException(IEnumerable<Type> providerTypes)\r\n            : base(DefaultMessage)\r\n        {\r\n            this.StoreProviderTypes(providerTypes);\r\n        }\r\n\r\n#if !NETSTANDARD1_6\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"MultipleRootPathProvidersLocatedException\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"info\">The <see cref=\"T:System.Runtime.Serialization.SerializationInfo\" /> that holds the serialized object data about the exception being thrown.</param>\r\n        /// <param name=\"context\">The <see cref=\"T:System.Runtime.Serialization.StreamingContext\" /> that contains contextual information about the source or destination.</param>\r\n        protected MultipleRootPathProvidersLocatedException(SerializationInfo info, StreamingContext context) : base(info, context)\r\n        {\r\n        }\r\n#endif\r\n\r\n        /// <summary>\r\n        /// Gets the provider types.\r\n        /// </summary>\r\n        /// <value> The provider types.</value>\r\n        public IEnumerable<Type> ProviderTypes { get; internal set; }\r\n\r\n        /// <summary>\r\n        /// Stores the provider types.\r\n        /// </summary>\r\n        /// <param name=\"providerTypes\">The provider types.</param>\r\n        private void StoreProviderTypes(IEnumerable<Type> providerTypes)\r\n        {\r\n            this.ProviderTypes =\r\n                providerTypes.ToList().AsReadOnly();\r\n\r\n            this.Data.Add(\"ProviderTypes\", this.ProviderTypes);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns a more friendly and informative message if the list of providers is available.\r\n        /// </summary>\r\n        /// <remarks>\r\n        /// Message generated will be of the format:\r\n        /// <example>\r\n        /// More than one IRootPathProvider was found:\r\n        ///    Nancy.Tests.Functional.Tests.CustomRootPathProvider2\r\n        ///    Nancy.Tests.Functional.Tests.CustomRootPathProvider\r\n        /// and since we do not know which one you want to use, you need to override the RootPathProvider property on your bootstrapper and specify which one to use. Sorry for the inconvenience.\r\n        /// </example>\r\n        /// </remarks>\r\n        public override string Message\r\n        {\r\n            get\r\n            {\r\n                return (this.errorMessage ?? (this.errorMessage = this.GetErrorMessage()));\r\n            }\r\n        }\r\n\r\n        private string GetErrorMessage()\r\n        {\r\n            if ((this.ProviderTypes == null) || (!this.ProviderTypes.Any()))\r\n            {\r\n                return base.Message;\r\n            }\r\n\r\n            var builder =\r\n                new StringBuilder(DefaultMessageIntroduction);\r\n\r\n            foreach (var providerType in this.ProviderTypes)\r\n            {\r\n                builder.AppendFormat(\"\\n    {0}\", providerType.FullName);\r\n            }\r\n\r\n            builder.AppendFormat(\"\\n {0}\", DefaultMessageConclusion);\r\n\r\n            return builder.ToString();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Bootstrapper/NancyBootstrapperBase.cs",
    "content": "﻿namespace Nancy.Bootstrapper\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Diagnostics.CodeAnalysis;\r\n    using System.Linq;\r\n\r\n    using Nancy.Configuration;\r\n    using Nancy.Conventions;\r\n    using Nancy.Cryptography;\r\n    using Nancy.Diagnostics;\r\n    using Nancy.Extensions;\r\n    using Nancy.ModelBinding;\r\n    using Nancy.Validation;\r\n    using Nancy.ViewEngines;\r\n\r\n    /// <summary>\r\n    /// Nancy bootstrapper base class\r\n    /// </summary>\r\n    /// <typeparam name=\"TContainer\">IoC container type</typeparam>\r\n    [SuppressMessage(\"Microsoft.StyleCop.CSharp.DocumentationRules\", \"SA1623:PropertySummaryDocumentationMustMatchAccessors\", Justification = \"Abstract base class - properties are described differently for overriding.\")]\r\n    public abstract class NancyBootstrapperBase<TContainer> : INancyBootstrapper, INancyModuleCatalog, IDisposable\r\n        where TContainer : class\r\n    {\r\n        /// <summary>\r\n        /// Stores whether the bootstrapper has been initialised\r\n        /// prior to calling GetEngine.\r\n        /// </summary>\r\n        private bool initialised;\r\n\r\n        /// <summary>\r\n        /// Stores whether the bootstrapper is in the process of\r\n        /// being disposed.\r\n        /// </summary>\r\n        private bool disposing;\r\n\r\n        /// <summary>\r\n        /// Stores the <see cref=\"IRootPathProvider\"/> used by Nancy\r\n        /// </summary>\r\n        private IRootPathProvider rootPathProvider;\r\n\r\n        /// <summary>\r\n        /// Default Nancy conventions\r\n        /// </summary>\r\n        private NancyConventions conventions;\r\n\r\n        /// <summary>\r\n        /// Internal configuration\r\n        /// </summary>\r\n        private Func<ITypeCatalog, NancyInternalConfiguration> internalConfigurationFactory;\r\n        private NancyInternalConfiguration internalConfiguration;\r\n\r\n        /// <summary>\r\n        /// Application pipelines.\r\n        /// Pipelines are \"cloned\" per request so they can be modified\r\n        /// at the request level.\r\n        /// </summary>\r\n        protected IPipelines ApplicationPipelines { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Nancy modules - built on startup from the app domain scanner\r\n        /// </summary>\r\n        private ModuleRegistration[] modules;\r\n\r\n        /// <summary>\r\n        /// Cache of request startup task types\r\n        /// </summary>\r\n        protected Type[] RequestStartupTaskTypeCache { get; private set; }\r\n\r\n        private IAssemblyCatalog assemblyCatalog;\r\n        private ITypeCatalog typeCatalog;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancyBootstrapperBase{TContainer}\"/> class.\r\n        /// </summary>\r\n        protected NancyBootstrapperBase()\r\n        {\r\n            this.ApplicationPipelines = new Pipelines();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the Container instance - automatically set during initialise.\r\n        /// </summary>\r\n        protected TContainer ApplicationContainer { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"IAssemblyCatalog\"/> that should be used by the application.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IAssemblyCatalog\"/> instance.</value>\r\n        protected virtual IAssemblyCatalog AssemblyCatalog\r\n        {\r\n            get {\r\n                return this.assemblyCatalog ?? (\r\n#if !CORE\r\n                    this.assemblyCatalog = new AppDomainAssemblyCatalog()\r\n#else\r\n                    this.assemblyCatalog = new DependencyContextAssemblyCatalog()\r\n#endif\r\n                );\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"ITypeCatalog\"/> that should be used by the application.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"ITypeCatalog\"/> instance.</value>\r\n        protected virtual ITypeCatalog TypeCatalog\r\n        {\r\n            get { return this.typeCatalog ?? (this.typeCatalog = new DefaultTypeCatalog(this.AssemblyCatalog)); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Nancy internal configuration\r\n        /// </summary>\r\n        protected virtual Func<ITypeCatalog, NancyInternalConfiguration> InternalConfiguration\r\n        {\r\n            get { return this.internalConfigurationFactory ?? (this.internalConfigurationFactory = NancyInternalConfiguration.Default); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Nancy conventions\r\n        /// </summary>\r\n        protected virtual NancyConventions Conventions\r\n        {\r\n            get\r\n            {\r\n                return this.conventions ?? (this.conventions = new NancyConventions(this.TypeCatalog));\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all available module types\r\n        /// </summary>\r\n        protected virtual IEnumerable<ModuleRegistration> Modules\r\n        {\r\n            get\r\n            {\r\n                return this.modules ?? (this.modules = this.TypeCatalog\r\n                    .GetTypesAssignableTo<INancyModule>(TypeResolveStrategies.ExcludeNancy)\r\n                    .NotOfType<DiagnosticModule>()\r\n                    .Select(t => new ModuleRegistration(t))\r\n                    .ToArray());\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the available view engine types\r\n        /// </summary>\r\n        protected virtual IEnumerable<Type> ViewEngines\r\n        {\r\n            get { return this.TypeCatalog.GetTypesAssignableTo<IViewEngine>(); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the available custom model binders\r\n        /// </summary>\r\n        protected virtual IEnumerable<Type> ModelBinders\r\n        {\r\n            get { return this.TypeCatalog.GetTypesAssignableTo<IModelBinder>(); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the available custom type converters\r\n        /// </summary>\r\n        protected virtual IEnumerable<Type> TypeConverters\r\n        {\r\n            get { return this.TypeCatalog.GetTypesAssignableTo<ITypeConverter>(TypeResolveStrategies.ExcludeNancy); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the available custom body deserializers\r\n        /// </summary>\r\n        protected virtual IEnumerable<Type> BodyDeserializers\r\n        {\r\n            get { return this.TypeCatalog.GetTypesAssignableTo<IBodyDeserializer>(TypeResolveStrategies.ExcludeNancy); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all application startup tasks\r\n        /// </summary>\r\n        protected virtual IEnumerable<Type> ApplicationStartupTasks\r\n        {\r\n            get { return this.TypeCatalog.GetTypesAssignableTo<IApplicationStartup>(); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all request startup tasks\r\n        /// </summary>\r\n        protected virtual IEnumerable<Type> RequestStartupTasks\r\n        {\r\n            get { return this.TypeCatalog.GetTypesAssignableTo<IRequestStartup>(); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all registration tasks\r\n        /// </summary>\r\n        protected virtual IEnumerable<Type> RegistrationTasks\r\n        {\r\n            get { return this.TypeCatalog.GetTypesAssignableTo<IRegistrations>(); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the root path provider\r\n        /// </summary>\r\n        protected virtual IRootPathProvider RootPathProvider\r\n        {\r\n            get { return this.rootPathProvider ?? (this.rootPathProvider = this.GetRootPathProvider()); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the validator factories.\r\n        /// </summary>\r\n        protected virtual IEnumerable<Type> ModelValidatorFactories\r\n        {\r\n            get { return this.TypeCatalog.GetTypesAssignableTo<IModelValidatorFactory>(); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the default favicon\r\n        /// </summary>\r\n        protected virtual byte[] FavIcon\r\n        {\r\n            get { return FavIconApplicationStartup.FavIcon; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the cryptography configuration\r\n        /// </summary>\r\n        protected virtual CryptographyConfiguration CryptographyConfiguration\r\n        {\r\n            get { return CryptographyConfiguration.Default; }\r\n        }\r\n\r\n        private NancyInternalConfiguration GetInitializedInternalConfiguration()\r\n        {\r\n            return this.internalConfiguration ?? (this.internalConfiguration = this.InternalConfiguration.Invoke(this.TypeCatalog));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initialise the bootstrapper. Must be called prior to GetEngine.\r\n        /// </summary>\r\n        public void Initialise()\r\n        {\r\n            var configuration =\r\n                this.GetInitializedInternalConfiguration();\r\n\r\n            if (configuration == null)\r\n            {\r\n                throw new InvalidOperationException(\"Configuration cannot be null\");\r\n            }\r\n\r\n            if (!configuration.IsValid)\r\n            {\r\n                throw new InvalidOperationException(\"Configuration is invalid\");\r\n            }\r\n\r\n            this.ApplicationContainer = this.GetApplicationContainer();\r\n\r\n            this.RegisterBootstrapperTypes(this.ApplicationContainer);\r\n\r\n            this.ConfigureApplicationContainer(this.ApplicationContainer);\r\n\r\n            var typeRegistrations =\r\n                configuration.GetTypeRegistrations();\r\n\r\n            var collectionTypeRegistrations = configuration\r\n                .GetCollectionTypeRegistrations()\r\n                .Concat(this.GetApplicationCollections());\r\n\r\n            // TODO - should this be after initialiseinternal?\r\n            this.ConfigureConventions(this.Conventions);\r\n            var conventionValidationResult = this.Conventions.Validate();\r\n            if (!conventionValidationResult.Item1)\r\n            {\r\n                throw new InvalidOperationException(string.Format(\"Conventions are invalid:\\n\\n{0}\", conventionValidationResult.Item2));\r\n            }\r\n\r\n            var instanceRegistrations = this.Conventions.GetInstanceRegistrations()\r\n                                            .Concat(this.GetAdditionalInstances());\r\n\r\n            this.RegisterTypes(this.ApplicationContainer, typeRegistrations);\r\n            this.RegisterCollectionTypes(this.ApplicationContainer, collectionTypeRegistrations);\r\n            this.RegisterInstances(this.ApplicationContainer, instanceRegistrations);\r\n            this.RegisterRegistrationTasks(this.GetRegistrationTasks());\r\n\r\n            var environment = this.GetEnvironmentConfigurator().ConfigureEnvironment(this.Configure);\r\n            this.RegisterNancyEnvironment(this.ApplicationContainer, environment);\r\n\r\n            this.RegisterModules(this.ApplicationContainer, this.Modules);\r\n\r\n            foreach (var applicationStartupTask in this.GetApplicationStartupTasks().ToList())\r\n            {\r\n                applicationStartupTask.Initialize(this.ApplicationPipelines);\r\n            }\r\n\r\n            this.ApplicationStartup(this.ApplicationContainer, this.ApplicationPipelines);\r\n\r\n            this.RequestStartupTaskTypeCache = this.RequestStartupTasks.ToArray();\r\n\r\n            if (this.FavIcon != null)\r\n            {\r\n                this.ApplicationPipelines.BeforeRequest.AddItemToStartOfPipeline(ctx =>\r\n                    {\r\n                        if (ctx.Request == null || string.IsNullOrEmpty(ctx.Request.Path))\r\n                        {\r\n                            return null;\r\n                        }\r\n\r\n                        if (String.Equals(ctx.Request.Path, \"/favicon.ico\", StringComparison.OrdinalIgnoreCase))\r\n                        {\r\n                            var response = new Response\r\n                                {\r\n                                    ContentType = \"image/vnd.microsoft.icon\",\r\n                                    StatusCode = HttpStatusCode.OK,\r\n                                    Contents = s => s.Write(this.FavIcon, 0, this.FavIcon.Length)\r\n                                };\r\n\r\n                            response.Headers[\"Cache-Control\"] = \"public, max-age=604800, must-revalidate\";\r\n\r\n                            return response;\r\n                        }\r\n\r\n                        return null;\r\n                    });\r\n            }\r\n\r\n            this.GetDiagnostics().Initialize(this.ApplicationPipelines);\r\n\r\n            this.initialised = true;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Configures the Nancy environment\r\n        /// </summary>\r\n        /// <param name=\"environment\">The <see cref=\"INancyEnvironment\"/> instance to configure</param>\r\n        public virtual void Configure(INancyEnvironment environment)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"INancyEnvironmentConfigurator\"/> used by th.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"INancyEnvironmentConfigurator\"/> instance.</returns>\r\n        protected abstract INancyEnvironmentConfigurator GetEnvironmentConfigurator();\r\n\r\n        /// <summary>\r\n        /// Gets the diagnostics for initialisation\r\n        /// </summary>\r\n        /// <returns>IDiagnostics implementation</returns>\r\n        protected abstract IDiagnostics GetDiagnostics();\r\n\r\n        /// <summary>\r\n        /// Gets all registered application startup tasks\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance containing <see cref=\"IApplicationStartup\"/> instances.</returns>\r\n        protected abstract IEnumerable<IApplicationStartup> GetApplicationStartupTasks();\r\n\r\n        /// <summary>\r\n        /// Registers and resolves all request startup tasks\r\n        /// </summary>\r\n        /// <param name=\"container\">Container to use</param>\r\n        /// <param name=\"requestStartupTypes\">Types to register</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance containing <see cref=\"IRequestStartup\"/> instances.</returns>\r\n        protected abstract IEnumerable<IRequestStartup> RegisterAndGetRequestStartupTasks(TContainer container, Type[] requestStartupTypes);\r\n\r\n        /// <summary>\r\n        /// Gets all registered application registration tasks\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance containing <see cref=\"IRegistrations\"/> instances.</returns>\r\n        protected abstract IEnumerable<IRegistrations> GetRegistrationTasks();\r\n\r\n        /// <summary>\r\n        /// Get all NancyModule implementation instances\r\n        /// </summary>\r\n        /// <param name=\"context\">The current context</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance containing <see cref=\"INancyModule\"/> instances.</returns>\r\n        public abstract IEnumerable<INancyModule> GetAllModules(NancyContext context);\r\n\r\n        /// <summary>\r\n        /// Retrieves a specific <see cref=\"INancyModule\"/> implementation - should be per-request lifetime\r\n        /// </summary>\r\n        /// <param name=\"moduleType\">Module type</param>\r\n        /// <param name=\"context\">The current context</param>\r\n        /// <returns>The <see cref=\"INancyModule\"/> instance</returns>\r\n        public abstract INancyModule GetModule(Type moduleType, NancyContext context);\r\n\r\n        /// <summary>\r\n        /// Gets the configured INancyEngine\r\n        /// </summary>\r\n        /// <returns>Configured INancyEngine</returns>\r\n        public INancyEngine GetEngine()\r\n        {\r\n            if (!this.initialised)\r\n            {\r\n                throw new InvalidOperationException(\"Bootstrapper is not initialised. Call Initialise before GetEngine\");\r\n            }\r\n\r\n            var engine = this.SafeGetNancyEngineInstance();\r\n\r\n            engine.RequestPipelinesFactory = this.InitializeRequestPipelines;\r\n\r\n            return engine;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the <see cref=\"INancyEnvironment\"/> instance.\r\n        /// </summary>\r\n        /// <returns>An configured <see cref=\"INancyEnvironment\"/> instance.</returns>\r\n        /// <remarks>The boostrapper must be initialised (<see cref=\"INancyBootstrapper.Initialise\"/>) prior to calling this.</remarks>\r\n        public abstract INancyEnvironment GetEnvironment();\r\n\r\n        /// <summary>\r\n        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.\r\n        /// </summary>\r\n        /// <filterpriority>2</filterpriority>\r\n        public void Dispose()\r\n        {\r\n            // Prevent StackOverflowException if ApplicationContainer.Dispose re-triggers this Dispose\r\n            if (this.disposing)\r\n            {\r\n                return;\r\n            }\r\n\r\n            // Only dispose if we're initialised, prevents possible issue with recursive disposing.\r\n            if (!this.initialised)\r\n            {\r\n                return;\r\n            }\r\n\r\n            this.disposing = true;\r\n\r\n            var container = this.ApplicationContainer as IDisposable;\r\n\r\n            if (container != null)\r\n            {\r\n                try\r\n                {\r\n                    container.Dispose();\r\n                }\r\n                catch (ObjectDisposedException)\r\n                {\r\n                }\r\n            }\r\n\r\n\r\n            Dispose(true);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Hides Equals from the overrides list\r\n        /// </summary>\r\n        /// <param name=\"obj\">Object to compare</param>\r\n        /// <returns>Boolean indicating equality</returns>\r\n        public override sealed bool Equals(object obj)\r\n        {\r\n            return base.Equals(obj);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Hides GetHashCode from the overrides list\r\n        /// </summary>\r\n        /// <returns>Hash code integer</returns>\r\n        public override sealed int GetHashCode()\r\n        {\r\n            return base.GetHashCode();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates and initializes the request pipelines.\r\n        /// </summary>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> used by the request.</param>\r\n        /// <returns>An <see cref=\"IPipelines\"/> instance.</returns>\r\n        protected virtual IPipelines InitializeRequestPipelines(NancyContext context)\r\n        {\r\n            var requestPipelines =\r\n                new Pipelines(this.ApplicationPipelines);\r\n\r\n            if (this.RequestStartupTaskTypeCache.Any())\r\n            {\r\n                var startupTasks = this.RegisterAndGetRequestStartupTasks(this.ApplicationContainer, this.RequestStartupTaskTypeCache);\r\n\r\n                foreach (var requestStartup in startupTasks)\r\n                {\r\n                    requestStartup.Initialize(requestPipelines, context);\r\n                }\r\n            }\r\n\r\n            this.RequestStartup(this.ApplicationContainer, requestPipelines, context);\r\n\r\n            return requestPipelines;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Hides ToString from the overrides list\r\n        /// </summary>\r\n        /// <returns>String representation</returns>\r\n        public override sealed string ToString()\r\n        {\r\n            return base.ToString();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initialise the bootstrapper - can be used for adding pre/post hooks and\r\n        /// any other initialisation tasks that aren't specifically container setup\r\n        /// related\r\n        /// </summary>\r\n        /// <param name=\"container\">Container instance for resolving types if required.</param>\r\n        /// <param name=\"pipelines\">Pipelines instance to be customized if required</param>\r\n        protected virtual void ApplicationStartup(TContainer container, IPipelines pipelines)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initialise the request - can be used for adding pre/post hooks and\r\n        /// any other per-request initialisation tasks that aren't specifically container setup\r\n        /// related\r\n        /// </summary>\r\n        /// <param name=\"container\">Container</param>\r\n        /// <param name=\"pipelines\">Current pipelines</param>\r\n        /// <param name=\"context\">Current context</param>\r\n        protected virtual void RequestStartup(TContainer container, IPipelines pipelines, NancyContext context)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Configure the application level container with any additional registrations.\r\n        /// </summary>\r\n        /// <param name=\"existingContainer\">Container instance</param>\r\n        protected virtual void ConfigureApplicationContainer(TContainer existingContainer)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Overrides/configures Nancy's conventions\r\n        /// </summary>\r\n        /// <param name=\"nancyConventions\">Convention object instance</param>\r\n        protected virtual void ConfigureConventions(NancyConventions nancyConventions)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Releases unmanaged and - optionally - managed resources.\r\n        /// </summary>\r\n        /// <param name=\"disposing\"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>\r\n        protected virtual void Dispose(bool disposing)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Resolve INancyEngine\r\n        /// </summary>\r\n        /// <returns>INancyEngine implementation</returns>\r\n        protected abstract INancyEngine GetEngineInternal();\r\n\r\n        /// <summary>\r\n        /// Gets the application level container\r\n        /// </summary>\r\n        /// <returns>Container instance</returns>\r\n        protected abstract TContainer GetApplicationContainer();\r\n\r\n        /// <summary>\r\n        /// Registers an <see cref=\"INancyEnvironment\"/> instance in the container.\r\n        /// </summary>\r\n        /// <param name=\"container\">The container to register into.</param>\r\n        /// <param name=\"environment\">The <see cref=\"INancyEnvironment\"/> instance to register.</param>\r\n        protected abstract void RegisterNancyEnvironment(TContainer container, INancyEnvironment environment);\r\n\r\n        /// <summary>\r\n        /// Register the bootstrapper's implemented types into the container.\r\n        /// This is necessary so a user can pass in a populated container but not have\r\n        /// to take the responsibility of registering things like INancyModuleCatalog manually.\r\n        /// </summary>\r\n        /// <param name=\"applicationContainer\">Application container to register into</param>\r\n        protected abstract void RegisterBootstrapperTypes(TContainer applicationContainer);\r\n\r\n        /// <summary>\r\n        /// Register the default implementations of internally used types into the container as singletons\r\n        /// </summary>\r\n        /// <param name=\"container\">Container to register into</param>\r\n        /// <param name=\"typeRegistrations\">Type registrations to register</param>\r\n        protected abstract void RegisterTypes(TContainer container, IEnumerable<TypeRegistration> typeRegistrations);\r\n\r\n        /// <summary>\r\n        /// Register the various collections into the container as singletons to later be resolved\r\n        /// by IEnumerable{Type} constructor dependencies.\r\n        /// </summary>\r\n        /// <param name=\"container\">Container to register into</param>\r\n        /// <param name=\"collectionTypeRegistrationsn\">Collection type registrations to register</param>\r\n        protected abstract void RegisterCollectionTypes(TContainer container, IEnumerable<CollectionTypeRegistration> collectionTypeRegistrationsn);\r\n\r\n        /// <summary>\r\n        /// Register the given module types into the container\r\n        /// </summary>\r\n        /// <param name=\"container\">Container to register into</param>\r\n        /// <param name=\"moduleRegistrationTypes\">NancyModule types</param>\r\n        protected abstract void RegisterModules(TContainer container, IEnumerable<ModuleRegistration> moduleRegistrationTypes);\r\n\r\n        /// <summary>\r\n        /// Register the given instances into the container\r\n        /// </summary>\r\n        /// <param name=\"container\">Container to register into</param>\r\n        /// <param name=\"instanceRegistrations\">Instance registration types</param>\r\n        protected abstract void RegisterInstances(TContainer container, IEnumerable<InstanceRegistration> instanceRegistrations);\r\n\r\n        /// <summary>\r\n        /// Gets any additional instance registrations that need to\r\n        /// be registered into the container\r\n        /// </summary>\r\n        /// <returns>Collection of InstanceRegistration types</returns>\r\n        private IEnumerable<InstanceRegistration> GetAdditionalInstances()\r\n        {\r\n            return new[] {\r\n                new InstanceRegistration(typeof(CryptographyConfiguration), this.CryptographyConfiguration),\r\n                new InstanceRegistration(typeof(NancyInternalConfiguration), this.GetInitializedInternalConfiguration()),\r\n                new InstanceRegistration(typeof(IRootPathProvider), this.RootPathProvider),\r\n                new InstanceRegistration(typeof(IAssemblyCatalog), this.AssemblyCatalog),\r\n                new InstanceRegistration(typeof(ITypeCatalog), this.TypeCatalog),\r\n            };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a list of types for the collection types that are\r\n        /// required to be registered in the application scope.\r\n        /// </summary>\r\n        /// <returns>Collection of CollectionTypeRegistration types</returns>\r\n        private IEnumerable<CollectionTypeRegistration> GetApplicationCollections()\r\n        {\r\n            return new[] {\r\n                new CollectionTypeRegistration(typeof(IViewEngine), this.ViewEngines),\r\n                new CollectionTypeRegistration(typeof(IModelBinder), this.ModelBinders),\r\n                new CollectionTypeRegistration(typeof(ITypeConverter), this.TypeConverters),\r\n                new CollectionTypeRegistration(typeof(IBodyDeserializer), this.BodyDeserializers),\r\n                new CollectionTypeRegistration(typeof(IApplicationStartup), this.ApplicationStartupTasks),\r\n                new CollectionTypeRegistration(typeof(IRegistrations), this.RegistrationTasks),\r\n                new CollectionTypeRegistration(typeof(IModelValidatorFactory), this.ModelValidatorFactories)\r\n            };\r\n        }\r\n\r\n        private INancyEngine SafeGetNancyEngineInstance()\r\n        {\r\n            try\r\n            {\r\n                return this.GetEngineInternal();\r\n            }\r\n            catch (Exception ex)\r\n            {\r\n                throw new InvalidOperationException(\r\n                    \"Something went wrong when trying to satisfy one of the dependencies during composition, make sure that you've registered all new dependencies in the container and inspect the innerexception for more details.\",\r\n                    ex);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Takes the registration tasks and calls the relevant methods to register them\r\n        /// </summary>\r\n        /// <param name=\"registrationTasks\">Registration tasks</param>\r\n        protected virtual void RegisterRegistrationTasks(IEnumerable<IRegistrations> registrationTasks)\r\n        {\r\n            foreach (var registrationTask in registrationTasks.ToList())\r\n            {\r\n                var applicationTypeRegistrations = registrationTask.TypeRegistrations;\r\n\r\n                if (applicationTypeRegistrations != null)\r\n                {\r\n                    this.RegisterTypes(this.ApplicationContainer, applicationTypeRegistrations);\r\n                }\r\n\r\n                var applicationCollectionRegistrations = registrationTask.CollectionTypeRegistrations;\r\n\r\n                if (applicationCollectionRegistrations != null)\r\n                {\r\n                    this.RegisterCollectionTypes(this.ApplicationContainer, applicationCollectionRegistrations);\r\n                }\r\n\r\n                var applicationInstanceRegistrations = registrationTask.InstanceRegistrations;\r\n\r\n                if (applicationInstanceRegistrations != null)\r\n                {\r\n                    this.RegisterInstances(this.ApplicationContainer, applicationInstanceRegistrations);\r\n                }\r\n            }\r\n        }\r\n\r\n        private IRootPathProvider GetRootPathProvider()\r\n        {\r\n            var providerTypes = this.TypeCatalog\r\n                .GetTypesAssignableTo<IRootPathProvider>(TypeResolveStrategies.ExcludeNancy)\r\n                .ToArray();\r\n\r\n            if (providerTypes.Length > 1)\r\n            {\r\n                throw new MultipleRootPathProvidersLocatedException(providerTypes);\r\n            }\r\n\r\n            var providerType =\r\n                providerTypes.SingleOrDefault() ?? typeof(DefaultRootPathProvider);\r\n\r\n            return Activator.CreateInstance(providerType) as IRootPathProvider;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Bootstrapper/NancyBootstrapperLocator.cs",
    "content": "﻿namespace Nancy.Bootstrapper\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using Nancy.Extensions;\r\n\r\n    /// <summary>\r\n    /// Class for locating an INancyBootstrapper implementation.\r\n    ///\r\n    /// Will search the app domain for a non-abstract one, and if it can't find one\r\n    /// it will use the default nancy one that uses TinyIoC.\r\n    /// </summary>\r\n    public static class NancyBootstrapperLocator\r\n    {\r\n        private static INancyBootstrapper instance;\r\n        private static readonly AssemblyName NancyAssemblyName = typeof(INancyEngine).GetTypeInfo().Assembly.GetName();\r\n\r\n        /// <summary>\r\n        /// Gets the located bootstrapper\r\n        /// </summary>\r\n        public static INancyBootstrapper Bootstrapper\r\n        {\r\n            get { return instance ?? (instance = LocateBootstrapper()); }\r\n            set { instance = value; }\r\n        }\r\n\r\n        private static INancyBootstrapper LocateBootstrapper()\r\n        {\r\n            var bootstrapperType = GetBootstrapperType();\r\n\r\n            try\r\n            {\r\n                return Activator.CreateInstance(bootstrapperType) as INancyBootstrapper;\r\n            }\r\n            catch (Exception ex)\r\n            {\r\n                var errorMessage = string.Format(\"Could not initialize bootstrapper of type '{0}'.\", bootstrapperType.FullName);\r\n                throw new BootstrapperException(errorMessage, ex);\r\n            }\r\n        }\r\n\r\n        private static ITypeCatalog GetDefaultTypeCatalog()\r\n        {\r\n            var assemblyCatalog = GetAssemblyCatalog();\r\n\r\n            return new DefaultTypeCatalog(assemblyCatalog);\r\n        }\r\n\r\n        private static IReadOnlyCollection<Type> GetAvailableBootstrapperTypes(ITypeCatalog types)\r\n        {\r\n            return types.GetTypesAssignableTo<INancyBootstrapper>(TypeResolveStrategies.ExcludeNancy);\r\n        }\r\n\r\n        private static IAssemblyCatalog GetAssemblyCatalog()\r\n        {\r\n#if CORE\r\n            return new DependencyContextAssemblyCatalog();\r\n#else\r\n            return new AppDomainAssemblyCatalog();\r\n#endif\r\n        }\r\n\r\n#if !CORE\r\n        private static bool IsNancyReferencing(Assembly assembly)\r\n        {\r\n            if (AssemblyName.ReferenceMatchesDefinition(assembly.GetName(), NancyAssemblyName))\r\n            {\r\n                return true;\r\n            }\r\n\r\n            foreach (var referencedAssemblyName in assembly.GetReferencedAssemblies())\r\n            {\r\n                if (AssemblyName.ReferenceMatchesDefinition(referencedAssemblyName, NancyAssemblyName))\r\n                {\r\n                    return true;\r\n                }\r\n            }\r\n\r\n            return false;\r\n        }\r\n#endif\r\n\r\n        internal static Type GetBootstrapperType()\r\n        {\r\n            return GetBootstrapperType(GetDefaultTypeCatalog());\r\n        }\r\n\r\n        internal static Type GetBootstrapperType(ITypeCatalog typeCatalog)\r\n        {\r\n            var customBootstrappers = GetAvailableBootstrapperTypes(typeCatalog);\r\n\r\n            if (!customBootstrappers.Any())\r\n            {\r\n                return typeof(DefaultNancyBootstrapper);\r\n            }\r\n\r\n            if (customBootstrappers.Count == 1)\r\n            {\r\n                return customBootstrappers.Single();\r\n            }\r\n\r\n            Type bootstrapper;\r\n            if (TryFindMostDerivedType(customBootstrappers, out bootstrapper))\r\n            {\r\n                return bootstrapper;\r\n            }\r\n\r\n            var errorMessage = GetMultipleBootstrappersMessage(customBootstrappers);\r\n\r\n            throw new BootstrapperException(errorMessage);\r\n        }\r\n\r\n        internal static bool TryFindMostDerivedType(IReadOnlyCollection<Type> customBootstrappers, out Type bootstrapper)\r\n        {\r\n            var set = new HashSet<Type>();\r\n            bootstrapper = null;\r\n\r\n            if (customBootstrappers.All(b => set.Add(b.GetTypeInfo().BaseType)))\r\n            {\r\n                var except = customBootstrappers.Except(set).ToList();\r\n                bootstrapper = except.Count == 1 ? except[0] : null;\r\n            }\r\n\r\n            return bootstrapper != null;\r\n        }\r\n\r\n        private static string GetMultipleBootstrappersMessage(IEnumerable<Type> customBootstrappers)\r\n        {\r\n            var bootstrapperNames = customBootstrappers.Select(x => string.Concat(\" - \", x.FullName));\r\n\r\n            var bootstrapperList = string.Join(Environment.NewLine, bootstrapperNames);\r\n\r\n            return string.Join(Environment.NewLine, new[]\r\n            {\r\n                \"Located multiple bootstrappers:\",\r\n                bootstrapperList,\r\n                string.Empty,\r\n                \"Either remove unused bootstrapper types or specify which type to use.\"\r\n            });\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Bootstrapper/NancyBootstrapperWithRequestContainerBase.cs",
    "content": "namespace Nancy.Bootstrapper\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Nancy bootstrapper base with per-request container support.\r\n    /// Stores/retrieves the child container in the context to ensure that\r\n    /// only one child container is stored per request, and that the child\r\n    /// container will be disposed at the end of the request.\r\n    /// </summary>\r\n    /// <typeparam name=\"TContainer\">IoC container type</typeparam>\r\n    public abstract class NancyBootstrapperWithRequestContainerBase<TContainer> : NancyBootstrapperBase<TContainer>\r\n        where TContainer : class\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancyBootstrapperWithRequestContainerBase{TContainer}\"/> class.\r\n        /// </summary>\r\n        protected NancyBootstrapperWithRequestContainerBase()\r\n        {\r\n            this.RequestScopedTypes = ArrayCache.Empty<TypeRegistration>();\r\n            this.RequestScopedCollectionTypes = ArrayCache.Empty<CollectionTypeRegistration>();\r\n        }\r\n        /// <summary>\r\n        /// Context key for storing the child container in the context\r\n        /// </summary>\r\n        private readonly string contextKey = typeof(TContainer).FullName + \"BootstrapperChildContainer\";\r\n\r\n        /// <summary>\r\n        /// Stores the module registrations to be registered into the request container\r\n        /// </summary>\r\n        private IEnumerable<ModuleRegistration> moduleRegistrationTypeCache;\r\n\r\n        /// <summary>\r\n        /// Stores the per-request type registrations\r\n        /// </summary>\r\n        private TypeRegistration[] RequestScopedTypes { get; set; }\r\n\r\n        /// <summary>\r\n        /// Stores the per-request collection registrations\r\n        /// </summary>\r\n        private CollectionTypeRegistration[] RequestScopedCollectionTypes { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets the context key for storing the child container in the context\r\n        /// </summary>\r\n        protected virtual string ContextKey\r\n        {\r\n            get\r\n            {\r\n                return this.contextKey;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get all <see cref=\"INancyModule\"/> implementation instances\r\n        /// </summary>\r\n        /// <param name=\"context\">The current context</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance containing <see cref=\"INancyModule\"/> instances.</returns>\r\n        public override sealed IEnumerable<INancyModule> GetAllModules(NancyContext context)\r\n        {\r\n            var requestContainer = this.GetConfiguredRequestContainer(context);\r\n\r\n            this.RegisterRequestContainerModules(requestContainer, this.moduleRegistrationTypeCache);\r\n\r\n            return this.GetAllModules(requestContainer);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Retrieves a specific <see cref=\"INancyModule\"/> implementation - should be per-request lifetime\r\n        /// </summary>\r\n        /// <param name=\"moduleType\">Module type</param>\r\n        /// <param name=\"context\">The current context</param>\r\n        /// <returns>The <see cref=\"INancyModule\"/> instance</returns>\r\n        public override sealed INancyModule GetModule(Type moduleType, NancyContext context)\r\n        {\r\n            var requestContainer = this.GetConfiguredRequestContainer(context);\r\n\r\n            return this.GetModule(requestContainer, moduleType);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates and initializes the request pipelines.\r\n        /// </summary>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> used by the request.</param>\r\n        /// <returns>An <see cref=\"IPipelines\"/> instance.</returns>\r\n        protected override sealed IPipelines InitializeRequestPipelines(NancyContext context)\r\n        {\r\n            var requestContainer =\r\n                this.GetConfiguredRequestContainer(context);\r\n\r\n            var requestPipelines =\r\n                new Pipelines(this.ApplicationPipelines);\r\n\r\n            if (this.RequestStartupTaskTypeCache.Any())\r\n            {\r\n                var startupTasks = this.RegisterAndGetRequestStartupTasks(requestContainer, this.RequestStartupTaskTypeCache);\r\n\r\n                foreach (var requestStartup in startupTasks)\r\n                {\r\n                    requestStartup.Initialize(requestPipelines, context);\r\n                }\r\n            }\r\n\r\n            this.RequestStartup(requestContainer, requestPipelines, context);\r\n\r\n            return requestPipelines;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Takes the registration tasks and calls the relevant methods to register them\r\n        /// </summary>\r\n        /// <param name=\"registrationTasks\">Registration tasks</param>\r\n        protected override sealed void RegisterRegistrationTasks(IEnumerable<IRegistrations> registrationTasks)\r\n        {\r\n            foreach (var applicationRegistrationTask in registrationTasks.ToList())\r\n            {\r\n                var applicationTypeRegistrations = applicationRegistrationTask.TypeRegistrations == null ?\r\n                                                        ArrayCache.Empty<TypeRegistration>() :\r\n                                                        applicationRegistrationTask.TypeRegistrations.ToArray();\r\n\r\n                this.RegisterTypes(this.ApplicationContainer, applicationTypeRegistrations.Where(tr => tr.Lifetime != Lifetime.PerRequest));\r\n                this.RequestScopedTypes = this.RequestScopedTypes.Concat(applicationTypeRegistrations.Where(tr => tr.Lifetime == Lifetime.PerRequest)\r\n                        .Select(tr => new TypeRegistration(tr.RegistrationType, tr.ImplementationType, Lifetime.Singleton)))\r\n                        .ToArray();\r\n\r\n                var applicationCollectionRegistrations = applicationRegistrationTask.CollectionTypeRegistrations == null ?\r\n                                                            ArrayCache.Empty<CollectionTypeRegistration>() :\r\n                                                            applicationRegistrationTask.CollectionTypeRegistrations.ToArray();\r\n\r\n                this.RegisterCollectionTypes(this.ApplicationContainer, applicationCollectionRegistrations.Where(tr => tr.Lifetime != Lifetime.PerRequest));\r\n                this.RequestScopedCollectionTypes = this.RequestScopedCollectionTypes.Concat(applicationCollectionRegistrations.Where(tr => tr.Lifetime == Lifetime.PerRequest)\r\n                                                      .Select(tr => new CollectionTypeRegistration(tr.RegistrationType, tr.ImplementationTypes, Lifetime.Singleton)))\r\n                                                      .ToArray();\r\n\r\n                var applicationInstanceRegistrations = applicationRegistrationTask.InstanceRegistrations;\r\n\r\n                if (applicationInstanceRegistrations != null)\r\n                {\r\n                    this.RegisterInstances(this.ApplicationContainer, applicationInstanceRegistrations);\r\n                }\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the per-request container\r\n        /// </summary>\r\n        /// <param name=\"context\">Current context</param>\r\n        /// <returns>Request container instance</returns>\r\n        protected TContainer GetConfiguredRequestContainer(NancyContext context)\r\n        {\r\n            object contextObject;\r\n            context.Items.TryGetValue(this.ContextKey, out contextObject);\r\n            var requestContainer = contextObject as TContainer;\r\n\r\n            if (requestContainer == null)\r\n            {\r\n                requestContainer = this.CreateRequestContainer(context);\r\n\r\n                context.Items[this.ContextKey] = requestContainer;\r\n\r\n                this.ConfigureRequestContainer(requestContainer, context);\r\n\r\n                this.RegisterTypes(requestContainer, this.RequestScopedTypes);\r\n                this.RegisterCollectionTypes(requestContainer, this.RequestScopedCollectionTypes);\r\n            }\r\n\r\n            return requestContainer;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Configure the request container\r\n        /// </summary>\r\n        /// <param name=\"container\">Request container instance</param>\r\n        /// <param name=\"context\"></param>\r\n        protected virtual void ConfigureRequestContainer(TContainer container, NancyContext context)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Register the given module types into the container\r\n        /// </summary>\r\n        /// <param name=\"container\">Container to register into</param>\r\n        /// <param name=\"moduleRegistrationTypes\">NancyModule types</param>\r\n        protected override sealed void RegisterModules(TContainer container, IEnumerable<ModuleRegistration> moduleRegistrationTypes)\r\n        {\r\n            this.moduleRegistrationTypeCache = moduleRegistrationTypes;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a per request child/nested container\r\n        /// </summary>\r\n        /// <param name=\"context\">Current context</param>\r\n        /// <returns>Request container instance</returns>\r\n        protected abstract TContainer CreateRequestContainer(NancyContext context);\r\n\r\n        /// <summary>\r\n        /// Register the given module types into the request container\r\n        /// </summary>\r\n        /// <param name=\"container\">Container to register into</param>\r\n        /// <param name=\"moduleRegistrationTypes\">NancyModule types</param>\r\n        protected abstract void RegisterRequestContainerModules(TContainer container, IEnumerable<ModuleRegistration> moduleRegistrationTypes);\r\n\r\n        /// <summary>\r\n        /// Retrieve all module instances from the container\r\n        /// </summary>\r\n        /// <param name=\"container\">Container to use</param>\r\n        /// <returns>Collection of NancyModule instances</returns>\r\n        protected abstract IEnumerable<INancyModule> GetAllModules(TContainer container);\r\n\r\n        /// <summary>\r\n        /// Retrieve a specific module instance from the container\r\n        /// </summary>\r\n        /// <param name=\"container\">Container to use</param> \r\n        /// <param name=\"moduleType\">Type of the module</param>\r\n        /// <returns>NancyModule instance</returns>\r\n        protected abstract INancyModule GetModule(TContainer container, Type moduleType);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Bootstrapper/NancyInternalConfiguration.cs",
    "content": "namespace Nancy.Bootstrapper\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using Nancy.Configuration;\r\n    using Nancy.Culture;\r\n    using Nancy.Diagnostics;\r\n    using Nancy.ErrorHandling;\r\n    using Nancy.Localization;\r\n    using Nancy.ModelBinding;\r\n    using Nancy.Responses;\r\n    using Nancy.Responses.Negotiation;\r\n    using Nancy.Routing;\r\n    using Nancy.Routing.Constraints;\r\n    using Nancy.Routing.Trie;\r\n    using Nancy.Security;\r\n    using Nancy.Validation;\r\n    using Nancy.ViewEngines;\r\n\r\n    /// <summary>\r\n    /// Configuration class for Nancy's internals.\r\n    /// Contains implementation types/configuration for Nancy that usually\r\n    /// do not require overriding in \"general use\".\r\n    /// </summary>\r\n    public sealed class NancyInternalConfiguration\r\n    {\r\n        /// <summary>\r\n        /// Gets the Nancy default configuration\r\n        /// </summary>\r\n        public static Func<ITypeCatalog, NancyInternalConfiguration> Default\r\n        {\r\n            get\r\n            {\r\n                return typeCatalog => new NancyInternalConfiguration\r\n                {\r\n                    Binder = typeof(DefaultBinder),\r\n                    BindingDefaults = typeof(BindingDefaults),\r\n                    ContextFactory = typeof(DefaultNancyContextFactory),\r\n                    CsrfTokenValidator = typeof(DefaultCsrfTokenValidator),\r\n                    CultureService = typeof(DefaultCultureService),\r\n                    DefaultConfigurationProviders = typeCatalog.GetTypesAssignableTo<INancyDefaultConfigurationProvider>().ToList(),\r\n                    Diagnostics = typeof(DefaultDiagnostics),\r\n                    EnvironmentFactory = typeof(DefaultNancyEnvironmentFactory),\r\n                    EnvironmentConfigurator = typeof(DefaultNancyEnvironmentConfigurator),\r\n                    FieldNameConverter = typeof(DefaultFieldNameConverter),\r\n                    InteractiveDiagnosticProviders = new List<Type>(typeCatalog.GetTypesAssignableTo<IDiagnosticsProvider>()),\r\n                    ModelBinderLocator = typeof(DefaultModelBinderLocator),\r\n                    ModelValidatorLocator = typeof(DefaultValidatorLocator),\r\n                    NancyEngine = typeof(NancyEngine),\r\n                    NancyModuleBuilder = typeof(DefaultNancyModuleBuilder),\r\n                    ObjectSerializer = typeof(DefaultObjectSerializer),\r\n                    RenderContextFactory = typeof(DefaultRenderContextFactory),\r\n                    RequestDispatcher = typeof(DefaultRequestDispatcher),\r\n                    RequestTraceFactory = typeof(DefaultRequestTraceFactory),\r\n                    RequestTracing = typeof(DefaultRequestTracing),\r\n                    ResourceAssemblyProvider = typeof(ResourceAssemblyProvider),\r\n                    ResourceReader = typeof(DefaultResourceReader),\r\n                    ResponseFormatterFactory = typeof(DefaultResponseFormatterFactory),\r\n                    ResponseNegotiator = typeof(DefaultResponseNegotiator),\r\n                    ResponseProcessors = typeCatalog.GetTypesAssignableTo<IResponseProcessor>().ToList(),\r\n                    RouteCache = typeof(RouteCache),\r\n                    RouteCacheProvider = typeof(DefaultRouteCacheProvider),\r\n                    RouteInvoker = typeof(DefaultRouteInvoker),\r\n                    RouteResolver = typeof(DefaultRouteResolver),\r\n                    RouteResolverTrie = typeof(RouteResolverTrie),\r\n                    RouteSegmentConstraints = typeCatalog.GetTypesAssignableTo<IRouteSegmentConstraint>().ToList(),\r\n                    RouteSegmentExtractor = typeof(DefaultRouteSegmentExtractor),\r\n                    RouteMetadataProviders = typeCatalog.GetTypesAssignableTo<IRouteMetadataProvider>().ToList(),\r\n                    RouteDescriptionProvider = typeof(DefaultRouteDescriptionProvider),\r\n                    RuntimeEnvironmentInformation = typeof(DefaultRuntimeEnvironmentInformation),\r\n                    SerializerFactory = typeof(DefaultSerializerFactory),\r\n                    Serializers = typeCatalog.GetTypesAssignableTo<ISerializer>(TypeResolveStrategies.ExcludeNancy).Union(new List<Type>(new[] { typeof(DefaultJsonSerializer), typeof(DefaultXmlSerializer) })).ToList(),\r\n                    StaticContentProvider = typeof(DefaultStaticContentProvider),\r\n                    StatusCodeHandlers = new List<Type>(typeCatalog.GetTypesAssignableTo<IStatusCodeHandler>(TypeResolveStrategies.ExcludeNancy).Concat(new[] { typeof(DefaultStatusCodeHandler) })),\r\n                    TextResource = typeof(ResourceBasedTextResource),\r\n                    TrieNodeFactory = typeof(TrieNodeFactory),\r\n                    ViewLocator = typeof(DefaultViewLocator),\r\n                    ViewFactory = typeof(DefaultViewFactory),\r\n                    ViewResolver = typeof(DefaultViewResolver),\r\n                    ViewCache = typeof(DefaultViewCache),\r\n                    ViewLocationProvider = typeof(FileSystemViewLocationProvider),\r\n                };\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the runtime environment information\r\n        /// </summary>\r\n        public Type RuntimeEnvironmentInformation { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the serializer factory.\r\n        /// </summary>\r\n        public Type SerializerFactory { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the default configuration providers\r\n        /// </summary>\r\n        public IList<Type> DefaultConfigurationProviders { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the environment configurator\r\n        /// </summary>\r\n        public Type EnvironmentConfigurator { get; set; }\r\n\r\n        /// <summary>\r\n        ///Gets or sets the environment factory\r\n        /// </summary>\r\n        public Type EnvironmentFactory { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the route metadata providers\r\n        /// </summary>\r\n        public IList<Type> RouteMetadataProviders { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the route resolver\r\n        /// </summary>\r\n        public Type RouteResolver { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the context factory\r\n        /// </summary>\r\n        public Type ContextFactory { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the nancy engine\r\n        /// </summary>\r\n        public Type NancyEngine { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the route cache\r\n        /// </summary>\r\n        public Type RouteCache { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the route cache provider\r\n        /// </summary>\r\n        public Type RouteCacheProvider { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the view locator\r\n        /// </summary>\r\n        public Type ViewLocator { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the view factory\r\n        /// </summary>\r\n        public Type ViewFactory { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the nancy module builder\r\n        /// </summary>\r\n        public Type NancyModuleBuilder { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the response formatter factory\r\n        /// </summary>\r\n        public Type ResponseFormatterFactory { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets themodel binder locator\r\n        /// </summary>\r\n        public Type ModelBinderLocator { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the binder\r\n        /// </summary>\r\n        public Type Binder { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the binding defaults\r\n        /// </summary>\r\n        public Type BindingDefaults { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the field name converter\r\n        /// </summary>\r\n        public Type FieldNameConverter { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the model validator locator\r\n        /// </summary>\r\n        public Type ModelValidatorLocator { get; set; }\r\n\r\n        /// <summary>\r\n        ///Gets or sets the view resolver\r\n        /// </summary>\r\n        public Type ViewResolver { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the view cache\r\n        /// </summary>\r\n        public Type ViewCache { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the render context factory\r\n        /// </summary>\r\n        public Type RenderContextFactory { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the view location provider\r\n        /// </summary>\r\n        public Type ViewLocationProvider { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the status code handlers\r\n        /// </summary>\r\n        public IList<Type> StatusCodeHandlers { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the CSRF token validator\r\n        /// </summary>\r\n        public Type CsrfTokenValidator { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the object serializer\r\n        /// </summary>\r\n        public Type ObjectSerializer { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the types for serializers\r\n        /// </summary>\r\n        public IList<Type> Serializers { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the interactive diagnostic providers\r\n        /// </summary>\r\n        public IList<Type> InteractiveDiagnosticProviders { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the request tracing\r\n        /// </summary>\r\n        public Type RequestTracing { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the route invoker\r\n        /// </summary>\r\n        public Type RouteInvoker { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the response processors\r\n        /// </summary>\r\n        public IList<Type> ResponseProcessors { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the request dispatcher\r\n        /// </summary>\r\n        public Type RequestDispatcher { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the diagnostics\r\n        /// </summary>\r\n        public Type Diagnostics { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the route segment extractor\r\n        /// </summary>\r\n        public Type RouteSegmentExtractor { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the route description provider\r\n        /// </summary>\r\n        public Type RouteDescriptionProvider { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the culture service\r\n        /// </summary>\r\n        public Type CultureService { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the text resource\r\n        /// </summary>\r\n        public Type TextResource { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the resource assembly provider\r\n        /// </summary>\r\n        public Type ResourceAssemblyProvider { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the resource reader\r\n        /// </summary>\r\n        public Type ResourceReader { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the static content provider\r\n        /// </summary>\r\n        public Type StaticContentProvider { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the route resolver trie\r\n        /// </summary>\r\n        public Type RouteResolverTrie { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the trie node factory\r\n        /// </summary>\r\n        public Type TrieNodeFactory { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the route segment constraints\r\n        /// </summary>\r\n        public IList<Type> RouteSegmentConstraints { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the request trace factory\r\n        /// </summary>\r\n        public Type RequestTraceFactory { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the response negotiator\r\n        /// </summary>\r\n        public Type ResponseNegotiator { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether the configuration is valid.\r\n        /// </summary>\r\n        public bool IsValid\r\n        {\r\n            get\r\n            {\r\n                try\r\n                {\r\n                    return this.GetTypeRegistrations().All(tr => tr.RegistrationType != null);\r\n                }\r\n                catch (ArgumentNullException)\r\n                {\r\n                    return false;\r\n                }\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a new nancy internal configuration initializer with overrides for default types.\r\n        /// </summary>\r\n        /// <param name=\"builder\">Action that overrides default configuration types</param>\r\n        /// <returns>Initializer with overriden default types</returns>\r\n        public static Func<ITypeCatalog, NancyInternalConfiguration> WithOverrides(Action<NancyInternalConfiguration> builder)\r\n        {\r\n            return catalog =>\r\n            {\r\n                var configuration =\r\n                    Default.Invoke(catalog);\r\n\r\n                builder.Invoke(configuration);\r\n\r\n                return configuration;\r\n            };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns the configuration types as a TypeRegistration collection\r\n        /// </summary>\r\n        /// <returns>TypeRegistration collection representing the configuration types</returns>\r\n        public IEnumerable<TypeRegistration> GetTypeRegistrations()\r\n        {\r\n            return new[]\r\n            {\r\n                new TypeRegistration(typeof(IRouteResolver), this.RouteResolver),\r\n                new TypeRegistration(typeof(INancyEngine), this.NancyEngine),\r\n                new TypeRegistration(typeof(IRouteCache), this.RouteCache),\r\n                new TypeRegistration(typeof(IRouteCacheProvider), this.RouteCacheProvider),\r\n                new TypeRegistration(typeof(IViewLocator), this.ViewLocator),\r\n                new TypeRegistration(typeof(IViewFactory), this.ViewFactory),\r\n                new TypeRegistration(typeof(INancyContextFactory), this.ContextFactory),\r\n                new TypeRegistration(typeof(INancyModuleBuilder), this.NancyModuleBuilder),\r\n                new TypeRegistration(typeof(IResponseFormatterFactory), this.ResponseFormatterFactory),\r\n                new TypeRegistration(typeof(IModelBinderLocator), this.ModelBinderLocator),\r\n                new TypeRegistration(typeof(IBinder), this.Binder),\r\n                new TypeRegistration(typeof(BindingDefaults), this.BindingDefaults),\r\n                new TypeRegistration(typeof(IFieldNameConverter), this.FieldNameConverter),\r\n                new TypeRegistration(typeof(IViewResolver), this.ViewResolver),\r\n                new TypeRegistration(typeof(IViewCache), this.ViewCache),\r\n                new TypeRegistration(typeof(IRenderContextFactory), this.RenderContextFactory),\r\n                new TypeRegistration(typeof(IViewLocationProvider), this.ViewLocationProvider),\r\n                new TypeRegistration(typeof(ICsrfTokenValidator), this.CsrfTokenValidator),\r\n                new TypeRegistration(typeof(IObjectSerializer), this.ObjectSerializer),\r\n                new TypeRegistration(typeof(IModelValidatorLocator), this.ModelValidatorLocator),\r\n                new TypeRegistration(typeof(IRequestTracing), this.RequestTracing),\r\n                new TypeRegistration(typeof(IRouteInvoker), this.RouteInvoker),\r\n                new TypeRegistration(typeof(IRequestDispatcher), this.RequestDispatcher),\r\n                new TypeRegistration(typeof(IDiagnostics), this.Diagnostics),\r\n                new TypeRegistration(typeof(IRouteSegmentExtractor), this.RouteSegmentExtractor),\r\n                new TypeRegistration(typeof(IRouteDescriptionProvider), this.RouteDescriptionProvider),\r\n                new TypeRegistration(typeof(ICultureService), this.CultureService),\r\n                new TypeRegistration(typeof(ITextResource), this.TextResource),\r\n                new TypeRegistration(typeof(IResourceAssemblyProvider), this.ResourceAssemblyProvider),\r\n                new TypeRegistration(typeof(IResourceReader), this.ResourceReader),\r\n                new TypeRegistration(typeof(IStaticContentProvider), this.StaticContentProvider),\r\n                new TypeRegistration(typeof(IRouteResolverTrie), this.RouteResolverTrie),\r\n                new TypeRegistration(typeof(ITrieNodeFactory), this.TrieNodeFactory),\r\n                new TypeRegistration(typeof(IRequestTraceFactory), this.RequestTraceFactory),\r\n                new TypeRegistration(typeof(IResponseNegotiator), this.ResponseNegotiator),\r\n                new TypeRegistration(typeof(INancyEnvironmentConfigurator), this.EnvironmentConfigurator),\r\n                new TypeRegistration(typeof(INancyEnvironmentFactory), this.EnvironmentFactory),\r\n                new TypeRegistration(typeof(ISerializerFactory), this.SerializerFactory),\r\n                new TypeRegistration(typeof(IRuntimeEnvironmentInformation), this.RuntimeEnvironmentInformation)\r\n            };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns the collection configuration types as a CollectionTypeRegistration collection\r\n        /// </summary>\r\n        /// <returns>CollectionTypeRegistration collection representing the configuration types</returns>\r\n        public IEnumerable<CollectionTypeRegistration> GetCollectionTypeRegistrations()\r\n        {\r\n            return new[]\r\n            {\r\n                new CollectionTypeRegistration(typeof(IResponseProcessor), this.ResponseProcessors),\r\n                new CollectionTypeRegistration(typeof(ISerializer), this.Serializers),\r\n                new CollectionTypeRegistration(typeof(IStatusCodeHandler), this.StatusCodeHandlers),\r\n                new CollectionTypeRegistration(typeof(IDiagnosticsProvider), this.InteractiveDiagnosticProviders),\r\n                new CollectionTypeRegistration(typeof(IRouteSegmentConstraint), this.RouteSegmentConstraints),\r\n                new CollectionTypeRegistration(typeof(IRouteMetadataProvider), this.RouteMetadataProviders),\r\n                new CollectionTypeRegistration(typeof(INancyDefaultConfigurationProvider), this.DefaultConfigurationProviders),\r\n            };\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Bootstrapper/Pipelines.cs",
    "content": "namespace Nancy.Bootstrapper\r\n{\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Default implementation of the Nancy pipelines\r\n    /// </summary>\r\n    public class Pipelines : IPipelines\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"Pipelines\"/> class.\r\n        /// </summary>\r\n        public Pipelines()\r\n        {\r\n            this.AfterRequest = new AfterPipeline();\r\n            this.BeforeRequest = new BeforePipeline();\r\n            this.OnError = new ErrorPipeline();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"Pipelines\"/> class and clones the hooks from\r\n        /// the provided <see cref=\"IPipelines\"/> instance.\r\n        /// </summary>\r\n        public Pipelines(IPipelines pipelines)\r\n        {\r\n            this.AfterRequest =\r\n                new AfterPipeline(pipelines.AfterRequest.PipelineItems.Count());\r\n\r\n            foreach (var pipelineItem in pipelines.AfterRequest.PipelineItems)\r\n            {\r\n                this.AfterRequest.AddItemToEndOfPipeline(pipelineItem);\r\n            }\r\n\r\n            this.BeforeRequest =\r\n                new BeforePipeline(pipelines.BeforeRequest.PipelineItems.Count());\r\n\r\n            foreach (var pipelineItem in pipelines.BeforeRequest.PipelineItems)\r\n            {\r\n                this.BeforeRequest.AddItemToEndOfPipeline(pipelineItem);\r\n            }\r\n\r\n            this.OnError =\r\n                new ErrorPipeline(pipelines.OnError.PipelineItems.Count());\r\n\r\n            foreach (var pipelineItem in pipelines.OnError.PipelineItems)\r\n            {\r\n                this.OnError.AddItemToEndOfPipeline(pipelineItem);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// <para>\r\n        /// The pre-request hook\r\n        /// </para>\r\n        /// <para>\r\n        /// The PreRequest hook is called prior to processing a request. If a hook returns\r\n        /// a non-null response then processing is aborted and the response provided is\r\n        /// returned.\r\n        /// </para>\r\n        /// </summary>\r\n        public BeforePipeline BeforeRequest { get; set; }\r\n\r\n        /// <summary>\r\n        /// <para>\r\n        /// The post-request hook\r\n        /// </para>\r\n        /// <para>\r\n        /// The post-request hook is called after the response is created. It can be used\r\n        /// to rewrite the response or add/remove items from the context.\r\n        /// </para>\r\n        /// </summary>\r\n        public AfterPipeline AfterRequest { get; set; }\r\n\r\n        /// <summary>\r\n        /// <para>\r\n        /// The error hook\r\n        /// </para>\r\n        /// <para>\r\n        /// The error hook is called if an exception is thrown at any time during the pipeline.\r\n        /// If no error hook exists a standard InternalServerError response is returned\r\n        /// </para>\r\n        /// </summary>\r\n        public ErrorPipeline OnError { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Bootstrapper/Registrations.cs",
    "content": "﻿namespace Nancy.Bootstrapper\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using Nancy.Extensions;\r\n\r\n    /// <summary>\r\n    /// Helper class for providing application registrations\r\n    /// </summary>\r\n    public abstract class Registrations : IRegistrations\r\n    {\r\n        private readonly ITypeCatalog typeCatalog;\r\n        private readonly IList<CollectionTypeRegistration> collectionRegistrations = new List<CollectionTypeRegistration>();\r\n        private readonly IList<InstanceRegistration> instanceRegistrations = new List<InstanceRegistration>();\r\n        private readonly IList<TypeRegistration> typeRegistrations = new List<TypeRegistration>();\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"Registrations\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"typeCatalog\">An <see cref=\"ITypeCatalog\"/> instance.</param>\r\n        protected Registrations(ITypeCatalog typeCatalog)\r\n        {\r\n            this.typeCatalog = typeCatalog;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the collection registrations to register for this startup task\r\n        /// </summary>\r\n        public IEnumerable<CollectionTypeRegistration> CollectionTypeRegistrations\r\n        {\r\n            get { return this.collectionRegistrations; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the instance registrations to register for this startup task\r\n        /// </summary>\r\n        public IEnumerable<InstanceRegistration> InstanceRegistrations\r\n        {\r\n            get { return this.instanceRegistrations; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the type registrations to register for this startup task\r\n        /// </summary>\r\n        public IEnumerable<TypeRegistration> TypeRegistrations\r\n        {\r\n            get { return this.typeRegistrations; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Scans for the implementation of <typeparamref name=\"TRegistration\"/> and registers it.\r\n        /// </summary>\r\n        /// <param name=\"lifetime\">Lifetime of the registration, defaults to singleton</param>\r\n        /// <typeparam name=\"TRegistration\">The <see cref=\"Type\"/> to scan for and register as.</typeparam>\r\n        public void Register<TRegistration>(Lifetime lifetime = Lifetime.Singleton)\r\n        {\r\n            var implementation = this.typeCatalog\r\n                .GetTypesAssignableTo<TRegistration>()\r\n                .Single();\r\n\r\n            this.typeRegistrations.Add(new TypeRegistration(typeof(TRegistration), implementation, lifetime));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Scans for all implementations of <typeparamref name=\"TRegistration\"/> and registers them.\r\n        /// </summary>\r\n        /// <param name=\"lifetime\">Lifetime of the registration, defaults to singleton</param>\r\n        /// <typeparam name=\"TRegistration\">The <see cref=\"Type\"/> to scan for and register as.</typeparam>\r\n        public void RegisterAll<TRegistration>(Lifetime lifetime = Lifetime.Singleton)\r\n        {\r\n            var implementations = this.typeCatalog\r\n                .GetTypesAssignableTo<TRegistration>();\r\n\r\n            var registration =\r\n                new CollectionTypeRegistration(typeof(TRegistration), implementations, lifetime);\r\n\r\n            this.collectionRegistrations.Add(registration);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Registers the types provided by the <paramref name=\"defaultImplementations\"/> parameters\r\n        /// as <typeparamref name=\"TRegistration\"/>.\r\n        /// </summary>\r\n        /// <typeparam name=\"TRegistration\">The <see cref=\"Type\"/> to register as.</typeparam>\r\n        /// <param name=\"defaultImplementations\">The types to register.</param>\r\n        /// <param name=\"lifetime\">Lifetime of the registration, defaults to singleton</param>\r\n        public void Register<TRegistration>(IEnumerable<Type> defaultImplementations, Lifetime lifetime = Lifetime.Singleton)\r\n        {\r\n            this.collectionRegistrations.Add(new CollectionTypeRegistration(typeof(TRegistration), defaultImplementations, lifetime));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Registers the type provided by the <paramref name=\"implementation\"/> parameter\r\n        /// as <typeparamref name=\"TRegistration\"/>.\r\n        /// </summary>\r\n        /// <param name=\"lifetime\">Lifetime of the registration, defaults to singleton</param>\r\n        /// <typeparam name=\"TRegistration\">The <see cref=\"Type\"/> to register as.</typeparam>\r\n        /// <param name=\"implementation\">The <see cref=\"Type\"/> to register as <typeparamref name=\"TRegistration\"/>.</param>\r\n        public void Register<TRegistration>(Type implementation, Lifetime lifetime = Lifetime.Singleton)\r\n        {\r\n            this.typeRegistrations.Add(new TypeRegistration(typeof(TRegistration), implementation, lifetime));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Registers an instance as <typeparamref name=\"TRegistration\"/>.\r\n        /// </summary>\r\n        /// <typeparam name=\"TRegistration\">The <see cref=\"Type\"/> to register as.</typeparam>\r\n        /// <param name=\"instance\">The instance to register.</param>\r\n        public void Register<TRegistration>(TRegistration instance)\r\n        {\r\n            this.instanceRegistrations.Add(new InstanceRegistration(typeof(TRegistration), instance));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Scans for a <see cref=\"Type\"/> that implements <typeparamref name=\"TRegistration\"/>. If found, then it\r\n        /// will be used for the registration, else it will use <paramref name=\"defaultImplementation\"/>.\r\n        /// </summary>\r\n        /// <param name=\"lifetime\">Lifetime of the registration, defaults to singleton</param>\r\n        /// <typeparam name=\"TRegistration\">The <see cref=\"Type\"/> to register as.</typeparam>\r\n        /// <param name=\"defaultImplementation\">The implementation of <typeparamref name=\"TRegistration\"/> that will be use if no other implementation can be found.</param>\r\n        /// <remarks>\r\n        /// When scanning, it will exclude the assembly that the <see cref=\"Registrations\"/> instance is defined in and it will also ignore\r\n        /// the type specified by <paramref name=\"defaultImplementation\"/>.\r\n        /// </remarks>\r\n        public void RegisterWithDefault<TRegistration>(Type defaultImplementation, Lifetime lifetime = Lifetime.Singleton)\r\n        {\r\n            var implementation = this.typeCatalog\r\n                .GetTypesAssignableTo<TRegistration>()\r\n                .Where(type => type.GetTypeInfo().Assembly != this.GetType().GetTypeInfo().Assembly)\r\n                .SingleOrDefault(type => type != defaultImplementation);\r\n\r\n            this.typeRegistrations.Add(new TypeRegistration(typeof(TRegistration), implementation ?? defaultImplementation, lifetime));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Scans for an implementation of <typeparamref name=\"TRegistration\"/> and registers it if found. If no implementation could\r\n        /// be found, it will retrieve an instance of <typeparamref name=\"TRegistration\"/> using the provided <paramref name=\"defaultImplementationFactory\"/>,\r\n        /// which will be used in the registration.\r\n        /// </summary>\r\n        /// <typeparam name=\"TRegistration\">The <see cref=\"Type\"/> to register as.</typeparam>\r\n        /// <param name=\"defaultImplementationFactory\">Factory that provides an instance of <typeparamref name=\"TRegistration\"/>.</param>\r\n        /// <remarks>When scanning, it will exclude the assembly that the <see cref=\"Registrations\"/> instance is defined in</remarks>\r\n        public void RegisterWithDefault<TRegistration>(Func<TRegistration> defaultImplementationFactory)\r\n        {\r\n            var implementation = this.typeCatalog\r\n                .GetTypesAssignableTo<TRegistration>()\r\n                .SingleOrDefault(type => type.GetTypeInfo().Assembly != this.GetType().GetTypeInfo().Assembly);\r\n\r\n\r\n            if (implementation != null)\r\n            {\r\n                this.typeRegistrations.Add(new TypeRegistration(typeof(TRegistration), implementation));\r\n            }\r\n            else\r\n            {\r\n                this.instanceRegistrations.Add(new InstanceRegistration(typeof(TRegistration), defaultImplementationFactory.Invoke()));\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Scans for all implementations of <typeparamref name=\"TRegistration\"/>. If no implementations could be found, then it\r\n        /// will register the types specified by <paramref name=\"defaultImplementations\"/>.\r\n        /// </summary>\r\n        /// <param name=\"lifetime\">Lifetime of the registration, defaults to singleton</param>\r\n        /// <typeparam name=\"TRegistration\">The <see cref=\"Type\"/> to register as.</typeparam>\r\n        /// <param name=\"defaultImplementations\">The types to register if non could be located while scanning.</param>\r\n        /// <remarks>\r\n        /// When scanning, it will exclude the assembly that the <see cref=\"Registrations\"/> instance is defined in and it will also ignore\r\n        /// the types specified by <paramref name=\"defaultImplementations\"/>.\r\n        /// </remarks>\r\n        public void RegisterWithDefault<TRegistration>(IEnumerable<Type> defaultImplementations, Lifetime lifetime = Lifetime.Singleton)\r\n        {\r\n            var implementations = this.typeCatalog\r\n                .GetTypesAssignableTo<TRegistration>()\r\n                .Where(type => type.GetAssembly() != this.GetType().GetTypeInfo().Assembly)\r\n                .Where(type => !defaultImplementations.Contains(type))\r\n                .ToList();\r\n\r\n            if (!implementations.Any())\r\n            {\r\n                implementations = defaultImplementations.ToList();\r\n            }\r\n\r\n            this.collectionRegistrations.Add(new CollectionTypeRegistration(typeof(TRegistration), implementations, lifetime));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Scans for all implementations of <typeparamref name=\"TRegistration\"/> and registers them, followed by the\r\n        /// types defined by the <paramref name=\"defaultImplementations\"/> parameter.\r\n        /// </summary>\r\n        /// <typeparam name=\"TRegistration\">The <see cref=\"Type\"/> to register as.</typeparam>\r\n        /// <param name=\"defaultImplementations\">The types to register last.</param>\r\n        /// <param name=\"lifetime\">Lifetime of the registration, defaults to singleton</param>\r\n        /// <remarks>\r\n        /// When scanning, it will exclude the assembly that the <see cref=\"Registrations\"/> instance is defined in and it will also ignore\r\n        /// the types specified by <paramref name=\"defaultImplementations\"/>.\r\n        /// </remarks>\r\n        public void RegisterWithUserThenDefault<TRegistration>(IEnumerable<Type> defaultImplementations, Lifetime lifetime = Lifetime.Singleton)\r\n        {\r\n            var implementations = this.typeCatalog\r\n                .GetTypesAssignableTo<TRegistration>()\r\n                .Where(type => type.GetAssembly() != this.GetType().GetTypeInfo().Assembly)\r\n                .Where(type => !defaultImplementations.Contains(type))\r\n                .ToList();\r\n\r\n            this.collectionRegistrations.Add(new CollectionTypeRegistration(typeof(TRegistration), implementations.Union(defaultImplementations), lifetime));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Bootstrapper/TypeRegistration.cs",
    "content": "namespace Nancy.Bootstrapper\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Represents a type to be registered into the container\r\n    /// </summary>\r\n    public sealed class TypeRegistration : ContainerRegistration\r\n    {\r\n        /// <summary>\r\n        /// Represents a type to be registered into the container\r\n        /// </summary>\r\n        /// <param name=\"registrationType\">Registration type i.e. IMyInterface</param>\r\n        /// <param name=\"implementationType\">Implementation type i.e. MyClassThatImplementsIMyInterface</param>\r\n        /// <param name=\"lifetime\">Lifetime to register the type as</param>\r\n        public TypeRegistration(Type registrationType, Type implementationType, Lifetime lifetime = Lifetime.Singleton)\r\n        {\r\n            if (registrationType == null)\r\n            {\r\n                throw new ArgumentNullException(\"registrationType\");\r\n            }\r\n\r\n            if (implementationType == null)\r\n            {\r\n                throw new ArgumentNullException(\"implementationType\");\r\n            }\r\n\r\n            this.RegistrationType = registrationType;\r\n            this.ImplementationType = implementationType;\r\n            this.Lifetime = lifetime;\r\n\r\n            this.ValidateTypeCompatibility(implementationType);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Implementation type i.e. MyClassThatImplementsIMyInterface\r\n        /// </summary>\r\n        public Type ImplementationType { get; private set; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Configuration/ConfigurationException.cs",
    "content": "namespace Nancy\r\n{\r\n    using System;\r\n    using Nancy.Configuration;\r\n\r\n    /// <summary>\r\n    /// An exception related to an invalid configuration created within <see cref=\"INancyEnvironment\"/>\r\n    /// </summary>\r\n    public class ConfigurationException : Exception\r\n    {\r\n        /// <summary>\r\n        /// Create an instance of <see cref=\"ConfigurationException\"/>\r\n        /// </summary>\r\n        /// <param name=\"message\">A message to be passed into the exception</param>\r\n        public ConfigurationException(string message)\r\n            : base(message)\r\n        {\r\n            \r\n        }\r\n\r\n        /// <summary>\r\n        /// Create an instance of <see cref=\"ConfigurationException\"/>\r\n        /// </summary>\r\n        /// <param name=\"message\">A message to be passed into the exception</param>\r\n        /// <param name = \"exception\">An inner exception to buble up</param>\r\n        public ConfigurationException(string message, Exception exception)\r\n            : base(message, exception)\r\n        {\r\n            \r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Configuration/DefaultNancyEnvironment.cs",
    "content": "﻿namespace Nancy.Configuration\r\n{\r\n    using System;\r\n    using System.Collections;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Default implementation of the <see cref=\"INancyEnvironment\"/> interface.\r\n    /// </summary>\r\n    public class DefaultNancyEnvironment : INancyEnvironment\r\n    {\r\n        private readonly IDictionary<string, object> values = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);\r\n\r\n        /// <summary>\r\n        /// Returns an enumerator that iterates through the environment.\r\n        /// </summary>\r\n        /// <returns>A <see cref=\"Dictionary{TKey,TValue}.Enumerator\"/> that can be used to iterate through the environment.</returns>\r\n        public IEnumerator<KeyValuePair<string, object>> GetEnumerator()\r\n        {\r\n            return this.values.GetEnumerator();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an enumerator that iterates through the environment.\r\n        /// </summary>\r\n        /// <returns> An <see cref=\"IEnumerator\"/> object that can be used to iterate through the environment.</returns>\r\n        IEnumerator IEnumerable.GetEnumerator()\r\n        {\r\n            return this.GetEnumerator();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the number of elements in the environment.\r\n        /// </summary>\r\n        /// <returns>The number of elements in the environment.</returns>\r\n        public int Count\r\n        {\r\n            get { return this.values.Count; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determines whether the environment contains an element that has the specified key.\r\n        /// </summary>\r\n        /// <returns><see langword=\"true\"/> if the environment contains an element that has the specified key; otherwise, <see langword=\"false\"/>.\r\n        /// </returns>\r\n        /// <param name=\"key\">The key to retrieve.</param>\r\n        public bool ContainsKey(string key)\r\n        {\r\n            return this.values.ContainsKey(key);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the value that is associated with the specified key.\r\n        /// </summary>\r\n        /// <returns><see langword=\"true\"/> if the environment contains an element that has the specified key; otherwise, <see langword=\"false\"/>.</returns>\r\n        /// <param name=\"key\">The key to locate.</param>\r\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 <paramref name=\"value\"/> parameter. This parameter is passed uninitialized.</param>\r\n        bool IReadOnlyDictionary<string, object>.TryGetValue(string key, out object value)\r\n        {\r\n            return this.values.TryGetValue(key, out value);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the element that has the specified key in the environment.\r\n        /// </summary>\r\n        /// <returns>The element that has the specified key in the environment.</returns>\r\n        /// <param name=\"key\">The key to locate.</param>\r\n        object IReadOnlyDictionary<string, object>.this[string key]\r\n        {\r\n            get { return this.values[key]; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets an enumerable collection that contains the keys in the environment.\r\n        /// </summary>\r\n        /// <returns>An enumerable collection that contains the keys in the environment.</returns>\r\n        public IEnumerable<string> Keys\r\n        {\r\n            get { return this.values.Keys; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets an enumerable collection that contains the values in the environment.\r\n        /// </summary>\r\n        /// <returns>An enumerable collection that contains the values in the environment.</returns>\r\n        public IEnumerable<object> Values\r\n        {\r\n            get { return this.values.Values; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds a <paramref name=\"value\"/>, using a provided <paramref name=\"key\"/>, to the environment.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The <see cref=\"Type\"/> of the value to add.</typeparam>\r\n        /// <param name=\"key\">The key to store the value as.</param>\r\n        /// <param name=\"value\">The value to store in the environment.</param>\r\n        public void AddValue<T>(string key, T value)\r\n        {\r\n            this.values.Add(key, value);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the value that is associated with the specified key.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The <see cref=\"Type\"/> of the value to retrieve.</typeparam>\r\n        /// <param name=\"key\">The key to get the value for.</param>\r\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. This parameter is passed uninitialized.</param>\r\n        /// <returns><see langword=\"true\" /> if the value could be retrieved, otherwise <see langword=\"false\" />.</returns>\r\n        public bool TryGetValue<T>(string key, out T value)\r\n        {\r\n            object objectValue;\r\n\r\n            if (this.values.TryGetValue(key, out objectValue))\r\n            {\r\n                value = (T) objectValue;\r\n                return true;\r\n            }\r\n\r\n            value = default(T);\r\n            return false;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Configuration/DefaultNancyEnvironmentConfigurator.cs",
    "content": "﻿namespace Nancy.Configuration\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Default implementation of the <see cref=\"INancyEnvironmentConfigurator\"/> interface.\r\n    /// </summary>\r\n    public class DefaultNancyEnvironmentConfigurator : INancyEnvironmentConfigurator\r\n    {\r\n        private readonly INancyEnvironmentFactory factory;\r\n        private readonly IEnumerable<INancyDefaultConfigurationProvider> defaultConfigurationProviders;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultNancyEnvironmentConfigurator\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"factory\">The <see cref=\"INancyEnvironmentFactory\"/> instance to use when configuring an environment.</param>\r\n        /// <param name=\"defaultConfigurationProviders\"><see cref=\"INancyDefaultConfigurationProvider\"/> instances that should be used during the configuration of the environment.</param>\r\n        public DefaultNancyEnvironmentConfigurator(INancyEnvironmentFactory factory, IEnumerable<INancyDefaultConfigurationProvider> defaultConfigurationProviders)\r\n        {\r\n            this.factory = factory;\r\n            this.defaultConfigurationProviders = defaultConfigurationProviders;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Configures an <see cref=\"INancyEnvironment\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"configuration\">The configuration to apply to the environment.</param>\r\n        /// <returns>An <see cref=\"INancyEnvironment\"/> instance.</returns>\r\n        public INancyEnvironment ConfigureEnvironment(Action<INancyEnvironment> configuration)\r\n        {\r\n            var environment =\r\n                this.factory.CreateEnvironment();\r\n\r\n            configuration.Invoke(environment);\r\n\r\n            foreach (var configurationProvider in this.defaultConfigurationProviders)\r\n            {\r\n                var defaultConfiguration =\r\n                    SafeGetDefaultConfiguration(configurationProvider);\r\n\r\n                if (defaultConfiguration == null)\r\n                {\r\n                    continue;\r\n                }\r\n\r\n                var configurationKey =\r\n                    configurationProvider.Key;\r\n\r\n                if (environment.ContainsKey(configurationKey))\r\n                {\r\n                    continue;\r\n                }\r\n\r\n                environment.AddValue(configurationKey, defaultConfiguration);\r\n            }\r\n\r\n            return environment;\r\n        }\r\n\r\n        private static object SafeGetDefaultConfiguration(INancyDefaultConfigurationProvider configurationProvider)\r\n        {\r\n            try\r\n            {\r\n                return configurationProvider.GetDefaultConfiguration();\r\n            }\r\n            catch(ConfigurationException)\r\n            {\r\n                throw;\r\n            }\r\n            catch (Exception ex)\r\n            {\r\n                throw new ConfigurationException(string.Format(\"Error loading default configuration for {0}\", configurationProvider.Key), ex);\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Configuration/DefaultNancyEnvironmentFactory.cs",
    "content": "﻿namespace Nancy.Configuration\r\n{\r\n    /// <summary>\r\n    /// Default implementation of the <see cref=\"INancyEnvironmentFactory\"/> interface.\r\n    /// </summary>\r\n    /// <remarks>Creates instances of the <see cref=\"DefaultNancyEnvironment\"/> type.</remarks>\r\n    public class DefaultNancyEnvironmentFactory : INancyEnvironmentFactory\r\n    {\r\n        /// <summary>\r\n        /// Creates a new <see cref=\"INancyEnvironment\"/> instance.\r\n        /// </summary>\r\n        /// <returns>A <see cref=\"INancyEnvironment\"/> instance.</returns>\r\n        public INancyEnvironment CreateEnvironment()\r\n        {\r\n            return new DefaultNancyEnvironment();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Configuration/INancyDefaultConfigurationProvider.cs",
    "content": "namespace Nancy.Configuration\r\n{\r\n    /// <summary>\r\n    /// Defines the functionality for providing default configuration values to the <see cref=\"INancyEnvironment\"/>.\r\n    /// </summary>\r\n    public interface INancyDefaultConfigurationProvider : IHideObjectMembers\r\n    {\r\n        /// <summary>\r\n        /// Gets the default configuration instance to register in the <see cref=\"INancyEnvironment\"/>.\r\n        /// </summary>\r\n        /// <returns>The configuration instance</returns>\r\n        object GetDefaultConfiguration();\r\n\r\n        /// <summary>\r\n        /// Gets the key that will be used to store the configuration object in the <see cref=\"INancyEnvironment\"/>.\r\n        /// </summary>\r\n        /// <returns>A <see cref=\"string\"/> containing the key.</returns>\r\n        string Key { get; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Configuration/INancyEnvironment.cs",
    "content": "namespace Nancy.Configuration\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality of a Nancy environment.\r\n    /// </summary>\r\n    public interface INancyEnvironment : IReadOnlyDictionary<string, object>, IHideObjectMembers\r\n    {\r\n        /// <summary>\r\n        /// Adds a <paramref name=\"value\"/>, using a provided <paramref name=\"key\"/>, to the environment.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The <see cref=\"Type\"/> of the value to add.</typeparam>\r\n        /// <param name=\"key\">The key to store the value as.</param>\r\n        /// <param name=\"value\">The value to store in the environment.</param>\r\n        void AddValue<T>(string key, T value);\r\n\r\n        /// <summary>\r\n        /// Gets the value that is associated with the specified key.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The <see cref=\"Type\"/> of the value to retrieve.</typeparam>\r\n        /// <param name=\"key\">The key to get the value for.</param>\r\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. This parameter is passed uninitialized.</param>\r\n        /// <returns><see langword=\"true\" /> if the value could be retrieved, otherwise <see langword=\"false\" />.</returns>\r\n        bool TryGetValue<T>(string key, out T value);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Configuration/INancyEnvironmentConfigurator.cs",
    "content": "namespace Nancy.Configuration\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality for applying configuration to an <see cref=\"INancyEnvironment\"/> instance.\r\n    /// </summary>\r\n    public interface INancyEnvironmentConfigurator : IHideObjectMembers\r\n    {\r\n        /// <summary>\r\n        /// Configures an <see cref=\"INancyEnvironment\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"configuration\">The configuration to apply to the environment.</param>\r\n        /// <returns>An <see cref=\"INancyEnvironment\"/> instance.</returns>\r\n        INancyEnvironment ConfigureEnvironment(Action<INancyEnvironment> configuration);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Configuration/INancyEnvironmentExtensions.cs",
    "content": "namespace Nancy.Configuration\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Contains extensions for the <see cref=\"INancyEnvironment\"/> type.\r\n    /// </summary>\r\n    public static class INancyEnvironmentExtensions\r\n    {\r\n        /// <summary>\r\n        /// Adds a value to the environment, using the full name of the type defined by <typeparamref name=\"T\"/> as the key.\r\n        /// </summary>\r\n        /// <param name=\"environment\">The <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        /// <param name=\"value\">The value to store in the environment.</param>\r\n        /// <typeparam name=\"T\">The <see cref=\"Type\"/> of the value to store in the environment.</typeparam>\r\n        public static void AddValue<T>(this INancyEnvironment environment, T value)\r\n        {\r\n            environment.AddValue(typeof(T).FullName, value);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a value from the environment, using the full name of the type defined by <typeparamref name=\"T\"/> as the key.\r\n        /// </summary>\r\n        /// <param name=\"environment\">The <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        /// <typeparam name=\"T\">The <see cref=\"Type\"/> of the value to retreive from the environment.</typeparam>\r\n        /// <returns></returns>\r\n        public static T GetValue<T>(this INancyEnvironment environment)\r\n        {\r\n            return environment.GetValue<T>(typeof(T).FullName);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a value from the environment, using the provided <paramref name=\"key\"/>.\r\n        /// </summary>\r\n        /// <param name=\"environment\">The <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        /// <param name=\"key\">The key to retrieve the value for.</param>\r\n        /// <typeparam name=\"T\">The <see cref=\"Type\"/> of the value to retreive from the environment.</typeparam>\r\n        /// <returns>The stored value.</returns>\r\n        public static T GetValue<T>(this INancyEnvironment environment, string key)\r\n        {\r\n            return (T) environment[key];\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a value from the environment, using the full name of the type defined by <typeparamref name=\"T\"/> as the key. If\r\n        /// the value could not be found, then a provided default value is returned.\r\n        /// </summary>\r\n        /// <param name=\"environment\">The <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        /// <param name=\"defaultValue\">The value to return if no stored value could be found.</param>\r\n        /// <typeparam name=\"T\">The <see cref=\"Type\"/> of the value to retreive from the environment.</typeparam>\r\n        /// <returns>The stored value.</returns>\r\n        public static T GetValueWithDefault<T>(this INancyEnvironment environment, T defaultValue)\r\n        {\r\n            T value;\r\n            return environment.TryGetValue(typeof(T).FullName, out value) ? value : defaultValue;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a value from the environment, using the provided <paramref name=\"key\"/>. If the value could not be found, then\r\n        /// a provided default value is returned.\r\n        /// </summary>\r\n        /// <param name=\"environment\">The <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        /// <param name=\"key\">The key to retrieve the value for.</param>\r\n        /// <param name=\"defaultValue\">The value to return if no stored value could be found.</param>\r\n        /// <typeparam name=\"T\">The <see cref=\"Type\"/> of the value to retreive from the environment.</typeparam>\r\n        /// <returns>The stored value.</returns>\r\n        public static T GetValueWithDefault<T>(this INancyEnvironment environment, string key, T defaultValue)\r\n        {\r\n            T value;\r\n            return environment.TryGetValue(key, out value) ? value : defaultValue;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Configuration/INancyEnvironmentFactory.cs",
    "content": "namespace Nancy.Configuration\r\n{\r\n    /// <summary>\r\n    /// Defines the functionality for creating a <see cref=\"INancyEnvironment\"/> instance.\r\n    /// </summary>\r\n    public interface INancyEnvironmentFactory : IHideObjectMembers\r\n    {\r\n        /// <summary>\r\n        /// Creates a new <see cref=\"INancyEnvironment\"/> instance.\r\n        /// </summary>\r\n        /// <returns>A <see cref=\"INancyEnvironment\"/> instance.</returns>\r\n        INancyEnvironment CreateEnvironment();\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Configuration/NancyDefaultConfigurationProvider.cs",
    "content": "namespace Nancy.Configuration\r\n{\r\n    /// <summary>\r\n    /// Default (abstract) implementation of <see cref=\"INancyDefaultConfigurationProvider\" /> interface.\r\n    /// </summary>\r\n    /// <typeparam name=\"T\">The type of the configuration object.</typeparam>\r\n    public abstract class NancyDefaultConfigurationProvider<T> : INancyDefaultConfigurationProvider\r\n    {\r\n        /// <summary>\r\n        /// Gets the default configuration instance to register in the <see cref=\"INancyEnvironment\"/>.\r\n        /// </summary>\r\n        /// <returns>The configuration instance</returns>\r\n        public abstract T GetDefaultConfiguration();\r\n\r\n        /// <summary>\r\n        /// Gets the default configuration instance to register in the <see cref=\"INancyEnvironment\"/>.\r\n        /// </summary>\r\n        /// <returns>The configuration instance</returns>\r\n        object INancyDefaultConfigurationProvider.GetDefaultConfiguration()\r\n        {\r\n            return this.GetDefaultConfiguration();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the full type name of <typeparamref name=\"T\"/>.\r\n        /// </summary>\r\n        /// <returns>A <see cref=\"string\"/> containing the key.</returns>\r\n        public virtual string Key\r\n        {\r\n            get { return typeof(T).FullName; }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Conventions/AcceptHeaderCoercionConventions.cs",
    "content": "﻿namespace Nancy.Conventions\r\n{\r\n    using System;\r\n    using System.Collections;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Collection of accept header coercions\r\n    /// </summary>\r\n    public class AcceptHeaderCoercionConventions : IEnumerable<Func<IEnumerable<Tuple<string, decimal>>, NancyContext, IEnumerable<Tuple<string, decimal>>>>\r\n    {\r\n        private readonly IList<Func<IEnumerable<Tuple<string, decimal>>, NancyContext, IEnumerable<Tuple<string, decimal>>>> conventions;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"AcceptHeaderCoercionConventions\"/> class., with\r\n        /// the provided <paramref name= \"conventions\" />\r\n        /// </summary>\r\n        /// <param name=\"conventions\">The conventions.</param>\r\n        public AcceptHeaderCoercionConventions(IList<Func<IEnumerable<Tuple<string, decimal>>, NancyContext, IEnumerable<Tuple<string, decimal>>>> conventions)\r\n        {\r\n            this.conventions = conventions;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an enumerator that iterates through the collection.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// An enumerator that can be used to iterate through the collection.\r\n        /// </returns>\r\n        public IEnumerator<Func<IEnumerable<Tuple<string, decimal>>, NancyContext, IEnumerable<Tuple<string, decimal>>>> GetEnumerator()\r\n        {\r\n            return this.conventions.GetEnumerator();\r\n        }\r\n\r\n        IEnumerator IEnumerable.GetEnumerator()\r\n        {\r\n            return GetEnumerator();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Conventions/BuiltInAcceptHeaderCoercions.cs",
    "content": "namespace Nancy.Conventions\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Built in functions for coercing accept headers.\r\n    /// <seealso cref=\"DefaultAcceptHeaderCoercionConventions\"/>\r\n    /// </summary>\r\n    public static class BuiltInAcceptHeaderCoercions\r\n    {\r\n        private const string HtmlContentType = \"text/html\";\r\n\r\n        private static readonly IEnumerable<Tuple<string, decimal>> DefaultAccept = new[] { Tuple.Create(HtmlContentType, 1.0m), Tuple.Create(\"*/*\", 0.9m) };\r\n\r\n        private static readonly string[] BrokenBrowsers = new[] {\"MSIE 8\", \"MSIE 7\", \"MSIE 6\", \"AppleWebKit\"};\r\n\r\n        /// <summary>\r\n        /// Adds a default accept header if there isn't one.\r\n        /// </summary>\r\n        /// <param name=\"currentAcceptHeaders\">Current headers</param>\r\n        /// <param name=\"context\">Context</param>\r\n        /// <returns>Modified headers or original if no modification required</returns>\r\n        public static IEnumerable<Tuple<string, decimal>> CoerceBlankAcceptHeader(IEnumerable<Tuple<string, decimal>> currentAcceptHeaders, NancyContext context)\r\n        {\r\n            var current = currentAcceptHeaders as Tuple<string, decimal>[] ?? currentAcceptHeaders.ToArray();\r\n\r\n            return !current.Any() ? DefaultAccept : current;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Replaces the accept header of stupid browsers that request XML instead\r\n        /// of HTML.\r\n        /// </summary>\r\n        /// <param name=\"currentAcceptHeaders\">Current headers</param>\r\n        /// <param name=\"context\">Context</param>\r\n        /// <returns>Modified headers or original if no modification required</returns>\r\n        public static IEnumerable<Tuple<string, decimal>> CoerceStupidBrowsers(IEnumerable<Tuple<string, decimal>> currentAcceptHeaders, NancyContext context)\r\n        {\r\n            var current = currentAcceptHeaders as Tuple<string, decimal>[] ?? currentAcceptHeaders.ToArray();\r\n\r\n            return IsStupidBrowser(current, context) ? DefaultAccept : current;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Boosts the priority of HTML for browsers that ask for xml and html with the\r\n        /// same priority.\r\n        /// </summary>\r\n        /// <param name=\"currentAcceptHeaders\">Current headers</param>\r\n        /// <param name=\"context\">Context</param>\r\n        /// <returns>Modified headers or original if no modification required</returns>\r\n        public static IEnumerable<Tuple<string, decimal>> BoostHtml(IEnumerable<Tuple<string, decimal>> currentAcceptHeaders, NancyContext context)\r\n        {\r\n            var current = currentAcceptHeaders as Tuple<string, decimal>[] ?? currentAcceptHeaders.ToArray();\r\n\r\n            var html = current.FirstOrDefault(h => string.Equals(h.Item1, HtmlContentType, StringComparison.OrdinalIgnoreCase) && h.Item2 < 1.0m);\r\n\r\n            if (html == null)\r\n            {\r\n                return current;\r\n            }\r\n\r\n            var index = Array.IndexOf(current, html);\r\n            if (index == -1)\r\n            {\r\n                return current;\r\n            }\r\n\r\n            current[index] = Tuple.Create(HtmlContentType, html.Item2 + 0.2m);\r\n\r\n            return current.OrderByDescending(x => x.Item2).ToArray();\r\n        }\r\n\r\n        private static bool IsStupidBrowser(Tuple<string, decimal>[] current, NancyContext context)\r\n        {\r\n            // If there's one or less accept headers then we can't be a stupid\r\n            // browser so just bail out early\r\n            if (current.Length <= 1)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            var maxScore = current.First().Item2;\r\n\r\n            if (IsPotentiallyBrokenBrowser(context.Request.Headers.UserAgent)\r\n                && !current.Any(h => h.Item2 == maxScore && string.Equals(HtmlContentType, h.Item1, StringComparison.OrdinalIgnoreCase)))\r\n            {\r\n                return true;\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        private static bool IsPotentiallyBrokenBrowser(string userAgent)\r\n        {\r\n            return BrokenBrowsers.Any(userAgent.Contains);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Conventions/BuiltInCultureConventions.cs",
    "content": "﻿namespace Nancy.Conventions\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Globalization;\r\n    using System.Linq;\r\n    using System.Threading;\r\n    using Nancy.Configuration;\r\n    using Nancy.Session;\r\n\r\n    /// <summary>\r\n    /// Built in functions for determining current culture\r\n    /// <seealso cref=\"DefaultCultureConventions\"/>\r\n    /// </summary>\r\n    public static class BuiltInCultureConventions\r\n    {\r\n        /// <summary>\r\n        /// Checks to see if the Form has a CurrentCulture key.\r\n        /// </summary>\r\n        /// <param name=\"context\">NancyContext</param>\r\n        /// <param name=\"configuration\">Culture configuration that contains allowed cultures</param>\r\n        /// <returns>CultureInfo if found in Form otherwise null</returns>\r\n        public static CultureInfo FormCulture(NancyContext context, GlobalizationConfiguration configuration)\r\n        {\r\n            if (context.Request.Form[\"CurrentCulture\"] != null)\r\n            {\r\n                string cultureLetters = context.Request.Form[\"CurrentCulture\"];\r\n\r\n                if (!IsValidCultureInfoName(cultureLetters, configuration))\r\n                {\r\n                    return null;\r\n                }\r\n\r\n                return new CultureInfo(cultureLetters);\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Checks to see if the first argument in the Path can be used to make a CultureInfo.\r\n        /// </summary>\r\n        /// <param name=\"context\">NancyContext</param>\r\n        /// <param name=\"configuration\">Culture configuration that contains allowed cultures</param>\r\n        /// <returns>CultureInfo if found in Path otherwise null</returns>\r\n        public static CultureInfo PathCulture(NancyContext context, GlobalizationConfiguration configuration)\r\n        {\r\n            var segments =\r\n                context.Request.Url.Path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);\r\n\r\n            var firstSegment =\r\n                segments.FirstOrDefault();\r\n\r\n            if (firstSegment != null && IsValidCultureInfoName(firstSegment, configuration))\r\n            {\r\n                context.Request.Url.Path =\r\n                    string.Concat(\"/\", string.Join(\"/\", segments.Skip(1)));\r\n\r\n                return new CultureInfo(firstSegment);\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Checks to see if the AcceptLanguage in the Headers can be used to make a CultureInfo. Uses highest weighted if multiple defined.\r\n        /// </summary>\r\n        /// <param name=\"context\">NancyContext</param>\r\n        /// <param name=\"configuration\">Culture configuration that contains allowed cultures</param>\r\n        /// <returns>CultureInfo if found in Headers otherwise null</returns>\r\n        public static CultureInfo HeaderCulture(NancyContext context, GlobalizationConfiguration configuration)\r\n        {\r\n            if (context.Request.Headers.AcceptLanguage.Any())\r\n            {\r\n                var cultureLetters = context.Request.Headers.AcceptLanguage.First().Item1;\r\n\r\n                if (!IsValidCultureInfoName(cultureLetters, configuration))\r\n                {\r\n                    return null;\r\n                }\r\n\r\n                return new CultureInfo(cultureLetters);\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Checks to see if the Session has a CurrentCulture key\r\n        /// </summary>\r\n        /// <param name=\"context\">NancyContext</param>\r\n        /// <param name=\"configuration\">Culture configuration that contains allowed cultures</param>\r\n        /// <returns>CultureInfo if found in Session otherwise null</returns>\r\n        public static CultureInfo SessionCulture(NancyContext context, GlobalizationConfiguration configuration)\r\n        {\r\n            var sessionType = context.Request.Session as NullSessionProvider;\r\n            if (sessionType == null && context.Request.Session[\"CurrentCulture\"] != null)\r\n            {\r\n                return (CultureInfo)context.Request.Session[\"CurrentCulture\"];\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Checks to see if the Cookies has a CurrentCulture key\r\n        /// </summary>\r\n        /// <param name=\"context\">NancyContext</param>\r\n        /// <param name=\"configuration\">Culture configuration that contains allowed cultures</param>\r\n        /// <returns>CultureInfo if found in Cookies otherwise null</returns>\r\n        public static CultureInfo CookieCulture(NancyContext context, GlobalizationConfiguration configuration)\r\n        {\r\n            string cookieCulture = null;\r\n\r\n            if (context.Request.Cookies.TryGetValue(\"CurrentCulture\", out cookieCulture))\r\n            {\r\n                if (!IsValidCultureInfoName(cookieCulture, configuration))\r\n                {\r\n                    return null;\r\n                }\r\n\r\n                return new CultureInfo(cookieCulture);\r\n            }\r\n\r\n            return null;\r\n        }\r\n        /// <summary>\r\n        /// Checks to see if a default culture has been set on <see cref=\"GlobalizationConfiguration\"/>\r\n        /// </summary>\r\n        /// <param name=\"context\">NancyContext</param>\r\n        /// <param name=\"configuration\">Culture configuration that contains allowed cultures</param>\r\n        /// <returns>CultureInfo if found in <see cref=\"GlobalizationConfiguration\"/> Default Culture else null</returns>\r\n        public static CultureInfo GlobalizationConfigurationCulture(NancyContext context, GlobalizationConfiguration configuration)\r\n        {\r\n            if (configuration.DefaultCulture != null)\r\n            {\r\n                if (!IsValidCultureInfoName(configuration.DefaultCulture, configuration))\r\n                {\r\n                    return null;\r\n                }\r\n\r\n                return new CultureInfo(configuration.DefaultCulture);\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Validates culture name\r\n        /// </summary>\r\n        /// <param name=\"name\">Culture name eg\\en-GB</param>\r\n        /// <param name=\"configuration\">Culture configuration that contains allowed cultures</param>\r\n        /// <returns>True/False if valid culture</returns>\r\n        public static bool IsValidCultureInfoName(string name, GlobalizationConfiguration configuration)\r\n        {\r\n            if (string.IsNullOrWhiteSpace(name))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            return configuration.SupportedCultureNames.Contains(name);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Conventions/CultureConventions.cs",
    "content": "﻿namespace Nancy.Conventions\r\n{\r\n    using System;\r\n    using System.Collections;\r\n    using System.Collections.Generic;\r\n    using System.Globalization;\r\n\r\n\r\n    /// <summary>\r\n    /// Collection class for static culture conventions\r\n    /// </summary>\r\n    /// <seealso cref=\"Func{TContext, TGlobalizationConfiguration, TResult}\" />\r\n    public class CultureConventions : IEnumerable<Func<NancyContext, GlobalizationConfiguration, CultureInfo>>\r\n    {\r\n        private readonly IEnumerable<Func<NancyContext, GlobalizationConfiguration, CultureInfo>> conventions;\r\n\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"CultureConventions\"/> class, with\r\n        /// the provided <paramref name=\"conventions\"/>.\r\n        /// </summary>\r\n        /// <param name=\"conventions\">The conventions.</param>\r\n        public CultureConventions(IEnumerable<Func<NancyContext, GlobalizationConfiguration, CultureInfo>> conventions)\r\n        {\r\n            this.conventions = conventions;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an enumerator that iterates through the collection.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// An enumerator that can be used to iterate through the collection.\r\n        /// </returns>\r\n        public IEnumerator<Func<NancyContext, GlobalizationConfiguration, CultureInfo>> GetEnumerator()\r\n        {\r\n            return this.conventions.GetEnumerator();\r\n        }\r\n\r\n        IEnumerator IEnumerable.GetEnumerator()\r\n        {\r\n            return this.GetEnumerator();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Conventions/DefaultAcceptHeaderCoercionConventions.cs",
    "content": "﻿namespace Nancy.Conventions\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Wires up the default conventions for the accept header coercion\r\n    /// </summary>\r\n    public class DefaultAcceptHeaderCoercionConventions : IConvention\r\n    {\r\n        /// <summary>\r\n        /// Initialise any conventions this class \"owns\"\r\n        /// </summary>\r\n        /// <param name=\"conventions\">Convention object instance</param>\r\n        public void Initialise(NancyConventions conventions)\r\n        {\r\n            this.ConfigureDefaultConventions(conventions);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Asserts that the conventions that this class \"owns\" are valid\r\n        /// </summary>\r\n        /// <param name=\"conventions\">Conventions object instance</param>\r\n        /// <returns>\r\n        /// Tuple containing true/false for valid/invalid, and any error messages\r\n        /// </returns>\r\n        public Tuple<bool, string> Validate(NancyConventions conventions)\r\n        {\r\n            if (conventions.AcceptHeaderCoercionConventions == null)\r\n            {\r\n                return Tuple.Create(false, \"The accept header coercion conventions cannot be null.\");\r\n            }\r\n\r\n            return Tuple.Create(true, string.Empty);\r\n        }\r\n\r\n        private void ConfigureDefaultConventions(NancyConventions conventions)\r\n        {\r\n            conventions.AcceptHeaderCoercionConventions = new List<Func<IEnumerable<Tuple<string, decimal>>, NancyContext, IEnumerable<Tuple<string, decimal>>>>(2)\r\n                                                              {\r\n                                                                 BuiltInAcceptHeaderCoercions.BoostHtml,\r\n                                                                 BuiltInAcceptHeaderCoercions.CoerceBlankAcceptHeader,\r\n                                                              };\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Conventions/DefaultCultureConventions.cs",
    "content": "﻿namespace Nancy.Conventions\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Globalization;\r\n\r\n    /// <summary>\r\n    /// Default implementation of <see cref=\"IConvention\"/>\r\n    /// </summary>\r\n    public class DefaultCultureConventions : IConvention\r\n    {\r\n        /// <summary>\r\n        /// Initialise culture conventions\r\n        /// </summary>\r\n        /// <param name=\"conventions\"></param>\r\n        public void Initialise(NancyConventions conventions)\r\n        {\r\n            ConfigureDefaultConventions(conventions);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determine if culture conventions are valid\r\n        /// </summary>\r\n        /// <param name=\"conventions\"></param>\r\n        /// <returns></returns>\r\n        public Tuple<bool, string> Validate(NancyConventions conventions)\r\n        {\r\n            if (conventions.CultureConventions == null)\r\n            {\r\n                return Tuple.Create(false, \"The culture conventions cannot be null.\");\r\n            }\r\n\r\n            return (conventions.CultureConventions.Count > 0) ?\r\n               Tuple.Create(true, string.Empty) :\r\n               Tuple.Create(false, \"The culture conventions cannot be empty.\");\r\n        }\r\n\r\n        /// <summary>\r\n        /// Setup default conventions\r\n        /// </summary>\r\n        /// <param name=\"conventions\"></param>\r\n        private static void ConfigureDefaultConventions(NancyConventions conventions)\r\n        {\r\n            conventions.CultureConventions = new List<Func<NancyContext, GlobalizationConfiguration, CultureInfo>>\r\n            {\r\n                BuiltInCultureConventions.FormCulture,\r\n                BuiltInCultureConventions.HeaderCulture,\r\n                BuiltInCultureConventions.SessionCulture,\r\n                BuiltInCultureConventions.CookieCulture,\r\n                BuiltInCultureConventions.GlobalizationConfigurationCulture,\r\n            };\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Conventions/DefaultStaticContentsConventions.cs",
    "content": "namespace Nancy.Conventions\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Defines the default static contents conventions.\r\n    /// </summary>\r\n    public class DefaultStaticContentsConventions : IConvention\r\n    {\r\n        /// <summary>\r\n        /// Initialise any conventions this class \"owns\".\r\n        /// </summary>\r\n        /// <param name=\"conventions\">Convention object instance.</param>\r\n        public void Initialise(NancyConventions conventions)\r\n        {\r\n            conventions.StaticContentsConventions = new List<Func<NancyContext, string, Response>>\r\n            {\r\n                StaticContentConventionBuilder.AddDirectory(\"Content\")\r\n            };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Asserts that the conventions that this class \"owns\" are valid\r\n        /// </summary>\r\n        /// <param name=\"conventions\">Conventions object instance.</param>\r\n        /// <returns>Tuple containing true/false for valid/invalid, and any error messages.</returns>\r\n        public Tuple<bool, string> Validate(NancyConventions conventions)\r\n        {\r\n            if (conventions.StaticContentsConventions == null)\r\n            {\r\n                return Tuple.Create(false, \"The static contents conventions cannot be null.\");\r\n            }\r\n\r\n            return (conventions.StaticContentsConventions.Count > 0) ?\r\n                Tuple.Create(true, string.Empty) :\r\n                Tuple.Create(false, \"The static contents conventions cannot be empty.\");\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Conventions/DefaultViewLocationConventions.cs",
    "content": "﻿namespace Nancy.Conventions\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    using Nancy.ViewEngines;\r\n\r\n    /// <summary>\r\n    /// Defines the default static contents conventions.\r\n    /// </summary>\r\n    public class DefaultViewLocationConventions : IConvention\r\n    {\r\n        /// <summary>\r\n        /// Initialise any conventions this class \"owns\".\r\n        /// </summary>\r\n        /// <param name=\"conventions\">Convention object instance.</param>\r\n        public void Initialise(NancyConventions conventions)\r\n        {\r\n            ConfigureViewLocationConventions(conventions);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Asserts that the conventions that this class \"owns\" are valid.\r\n        /// </summary>\r\n        /// <param name=\"conventions\">Conventions object instance.</param>\r\n        /// <returns>Tuple containing true/false for valid/invalid, and any error messages.</returns>\r\n        public Tuple<bool, string> Validate(NancyConventions conventions)\r\n        {\r\n            if (conventions.ViewLocationConventions == null)\r\n            {\r\n                return Tuple.Create(false, \"The view conventions cannot be null.\");\r\n            }\r\n\r\n            return (conventions.ViewLocationConventions.Count > 0) ?\r\n                Tuple.Create(true, string.Empty) :\r\n                Tuple.Create(false, \"The view conventions cannot be empty.\");\r\n        }\r\n\r\n        private static void ConfigureViewLocationConventions(NancyConventions conventions)\r\n        {\r\n            conventions.ViewLocationConventions = new List<Func<string, object, ViewLocationContext, string>>\r\n            {\r\n                (viewName, model, viewLocationContext) =>{\r\n                    if (string.IsNullOrEmpty(viewLocationContext.ModulePath))\r\n                    {\r\n                        return string.Empty;\r\n                    }\r\n\r\n                    var path = viewLocationContext.ModulePath.TrimStart(new[] { '/' });\r\n\r\n                    return string.Concat(\"views/\", path, \"/\", viewLocationContext.ModuleName, \"/\", viewName, \"-\", viewLocationContext.Context.Culture);\r\n                },\r\n\r\n                // 0 Handles: views / *modulepath* / *modulename* / *viewname*\r\n                (viewName, model, viewLocationContext) =>{\r\n                    if (string.IsNullOrEmpty(viewLocationContext.ModulePath))\r\n                    {\r\n                        return string.Empty;\r\n                    }\r\n\r\n                    var path = viewLocationContext.ModulePath.TrimStart(new[] { '/' });\r\n\r\n                    return  string.Concat(\"views/\", path, \"/\", viewLocationContext.ModuleName, \"/\", viewName);\r\n                },\r\n\r\n                (viewName, model, viewLocationContext) =>{\r\n                    if (string.IsNullOrEmpty(viewLocationContext.ModulePath))\r\n                    {\r\n                        return string.Empty;\r\n                    }\r\n\r\n                    var path = viewLocationContext.ModulePath.TrimStart(new[] { '/' });\r\n\r\n                    return string.Concat(path, \"/\", viewLocationContext.ModuleName, \"/\", viewName, \"-\", viewLocationContext.Context.Culture);\r\n                },\r\n\r\n                // 1 Handles: *modulepath* / *modulename* / *viewname*\r\n                (viewName, model, viewLocationContext) =>{\r\n                    if (string.IsNullOrEmpty(viewLocationContext.ModulePath))\r\n                    {\r\n                        return string.Empty;\r\n                    }\r\n\r\n                    var path = viewLocationContext.ModulePath.TrimStart(new[] { '/' });\r\n\r\n                    return  string.Concat(path, \"/\", viewLocationContext.ModuleName, \"/\", viewName);\r\n                },\r\n\r\n                (viewName, model, viewLocationContext) =>{\r\n                    return string.IsNullOrEmpty(viewLocationContext.ModulePath) ? string.Empty : string.Concat(\"views/\", viewLocationContext.ModulePath.TrimStart(new[] { '/' }), \"/\", viewName, \"-\", viewLocationContext.Context.Culture);\r\n                },\r\n\r\n                // 2 Handles: views / *modulepath* / *viewname*\r\n                (viewName, model, viewLocationContext) =>{\r\n                    return string.IsNullOrEmpty(viewLocationContext.ModulePath) ? string.Empty : string.Concat(\"views/\", viewLocationContext.ModulePath.TrimStart(new[] {'/'}), \"/\", viewName);\r\n                },\r\n\r\n                (viewName, model, viewLocationContext) =>{\r\n                    return string.IsNullOrEmpty(viewLocationContext.ModulePath) ? string.Empty : string.Concat(viewLocationContext.ModulePath.TrimStart(new[] { '/' }), \"/\", viewName, \"-\", viewLocationContext.Context.Culture);\r\n                },\r\n\r\n                // 3 Handles: *modulepath* / *viewname*\r\n                (viewName, model, viewLocationContext) =>{\r\n                    return string.IsNullOrEmpty(viewLocationContext.ModulePath) ? string.Empty : string.Concat(viewLocationContext.ModulePath.TrimStart(new[] { '/' }), \"/\", viewName);\r\n                },\r\n\r\n                (viewName, model, viewLocationContext) => {\r\n                    return string.Concat(\"views/\", viewLocationContext.ModuleName, \"/\", viewName, \"-\", viewLocationContext.Context.Culture);\r\n                },\r\n\r\n                // 4 Handles: views / *modulename* / *viewname*\r\n                (viewName, model, viewLocationContext) => {\r\n                    return string.Concat(\"views/\", viewLocationContext.ModuleName, \"/\", viewName);\r\n                },\r\n\r\n                (viewName, model, viewLocationContext) => {\r\n                    return string.Concat(viewLocationContext.ModuleName, \"/\", viewName, \"-\", viewLocationContext.Context.Culture);\r\n                },\r\n\r\n                // 5 Handles: *modulename* / *viewname*\r\n                (viewName, model, viewLocationContext) => {\r\n                    return string.Concat(viewLocationContext.ModuleName, \"/\", viewName);\r\n                },\r\n\r\n                (viewName, model, viewLocationContext) => {\r\n                    return string.Concat(\"views/\", viewName, \"-\", viewLocationContext.Context.Culture);\r\n                },\r\n\r\n                // 6 Handles: views / *viewname*\r\n                (viewName, model, viewLocationContext) => {\r\n                    return string.Concat(\"views/\", viewName);\r\n                },\r\n\r\n                (viewName, model, viewLocationContext) => {\r\n                    return string.Concat(viewName, \"-\", viewLocationContext.Context.Culture);\r\n                },\r\n\r\n                // 7 Handles: *viewname*\r\n                (viewName, model, viewLocationContext) => {\r\n                    return viewName;\r\n                }\r\n            };\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Conventions/IConvention.cs",
    "content": "namespace Nancy.Conventions\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Provides Nancy convention defaults and validation\r\n    /// </summary>\r\n    public interface IConvention\r\n    {\r\n        /// <summary>\r\n        /// Initialise any conventions this class \"owns\"\r\n        /// </summary>\r\n        /// <param name=\"conventions\">Convention object instance</param>\r\n        void Initialise(NancyConventions conventions);\r\n\r\n        /// <summary>\r\n        /// Asserts that the conventions that this class \"owns\" are valid\r\n        /// </summary>\r\n        /// <param name=\"conventions\">Conventions object instance</param>\r\n        /// <returns>Tuple containing true/false for valid/invalid, and any error messages</returns>\r\n        Tuple<bool, string> Validate(NancyConventions conventions);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Conventions/NancyConventions.cs",
    "content": "﻿namespace Nancy.Conventions\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Globalization;\r\n    using System.Linq;\r\n    using System.Text;\r\n\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.ViewEngines;\r\n\r\n    /// <summary>\r\n    /// Nancy configurable conventions\r\n    /// </summary>\r\n    public class NancyConventions\r\n    {\r\n        private readonly ITypeCatalog typeCatalog;\r\n        private IEnumerable<IConvention> conventions;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancyConventions\"/> class.\r\n        /// </summary>\r\n        public NancyConventions(ITypeCatalog typeCatalog)\r\n        {\r\n            this.typeCatalog = typeCatalog;\r\n            this.BuildDefaultConventions();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the conventions for locating view templates\r\n        /// </summary>\r\n        public IList<Func<string, dynamic, ViewLocationContext, string>> ViewLocationConventions { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the conventions for locating and serving static content\r\n        /// </summary>\r\n        public IList<Func<NancyContext, string, Response>> StaticContentsConventions { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the conventions for coercing accept headers from their source\r\n        /// values to the real values for content negotiation\r\n        /// <seealso cref=\"BuiltInAcceptHeaderCoercions\"/>\r\n        /// </summary>\r\n        public IList<Func<IEnumerable<Tuple<string, decimal>>, NancyContext, IEnumerable<Tuple<string, decimal>>>> AcceptHeaderCoercionConventions { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the conventions for determining request culture\r\n        /// </summary>\r\n        public IList<Func<NancyContext, GlobalizationConfiguration, CultureInfo>> CultureConventions { get; set; }\r\n\r\n        /// <summary>\r\n        /// Validates the conventions\r\n        /// </summary>\r\n        /// <returns>A tuple containing a flag indicating validity, and any error messages</returns>\r\n        public Tuple<bool, string> Validate()\r\n        {\r\n            var isValid = true;\r\n            var errorMessageBuilder = new StringBuilder();\r\n\r\n            foreach (var result in this.conventions.Select(convention => convention.Validate(this)).Where(result => !result.Item1))\r\n            {\r\n                isValid = false;\r\n                errorMessageBuilder.AppendLine(result.Item2);\r\n            }\r\n\r\n            return new Tuple<bool, string>(isValid, errorMessageBuilder.ToString());\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the instance registrations for registering into the container\r\n        /// </summary>\r\n        /// <returns>Enumeration of InstanceRegistration types</returns>\r\n        public IEnumerable<InstanceRegistration> GetInstanceRegistrations()\r\n        {\r\n            return new[]\r\n            {\r\n                new InstanceRegistration(typeof(ViewLocationConventions), new ViewLocationConventions(this.ViewLocationConventions)),\r\n                new InstanceRegistration(typeof(StaticContentsConventions), new StaticContentsConventions(this.StaticContentsConventions)),\r\n                new InstanceRegistration(typeof(AcceptHeaderCoercionConventions), new AcceptHeaderCoercionConventions(this.AcceptHeaderCoercionConventions)),\r\n                new InstanceRegistration(typeof(CultureConventions), new CultureConventions(this.CultureConventions))\r\n            };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Locates all the default conventions and calls them in\r\n        /// turn to build up the default conventions.\r\n        /// </summary>\r\n        private void BuildDefaultConventions()\r\n        {\r\n            var defaultConventions =\r\n                this.typeCatalog.GetTypesAssignableTo<IConvention>(TypeResolveStrategies.OnlyNancy);\r\n\r\n            this.conventions = defaultConventions\r\n                .Union(this.typeCatalog.GetTypesAssignableTo<IConvention>(TypeResolveStrategies.ExcludeNancy))\r\n                .Select(t => (IConvention)Activator.CreateInstance(t));\r\n\r\n            foreach (var convention in this.conventions)\r\n            {\r\n                convention.Initialise(this);\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Conventions/StaticContentConventionBuilder.cs",
    "content": "using Nancy.Diagnostics;\r\n\r\nnamespace Nancy.Conventions\r\n{\r\n    using System;\r\n    using System.Collections.Concurrent;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Text.RegularExpressions;\r\n\r\n    using Nancy.Helpers;\r\n    using Nancy.Responses;\r\n\r\n    /// <summary>\r\n    /// Helper class for defining directory-based conventions for static contents.\r\n    /// </summary>\r\n    public class StaticContentConventionBuilder\r\n    {\r\n        private static readonly ConcurrentDictionary<ResponseFactoryCacheKey, Func<NancyContext, Response>> ResponseFactoryCache;\r\n        private static readonly Regex PathReplaceRegex = new Regex(@\"[/\\\\]\", RegexOptions.Compiled);\r\n\r\n        static StaticContentConventionBuilder()\r\n        {\r\n            ResponseFactoryCache = new ConcurrentDictionary<ResponseFactoryCacheKey, Func<NancyContext, Response>>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds a directory-based convention for static convention.\r\n        /// </summary>\r\n        /// <param name=\"requestedPath\">The path that should be matched with the request.</param>\r\n        /// <param name=\"contentPath\">The path to where the content is stored in your application, relative to the root. If this is <see langword=\"null\" /> then it will be the same as <paramref name=\"requestedPath\"/>.</param>\r\n        /// <param name=\"allowedExtensions\">A list of extensions that is valid for the conventions. If not supplied, all extensions are valid.</param>\r\n        /// <returns>A <see cref=\"GenericFileResponse\"/> instance for the requested static contents if it was found, otherwise <see langword=\"null\"/>.</returns>\r\n        public static Func<NancyContext, string, Response> AddDirectory(string requestedPath, string contentPath = null, params string[] allowedExtensions)\r\n        {\r\n            if (!requestedPath.StartsWith(\"/\"))\r\n            {\r\n                requestedPath = string.Concat(\"/\", requestedPath);\r\n            }\r\n\r\n            return (ctx, root) =>\r\n            {\r\n                var path =\r\n                    HttpUtility.UrlDecode(ctx.Request.Path);\r\n\r\n                var fileName = GetSafeFileName(path);\r\n\r\n                if (string.IsNullOrEmpty(fileName))\r\n                {\r\n                    return null;\r\n                }\r\n\r\n                var pathWithoutFilename =\r\n                    GetPathWithoutFilename(fileName, path);\r\n\r\n                if (!pathWithoutFilename.StartsWith(requestedPath, StringComparison.OrdinalIgnoreCase))\r\n                {\r\n                    (ctx.Trace.TraceLog ?? new NullLog()).WriteLog(x => x.AppendLine(string.Concat(\"[StaticContentConventionBuilder] The requested resource '\", path, \"' does not match convention mapped to '\", requestedPath, \"'\" )));\r\n                    return null;\r\n                }\r\n\r\n                contentPath =\r\n                    GetContentPath(requestedPath, contentPath);\r\n\r\n                if (contentPath.Equals(\"/\"))\r\n                {\r\n                    throw new ArgumentException(\"This is not the security vulnerability you are looking for. Mapping static content to the root of your application is not a good idea.\");\r\n                }\r\n\r\n                var responseFactory =\r\n                    ResponseFactoryCache.GetOrAdd(new ResponseFactoryCacheKey(path, root), BuildContentDelegate(ctx, root, requestedPath, contentPath, allowedExtensions));\r\n\r\n                return responseFactory.Invoke(ctx);\r\n            };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds a file-based convention for static convention.\r\n        /// </summary>\r\n        /// <param name=\"requestedFile\">The file that should be matched with the request.</param>\r\n        /// <param name=\"contentFile\">The file that should be served when the requested path is matched.</param>\r\n        public static Func<NancyContext, string, Response> AddFile(string requestedFile, string contentFile)\r\n        {\r\n            return (ctx, root) =>\r\n            {\r\n\r\n                var path =\r\n                    ctx.Request.Path;\r\n\r\n                if (!path.Equals(requestedFile, StringComparison.OrdinalIgnoreCase))\r\n                {\r\n                    ctx.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat(\"[StaticContentConventionBuilder] The requested resource '\", path, \"' does not match convention mapped to '\", requestedFile, \"'\")));\r\n                    return null;\r\n                }\r\n\r\n                var responseFactory =\r\n                    ResponseFactoryCache.GetOrAdd(new ResponseFactoryCacheKey(path, root), BuildContentDelegate(ctx, root, requestedFile, contentFile, ArrayCache.Empty<string>()));\r\n\r\n                return responseFactory.Invoke(ctx);\r\n            };\r\n        }\r\n\r\n        private static string GetSafeFileName(string path)\r\n        {\r\n            try\r\n            {\r\n                return Path.GetFileName(path);\r\n            }\r\n            catch (Exception)\r\n            {\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        private static string GetSafeFullPath(string path)\r\n        {\r\n            try\r\n            {\r\n                return Path.GetFullPath(path);\r\n            }\r\n            catch (Exception)\r\n            {\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        private static string GetContentPath(string requestedPath, string contentPath)\r\n        {\r\n            contentPath =\r\n                contentPath ?? requestedPath;\r\n\r\n            if (!contentPath.StartsWith(\"/\"))\r\n            {\r\n                contentPath = string.Concat(\"/\", contentPath);\r\n            }\r\n\r\n            return contentPath;\r\n        }\r\n\r\n        private static Func<ResponseFactoryCacheKey, Func<NancyContext, Response>> BuildContentDelegate(NancyContext context, string applicationRootPath, string requestedPath, string contentPath, string[] allowedExtensions)\r\n        {\r\n            return pathAndRootPair =>\r\n            {\r\n                context.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat(\"[StaticContentConventionBuilder] Attempting to resolve static content '\", pathAndRootPair, \"'\")));\r\n\r\n                var extension =\r\n                    Path.GetExtension(pathAndRootPair.Path);\r\n\r\n                if (!string.IsNullOrEmpty(extension))\r\n                {\r\n                    extension = extension.Substring(1);\r\n                }\r\n\r\n                if (allowedExtensions.Length != 0 && !allowedExtensions.Any(e => string.Equals(e.TrimStart(new [] {'.'}), extension, StringComparison.OrdinalIgnoreCase)))\r\n                {\r\n                    context.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat(\"[StaticContentConventionBuilder] The requested extension '\", extension, \"' does not match any of the valid extensions for the convention '\", string.Join(\",\", allowedExtensions), \"'\")));\r\n                    return ctx => null;\r\n                }\r\n\r\n                var transformedRequestPath =\r\n                    GetSafeRequestPath(pathAndRootPair.Path, requestedPath, contentPath);\r\n\r\n                transformedRequestPath =\r\n                    GetEncodedPath(transformedRequestPath);\r\n\r\n                var relativeFileName =\r\n                    Path.Combine(applicationRootPath, transformedRequestPath);\r\n\r\n                var fileName =\r\n                    GetSafeFullPath(relativeFileName);\r\n\r\n                if (fileName == null)\r\n                {\r\n                    context.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat(\"[StaticContentConventionBuilder] The request '\", relativeFileName, \"' contains an invalid path character\")));\r\n                    return ctx => null;\r\n                }\r\n\r\n                var relatveContentRootPath =\r\n                    Path.Combine(applicationRootPath, GetEncodedPath(contentPath));\r\n\r\n                var contentRootPath =\r\n                    GetSafeFullPath(relatveContentRootPath);\r\n\r\n                if (contentRootPath == null)\r\n                {\r\n                    context.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat(\"[StaticContentConventionBuilder] The request '\", fileName, \"' is trying to access a path inside the content folder, which contains an invalid path character '\", relatveContentRootPath, \"'\")));\r\n                    return ctx => null;\r\n                }\r\n\r\n                if (!IsWithinContentFolder(contentRootPath, fileName))\r\n                {\r\n                    context.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat(\"[StaticContentConventionBuilder] The request '\", fileName, \"' is trying to access a path outside the content folder '\", contentPath, \"'\")));\r\n                    return ctx => null;\r\n                }\r\n\r\n                if (!File.Exists(fileName))\r\n                {\r\n                    context.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat(\"[StaticContentConventionBuilder] The requested file '\", fileName, \"' does not exist\")));\r\n                    return ctx => null;\r\n                }\r\n\r\n                context.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat(\"[StaticContentConventionBuilder] Returning file '\", fileName, \"'\")));\r\n                return ctx => new GenericFileResponse(fileName, ctx);\r\n            };\r\n        }\r\n\r\n        private static string GetEncodedPath(string path)\r\n        {\r\n            return PathReplaceRegex.Replace(path.TrimStart(new[] { '/' }), Path.DirectorySeparatorChar.ToString());\r\n        }\r\n\r\n        private static string GetPathWithoutFilename(string fileName, string path)\r\n        {\r\n            var pathWithoutFileName =\r\n                path.Replace(fileName, string.Empty);\r\n\r\n            return (pathWithoutFileName.Equals(\"/\")) ?\r\n                pathWithoutFileName :\r\n                pathWithoutFileName.TrimEnd(new[] {'/'});\r\n        }\r\n\r\n        private static string GetSafeRequestPath(string requestPath, string requestedPath, string contentPath)\r\n        {\r\n            var actualContentPath =\r\n                (contentPath.Equals(\"/\") ? string.Empty : contentPath);\r\n\r\n            if (requestedPath.Equals(\"/\"))\r\n            {\r\n                return string.Concat(actualContentPath, requestPath);\r\n            }\r\n\r\n            var expression =\r\n                new Regex(Regex.Escape(requestedPath), RegexOptions.IgnoreCase);\r\n\r\n            return expression.Replace(requestPath, actualContentPath, 1);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns whether the given filename is contained within the content folder\r\n        /// </summary>\r\n        /// <param name=\"contentRootPath\">Content root path</param>\r\n        /// <param name=\"fileName\">Filename requested</param>\r\n        /// <returns>True if contained within the content root, false otherwise</returns>\r\n        private static bool IsWithinContentFolder(string contentRootPath, string fileName)\r\n        {\r\n            return fileName.StartsWith(contentRootPath, StringComparison.Ordinal);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Used to uniquely identify a request. Needed for when two Nancy applications want to serve up static content of the same\r\n        /// name from within the same AppDomain.\r\n        /// </summary>\r\n        private class ResponseFactoryCacheKey : IEquatable<ResponseFactoryCacheKey>\r\n        {\r\n            private readonly string path;\r\n            private readonly string rootPath;\r\n\r\n            public ResponseFactoryCacheKey(string path, string rootPath)\r\n            {\r\n                this.path = path;\r\n                this.rootPath = rootPath;\r\n            }\r\n\r\n            /// <summary>\r\n            /// The path of the static content for which this response is being issued\r\n            /// </summary>\r\n            public string Path\r\n            {\r\n                get { return this.path; }\r\n            }\r\n\r\n            /// <summary>\r\n            /// The root folder path of the Nancy application for which this response will be issued\r\n            /// </summary>\r\n            public string RootPath\r\n            {\r\n                get { return this.rootPath; }\r\n            }\r\n\r\n            public bool Equals(ResponseFactoryCacheKey other)\r\n            {\r\n                if (ReferenceEquals(null, other))\r\n                {\r\n                    return false;\r\n                }\r\n\r\n                if (ReferenceEquals(this, other))\r\n                {\r\n                    return true;\r\n                }\r\n\r\n                return string.Equals(this.path, other.path) && string.Equals(this.rootPath, other.rootPath);\r\n            }\r\n\r\n            public override bool Equals(object obj)\r\n            {\r\n                if (ReferenceEquals(null, obj))\r\n                {\r\n                    return false;\r\n                }\r\n\r\n                if (ReferenceEquals(this, obj))\r\n                {\r\n                    return true;\r\n                }\r\n\r\n                if (obj.GetType() != this.GetType())\r\n                {\r\n                    return false;\r\n                }\r\n\r\n                return Equals((ResponseFactoryCacheKey)obj);\r\n            }\r\n\r\n            public override int GetHashCode()\r\n            {\r\n                unchecked\r\n                {\r\n                    return ((this.path != null ? this.path.GetHashCode() : 0) * 397) ^ (this.rootPath != null ? this.rootPath.GetHashCode() : 0);\r\n                }\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Conventions/StaticContentHelper.cs",
    "content": "﻿namespace Nancy.Conventions\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Nancy static convention helper\r\n    /// </summary>\r\n    public static class StaticContentHelper\r\n    {\r\n        /// <summary>\r\n        /// Extension method for NancyConventions\r\n        /// <code>\r\n        /// conventions.MapStaticContent((File, Directory) =>\r\n        /// {\r\n        ///     File[\"/page.js\"] = \"page.js\";\r\n        ///     Directory[\"/images\"] = \"images\";\r\n        /// });\r\n        /// </code>\r\n        /// </summary>\r\n        /// <param name=\"conventions\">The conventions to add to.</param>\r\n        /// <param name=\"staticConventions\">The callback method allows you to describe the static content</param>\r\n        public static void MapStaticContent(this NancyConventions conventions, Action<StaticFileContent, StaticDirectoryContent> staticConventions)\r\n        {\r\n            staticConventions(new StaticFileContent(conventions), new StaticDirectoryContent(conventions));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Conventions/StaticContentsConventions.cs",
    "content": "namespace Nancy.Conventions\r\n{\r\n    using System;\r\n    using System.Collections;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Collection class for static content conventions\r\n    /// </summary>\r\n    public class StaticContentsConventions : IEnumerable<Func<NancyContext, string, Response>>\r\n    {\r\n        private readonly IEnumerable<Func<NancyContext, string, Response>> conventions;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"StaticContentsConventions\"/> class, with\r\n        /// the provided <paramref name=\"conventions\"/>.\r\n        /// </summary>\r\n        /// <param name=\"conventions\">The conventions.</param>\r\n        public StaticContentsConventions(IEnumerable<Func<NancyContext, string, Response>> conventions)\r\n        {\r\n            this.conventions = conventions;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an enumerator that iterates through the collection.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// An enumerator that can be used to iterate through the collection.\r\n        /// </returns>\r\n        public IEnumerator<Func<NancyContext, string, Response>> GetEnumerator()\r\n        {\r\n            return conventions.GetEnumerator();\r\n        }\r\n\r\n        IEnumerator IEnumerable.GetEnumerator()\r\n        {\r\n            return GetEnumerator();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Conventions/StaticContentsConventionsExtensions.cs",
    "content": "﻿namespace Nancy.Conventions\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Extension methods to adding static content conventions.\r\n    /// </summary>\r\n    public static class StaticContentsConventionsExtensions\r\n    {\r\n        /// <summary>\r\n        /// Adds a directory-based convention for static convention.\r\n        /// </summary>\r\n        /// <param name=\"conventions\">The conventions to add to.</param>\r\n        /// <param name=\"requestedPath\">The path that should be matched with the request.</param>\r\n        /// <param name=\"contentPath\">The path to where the content is stored in your application, relative to the root. If this is <see langword=\"null\" /> then it will be the same as <paramref name=\"requestedPath\"/>.</param>\r\n        /// <param name=\"allowedExtensions\">A list of extensions that is valid for the conventions. If not supplied, all extensions are valid.</param>\r\n        public static void AddDirectory(this IList<Func<NancyContext, string, Response>> conventions, string requestedPath, string contentPath = null, params string[] allowedExtensions)\r\n        {\r\n            conventions.Add(StaticContentConventionBuilder.AddDirectory(requestedPath, contentPath, allowedExtensions));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds a directory-based convention for static convention.\r\n        /// </summary>\r\n        /// <param name=\"conventions\">The conventions to add to.</param>\r\n        /// <param name=\"requestedFile\">The file that should be matched with the request.</param>\r\n        /// <param name=\"contentFile\">The file that should be served when the requested path is matched.</param>\r\n        public static void AddFile(this IList<Func<NancyContext, string, Response>> conventions, string requestedFile, string contentFile)\r\n        {\r\n            conventions.Add(StaticContentConventionBuilder.AddFile(requestedFile, contentFile));\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Conventions/StaticDirectoryContent.cs",
    "content": "﻿namespace Nancy.Conventions\r\n{\r\n    /// <summary>\r\n    /// Nancy static directory convention helper\r\n    /// </summary>\r\n    public class StaticDirectoryContent\r\n    {\r\n        private readonly NancyConventions conventions;\r\n\r\n        /// <summary>\r\n        /// Creates a new instance of StaticDirectoryContent\r\n        /// </summary>\r\n        /// <param name=\"conventions\">NancyConventions, to which static directories get added</param>\r\n        public StaticDirectoryContent(NancyConventions conventions)\r\n        {\r\n            this.conventions = conventions;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds a new static directory to the nancy conventions\r\n        /// </summary>\r\n        /// <param name=\"requestDirectory\">The route of the file</param>\r\n        /// <param name=\"allowedExtensions\">A list of extensions that is valid for the conventions. If not supplied, all extensions are valid</param>\r\n        public string this[string requestDirectory, params string[] allowedExtensions]\r\n        {\r\n            set\r\n            {\r\n                this.conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory(requestDirectory, value, allowedExtensions));\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Conventions/StaticFileContent.cs",
    "content": "﻿namespace Nancy.Conventions\r\n{\r\n    /// <summary>\r\n    /// Nancy static file convention helper\r\n    /// </summary>\r\n    public class StaticFileContent\r\n    {\r\n        private readonly NancyConventions conventions;\r\n\r\n        /// <summary>\r\n        /// Creates a new instance of StaticFileContent\r\n        /// </summary>\r\n        /// <param name=\"conventions\">NancyConventions, to which static files get added</param>\r\n        public StaticFileContent(NancyConventions conventions)\r\n        {\r\n            this.conventions = conventions;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds a new static file to the nancy conventions\r\n        /// </summary>\r\n        /// <param name=\"requestFile\">The route of the file</param>\r\n        public string this[string requestFile]\r\n        {\r\n            set\r\n            {\r\n                this.conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddFile(requestFile, value));\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Conventions/ViewLocationConventions.cs",
    "content": "﻿namespace Nancy.Conventions\r\n{\r\n    using System;\r\n    using System.Collections;\r\n    using System.Collections.Generic;\r\n\r\n    using Nancy.ViewEngines;\r\n\r\n    /// <summary>\r\n    /// This is a wrapper around the type\r\n    /// <c>IEnumerable&lt;Func&lt;string, object, ViewLocationContext, string&gt;&gt;</c> and its\r\n    /// only purpose is to make Ninject happy which was throwing an exception\r\n    /// when constructor injecting this type.\r\n    /// </summary>\r\n    public class ViewLocationConventions : IEnumerable<Func<string, object, ViewLocationContext, string>>\r\n    {\r\n        private readonly IEnumerable<Func<string, object, ViewLocationContext, string>> conventions;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ViewLocationConventions\"/> class, with\r\n        /// the provided <paramref name=\"conventions\"/>.\r\n        /// </summary>\r\n        /// <param name=\"conventions\">The conventions.</param>\r\n        public ViewLocationConventions(IEnumerable<Func<string, object, ViewLocationContext, string>> conventions)\r\n        {\r\n            this.conventions = conventions;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an enumerator that iterates through the collection.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// An enumerator that can be used to iterate through the collection.\r\n        /// </returns>\r\n        public IEnumerator<Func<string, object, ViewLocationContext, string>> GetEnumerator()\r\n        {\r\n            return conventions.GetEnumerator();\r\n        }\r\n\r\n        IEnumerator IEnumerable.GetEnumerator()\r\n        {\r\n            return GetEnumerator();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Cookies/INancyCookie.cs",
    "content": "namespace Nancy.Cookies\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality of a Nancy context\r\n    /// </summary>\r\n    public interface INancyCookie\r\n    {\r\n        /// <summary>\r\n        /// The domain to restrict the cookie to\r\n        /// </summary>\r\n        string Domain { get; set; }\r\n\r\n        /// <summary>\r\n        /// When the cookie should expire\r\n        /// </summary>\r\n        /// <value>A <see cref=\"DateTime\"/> instance containing the date and time when the cookie should expire; otherwise <see langword=\"null\"/> if it should expire at the end of the session.</value>\r\n        DateTime? Expires { get; set; }\r\n\r\n        /// <summary>\r\n        /// The name of the cookie\r\n        /// </summary>\r\n        string Name { get; }\r\n\r\n        /// <summary>\r\n        /// Gets the encoded name of the cookie\r\n        /// </summary>\r\n        string EncodedName { get; }\r\n\r\n        /// <summary>\r\n        /// The path to restrict the cookie to\r\n        /// </summary>\r\n        string Path { get; set; }\r\n\r\n        /// <summary>\r\n        /// The value of the cookie\r\n        /// </summary>\r\n        string Value { get; }\r\n\r\n        /// <summary>\r\n        /// Gets the encoded value of the cookie\r\n        /// </summary>\r\n        string EncodedValue { get; }\r\n\r\n        /// <summary>\r\n        /// Whether the cookie is http only\r\n        /// </summary>\r\n        bool HttpOnly { get; }\r\n\r\n        /// <summary>\r\n        /// Whether the cookie is secure (i.e. HTTPS only)\r\n        /// </summary>\r\n        bool Secure { get; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Cookies/NancyCookie.cs",
    "content": "namespace Nancy.Cookies\r\n{\r\n    using System;\r\n    using System.Globalization;\r\n    using System.Text;\r\n\r\n    using Nancy.Helpers;\r\n\r\n    /// <summary>\r\n    /// Default cookie implementation for Nancy.\r\n    /// </summary>\r\n    public class NancyCookie : INancyCookie\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancyCookie\"/> class, with\r\n        /// the provided <paramref name=\"name\"/> and <paramref name=\"value\"/>.\r\n        /// </summary>\r\n        /// <param name=\"name\">The name of the cookie.</param>\r\n        /// <param name=\"value\">The value of the cookie.</param>\r\n        public NancyCookie(string name, string value)\r\n            : this(name, value, false)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancyCookie\"/> class, with\r\n        /// the provided <paramref name=\"name\"/>, <paramref name=\"value\"/> and  <paramref name=\"expires\"/>.\r\n        /// </summary>\r\n        /// <param name=\"name\">The name of the cookie.</param>\r\n        /// <param name=\"value\">The value of the cookie.</param>\r\n        /// <param name=\"expires\">The expiration date of the cookie. Can be <see langword=\"null\" /> if it should expire at the end of the session.</param>\r\n        public NancyCookie(string name, string value, DateTime expires)\r\n            : this(name, value, false, false, expires)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancyCookie\"/> class, with\r\n        /// the provided <paramref name=\"name\"/>, <paramref name=\"value\"/> and  <paramref name=\"httpOnly\"/>.\r\n        /// </summary>\r\n        /// <param name=\"name\">The name of the cookie.</param>\r\n        /// <param name=\"value\">The value of the cookie.</param>\r\n        /// <param name=\"httpOnly\">Whether the cookie is http only.</param>\r\n        public NancyCookie(string name, string value, bool httpOnly)\r\n            : this(name, value, httpOnly, false, null)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancyCookie\"/> class, with\r\n        /// the provided <paramref name=\"name\"/>, <paramref name=\"value\"/>, <paramref name=\"httpOnly\"/> and <paramref name=\"secure\"/>.\r\n        /// </summary>\r\n        /// <param name=\"name\">The name of the cookie.</param>\r\n        /// <param name=\"value\">The value of the cookie.</param>\r\n        /// <param name=\"httpOnly\">Whether the cookie is http only.</param>\r\n        /// <param name=\"secure\">Whether the cookie is secure (i.e. HTTPS only).</param>\r\n        public NancyCookie(string name, string value, bool httpOnly, bool secure)\r\n            : this(name, value, httpOnly, secure, null)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancyCookie\"/> class, with\r\n        /// the provided <paramref name=\"name\"/>, <paramref name=\"value\"/>, <paramref name=\"httpOnly\"/>, <paramref name=\"secure\"/> and  <paramref name=\"expires\"/>.\r\n        /// </summary>\r\n        /// <param name=\"name\">The name of the cookie.</param>\r\n        /// <param name=\"value\">The value of the cookie.</param>\r\n        /// <param name=\"httpOnly\">Whether the cookie is http only.</param>\r\n        /// <param name=\"secure\">Whether the cookie is secure (i.e. HTTPS only).</param>\r\n        /// <param name=\"expires\">The expiration date of the cookie. Can be <see langword=\"null\" /> if it should expire at the end of the session.</param>\r\n        public NancyCookie(string name, string value, bool httpOnly, bool secure, DateTime? expires)\r\n        {\r\n            this.Name = name;\r\n            this.Value = value;\r\n            this.HttpOnly = httpOnly;\r\n            this.Secure = secure;\r\n            this.Expires = expires;\r\n        }\r\n\r\n        /// <summary>\r\n        /// The domain to restrict the cookie to\r\n        /// </summary>\r\n        public string Domain { get; set; }\r\n\r\n        /// <summary>\r\n        /// When the cookie should expire\r\n        /// </summary>\r\n        /// <value>A <see cref=\"DateTime\"/> instance containing the date and time when the cookie should expire; otherwise <see langword=\"null\"/> if it should expire at the end of the session.</value>\r\n        public DateTime? Expires { get; set; }\r\n\r\n        /// <summary>\r\n        /// The name of the cookie\r\n        /// </summary>\r\n        public string Name { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the encoded name of the cookie\r\n        /// </summary>\r\n        public string EncodedName\r\n        {\r\n            get\r\n            {\r\n                return HttpUtility.UrlEncode(this.Name);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// The path to restrict the cookie to\r\n        /// </summary>\r\n        public string Path { get; set; }\r\n\r\n        /// <summary>\r\n        /// The value of the cookie\r\n        /// </summary>\r\n        public string Value { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the encoded value of the cookie\r\n        /// </summary>\r\n        public string EncodedValue\r\n        {\r\n            get\r\n            {\r\n                return HttpUtility.UrlEncode(this.Value);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Whether the cookie is http only\r\n        /// </summary>\r\n        public bool HttpOnly { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Whether the cookie is secure (i.e. HTTPS only)\r\n        /// </summary>\r\n        public bool Secure { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Returns a <see cref=\"System.String\" /> that represents this instance.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// A <see cref=\"System.String\" /> that represents this instance.\r\n        /// </returns>\r\n        public override string ToString()\r\n        {\r\n            var sb = new StringBuilder(50);\r\n            sb.AppendFormat(\"{0}={1}; path={2}\", this.EncodedName, this.EncodedValue, Path ?? \"/\");\r\n\r\n            if (Expires != null)\r\n            {\r\n                sb.Append(\"; expires=\");\r\n                sb.Append(Expires.Value.ToUniversalTime().ToString(\"ddd, dd-MMM-yyyy HH:mm:ss\", DateTimeFormatInfo.InvariantInfo));\r\n                sb.Append(\" GMT\");\r\n            }\r\n\r\n            if (Domain != null)\r\n            {\r\n                sb.Append(\"; domain=\");\r\n                sb.Append(Domain);\r\n            }\r\n\r\n            if (Secure)\r\n            {\r\n                sb.Append(\"; Secure\");\r\n            }\r\n\r\n            if (HttpOnly)\r\n            {\r\n                sb.Append(\"; HttpOnly\");\r\n            }\r\n\r\n            return sb.ToString();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Cryptography/AesEncryptionProvider.cs",
    "content": "namespace Nancy.Cryptography\r\n{\r\n    using System;\r\n    using System.Security.Cryptography;\r\n    using System.Text;\r\n\r\n    /// <summary>\r\n    /// Default encryption provider using Aes\r\n    /// </summary>\r\n    public class AesEncryptionProvider : IEncryptionProvider\r\n    {\r\n        private readonly byte[] key;\r\n\r\n        private readonly byte[] iv;\r\n\r\n        /// <summary>\r\n        /// Creates a new instance of the AesEncryptionProvider class\r\n        /// </summary>\r\n        /// <param name=\"keyGenerator\">Key generator to use to generate the key and iv</param>\r\n        public AesEncryptionProvider(IKeyGenerator keyGenerator)\r\n        {\r\n            this.key = keyGenerator.GetBytes(32);\r\n            this.iv = keyGenerator.GetBytes(16);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Encrypt data\r\n        /// </summary>\r\n        /// <param name=\"data\">Data to encrypt</param>\r\n        /// <returns>Encrypted string</returns>\r\n        public string Encrypt(string data)\r\n        {\r\n            using (var provider = Aes.Create())\r\n            using (var encryptor = provider.CreateEncryptor(this.key, this.iv))\r\n            {\r\n                var input = Encoding.UTF8.GetBytes(data);\r\n                var output = encryptor.TransformFinalBlock(input, 0, input.Length);\r\n\r\n                return Convert.ToBase64String(output);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Decrypt string\r\n        /// </summary>\r\n        /// <param name=\"data\">Data to decrypt</param>\r\n        /// <returns>Decrypted string</returns>\r\n        public string Decrypt(string data)\r\n        {\r\n            try\r\n            {\r\n                using (var provider = Aes.Create())\r\n                using (var decryptor = provider.CreateDecryptor(this.key, this.iv))\r\n                {\r\n                    var input = Convert.FromBase64String(data);\r\n                    var output = decryptor.TransformFinalBlock(input, 0, input.Length);\r\n\r\n                    return Encoding.UTF8.GetString(output);\r\n                }\r\n            }\r\n            catch (FormatException)\r\n            {\r\n                return String.Empty;\r\n            }\r\n            catch (CryptographicException)\r\n            {\r\n                return String.Empty;\r\n            }\r\n            catch(ArgumentException ex)\r\n            {\r\n                if (ex.ParamName == null)\r\n                {\r\n                    return String.Empty;\r\n                }\r\n                throw;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Cryptography/Base64Helpers.cs",
    "content": "namespace Nancy.Cryptography\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Helper class for base64 encoding related tasks.\r\n    /// </summary>\r\n    public static class Base64Helpers\r\n    {\r\n        /// <summary>\r\n        /// Calculates how long a byte array of X length will be after base64 encoding\r\n        /// </summary>\r\n        /// <param name=\"normalLength\">The normal, 8bit per byte, length of the byte array</param>\r\n        /// <returns>Base64 encoded length</returns>\r\n        public static int GetBase64Length(int normalLength)\r\n        {\r\n            var inputPadding = (normalLength % 3 != 0) ? (3 - (normalLength % 3)) : 0;\r\n\r\n            return (int)Math.Ceiling((normalLength + inputPadding) * 4.0 / 3.0);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Cryptography/CryptographyConfiguration.cs",
    "content": "﻿namespace Nancy.Cryptography\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Cryptographic setup for classes that use encryption and HMAC\r\n    /// </summary>\r\n    public class CryptographyConfiguration\r\n    {\r\n        private static readonly Lazy<CryptographyConfiguration> DefaultConfiguration =\r\n            new Lazy<CryptographyConfiguration>(() => new CryptographyConfiguration(\r\n                                                          new AesEncryptionProvider(new RandomKeyGenerator()),\r\n                                                          new DefaultHmacProvider(new RandomKeyGenerator())));\r\n\r\n        private static readonly Lazy<CryptographyConfiguration> NoEncryptionConfiguration =\r\n            new Lazy<CryptographyConfiguration>(() => new CryptographyConfiguration(\r\n                                                          new NoEncryptionProvider(),\r\n                                                          new DefaultHmacProvider(new RandomKeyGenerator())));\r\n\r\n        /// <summary>\r\n        /// Creates a new instance of the CryptographyConfiguration class\r\n        /// </summary>\r\n        /// <param name=\"encryptionProvider\">Encryption provider</param>\r\n        /// <param name=\"hmacProvider\">HMAC provider</param>\r\n        public CryptographyConfiguration(IEncryptionProvider encryptionProvider, IHmacProvider hmacProvider)\r\n        {\r\n            this.EncryptionProvider = encryptionProvider;\r\n            this.HmacProvider = hmacProvider;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the default configuration - Rijndael encryption, HMACSHA256 HMAC, random keys\r\n        /// </summary>\r\n        public static CryptographyConfiguration Default\r\n        {\r\n            get { return DefaultConfiguration.Value; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets configuration with no encryption and HMACSHA256 HMAC with a random key\r\n        /// </summary>\r\n        public static CryptographyConfiguration NoEncryption\r\n        {\r\n            get { return NoEncryptionConfiguration.Value; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the encryption provider\r\n        /// </summary>\r\n        public IEncryptionProvider EncryptionProvider { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the hmac provider\r\n        /// </summary>\r\n        public IHmacProvider HmacProvider { get; private set; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Cryptography/DefaultHmacProvider.cs",
    "content": "namespace Nancy.Cryptography\r\n{\r\n    using System.Security.Cryptography;\r\n    using System.Text;\r\n\r\n    /// <summary>\r\n    /// Provides SHA-256 HMACs\r\n    /// </summary>\r\n    public class DefaultHmacProvider : IHmacProvider\r\n    {\r\n        /// <summary>\r\n        /// HMAC length\r\n        /// </summary>\r\n        private readonly int hmacLength = new HMACSHA256().HashSize / 8;\r\n\r\n        /// <summary>\r\n        /// Preferred key size for HMACSHA256\r\n        /// </summary>\r\n        private const int PreferredKeySize = 64;\r\n\r\n        /// <summary>\r\n        /// Key\r\n        /// </summary>\r\n        private readonly byte[] key;\r\n\r\n        /// <summary>\r\n        /// Creates a new instance of the DefaultHmacProvider type\r\n        /// </summary>\r\n        /// <param name=\"keyGenerator\">Key generator to use to generate the key</param>\r\n        public DefaultHmacProvider(IKeyGenerator keyGenerator)\r\n        {\r\n            this.key = keyGenerator.GetBytes(PreferredKeySize);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the length of the HMAC signature\r\n        /// </summary>\r\n        public int HmacLength\r\n        {\r\n            get { return this.hmacLength; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Create a hmac from the given data using the given passPhrase\r\n        /// </summary>\r\n        /// <param name=\"data\">Data to create hmac from</param>\r\n        /// <returns>String representation of the hmac</returns>\r\n        public byte[] GenerateHmac(string data)\r\n        {\r\n            return this.GenerateHmac(Encoding.UTF8.GetBytes(data));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Create a hmac from the given data\r\n        /// </summary>\r\n        /// <param name=\"data\">Data to create hmac from</param>\r\n        /// <returns>Hmac bytes</returns>\r\n        public byte[] GenerateHmac(byte[] data)\r\n        {\r\n            using (var hmacGenerator = new HMACSHA256(this.key))\r\n            {\r\n                return hmacGenerator.ComputeHash(data);\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Cryptography/HmacComparer.cs",
    "content": "namespace Nancy.Cryptography\r\n{\r\n    using System;\r\n    using System.Runtime.CompilerServices;\r\n\r\n    /// <summary>\r\n    /// Compares two HMAC\r\n    /// </summary>\r\n    public static class HmacComparer\r\n    {\r\n        /// <summary>\r\n        /// Compare two hmac byte arrays without any early exits\r\n        /// </summary>\r\n        /// <param name=\"hmac1\">First hmac</param>\r\n        /// <param name=\"hmac2\">Second hmac</param>\r\n        /// <param name=\"hashLength\">Expected length of the hash</param>\r\n        /// <returns>True if equal, false otherwise</returns>\r\n        [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]\r\n        public static bool Compare(byte[] hmac1, byte[] hmac2, int hashLength)\r\n        {\r\n            var hasResized = false;\r\n\r\n            if (hmac1.Length != hashLength)\r\n            {\r\n                Array.Resize(ref hmac1, hashLength);\r\n                hasResized = true;\r\n            }\r\n\r\n            if (hmac2.Length != hashLength)\r\n            {\r\n                Array.Resize(ref hmac2, hashLength);\r\n                hasResized = true;\r\n            }\r\n\r\n            var isValid = true;\r\n            for (int i = 0; i < hashLength; i++)\r\n            {\r\n                if (hmac1[i] != hmac2[i])\r\n                {\r\n                    isValid = false;\r\n                }\r\n            }\r\n\r\n            return hasResized ? false : isValid;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Cryptography/IEncryptionProvider.cs",
    "content": "namespace Nancy.Cryptography\r\n{\r\n    /// <summary>\r\n    /// Provides symmetrical encryption support\r\n    /// </summary>\r\n    public interface IEncryptionProvider\r\n    {\r\n        /// <summary>\r\n        /// Encrypt and base64 encode the string\r\n        /// </summary>\r\n        /// <param name=\"data\">Data to encrypt</param>\r\n        /// <returns>Encrypted string</returns>\r\n        string Encrypt(string data);\r\n\r\n        /// <summary>\r\n        /// Decrypt string\r\n        /// </summary>\r\n        /// <param name=\"data\">Data to decrypt</param>\r\n        /// <returns>Decrypted string</returns>\r\n        string Decrypt(string data);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Cryptography/IHmacProvider.cs",
    "content": "namespace Nancy.Cryptography\r\n{\r\n    /// <summary>\r\n    /// Creates Hash-based Message Authentication Codes (HMACs)\r\n    /// </summary>\r\n    public interface IHmacProvider\r\n    {\r\n        /// <summary>\r\n        /// Gets the length of the HMAC signature in bytes\r\n        /// </summary>\r\n        int HmacLength { get; }\r\n\r\n        /// <summary>\r\n        /// Create a hmac from the given data\r\n        /// </summary>\r\n        /// <param name=\"data\">Data to create hmac from</param>\r\n        /// <returns>Hmac bytes</returns>\r\n        byte[] GenerateHmac(string data);\r\n\r\n        /// <summary>\r\n        /// Create a hmac from the given data\r\n        /// </summary>\r\n        /// <param name=\"data\">Data to create hmac from</param>\r\n        /// <returns>Hmac bytes</returns>\r\n        byte[] GenerateHmac(byte[] data);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Cryptography/IKeyGenerator.cs",
    "content": "namespace Nancy.Cryptography\r\n{\r\n    /// <summary>\r\n    /// Provides key byte generation\r\n    /// </summary>\r\n    public interface IKeyGenerator\r\n    {\r\n        /// <summary>\r\n        /// Generate a sequence of bytes\r\n        /// </summary>\r\n        /// <param name=\"count\">Number of bytes to return</param>\r\n        /// <returns>Array <see paramref=\"count\"/> bytes</returns>\r\n        byte[] GetBytes(int count);\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Cryptography/NoEncryptionProvider.cs",
    "content": "namespace Nancy.Cryptography\r\n{\r\n    using System;\r\n    using System.Text;\r\n\r\n    /// <summary>\r\n    /// A \"no op\" encryption provider\r\n    /// Useful for debugging or performance.\r\n    /// </summary>\r\n    public class NoEncryptionProvider : IEncryptionProvider\r\n    {\r\n        /// <summary>\r\n        /// Encrypt data\r\n        /// </summary>\r\n        /// <param name=\"data\">Data to encrypt</param>\r\n        /// <returns>Encrypted string</returns>\r\n        public string Encrypt(string data)\r\n        {\r\n            return Convert.ToBase64String(Encoding.UTF8.GetBytes(data));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Decrypt string\r\n        /// </summary>\r\n        /// <param name=\"data\">Data to decrypt</param>\r\n        /// <returns>Decrypted string</returns>\r\n        public string Decrypt(string data)\r\n        {\r\n            return Encoding.UTF8.GetString(Convert.FromBase64String(data));\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Cryptography/PassphraseKeyGenerator.cs",
    "content": "﻿namespace Nancy.Cryptography\r\n{\r\n    using System;\r\n    using System.Security.Cryptography;\r\n\r\n    /// <summary>\r\n    /// Provides key generation using PBKDF2 / Rfc2898\r\n    /// NOTE: the salt is static so the passphrase should be long and complex\r\n    /// (As the bytes are generated at app startup, because it's too slow to do per\r\n    /// request, so the salt cannot be randomly generated and stored)\r\n    /// </summary>\r\n    public class PassphraseKeyGenerator : IKeyGenerator\r\n    {\r\n        private readonly Rfc2898DeriveBytes provider;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"PassphraseKeyGenerator\"/> class, with\r\n        /// the provided <paramref name=\"passphrase\"/>, <paramref name=\"salt\"/> and optional\r\n        /// number of <paramref name=\"iterations\"/>\r\n        /// </summary>\r\n        /// <param name=\"passphrase\">The passphrase that should be used.</param>\r\n        /// <param name=\"salt\">The salt</param>\r\n        /// <param name=\"iterations\">The number of iterations. The default value is 10000.</param>\r\n        public PassphraseKeyGenerator(string passphrase, byte[] salt, int iterations = 10000)\r\n        {\r\n            if (salt.Length < 8)\r\n            {\r\n                throw new ArgumentOutOfRangeException(\"salt\", \"salt must be at least 8 bytes in length\");\r\n            }\r\n\r\n            this.provider = new Rfc2898DeriveBytes(passphrase, salt, iterations);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Generate a sequence of bytes\r\n        /// </summary>\r\n        /// <param name=\"count\">Number of bytes to return</param>\r\n        /// <returns>Array <see paramref=\"count\"/> bytes</returns>\r\n        public byte[] GetBytes(int count)\r\n        {\r\n            return provider.GetBytes(count);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Cryptography/RandomKeyGenerator.cs",
    "content": "namespace Nancy.Cryptography\r\n{\r\n    using System.Security.Cryptography;\r\n\r\n    /// <summary>\r\n    /// Generates random secure keys using RandomNumberGenerator\r\n    /// </summary>\r\n    public class RandomKeyGenerator : IKeyGenerator\r\n    {\r\n        private readonly RandomNumberGenerator provider = RandomNumberGenerator.Create();\r\n\r\n        /// <summary>\r\n        /// Generate a sequence of bytes\r\n        /// </summary>\r\n        /// <param name=\"count\">Number of bytes to return</param>\r\n        /// <returns>\r\n        /// Array <see paramref=\"count\" /> bytes\r\n        /// </returns>\r\n        public byte[] GetBytes(int count)\r\n        {\r\n            var buffer = new byte[count];\r\n\r\n            this.provider.GetBytes(buffer);\r\n\r\n            return buffer;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Culture/DefaultCultureService.cs",
    "content": "﻿namespace Nancy.Culture\r\n{\r\n    using System.Globalization;\r\n    using Nancy.Configuration;\r\n    using Nancy.Conventions;\r\n\r\n    /// <summary>\r\n    /// Determines current culture for context\r\n    /// </summary>\r\n    public class DefaultCultureService : ICultureService\r\n    {\r\n        private readonly CultureConventions cultureConventions;\r\n        private readonly GlobalizationConfiguration configuration;\r\n\r\n        /// <summary>\r\n        /// Creates a new instance of DefaultCultureService\r\n        /// </summary>\r\n        /// <param name=\"cultureConventions\">CultureConventions to use for determining culture</param>\r\n        /// <param name=\"environment\">An instance of <see cref=\"INancyEnvironment\"/> to retrieve <see cref=\"GlobalizationConfiguration\"/> from.</param>\r\n        public DefaultCultureService(CultureConventions cultureConventions, INancyEnvironment environment)\r\n        {\r\n            this.cultureConventions = cultureConventions;\r\n            this.configuration = environment.GetValue<GlobalizationConfiguration>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determine current culture for NancyContext\r\n        /// </summary>\r\n        /// <param name=\"context\">NancyContext</param>\r\n        /// <returns>CultureInfo</returns>\r\n        public CultureInfo DetermineCurrentCulture(NancyContext context)\r\n        {\r\n            CultureInfo culture = null;\r\n\r\n            foreach (var convention in this.cultureConventions)\r\n            {\r\n                culture = convention(context, this.configuration);\r\n                if (culture != null)\r\n                {\r\n                    break;\r\n                }\r\n            }\r\n\r\n            return culture;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Culture/ICultureService.cs",
    "content": "﻿namespace Nancy.Culture\r\n{\r\n    using System.Globalization;\r\n\r\n    /// <summary>\r\n    /// Provides current culture for Nancy context\r\n    /// </summary>\r\n    public interface ICultureService\r\n    {\r\n        /// <summary>\r\n        /// Determine current culture for NancyContext\r\n        /// </summary>\r\n        /// <param name=\"context\">NancyContext</param>\r\n        /// <returns>CultureInfo</returns>\r\n        CultureInfo DetermineCurrentCulture(NancyContext context);\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/DefaultGlobalizationConfigurationProvider.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using Nancy.Configuration;\r\n\r\n    /// <summary>\r\n    /// Provides the default <see cref=\"GlobalizationConfiguration\"/>.\r\n    /// </summary>\r\n    public class DefaultGlobalizationConfigurationProvider : NancyDefaultConfigurationProvider<GlobalizationConfiguration>\r\n    {\r\n        /// <summary>\r\n        /// Gets the default <see cref=\"GlobalizationConfiguration\"/> configuration instance to register in the <see cref=\"INancyEnvironment\"/> .\r\n        /// </summary>\r\n        /// <returns>The configuration instance</returns>\r\n        public override GlobalizationConfiguration GetDefaultConfiguration()\r\n        {\r\n            return GlobalizationConfiguration.Default;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/DefaultNancyBootstrapper.cs",
    "content": "namespace Nancy\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Configuration;\r\n    using Nancy.Diagnostics;\r\n    using Nancy.TinyIoc;\r\n    using Extensions;\r\n    /// <summary>\r\n    /// TinyIoC bootstrapper - registers default route resolver and registers itself as\r\n    /// INancyModuleCatalog for resolving modules but behavior can be overridden if required.\r\n    /// </summary>\r\n    public class DefaultNancyBootstrapper : NancyBootstrapperWithRequestContainerBase<TinyIoCContainer>\r\n    {\r\n        /// <summary>\r\n        /// Default assemblies that are ignored for autoregister\r\n        /// </summary>\r\n        public static IEnumerable<Func<Assembly, bool>> DefaultAutoRegisterIgnoredAssemblies = new Func<Assembly, bool>[]\r\n            {\r\n                asm => asm.FullName.StartsWith(\"Microsoft.\", StringComparison.Ordinal),\r\n                asm => asm.FullName.StartsWith(\"System.\", StringComparison.Ordinal),\r\n                asm => asm.FullName.StartsWith(\"System,\", StringComparison.Ordinal),\r\n                asm => asm.FullName.StartsWith(\"CR_ExtUnitTest\", StringComparison.Ordinal),\r\n                asm => asm.FullName.StartsWith(\"mscorlib,\", StringComparison.Ordinal),\r\n                asm => asm.FullName.StartsWith(\"CR_VSTest\", StringComparison.Ordinal),\r\n                asm => asm.FullName.StartsWith(\"DevExpress.CodeRush\", StringComparison.Ordinal),\r\n                asm => asm.FullName.StartsWith(\"IronPython\", StringComparison.Ordinal),\r\n                asm => asm.FullName.StartsWith(\"IronRuby\", StringComparison.Ordinal),\r\n                asm => asm.FullName.StartsWith(\"xunit\", StringComparison.Ordinal),\r\n                asm => asm.FullName.StartsWith(\"Nancy.Testing\", StringComparison.Ordinal),\r\n                asm => asm.FullName.StartsWith(\"MonoDevelop.NUnit\", StringComparison.Ordinal),\r\n                asm => asm.FullName.StartsWith(\"SMDiagnostics\", StringComparison.Ordinal),\r\n                asm => asm.FullName.StartsWith(\"CppCodeProvider\", StringComparison.Ordinal),\r\n                asm => asm.FullName.StartsWith(\"WebDev.WebHost40\", StringComparison.Ordinal),\r\n                asm => asm.FullName.StartsWith(\"nunit\", StringComparison.Ordinal),\r\n                asm => asm.FullName.StartsWith(\"nCrunch\", StringComparison.Ordinal),\r\n            };\r\n\r\n        /// <summary>\r\n        /// Gets the assemblies to ignore when autoregistering the application container\r\n        /// Return true from the delegate to ignore that particular assembly, returning false\r\n        /// does not mean the assembly *will* be included, a true from another delegate will\r\n        /// take precedence.\r\n        /// </summary>\r\n        protected virtual IEnumerable<Func<Assembly, bool>> AutoRegisterIgnoredAssemblies\r\n        {\r\n            get { return DefaultAutoRegisterIgnoredAssemblies; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Configures the container using AutoRegister followed by registration\r\n        /// of default INancyModuleCatalog and IRouteResolver.\r\n        /// </summary>\r\n        /// <param name=\"container\">Container instance</param>\r\n        protected override void ConfigureApplicationContainer(TinyIoCContainer container)\r\n        {\r\n            AutoRegister(container, this.AutoRegisterIgnoredAssemblies);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Resolve INancyEngine\r\n        /// </summary>\r\n        /// <returns>INancyEngine implementation</returns>\r\n        protected override sealed INancyEngine GetEngineInternal()\r\n        {\r\n            return this.ApplicationContainer.Resolve<INancyEngine>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Create a default, unconfigured, container\r\n        /// </summary>\r\n        /// <returns>Container instance</returns>\r\n        protected override TinyIoCContainer GetApplicationContainer()\r\n        {\r\n            return new TinyIoCContainer();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Registers an <see cref=\"INancyEnvironment\"/> instance in the container.\r\n        /// </summary>\r\n        /// <param name=\"container\">The container to register into.</param>\r\n        /// <param name=\"environment\">The <see cref=\"INancyEnvironment\"/> instance to register.</param>\r\n        protected override void RegisterNancyEnvironment(TinyIoCContainer container, INancyEnvironment environment)\r\n        {\r\n            container.Register(environment);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Register the bootstrapper's implemented types into the container.\r\n        /// This is necessary so a user can pass in a populated container but not have\r\n        /// to take the responsibility of registering things like INancyModuleCatalog manually.\r\n        /// </summary>\r\n        /// <param name=\"applicationContainer\">Application container to register into</param>\r\n        protected override sealed void RegisterBootstrapperTypes(TinyIoCContainer applicationContainer)\r\n        {\r\n            applicationContainer.Register<INancyModuleCatalog>(this);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Register the default implementations of internally used types into the container as singletons\r\n        /// </summary>\r\n        /// <param name=\"container\">Container to register into</param>\r\n        /// <param name=\"typeRegistrations\">Type registrations to register</param>\r\n        protected override sealed void RegisterTypes(TinyIoCContainer container, IEnumerable<TypeRegistration> typeRegistrations)\r\n        {\r\n            foreach (var typeRegistration in typeRegistrations)\r\n            {\r\n                switch (typeRegistration.Lifetime)\r\n                {\r\n                    case Lifetime.Transient:\r\n                        container.Register(typeRegistration.RegistrationType, typeRegistration.ImplementationType).AsMultiInstance();\r\n                        break;\r\n                    case Lifetime.Singleton:\r\n                        container.Register(typeRegistration.RegistrationType, typeRegistration.ImplementationType).AsSingleton();\r\n                        break;\r\n                    case Lifetime.PerRequest:\r\n                        throw new InvalidOperationException(\"Unable to directly register a per request lifetime.\");\r\n                    default:\r\n                        throw new ArgumentOutOfRangeException();\r\n                }\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Register the various collections into the container as singletons to later be resolved\r\n        /// by IEnumerable{Type} constructor dependencies.\r\n        /// </summary>\r\n        /// <param name=\"container\">Container to register into</param>\r\n        /// <param name=\"collectionTypeRegistrations\">Collection type registrations to register</param>\r\n        protected override sealed void RegisterCollectionTypes(TinyIoCContainer container, IEnumerable<CollectionTypeRegistration> collectionTypeRegistrations)\r\n        {\r\n            foreach (var collectionTypeRegistration in collectionTypeRegistrations)\r\n            {\r\n                switch (collectionTypeRegistration.Lifetime)\r\n                {\r\n                    case Lifetime.Transient:\r\n                        container.RegisterMultiple(collectionTypeRegistration.RegistrationType, collectionTypeRegistration.ImplementationTypes).AsMultiInstance();\r\n                        break;\r\n                    case Lifetime.Singleton:\r\n                        container.RegisterMultiple(collectionTypeRegistration.RegistrationType, collectionTypeRegistration.ImplementationTypes).AsSingleton();\r\n                        break;\r\n                    case Lifetime.PerRequest:\r\n                        throw new InvalidOperationException(\"Unable to directly register a per request lifetime.\");\r\n                    default:\r\n                        throw new ArgumentOutOfRangeException();\r\n                }\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Register the given module types into the container\r\n        /// </summary>\r\n        /// <param name=\"container\">Container to register into</param>\r\n        /// <param name=\"moduleRegistrationTypes\">NancyModule types</param>\r\n        protected override sealed void RegisterRequestContainerModules(TinyIoCContainer container, IEnumerable<ModuleRegistration> moduleRegistrationTypes)\r\n        {\r\n            foreach (var moduleRegistrationType in moduleRegistrationTypes)\r\n            {\r\n                container.Register(\r\n                    typeof(INancyModule),\r\n                    moduleRegistrationType.ModuleType,\r\n                    moduleRegistrationType.ModuleType.FullName).\r\n                    AsSingleton();\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Register the given instances into the container\r\n        /// </summary>\r\n        /// <param name=\"container\">Container to register into</param>\r\n        /// <param name=\"instanceRegistrations\">Instance registration types</param>\r\n        protected override void RegisterInstances(TinyIoCContainer container, IEnumerable<InstanceRegistration> instanceRegistrations)\r\n        {\r\n            foreach (var instanceRegistration in instanceRegistrations)\r\n            {\r\n                container.Register(\r\n                    instanceRegistration.RegistrationType,\r\n                    instanceRegistration.Implementation);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a per request child/nested container\r\n        /// </summary>\r\n        /// <param name=\"context\">Current context</param>\r\n        /// <returns>Request container instance</returns>\r\n        protected override TinyIoCContainer CreateRequestContainer(NancyContext context)\r\n        {\r\n            return this.ApplicationContainer.GetChildContainer();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"INancyEnvironmentConfigurator\"/> used by th.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"INancyEnvironmentConfigurator\"/> instance.</returns>\r\n        protected override INancyEnvironmentConfigurator GetEnvironmentConfigurator()\r\n        {\r\n            return this.ApplicationContainer.Resolve<INancyEnvironmentConfigurator>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the diagnostics for initialization\r\n        /// </summary>\r\n        /// <returns>IDiagnostics implementation</returns>\r\n        protected override IDiagnostics GetDiagnostics()\r\n        {\r\n            return this.ApplicationContainer.Resolve<IDiagnostics>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all registered startup tasks\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance containing <see cref=\"IApplicationStartup\"/> instances. </returns>\r\n        protected override IEnumerable<IApplicationStartup> GetApplicationStartupTasks()\r\n        {\r\n            return this.ApplicationContainer.ResolveAll<IApplicationStartup>(false);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all registered request startup tasks\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance containing <see cref=\"IRequestStartup\"/> instances.</returns>\r\n        protected override IEnumerable<IRequestStartup> RegisterAndGetRequestStartupTasks(TinyIoCContainer container, Type[] requestStartupTypes)\r\n        {\r\n            container.RegisterMultiple(typeof(IRequestStartup), requestStartupTypes);\r\n\r\n            return container.ResolveAll<IRequestStartup>(false);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all registered application registration tasks\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance containing <see cref=\"IRegistrations\"/> instances.</returns>\r\n        protected override IEnumerable<IRegistrations> GetRegistrationTasks()\r\n        {\r\n            return this.ApplicationContainer.ResolveAll<IRegistrations>(false);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the <see cref=\"INancyEnvironment\"/> instance.\r\n        /// </summary>\r\n        /// <returns>An configured <see cref=\"INancyEnvironment\"/> instance.</returns>\r\n        /// <remarks>The boostrapper must be initialised (<see cref=\"INancyBootstrapper.Initialise\"/>) prior to calling this.</remarks>\r\n        public override INancyEnvironment GetEnvironment()\r\n        {\r\n            return this.ApplicationContainer.Resolve<INancyEnvironment>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Retrieve all module instances from the container\r\n        /// </summary>\r\n        /// <param name=\"container\">Container to use</param>\r\n        /// <returns>Collection of NancyModule instances</returns>\r\n        protected override sealed IEnumerable<INancyModule> GetAllModules(TinyIoCContainer container)\r\n        {\r\n            var nancyModules = container.ResolveAll<INancyModule>(false);\r\n            return nancyModules;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Retrieve a specific module instance from the container\r\n        /// </summary>\r\n        /// <param name=\"container\">Container to use</param>\r\n        /// <param name=\"moduleType\">Type of the module</param>\r\n        /// <returns>NancyModule instance</returns>\r\n        protected override sealed INancyModule GetModule(TinyIoCContainer container, Type moduleType)\r\n        {\r\n            container.Register(typeof(INancyModule), moduleType);\r\n\r\n            return container.Resolve<INancyModule>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Executes auto registration with the given container.\r\n        /// </summary>\r\n        /// <param name=\"container\">Container instance</param>\r\n        /// <param name=\"ignoredAssemblies\">List of ignored assemblies</param>\r\n        private void AutoRegister(TinyIoCContainer container, IEnumerable<Func<Assembly, bool>> ignoredAssemblies)\r\n        {\r\n            var assembly = typeof(NancyEngine).GetTypeInfo().Assembly;\r\n\r\n            container.AutoRegister(this.AssemblyCatalog.GetAssemblies().Where(a => !ignoredAssemblies.Any(ia => ia(a))), DuplicateImplementationActions.RegisterMultiple, t => t.GetAssembly() != assembly);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/DefaultNancyContextFactory.cs",
    "content": "namespace Nancy\r\n{\r\n    using Nancy.Configuration;\r\n    using Nancy.Culture;\r\n    using Nancy.Diagnostics;\r\n    using Nancy.Localization;\r\n\r\n    /// <summary>\r\n    /// Creates NancyContext instances\r\n    /// </summary>\r\n    public class DefaultNancyContextFactory : INancyContextFactory\r\n    {\r\n        private readonly ICultureService cultureService;\r\n        private readonly IRequestTraceFactory requestTraceFactory;\r\n        private readonly ITextResource textResource;\r\n        private readonly INancyEnvironment environment;\r\n\r\n        /// <summary>\r\n        /// Creates a new instance of the <see cref=\"DefaultNancyContextFactory\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"cultureService\">An <see cref=\"ICultureService\"/> instance.</param>\r\n        /// <param name=\"requestTraceFactory\">An <see cref=\"IRequestTraceFactory\"/> instance.</param>\r\n        /// <param name=\"textResource\">An <see cref=\"ITextResource\"/> instance.</param>\r\n        /// <param name=\"environment\">An <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        public DefaultNancyContextFactory(ICultureService cultureService, IRequestTraceFactory requestTraceFactory, ITextResource textResource, INancyEnvironment environment)\r\n        {\r\n            this.cultureService = cultureService;\r\n            this.requestTraceFactory = requestTraceFactory;\r\n            this.textResource = textResource;\r\n            this.environment = environment;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Create a new <see cref=\"NancyContext\"/> instance.\r\n        /// </summary>\r\n        /// <returns>A <see cref=\"NancyContext\"/> instance.</returns>\r\n        public NancyContext Create(Request request)\r\n        {\r\n            var context =\r\n                new NancyContext();\r\n\r\n            context.Trace = this.requestTraceFactory.Create(request);\r\n            context.Request = request;\r\n            context.Culture = this.cultureService.DetermineCurrentCulture(context);\r\n            context.Text = new TextResourceFinder(this.textResource, context);\r\n            context.Environment = this.environment;\r\n\r\n            // Move this to DefaultRequestTrace.\r\n            context.Trace.TraceLog.WriteLog(s => s.AppendLine(\"New Request Started\"));\r\n\r\n            return context;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/DefaultObjectSerializer.cs",
    "content": "namespace Nancy\r\n{\r\n    using Extensions;\r\n    using System;\r\n    using System.IO;\r\n    using System.Reflection;\r\n    using System.Runtime.Serialization;\r\n    using System.Text;\r\n\r\n    /// <summary>\r\n    /// Serializes/Deserializes objects for sessions\r\n    /// </summary>\r\n    public class DefaultObjectSerializer : IObjectSerializer\r\n    {\r\n        /// <summary>\r\n        /// Serialize an object\r\n        /// </summary>\r\n        /// <param name=\"sourceObject\">Source object</param>\r\n        /// <returns>Serialised object string</returns>\r\n        public string Serialize(object sourceObject)\r\n        {\r\n            if (sourceObject == null)\r\n            {\r\n                return string.Empty;\r\n            }\r\n\r\n            dynamic serializedObject = (sourceObject is string)\r\n                ? sourceObject\r\n                : AddTypeInformation(sourceObject);\r\n\r\n            var json = SimpleJson.SerializeObject(serializedObject);\r\n            return Convert.ToBase64String(Encoding.UTF8.GetBytes(json));\r\n        }\r\n\r\n        private static dynamic AddTypeInformation(object sourceObject)\r\n        {\r\n            var assemblyQualifiedName = sourceObject.GetType().GetTypeInfo().AssemblyQualifiedName;\r\n\r\n            dynamic serializedObject = sourceObject.ToDynamic();\r\n            serializedObject.TypeObject = assemblyQualifiedName;\r\n\r\n            return serializedObject;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Deserialize an object string\r\n        /// </summary>\r\n        /// <param name=\"sourceString\">Source object string</param>\r\n        /// <returns>Deserialized object</returns>\r\n        public object Deserialize(string sourceString)\r\n        {\r\n            if (string.IsNullOrEmpty(sourceString))\r\n            {\r\n                return null;\r\n            }\r\n\r\n            try\r\n            {\r\n                var inputBytes = Convert.FromBase64String(sourceString);\r\n                var json = Encoding.UTF8.GetString(inputBytes);\r\n\r\n                if (!ContainsTypeDescription(json))\r\n                {\r\n                    return SimpleJson.DeserializeObject(json);\r\n                }\r\n\r\n                dynamic serializedObject = SimpleJson.DeserializeObject(json);\r\n\r\n                return SimpleJson.DeserializeObject(json, Type.GetType(serializedObject.TypeObject));\r\n            }\r\n            catch (FormatException)\r\n            {\r\n                return null;\r\n            }\r\n            catch (SerializationException)\r\n            {\r\n                return null;\r\n            }\r\n            catch (IOException)\r\n            {\r\n                return null;\r\n            }\r\n        }\r\n\r\n        private static bool ContainsTypeDescription(string json)\r\n        {\r\n            return json.Contains(\"TypeObject\");\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/DefaultResponseFormatter.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using Nancy.Configuration;\r\n\r\n    /// <summary>\r\n    /// The default implementation of the <see cref=\"IResponseFormatter\"/> interface.\r\n    /// </summary>\r\n    public class DefaultResponseFormatter : IResponseFormatter\r\n    {\r\n        private readonly IRootPathProvider rootPathProvider;\r\n        private readonly NancyContext context;\r\n        private readonly ISerializerFactory serializerFactory;\r\n        private readonly INancyEnvironment environment;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultResponseFormatter\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"rootPathProvider\">The <see cref=\"IRootPathProvider\"/> that should be used by the instance.</param>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> that should be used by the instance.</param>\r\n        /// <param name=\"serializerFactory\">An <see cref=\"ISerializerFactory\" /> instance\"/>.</param>\r\n        /// <param name=\"environment\">An <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        public DefaultResponseFormatter(IRootPathProvider rootPathProvider, NancyContext context, ISerializerFactory serializerFactory, INancyEnvironment environment)\r\n        {\r\n            this.rootPathProvider = rootPathProvider;\r\n            this.context = context;\r\n            this.serializerFactory = serializerFactory;\r\n            this.environment = environment;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all <see cref=\"ISerializerFactory\"/> factory.\r\n        /// </summary>\r\n        public ISerializerFactory SerializerFactory\r\n        {\r\n            get { return this.serializerFactory; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the context for which the response is being formatted.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"NancyContext\"/> instance.</value>\r\n        public NancyContext Context\r\n        {\r\n            get { return this.context; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"INancyEnvironment\"/>.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"INancyEnvironment\"/> instance.</value>\r\n        public INancyEnvironment Environment\r\n        {\r\n            get { return this.environment; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the root path of the application.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the root path.</value>\r\n        public string RootPath\r\n        {\r\n            get { return this.rootPathProvider.GetRootPath(); }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/DefaultResponseFormatterFactory.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using Nancy.Configuration;\r\n\r\n    /// <summary>\r\n    /// The default implementation of the <see cref=\"IResponseFormatterFactory\"/> interface.\r\n    /// </summary>\r\n    public class DefaultResponseFormatterFactory : IResponseFormatterFactory\r\n    {\r\n        private readonly IRootPathProvider rootPathProvider;\r\n        private readonly ISerializerFactory serializerFactory;\r\n        private readonly INancyEnvironment environment;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultResponseFormatter\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"rootPathProvider\">An <see cref=\"IRootPathProvider\"/> instance.</param>\r\n        /// <param name=\"serializerFactory\">An <see cref=\"ISerializerFactory\"/> instance.</param>\r\n        /// <param name=\"environment\">An <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        public DefaultResponseFormatterFactory(IRootPathProvider rootPathProvider, ISerializerFactory serializerFactory, INancyEnvironment environment)\r\n        {\r\n            this.rootPathProvider = rootPathProvider;\r\n            this.serializerFactory = serializerFactory;\r\n            this.environment = environment;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a new <see cref=\"IResponseFormatter\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> instance that should be used by the response formatter.</param>\r\n        /// <returns>An <see cref=\"IResponseFormatter\"/> instance.</returns>\r\n        public IResponseFormatter Create(NancyContext context)\r\n        {\r\n            return new DefaultResponseFormatter(this.rootPathProvider, context, this.serializerFactory, this.environment);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/DefaultRootPathProvider.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Default implementation of <see cref=\"IRootPathProvider\"/>.\r\n    /// </summary>\r\n    public class DefaultRootPathProvider : IRootPathProvider\r\n    {\r\n        /// <summary>\r\n        /// Returns the root folder path of the current Nancy application.\r\n        /// </summary>\r\n        /// <returns>A <see cref=\"string\"/> containing the path of the root folder.</returns>\r\n        public string GetRootPath()\r\n        {\r\n#if CORE\r\n            return Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.ApplicationBasePath;\r\n#else\r\n            return AppDomain.CurrentDomain.BaseDirectory;\r\n#endif\r\n        }\r\n    }\r\n}\r\n\r\n"
  },
  {
    "path": "src/Nancy/DefaultRouteConfigurationProvider.cs",
    "content": "namespace Nancy\r\n{\r\n    using Nancy.Configuration;\r\n\r\n    /// <summary>\r\n    /// Provides the default configuration for <see cref=\"RouteConfiguration\"/>.\r\n    /// </summary>\r\n    public class DefaultRouteConfigurationProvider : NancyDefaultConfigurationProvider<RouteConfiguration>\r\n    {\r\n        /// <summary>\r\n        /// Gets the default configuration instance to register in the <see cref=\"INancyEnvironment\"/>.\r\n        /// </summary>\r\n        /// <remarks>Will return <see cref=\"ViewConfiguration.Default\"/>.</remarks>\r\n        public override RouteConfiguration GetDefaultConfiguration()\r\n        {\r\n            return RouteConfiguration.Default;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/DefaultRuntimeEnvironmentInformation.cs",
    "content": "namespace Nancy\r\n{\r\n    using System;\r\n    using System.Diagnostics;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n\r\n    /// <summary>\r\n    /// Default implementation of the <see cref=\"IRuntimeEnvironmentInformation\"/> interface.\r\n    /// </summary>\r\n    public class DefaultRuntimeEnvironmentInformation : IRuntimeEnvironmentInformation\r\n    {\r\n        private readonly Lazy<bool> isDebug;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultRuntimeEnvironmentInformation\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"typeCatalog\">An <see cref=\"ITypeCatalog\"/> instance.</param>\r\n        public DefaultRuntimeEnvironmentInformation(ITypeCatalog typeCatalog)\r\n        {\r\n            this.isDebug = new Lazy<bool>(() => GetDebugMode(typeCatalog));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating if the application is running in debug mode.\r\n        /// </summary>\r\n        /// <returns><see langword=\"true\"/> if the application is running in debug mode, otherwise <see langword=\"false\"/>.</returns>\r\n        public virtual bool IsDebug\r\n        {\r\n            get { return this.isDebug.Value; }\r\n        }\r\n\r\n        private static bool GetDebugMode(ITypeCatalog typeCatalog)\r\n        {\r\n            try\r\n            {\r\n                return Debugger.IsAttached;\r\n            }\r\n            catch\r\n            {\r\n                return false;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/DefaultSerializerFactory.cs",
    "content": "namespace Nancy\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using Nancy.Extensions;\r\n    using Nancy.Responses.Negotiation;\r\n\r\n    /// <summary>\r\n    /// Default implementation of the <see cref=\"ISerializerFactory\"/> interface.\r\n    /// </summary>\r\n    /// <remarks>This implementation will ignore the default implementations (those found in the Nancy assembly) unless no other match could be made.</remarks>\r\n    public class DefaultSerializerFactory : ISerializerFactory\r\n    {\r\n        private readonly IEnumerable<ISerializer> serializers;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultSerializerFactory\"/> class,\r\n        /// with the provided <paramref name=\"serializers\"/>.\r\n        /// </summary>\r\n        /// <param name=\"serializers\">The <see cref=\"ISerializer\"/> implementations that should be available to the factory.</param>\r\n        public DefaultSerializerFactory(IEnumerable<ISerializer> serializers)\r\n        {\r\n            this.serializers = serializers;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"ISerializer\"/> implementation that can serialize the provided <paramref name=\"mediaRange\"/>.\r\n        /// </summary>\r\n        /// <param name=\"mediaRange\">The <see cref=\"MediaRange\"/> to get a serializer for.</param>\r\n        /// <returns>An <see cref=\"ISerializer\"/> instance, or <see langword=\"null\" /> if not match was found.</returns>\r\n        /// <exception cref=\"InvalidOperationException\">If more than one <see cref=\"ISerializer\"/> (not counting the default serializers) matched the provided media range.</exception>\r\n        public ISerializer GetSerializer(MediaRange mediaRange)\r\n        {\r\n            var defaultSerializerForMediaRange =\r\n                this.GetDefaultSerializerForMediaRange(mediaRange);\r\n\r\n            var matches = this.serializers\r\n                .Where(x => x != defaultSerializerForMediaRange)\r\n                .Where(x => SafeCanSerialize(x, mediaRange)).ToArray();\r\n\r\n            if (matches.Length > 1)\r\n            {\r\n                throw new InvalidOperationException(GetErrorMessage(matches, mediaRange));\r\n            }\r\n\r\n            return matches\r\n                .Concat(new[] { defaultSerializerForMediaRange })\r\n                .FirstOrDefault();\r\n        }\r\n\r\n        private ISerializer GetDefaultSerializerForMediaRange(MediaRange mediaRange)\r\n        {\r\n            try\r\n            {\r\n                return this.serializers\r\n                    .Where(x => x.GetType().GetTypeInfo().Assembly.Equals(typeof(INancyEngine).GetAssembly()))\r\n                    .SingleOrDefault(x => x.CanSerialize(mediaRange));\r\n            }\r\n            catch\r\n            {\r\n                return null;\r\n            }\r\n        }\r\n\r\n        private static string GetErrorMessage(IEnumerable<ISerializer> matches, MediaRange mediaRange)\r\n        {\r\n            var details =\r\n                string.Join(\"\\n\", matches.Select(x => string.Concat(\" - \", x.GetType().FullName)));\r\n\r\n            return string.Format(\"Multiple ISerializer implementations matched the '{0}' media range.\\nThe following serializers matched \\n\\n{1}\", mediaRange, details);\r\n        }\r\n\r\n        private static bool SafeCanSerialize(ISerializer serializer, MediaRange mediaRange)\r\n        {\r\n            try\r\n            {\r\n                return serializer.CanSerialize(mediaRange);\r\n            }\r\n            catch\r\n            {\r\n                return false;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/DefaultStaticContentConfigurationProvider.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using Nancy.Configuration;\r\n\r\n    /// <summary>\r\n    /// Provides the default <see cref=\"StaticContentConfiguration\"/>. \r\n    /// </summary>\r\n    public class DefaultStaticContentConfigurationProvider : NancyDefaultConfigurationProvider<StaticContentConfiguration>\r\n    {\r\n        private readonly IRootPathProvider rootPathProvider;\r\n\r\n        /// <summary>\r\n        /// Creates and instance of <see cref=\"DefaultStaticContentConfigurationProvider\" />. \r\n        /// </summary>\r\n        /// <param name=\"rootPathProvider\">Use <see cref=\"IRootPathProvider\"/> to get the root path of the application</param>\r\n        public DefaultStaticContentConfigurationProvider(IRootPathProvider rootPathProvider)\r\n        {\r\n            this.rootPathProvider = rootPathProvider;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the default <see cref=\"StaticContentConfiguration\"/> configuration instance to register in the <see cref=\"INancyEnvironment\"/> .\r\n        /// </summary>\r\n        /// <returns>The configuration instance.</returns>\r\n        public override StaticContentConfiguration GetDefaultConfiguration()\r\n        {\r\n            return new StaticContentConfiguration(safePaths:new []{this.rootPathProvider.GetRootPath()});\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/DefaultStaticContentProvider.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using Nancy.Conventions;\r\n\r\n    /// <summary>\r\n    /// The default static content provider that uses <see cref=\"StaticContentsConventions\"/>\r\n    /// to determine what static content to serve.\r\n    /// </summary>\r\n    public class DefaultStaticContentProvider : IStaticContentProvider\r\n    {\r\n        private readonly IRootPathProvider rootPathProvider;\r\n        private readonly StaticContentsConventions conventions;\r\n        private string rootPath;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultStaticContentProvider\"/> class, using the\r\n        /// provided <paramref name=\"rootPathProvider\"/> and <paramref name=\"conventions\"/>.\r\n        /// </summary>\r\n        /// <param name=\"rootPathProvider\">The current root path provider.</param>\r\n        /// <param name=\"conventions\">The static content conventions.</param>\r\n        public DefaultStaticContentProvider(IRootPathProvider rootPathProvider, StaticContentsConventions conventions)\r\n        {\r\n            this.rootPathProvider = rootPathProvider;\r\n            this.rootPath = this.rootPathProvider.GetRootPath();\r\n            this.conventions = conventions;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the static content response, if possible.\r\n        /// </summary>\r\n        /// <param name=\"context\">Current context</param>\r\n        /// <returns>Response if serving content, null otherwise</returns>\r\n        public Response GetContent(NancyContext context)\r\n        {\r\n            foreach (var convention in this.conventions)\r\n            {\r\n                var result = convention.Invoke(context, this.rootPath);\r\n\r\n                if (result != null)\r\n                {\r\n                    return result;\r\n                }\r\n            }\r\n\r\n            return null;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/DefaultTraceConfigurationProvider.cs",
    "content": "namespace Nancy\r\n{\r\n    using Nancy.Configuration;\r\n\r\n    /// <summary>\r\n    /// Provides the default configuration for <see cref=\"TraceConfiguration\"/>.\r\n    /// </summary>\r\n    public class DefaultTraceConfigurationProvider : NancyDefaultConfigurationProvider<TraceConfiguration>\r\n    {\r\n        private readonly IRuntimeEnvironmentInformation runtimeEnvironmentInformation;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultTraceConfigurationProvider\"/> class.\r\n        /// </summary>\r\n        public DefaultTraceConfigurationProvider(IRuntimeEnvironmentInformation runtimeEnvironmentInformation)\r\n        {\r\n            this.runtimeEnvironmentInformation = runtimeEnvironmentInformation;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the default configuration instance to register in the <see cref=\"INancyEnvironment\"/>.\r\n        /// </summary>\r\n        /// <returns>The configuration instance</returns>\r\n        public override TraceConfiguration GetDefaultConfiguration()\r\n        {\r\n            var isDebugMode =\r\n                this.runtimeEnvironmentInformation.IsDebug;\r\n\r\n            return new TraceConfiguration(\r\n                enabled: false,\r\n                displayErrorTraces: isDebugMode);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/DefaultTypeCatalog.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using System;\r\n    using System.Collections.Concurrent;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using Nancy.Extensions;\r\n\r\n    /// <summary>\r\n    /// Default implementation of the <see cref=\"ITypeCatalog\"/> interface.\r\n    /// </summary>\r\n    public class DefaultTypeCatalog : ITypeCatalog\r\n    {\r\n        private readonly IAssemblyCatalog assemblyCatalog;\r\n        private readonly ConcurrentDictionary<Type, IReadOnlyCollection<Type>> cache;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultTypeCatalog\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"assemblyCatalog\">An <see cref=\"IAssemblyCatalog\"/> instanced, used to get the assemblies that types should be resolved from.</param>\r\n        public DefaultTypeCatalog(IAssemblyCatalog assemblyCatalog)\r\n        {\r\n            this.assemblyCatalog = assemblyCatalog;\r\n            this.cache = new ConcurrentDictionary<Type, IReadOnlyCollection<Type>>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all types that are assignable to the provided <paramref name=\"type\"/>.\r\n        /// </summary>\r\n        /// <param name=\"type\">The <see cref=\"Type\"/> that returned types should be assignable to.</param>\r\n        /// <param name=\"strategy\">A <see cref=\"TypeResolveStrategy\"/> that should be used when retrieving types.</param>\r\n        /// <returns>An <see cref=\"IReadOnlyCollection{T}\"/> of <see cref=\"Type\"/> instances.</returns>\r\n        public IReadOnlyCollection<Type> GetTypesAssignableTo(Type type, TypeResolveStrategy strategy)\r\n        {\r\n            return this.cache.GetOrAdd(type, t => this.GetTypesAssignableTo(type)).Where(strategy.Invoke).ToArray();\r\n        }\r\n\r\n        private IReadOnlyCollection<Type> GetTypesAssignableTo(Type type)\r\n        {\r\n            return this.assemblyCatalog\r\n                .GetAssemblies()\r\n                .SelectMany(assembly => assembly.SafeGetExportedTypes())\r\n                .Where(type.IsAssignableFrom)\r\n                .Where(t => !t.GetTypeInfo().IsAbstract)\r\n                .ToArray();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/DefaultViewConfigurationProvider.cs",
    "content": "namespace Nancy\r\n{\r\n    using Configuration;\r\n\r\n    /// <summary>\r\n    /// Provides the default configuration for <see cref=\"ViewConfiguration\"/>.\r\n    /// </summary>\r\n    public class DefaultViewConfigurationProvider : NancyDefaultConfigurationProvider<ViewConfiguration>\r\n    {\r\n        /// <summary>\r\n        /// Gets the default configuration instance to register in the <see cref=\"INancyEnvironment\"/>.\r\n        /// </summary>\r\n        /// <returns>The configuration instance</returns>\r\n        /// <remarks>Will return <see cref=\"ViewConfiguration.Default\"/>.</remarks>\r\n        public override ViewConfiguration GetDefaultConfiguration()\r\n        {\r\n            return ViewConfiguration.Default;;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/DependencyContextAssemblyCatalog.cs",
    "content": "#if CORE\r\nnamespace Nancy\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using Microsoft.Extensions.DependencyModel;\r\n\r\n    /// <summary>\r\n    /// Default implementation of the <see cref=\"IAssemblyCatalog\"/> interface, based on\r\n    /// retrieving <see cref=\"Assembly\"/> information from <see cref=\"DependencyContext\"/>.\r\n    /// </summary>\r\n    public class DependencyContextAssemblyCatalog : IAssemblyCatalog\r\n    {\r\n        private static readonly Assembly NancyAssembly = typeof(INancyEngine).GetTypeInfo().Assembly;\r\n        private readonly DependencyContext dependencyContext;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DependencyContextAssemblyCatalog\"/> class,\r\n        /// using <see cref=\"Assembly.GetEntryAssembly()\"/>.\r\n        /// </summary>\r\n        public DependencyContextAssemblyCatalog()\r\n            : this(Assembly.GetEntryAssembly())\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DependencyContextAssemblyCatalog\"/> class,\r\n        /// using <paramref name=\"entryAssembly\"/>.\r\n        /// </summary>\r\n        public DependencyContextAssemblyCatalog(Assembly entryAssembly)\r\n        {\r\n            this.dependencyContext = DependencyContext.Load(entryAssembly);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all <see cref=\"Assembly\"/> instances in the catalog.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IReadOnlyCollection{T}\"/> of <see cref=\"Assembly\"/> instances.</returns>\r\n        public virtual IReadOnlyCollection<Assembly> GetAssemblies()\r\n        {\r\n            var results = new HashSet<Assembly>\r\n            {\r\n                typeof (DependencyContextAssemblyCatalog).GetTypeInfo().Assembly\r\n            };\r\n\r\n            foreach (var library in this.dependencyContext.RuntimeLibraries)\r\n            {\r\n                if (IsReferencingNancy(library))\r\n                {\r\n                    foreach (var assemblyName in library.GetDefaultAssemblyNames(this.dependencyContext))\r\n                    {\r\n                        results.Add(SafeLoadAssembly(assemblyName));\r\n                    }\r\n                }\r\n            }\r\n\r\n            return results.ToArray();\r\n        }\r\n\r\n        private static Assembly SafeLoadAssembly(AssemblyName assemblyName)\r\n        {\r\n            try\r\n            {\r\n                return Assembly.Load(assemblyName);\r\n            }\r\n            catch (Exception)\r\n            {\r\n                return null;\r\n            }\r\n        }\r\n\r\n        private static bool IsReferencingNancy(Library library)\r\n        {\r\n            return library.Dependencies.Any(dependency => dependency.Name.Equals(NancyAssembly.GetName().Name));\r\n        }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "src/Nancy/Diagnostics/ConcurrentLimitedCollection.cs",
    "content": "﻿namespace Nancy.Diagnostics\r\n{\r\n    using System.Collections;\r\n    using System.Collections.Concurrent;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Provides a thread safe, limited size, collection of objects\r\n    /// If the collection is full the oldest item gets removed.\r\n    /// </summary>\r\n    /// <typeparam name=\"T\">Type to store</typeparam>\r\n    public class ConcurrentLimitedCollection<T> : IEnumerable<T>\r\n    {\r\n        private readonly int maxSize;\r\n\r\n        private ConcurrentQueue<T> internalStore;\r\n\r\n        /// <summary>\r\n        /// Gets the current size for the collection.\r\n        /// </summary>\r\n        /// <value> Current size of the collection.</value>\r\n        public int CurrentSize\r\n        {\r\n            get\r\n            {\r\n                return this.internalStore.Count;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ConcurrentLimitedCollection{T}\"/> class, with\r\n        /// the provided <paramref name=\"maxSize\"/>.\r\n        /// </summary>\r\n        /// <param name=\"maxSize\">The maximum size for the collection.</param>\r\n        public ConcurrentLimitedCollection(int maxSize)\r\n        {\r\n            this.maxSize = maxSize;\r\n            this.internalStore = new ConcurrentQueue<T>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an enumerator that iterates through the collection.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// A <see cref=\"T:System.Collections.Generic.IEnumerator`1\"/> that can be used to iterate through the collection.\r\n        /// </returns>\r\n        /// <filterpriority>1</filterpriority>\r\n        public IEnumerator<T> GetEnumerator()\r\n        {\r\n            return this.internalStore.GetEnumerator();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an enumerator that iterates through a collection.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// An <see cref=\"T:System.Collections.IEnumerator\"/> object that can be used to iterate through the collection.\r\n        /// </returns>\r\n        /// <filterpriority>2</filterpriority>\r\n        IEnumerator IEnumerable.GetEnumerator()\r\n        {\r\n            return this.GetEnumerator();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds an item to the collection.\r\n        /// If the collection is full, the oldest item is removed and the new item\r\n        /// is added to the end of the collection.\r\n        /// </summary>\r\n        /// <param name=\"item\">Item to add</param>\r\n        public void Add(T item)\r\n        {\r\n            if (this.internalStore.Count == this.maxSize)\r\n            {\r\n                T temp;\r\n                this.internalStore.TryDequeue(out temp);\r\n            }\r\n\r\n            this.internalStore.Enqueue(item);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Clear the collection\r\n        /// </summary>\r\n        public void Clear()\r\n        {\r\n            this.internalStore = new ConcurrentQueue<T>();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/DefaultDiagnostics.cs",
    "content": "﻿namespace Nancy.Diagnostics\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Configuration;\r\n    using Nancy.Conventions;\r\n    using Nancy.Culture;\r\n    using Nancy.Localization;\r\n    using Nancy.ModelBinding;\r\n    using Nancy.Responses.Negotiation;\r\n    using Nancy.Routing;\r\n    using Nancy.Routing.Constraints;\r\n\r\n    /// <summary>\r\n    /// Wires up the diagnostics support at application startup.\r\n    /// </summary>\r\n    public class DefaultDiagnostics : IDiagnostics\r\n    {\r\n        private readonly IEnumerable<IDiagnosticsProvider> diagnosticProviders;\r\n        private readonly IRootPathProvider rootPathProvider;\r\n        private readonly IRequestTracing requestTracing;\r\n        private readonly NancyInternalConfiguration configuration;\r\n        private readonly IModelBinderLocator modelBinderLocator;\r\n        private readonly IEnumerable<IResponseProcessor> responseProcessors;\r\n        private readonly IEnumerable<IRouteSegmentConstraint> routeSegmentConstraints;\r\n        private readonly ICultureService cultureService;\r\n        private readonly IRequestTraceFactory requestTraceFactory;\r\n        private readonly IEnumerable<IRouteMetadataProvider> routeMetadataProviders;\r\n        private readonly ITextResource textResource;\r\n        private readonly INancyEnvironment environment;\r\n        private readonly ITypeCatalog typeCatalog;\r\n        private readonly IAssemblyCatalog assemblyCatalog;\r\n        private readonly AcceptHeaderCoercionConventions acceptHeaderCoercionConventions;\r\n\r\n        /// <summary>\r\n        /// Creates a new instance of the <see cref=\"DefaultDiagnostics\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"diagnosticProviders\"></param>\r\n        /// <param name=\"rootPathProvider\"></param>\r\n        /// <param name=\"requestTracing\"></param>\r\n        /// <param name=\"configuration\"></param>\r\n        /// <param name=\"modelBinderLocator\"></param>\r\n        /// <param name=\"responseProcessors\"></param>\r\n        /// <param name=\"routeSegmentConstraints\"></param>\r\n        /// <param name=\"cultureService\"></param>\r\n        /// <param name=\"requestTraceFactory\"></param>\r\n        /// <param name=\"routeMetadataProviders\"></param>\r\n        /// <param name=\"textResource\"></param>\r\n        /// <param name=\"environment\"></param>\r\n        /// <param name=\"typeCatalog\"></param>\r\n        /// <param name=\"assemblyCatalog\"></param>\r\n        /// <param name=\"acceptHeaderCoercionConventions\"></param>\r\n        public DefaultDiagnostics(\r\n            IEnumerable<IDiagnosticsProvider> diagnosticProviders,\r\n            IRootPathProvider rootPathProvider,\r\n            IRequestTracing requestTracing,\r\n            NancyInternalConfiguration configuration,\r\n            IModelBinderLocator modelBinderLocator,\r\n            IEnumerable<IResponseProcessor> responseProcessors,\r\n            IEnumerable<IRouteSegmentConstraint> routeSegmentConstraints,\r\n            ICultureService cultureService,\r\n            IRequestTraceFactory requestTraceFactory,\r\n            IEnumerable<IRouteMetadataProvider> routeMetadataProviders,\r\n            ITextResource textResource,\r\n            INancyEnvironment environment,\r\n            ITypeCatalog typeCatalog,\r\n            IAssemblyCatalog assemblyCatalog,\r\n            AcceptHeaderCoercionConventions acceptHeaderCoercionConventions)\r\n        {\r\n            this.diagnosticProviders = diagnosticProviders;\r\n            this.rootPathProvider = rootPathProvider;\r\n            this.requestTracing = requestTracing;\r\n            this.configuration = configuration;\r\n            this.modelBinderLocator = modelBinderLocator;\r\n            this.responseProcessors = responseProcessors;\r\n            this.routeSegmentConstraints = routeSegmentConstraints;\r\n            this.cultureService = cultureService;\r\n            this.requestTraceFactory = requestTraceFactory;\r\n            this.routeMetadataProviders = routeMetadataProviders;\r\n            this.textResource = textResource;\r\n            this.environment = environment;\r\n            this.typeCatalog = typeCatalog;\r\n            this.assemblyCatalog = assemblyCatalog;\r\n            this.acceptHeaderCoercionConventions = acceptHeaderCoercionConventions;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initialize diagnostics\r\n        /// </summary>\r\n        /// <param name=\"pipelines\">Application pipelines</param>\r\n        public void Initialize(IPipelines pipelines)\r\n        {\r\n            DiagnosticsHook.Enable(\r\n                pipelines,\r\n                this.diagnosticProviders,\r\n                this.rootPathProvider,\r\n                this.requestTracing,\r\n                this.configuration,\r\n                this.modelBinderLocator,\r\n                this.responseProcessors,\r\n                this.routeSegmentConstraints,\r\n                this.cultureService,\r\n                this.requestTraceFactory,\r\n                this.routeMetadataProviders,\r\n                this.textResource,\r\n                this.environment,\r\n                this.typeCatalog,\r\n                this.assemblyCatalog,\r\n                this.acceptHeaderCoercionConventions);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/DefaultDiagnosticsConfigurationProvider.cs",
    "content": "﻿namespace Nancy.Diagnostics\r\n{\r\n    using Nancy.Configuration;\r\n\r\n    /// <summary>\r\n    /// Provides the default configuration for <see cref=\"DiagnosticsConfiguration\"/>.\r\n    /// </summary>\r\n    public class DefaultDiagnosticsConfigurationProvider : NancyDefaultConfigurationProvider<DiagnosticsConfiguration>\r\n    {\r\n        /// <summary>\r\n        /// Gets the default configuration instance to register in the <see cref=\"INancyEnvironment\"/>.\r\n        /// </summary>\r\n        /// <returns>The configuration instance</returns>\r\n        /// <remarks>Will return <see cref=\"DiagnosticsConfiguration.Default\"/></remarks>\r\n        public override DiagnosticsConfiguration GetDefaultConfiguration()\r\n        {\r\n            return DiagnosticsConfiguration.Default;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/DefaultRequestTrace.cs",
    "content": "﻿namespace Nancy.Diagnostics\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// The default implementation of the <see cref=\"IRequestTrace\"/> interface.\r\n    /// </summary>\r\n    public class DefaultRequestTrace : IRequestTrace\r\n    {\r\n        /// <summary>\r\n        /// Gets the generic item store.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IDictionary{TKey,TValue}\"/> instance containing the items.</value>\r\n        public IDictionary<string, object> Items { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the information about the request.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"RequestData\"/> instance.</value>\r\n        public RequestData RequestData { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the information about the response.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"ResponseData\"/> instance.</value>\r\n        public ResponseData ResponseData { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the trace log.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"ITraceLog\"/> instance.</value>\r\n        public ITraceLog TraceLog { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/DefaultRequestTraceFactory.cs",
    "content": "namespace Nancy.Diagnostics\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using Nancy.Configuration;\r\n\r\n    /// <summary>\r\n    /// Default implementation of the <see cref=\"IRequestTraceFactory\"/> interface.\r\n    /// </summary>\r\n    public class DefaultRequestTraceFactory : IRequestTraceFactory\r\n    {\r\n        private readonly TraceConfiguration configuration;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultRequestTraceFactory\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"environment\">An <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        public DefaultRequestTraceFactory(INancyEnvironment environment)\r\n        {\r\n            this.configuration = environment.GetValue<TraceConfiguration>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates an <see cref=\"IRequestTrace\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"request\">A <see cref=\"Request\"/> instance.</param>\r\n        /// <returns>An <see cref=\"IRequestTrace\"/> instance.</returns>\r\n        public IRequestTrace Create(Request request)\r\n        {\r\n            var requestTrace =\r\n                new DefaultRequestTrace();\r\n\r\n            var comparer = (StaticConfiguration.CaseSensitive) ?\r\n                StringComparer.Ordinal :\r\n                StringComparer.OrdinalIgnoreCase;\r\n\r\n            requestTrace.Items =\r\n                new Dictionary<string, object>(comparer);\r\n\r\n            requestTrace.RequestData = request;\r\n\r\n            requestTrace.TraceLog = (this.configuration.DisplayErrorTraces) ?\r\n                (ITraceLog)new DefaultTraceLog() :\r\n                (ITraceLog)new NullLog();\r\n\r\n            return requestTrace;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/DefaultRequestTracing.cs",
    "content": "namespace Nancy.Diagnostics\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Default implementation of the <see cref=\"IRequestTracing\"/> interface.\r\n    /// </summary>\r\n    public class DefaultRequestTracing : IRequestTracing\r\n    {\r\n        private const int MaxSize = 50;\r\n\r\n        private readonly ConcurrentLimitedCollection<RequestTraceSession> sessions = new ConcurrentLimitedCollection<RequestTraceSession>(MaxSize);\r\n\r\n        /// <summary>\r\n        /// Adds the <see cref=\"IRequestTrace\"/>, of the provided, <see cref=\"NancyContext\"/> to the trace log.\r\n        /// </summary>\r\n        /// <param name=\"sessionId\">The identifier of the trace.</param>\r\n        /// <param name=\"context\">A <see cref=\"NancyContext\"/> instance.</param>\r\n        public void AddRequestDiagnosticToSession(Guid sessionId, NancyContext context)\r\n        {\r\n            var session = this.sessions.FirstOrDefault(s => s.Id == sessionId);\r\n\r\n            if (session == null)\r\n            {\r\n                return;\r\n            }\r\n\r\n            session.AddRequestTrace(context.Trace);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Clears the trace log.\r\n        /// </summary>\r\n        public void Clear()\r\n        {\r\n            this.sessions.Clear();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a new trace session.\r\n        /// </summary>\r\n        /// <returns>A <see cref=\"Guid\"/> which represents the identifier of the new trace session.</returns>\r\n        public Guid CreateSession()\r\n        {\r\n            var id = Guid.NewGuid();\r\n\r\n            this.sessions.Add(new RequestTraceSession(id));\r\n\r\n            return id;\r\n        }\r\n\r\n        // TODO - remove above method and return guid from here?\r\n\r\n        /// <summary>\r\n        /// Gets all the available <see cref=\"RequestTraceSession\"/> instances.\r\n        /// </summary>\r\n        /// <returns></returns>\r\n        public IEnumerable<RequestTraceSession> GetSessions()\r\n        {\r\n            return this.sessions;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Checks if the provided <paramref name=\"sessionId\"/> is valid or not.\r\n        /// </summary>\r\n        /// <param name=\"sessionId\">A <see cref=\"Guid\"/> representing the session to check.</param>\r\n        /// <returns><see langword=\"true\"/> if the session is valid, otherwise <see langword=\"false\"/>.</returns>\r\n        public bool IsValidSessionId(Guid sessionId)\r\n        {\r\n            return this.sessions.Any(s => s.Id == sessionId);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/DefaultTraceLog.cs",
    "content": "namespace Nancy.Diagnostics\r\n{\r\n    using System;\r\n    using System.Text;\r\n\r\n    /// <summary>\r\n    /// Default implementation of the <see cref=\"ITraceLog\"/> interface.\r\n    /// </summary>\r\n    public class DefaultTraceLog : ITraceLog\r\n    {\r\n        private readonly StringBuilder log;\r\n\r\n        /// <summary>\r\n        /// Creates a new instance of the <see cref=\"DefaultTraceLog\"/> class.\r\n        /// </summary>\r\n        public DefaultTraceLog()\r\n        {\r\n            this.log = new StringBuilder();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Write to the log\r\n        /// </summary>\r\n        /// <param name=\"logDelegate\">Log writing delegate</param>\r\n        public void WriteLog(Action<StringBuilder> logDelegate)\r\n        {\r\n            if (this.log != null)\r\n            {\r\n                logDelegate.Invoke(this.log);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns a string that represents the current object.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// A string that represents the current object.\r\n        /// </returns>\r\n        public override string ToString()\r\n        {\r\n            return this.log != null ? this.log.ToString() : string.Empty;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/DescriptionAttribute.cs",
    "content": "namespace Nancy.Diagnostics\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Attribute for specifying Method and Property descriptions.\r\n    /// </summary>\r\n    /// <seealso cref=\"System.Attribute\" />\r\n    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]\r\n    public class DescriptionAttribute : Attribute\r\n    {\r\n        /// <summary>\r\n        /// Gets or sets the description.\r\n        /// </summary>\r\n        /// <value> The description. </value>\r\n        public string Description { get; set; }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DescriptionAttribute\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"description\">The description.</param>\r\n        public DescriptionAttribute(string description)\r\n        {\r\n            this.Description = description;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/DiagnosticModule.cs",
    "content": "﻿namespace Nancy.Diagnostics\r\n{\r\n    using Configuration;\r\n\r\n    /// <summary>\r\n    /// Abstract base class for Nancy diagnostics module.\r\n    /// </summary>\r\n    /// <seealso cref=\"Nancy.NancyModule\" />\r\n    public abstract class DiagnosticModule : NancyModule\r\n    {\r\n        private readonly INancyEnvironment environment;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DiagnosticModule\"/> class.\r\n        /// </summary>\r\n        protected DiagnosticModule()\r\n            : this(string.Empty)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DiagnosticModule\"/> class, with\r\n        /// the provided <paramref name=\"basePath\"/>.\r\n        /// </summary>\r\n        /// <param name=\"basePath\">The base path.</param>\r\n        protected DiagnosticModule(string basePath)\r\n            : base(basePath)\r\n        {\r\n            this.environment = new DefaultNancyEnvironment();\r\n            this.environment.AddValue(ViewConfiguration.Default);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Renders a view from inside a route handler.\r\n        /// </summary>\r\n        /// <value>  A <see cref=\"ViewRenderer\" /> instance that is used to determine which view that should be rendered. </value>\r\n        public new DiagnosticsViewRenderer View\r\n        {\r\n            get { return new DiagnosticsViewRenderer(this.Context, this.environment); }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Diagnostics/DiagnosticsConfiguration.cs",
    "content": "﻿namespace Nancy.Diagnostics\r\n{\r\n    using Nancy.Cryptography;\r\n\r\n    /// <summary>\r\n    /// Configuration for the diagnostics dashboard.\r\n    /// </summary>\r\n    public class DiagnosticsConfiguration\r\n    {\r\n        /// <summary>\r\n        /// A default instance of the <see cref=\"DiagnosticsConfiguration\"/> class.\r\n        /// </summary>\r\n        public static readonly DiagnosticsConfiguration Default = new DiagnosticsConfiguration\r\n        {\r\n            Enabled = false,\r\n            CookieName = \"__ncd\",\r\n            CryptographyConfiguration = CryptographyConfiguration.Default,\r\n            Password = null,\r\n            Path = \"/_Nancy\",\r\n            SlidingTimeout = 15\r\n        };\r\n\r\n        private DiagnosticsConfiguration()\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DiagnosticsConfiguration\"/> class\r\n        /// </summary>\r\n        /// <param name=\"enabled\"></param>\r\n        /// <param name=\"password\">Password used to secure the dashboard.</param>\r\n        /// <param name=\"path\">Relative path of the dashboard.</param>\r\n        /// <param name=\"cookieName\">Name of the cookie to store diagnostics information.</param>\r\n        /// <param name=\"slidingTimeout\">Number of minutes that expiry of the diagnostics dashboard.</param>\r\n        /// <param name=\"cryptographyConfiguration\">Cryptography config to use for securing the dashboard.</param>\r\n        public DiagnosticsConfiguration(bool enabled, string password, string path, string cookieName, int slidingTimeout, CryptographyConfiguration cryptographyConfiguration)\r\n        {\r\n            this.Password = password ?? Default.Password;\r\n            this.Path = GetNormalizedPath(path ?? Default.Path);\r\n            this.CookieName = cookieName ?? Default.CookieName;\r\n            this.Enabled = enabled;\r\n            this.SlidingTimeout = slidingTimeout;\r\n            this.CryptographyConfiguration = cryptographyConfiguration ?? Default.CryptographyConfiguration;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the name of the cookie used by the diagnostics dashboard.\r\n        /// </summary>\r\n        /// <remarks>The default is __ncd</remarks>\r\n        public string CookieName { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the cryptography config to use for securing the diagnostics dashboard\r\n        /// </summary>\r\n        /// <remarks>The default is <see cref=\"CryptographyConfiguration.Default\"/></remarks>\r\n        public CryptographyConfiguration CryptographyConfiguration { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating if diagnostics is enabled or not.\r\n        /// </summary>\r\n        public bool Enabled { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets password for accessing the diagnostics screen.\r\n        /// </summary>\r\n        /// <remarks>The default value is <see langword=\"null\" />.</remarks>\r\n        public string Password { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the path that the diagnostics dashboard will be accessible on.\r\n        /// </summary>\r\n        /// <remarks>The default is /_Nancy.</remarks>\r\n        public string Path { get; private set; }\r\n\r\n        /// <summary>\r\n        /// The number of minutes that expiry of the diagnostics dashboard. Will be extended each time it is used.\r\n        /// </summary>\r\n        /// <remarks>The default is 15 minutes.</remarks>\r\n        public int SlidingTimeout { get; private set; }\r\n\r\n        private static string GetNormalizedPath(string path)\r\n        {\r\n            return (!path.StartsWith(\"/\")) ? string.Concat(\"/\", path) : path;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Diagnostics/DiagnosticsConfigurationExtensions.cs",
    "content": "﻿namespace Nancy.Diagnostics\r\n{\r\n    using Nancy.Configuration;\r\n    using Nancy.Cryptography;\r\n\r\n    /// <summary>\r\n    /// Contains <see cref=\"DiagnosticsConfiguration\"/> configuration extensions for <see cref=\"INancyEnvironment\"/>.\r\n    /// </summary>\r\n    public static class DiagnosticsConfigurationExtensions\r\n    {\r\n        /// <summary>\r\n        /// Configures diagnostics.\r\n        /// </summary>\r\n        /// <param name=\"environment\"><see cref=\"INancyEnvironment\"/> that should be configured.</param>\r\n        /// <param name=\"password\">Password used to secure the dashboard.</param>\r\n        /// <param name=\"path\">Relative path of the dashboard.</param>\r\n        /// <param name=\"cookieName\">Name of the cookie to store diagnostics information.</param>\r\n        /// <param name=\"slidingTimeout\">Number of minutes that expiry of the diagnostics dashboard.</param>\r\n        /// <param name=\"cryptographyConfiguration\">Cryptography config to use for securing the dashboard.</param>\r\n        /// <remarks>This will implicitly enable diagnostics. If you need control, please explicitly set enabled to either <see langword=\"true\"/> or <see langword=\"false\"/>.</remarks>\r\n        public static void Diagnostics(this INancyEnvironment environment, string password, string path = null, string cookieName = null, int slidingTimeout = 15, CryptographyConfiguration cryptographyConfiguration = null)\r\n        {\r\n            Diagnostics(\r\n                environment,\r\n                enabled: true,\r\n                password: password,\r\n                path: path,\r\n                cookieName: cookieName,\r\n                slidingTimeout: slidingTimeout,\r\n                cryptographyConfiguration: cryptographyConfiguration);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Configures diagnostics.\r\n        /// </summary>\r\n        /// <param name=\"environment\"><see cref=\"INancyEnvironment\"/> that should be configured.</param>\r\n        /// <param name=\"enabled\"><see langword=\"true\"/> if diagnostics should be enabled, otherwise <see langword=\"false\"/>.</param>\r\n        /// <param name=\"password\">Password used to secure the dashboard.</param>\r\n        /// <param name=\"path\">Relative path of the dashboard.</param>\r\n        /// <param name=\"cookieName\">Name of the cookie to store diagnostics information.</param>\r\n        /// <param name=\"slidingTimeout\">Number of minutes that expiry of the diagnostics dashboard.</param>\r\n        /// <param name=\"cryptographyConfiguration\">Cryptography config to use for securing the dashboard.</param>\r\n        public static void Diagnostics(this INancyEnvironment environment, bool enabled, string password, string path = null, string cookieName = null, int slidingTimeout = 15, CryptographyConfiguration cryptographyConfiguration = null)\r\n        {\r\n            environment.AddValue(new DiagnosticsConfiguration(\r\n                enabled: enabled,\r\n                password: password,\r\n                path: path,\r\n                cookieName: cookieName,\r\n                slidingTimeout: slidingTimeout,\r\n                cryptographyConfiguration: cryptographyConfiguration));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Diagnostics/DiagnosticsHook.cs",
    "content": "namespace Nancy.Diagnostics\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using System.Threading;\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Configuration;\r\n    using Nancy.Conventions;\r\n    using Nancy.Cookies;\r\n    using Nancy.Cryptography;\r\n    using Nancy.Culture;\r\n    using Nancy.Json;\r\n    using Nancy.Localization;\r\n    using Nancy.ModelBinding;\r\n    using Nancy.Responses;\r\n    using Nancy.Responses.Negotiation;\r\n    using Nancy.Routing;\r\n    using Nancy.Routing.Constraints;\r\n    using Nancy.Routing.Trie;\r\n\r\n    /// <summary>\r\n    /// Pipeline hook to handle diagnostics dashboard requests.\r\n    /// </summary>\r\n    public static class DiagnosticsHook\r\n    {\r\n        private static readonly CancellationToken CancellationToken = new CancellationToken();\r\n        private const string PipelineKey = \"__Diagnostics\";\r\n        internal const string ItemsKey = \"DIAGS_REQUEST\";\r\n\r\n        /// <summary>\r\n        /// Enables the diagnostics dashboard and will intercept all requests that are passed to\r\n        /// the condigured paths.\r\n        /// </summary>\r\n        public static void Enable(IPipelines pipelines, IEnumerable<IDiagnosticsProvider> providers, IRootPathProvider rootPathProvider, IRequestTracing requestTracing, NancyInternalConfiguration configuration, IModelBinderLocator modelBinderLocator, IEnumerable<IResponseProcessor> responseProcessors, IEnumerable<IRouteSegmentConstraint> routeSegmentConstraints, ICultureService cultureService, IRequestTraceFactory requestTraceFactory, IEnumerable<IRouteMetadataProvider> routeMetadataProviders, ITextResource textResource, INancyEnvironment environment, ITypeCatalog typeCatalog, IAssemblyCatalog assemblyCatalog, AcceptHeaderCoercionConventions acceptHeaderCoercionConventions)\r\n        {\r\n            var diagnosticsConfiguration =\r\n                environment.GetValue<DiagnosticsConfiguration>();\r\n\r\n            var diagnosticsEnvironment =\r\n                GetDiagnosticsEnvironment();\r\n\r\n            var diagnosticsModuleCatalog = new DiagnosticsModuleCatalog(providers, rootPathProvider, requestTracing, configuration, diagnosticsEnvironment, typeCatalog, assemblyCatalog);\r\n\r\n            var diagnosticsRouteCache = new RouteCache(\r\n                diagnosticsModuleCatalog,\r\n                new DefaultNancyContextFactory(cultureService, requestTraceFactory, textResource, environment),\r\n                new DefaultRouteSegmentExtractor(),\r\n                new DefaultRouteDescriptionProvider(),\r\n                cultureService,\r\n                routeMetadataProviders);\r\n\r\n            var diagnosticsRouteResolver = new DefaultRouteResolver(\r\n                diagnosticsModuleCatalog,\r\n                new DiagnosticsModuleBuilder(rootPathProvider, modelBinderLocator, diagnosticsEnvironment, environment),\r\n                diagnosticsRouteCache,\r\n                new RouteResolverTrie(new TrieNodeFactory(routeSegmentConstraints)),\r\n                environment);\r\n            var diagnosticResponseNegotiator = new DefaultResponseNegotiator(responseProcessors, acceptHeaderCoercionConventions);\r\n            var diagnosticRouteInvoker = new DefaultRouteInvoker(diagnosticResponseNegotiator);\r\n\r\n            var serializer = new DefaultObjectSerializer();\r\n\r\n            pipelines.BeforeRequest.AddItemToStartOfPipeline(\r\n                new PipelineItem<Func<NancyContext, Response>>(\r\n                    PipelineKey,\r\n                    ctx =>\r\n                    {\r\n                        if (!ctx.ControlPanelEnabled)\r\n                        {\r\n                            return null;\r\n                        }\r\n\r\n                        if (!ctx.Request.Path.StartsWith(diagnosticsConfiguration.Path, StringComparison.OrdinalIgnoreCase))\r\n                        {\r\n                            return null;\r\n                        }\r\n\r\n                        if (!diagnosticsConfiguration.Enabled)\r\n                        {\r\n                            return HttpStatusCode.NotFound;\r\n                        }\r\n\r\n                        ctx.Items[ItemsKey] = true;\r\n\r\n                        var resourcePrefix =\r\n                            string.Concat(diagnosticsConfiguration.Path, \"/Resources/\");\r\n\r\n                        if (ctx.Request.Path.StartsWith(resourcePrefix, StringComparison.OrdinalIgnoreCase))\r\n                        {\r\n                            var resourceNamespace = \"Nancy.Diagnostics.Resources\";\r\n\r\n                            var path = Path.GetDirectoryName(ctx.Request.Url.Path.Replace(resourcePrefix, string.Empty)) ?? string.Empty;\r\n                            if (!string.IsNullOrEmpty(path))\r\n                            {\r\n                                resourceNamespace += string.Format(\".{0}\", path.Replace(Path.DirectorySeparatorChar, '.'));\r\n                            }\r\n\r\n                            return new EmbeddedFileResponse(\r\n                                typeof(DiagnosticsHook).GetTypeInfo().Assembly,\r\n                                resourceNamespace,\r\n                                Path.GetFileName(ctx.Request.Url.Path));\r\n                        }\r\n\r\n                        RewriteDiagnosticsUrl(diagnosticsConfiguration, ctx);\r\n\r\n                        return ValidateConfiguration(diagnosticsConfiguration)\r\n                                   ? ExecuteDiagnostics(ctx, diagnosticsRouteResolver, diagnosticsConfiguration, serializer, diagnosticsEnvironment, diagnosticRouteInvoker)\r\n                                   : new DiagnosticsViewRenderer(ctx, environment)[\"help\"];\r\n                    }));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a special <see cref=\"INancyEnvironment\"/> instance that is separate from the\r\n        /// one used by the application.\r\n        /// </summary>\r\n        /// <returns></returns>\r\n        private static INancyEnvironment GetDiagnosticsEnvironment()\r\n        {\r\n            var diagnosticsEnvironment =\r\n                new DefaultNancyEnvironment();\r\n\r\n            diagnosticsEnvironment.Globalization(new[] { \"en-US\" });\r\n            diagnosticsEnvironment.Json(retainCasing: false);\r\n            diagnosticsEnvironment.AddValue(ViewConfiguration.Default);\r\n            diagnosticsEnvironment.Tracing(\r\n                enabled: true,\r\n                displayErrorTraces: true);\r\n\r\n            return diagnosticsEnvironment;\r\n        }\r\n\r\n        private static bool ValidateConfiguration(DiagnosticsConfiguration configuration)\r\n        {\r\n            return !string.IsNullOrWhiteSpace(configuration.Password) &&\r\n                !string.IsNullOrWhiteSpace(configuration.CookieName) &&\r\n                !string.IsNullOrWhiteSpace(configuration.Path) &&\r\n                configuration.SlidingTimeout != 0;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Disables the specified pipelines.\r\n        /// <seealso cref=\"IPipelines\"/>\r\n        /// </summary>\r\n        /// <param name=\"pipelines\">The pipelines.</param>\r\n        public static void Disable(IPipelines pipelines)\r\n        {\r\n            pipelines.BeforeRequest.RemoveByName(PipelineKey);\r\n        }\r\n\r\n        private static Response GetDiagnosticsLoginView(NancyContext ctx, INancyEnvironment environment)\r\n        {\r\n            var renderer = new DiagnosticsViewRenderer(ctx, environment);\r\n\r\n            return renderer[\"login\"];\r\n        }\r\n\r\n        private static Response ExecuteDiagnostics(NancyContext ctx, IRouteResolver routeResolver, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer, INancyEnvironment environment, IRouteInvoker routeInvoker)\r\n        {\r\n            var session = GetSession(ctx, diagnosticsConfiguration, serializer);\r\n\r\n            if (session == null)\r\n            {\r\n                var view = GetDiagnosticsLoginView(ctx, environment);\r\n\r\n                view.WithCookie(\r\n                    new NancyCookie(diagnosticsConfiguration.CookieName, string.Empty, true) { Expires = DateTime.Now.AddDays(-1) });\r\n\r\n                return view;\r\n            }\r\n\r\n            var resolveResult = routeResolver.Resolve(ctx);\r\n\r\n            ctx.Parameters = resolveResult.Parameters;\r\n            ExecuteRoutePreReq(ctx, CancellationToken, resolveResult.Before);\r\n\r\n            if (ctx.Response == null)\r\n            {\r\n                var routeResult = routeInvoker.Invoke(resolveResult.Route, CancellationToken, resolveResult.Parameters, ctx);\r\n                ctx.Response = routeResult.Result;\r\n            }\r\n\r\n            if (ctx.Request.Method.Equals(\"HEAD\", StringComparison.OrdinalIgnoreCase))\r\n            {\r\n                ctx.Response = new HeadResponse(ctx.Response);\r\n            }\r\n\r\n            if (resolveResult.After != null)\r\n            {\r\n                resolveResult.After.Invoke(ctx, CancellationToken);\r\n            }\r\n\r\n            AddUpdateSessionCookie(session, ctx, diagnosticsConfiguration, serializer);\r\n\r\n            return ctx.Response;\r\n        }\r\n\r\n        private static void AddUpdateSessionCookie(DiagnosticsSession session, NancyContext context, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer)\r\n        {\r\n            if (context.Response == null)\r\n            {\r\n                return;\r\n            }\r\n\r\n            session.Expiry = DateTime.Now.AddMinutes(diagnosticsConfiguration.SlidingTimeout);\r\n            var serializedSession = serializer.Serialize(session);\r\n\r\n            var encryptedSession = diagnosticsConfiguration.CryptographyConfiguration.EncryptionProvider.Encrypt(serializedSession);\r\n            var hmacBytes = diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.GenerateHmac(encryptedSession);\r\n            var hmacString = Convert.ToBase64String(hmacBytes);\r\n\r\n            var cookie = new NancyCookie(diagnosticsConfiguration.CookieName, string.Format(\"{1}{0}\", encryptedSession, hmacString), true);\r\n\r\n            context.Response.WithCookie(cookie);\r\n        }\r\n\r\n        private static DiagnosticsSession GetSession(NancyContext context, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer)\r\n        {\r\n            if (context.Request == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            if (IsLoginRequest(context, diagnosticsConfiguration))\r\n            {\r\n                return ProcessLogin(context, diagnosticsConfiguration, serializer);\r\n            }\r\n\r\n            string encryptedValue;\r\n            if (!context.Request.Cookies.TryGetValue(diagnosticsConfiguration.CookieName, out encryptedValue))\r\n            {\r\n                return null;\r\n            }\r\n\r\n            var hmacStringLength = Base64Helpers.GetBase64Length(diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.HmacLength);\r\n            var encryptedSession = encryptedValue.Substring(hmacStringLength);\r\n            var hmacString = encryptedValue.Substring(0, hmacStringLength);\r\n\r\n            var hmacBytes = Convert.FromBase64String(hmacString);\r\n            var newHmac = diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.GenerateHmac(encryptedSession);\r\n            var hmacValid = HmacComparer.Compare(newHmac, hmacBytes, diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.HmacLength);\r\n\r\n            if (!hmacValid)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            var decryptedValue = diagnosticsConfiguration.CryptographyConfiguration.EncryptionProvider.Decrypt(encryptedSession);\r\n            var session = serializer.Deserialize(decryptedValue) as DiagnosticsSession;\r\n\r\n            if (session == null || session.Expiry < DateTimeOffset.Now || !SessionPasswordValid(session, diagnosticsConfiguration.Password))\r\n            {\r\n                return null;\r\n            }\r\n\r\n            return session;\r\n        }\r\n\r\n        private static bool SessionPasswordValid(DiagnosticsSession session, string realPassword)\r\n        {\r\n            var newHash = DiagnosticsSession.GenerateSaltedHash(realPassword, session.Salt);\r\n\r\n            return (newHash.Length == session.Hash.Length && newHash.SequenceEqual(session.Hash));\r\n        }\r\n\r\n        private static DiagnosticsSession ProcessLogin(NancyContext context, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer)\r\n        {\r\n            string password = context.Request.Form.Password;\r\n\r\n            if (!string.Equals(password, diagnosticsConfiguration.Password, StringComparison.Ordinal))\r\n            {\r\n                return null;\r\n            }\r\n\r\n            var salt = DiagnosticsSession.GenerateRandomSalt();\r\n            var hash = DiagnosticsSession.GenerateSaltedHash(password, salt);\r\n            var session = new DiagnosticsSession\r\n            {\r\n                Hash = hash,\r\n                Salt = salt,\r\n                Expiry = DateTime.Now.AddMinutes(diagnosticsConfiguration.SlidingTimeout)\r\n            };\r\n\r\n            return session;\r\n        }\r\n\r\n        private static bool IsLoginRequest(NancyContext context, DiagnosticsConfiguration diagnosticsConfiguration)\r\n        {\r\n            return context.Request.Method.Equals(\"POST\", StringComparison.OrdinalIgnoreCase) &&\r\n                context.Request.Url.BasePath.TrimEnd('/').EndsWith(diagnosticsConfiguration.Path) &&\r\n                context.Request.Url.Path == \"/\";\r\n        }\r\n\r\n        private static void ExecuteRoutePreReq(NancyContext context, CancellationToken cancellationToken, BeforePipeline resolveResultPreReq)\r\n        {\r\n            if (resolveResultPreReq == null)\r\n            {\r\n                return;\r\n            }\r\n\r\n            var resolveResultPreReqResponse = resolveResultPreReq.Invoke(context, cancellationToken).Result;\r\n\r\n            if (resolveResultPreReqResponse != null)\r\n            {\r\n                context.Response = resolveResultPreReqResponse;\r\n            }\r\n        }\r\n\r\n        private static void RewriteDiagnosticsUrl(DiagnosticsConfiguration diagnosticsConfiguration, NancyContext ctx)\r\n        {\r\n            ctx.Request.Url.BasePath =\r\n                string.Concat(ctx.Request.Url.BasePath, diagnosticsConfiguration.Path);\r\n\r\n            ctx.Request.Url.Path =\r\n                ctx.Request.Url.Path.Substring(diagnosticsConfiguration.Path.Length);\r\n\r\n            if (ctx.Request.Url.Path.Length.Equals(0))\r\n            {\r\n                ctx.Request.Url.Path = \"/\";\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Diagnostics/DiagnosticsModuleBuilder.cs",
    "content": "namespace Nancy.Diagnostics\r\n{\r\n    using Nancy.Configuration;\r\n    using Nancy.ModelBinding;\r\n    using Nancy.Routing;\r\n\r\n    internal class DiagnosticsModuleBuilder : INancyModuleBuilder\r\n    {\r\n        private readonly IRootPathProvider rootPathProvider;\r\n        private readonly ISerializerFactory serializerFactory;\r\n        private readonly IModelBinderLocator modelBinderLocator;\r\n        private readonly INancyEnvironment environment;\r\n\r\n        public DiagnosticsModuleBuilder(IRootPathProvider rootPathProvider, IModelBinderLocator modelBinderLocator, INancyEnvironment diagnosticsEnvironment, INancyEnvironment environment)\r\n        {\r\n            this.rootPathProvider = rootPathProvider;\r\n            this.serializerFactory = new DiagnosticsSerializerFactory(diagnosticsEnvironment);\r\n            this.modelBinderLocator = modelBinderLocator;\r\n            this.environment = environment;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Builds a fully configured <see cref=\"INancyModule\"/> instance, based upon the provided <paramref name=\"module\"/>.\r\n        /// </summary>\r\n        /// <param name=\"module\">The <see cref=\"INancyModule\"/> that should be configured.</param>\r\n        /// <param name=\"context\">The current request context.</param>\r\n        /// <returns>A fully configured <see cref=\"INancyModule\"/> instance.</returns>\r\n        public INancyModule BuildModule(INancyModule module, NancyContext context)\r\n        {\r\n            module.Context = context;\r\n            module.Response = new DefaultResponseFormatter(rootPathProvider, context, this.serializerFactory, this.environment);\r\n            module.ModelBinderLocator = this.modelBinderLocator;\r\n\r\n            module.After = new AfterPipeline();\r\n            module.Before = new BeforePipeline();\r\n            module.OnError = new ErrorPipeline();\r\n\r\n            return module;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/DiagnosticsModuleCatalog.cs",
    "content": "namespace Nancy.Diagnostics\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Configuration;\r\n    using Nancy.Json;\r\n    using Nancy.ModelBinding;\r\n    using Nancy.Responses;\r\n    using Nancy.TinyIoc;\r\n\r\n    internal class DiagnosticsModuleCatalog : INancyModuleCatalog\r\n    {\r\n        private readonly TinyIoCContainer container;\r\n\r\n        public DiagnosticsModuleCatalog(IEnumerable<IDiagnosticsProvider> providers, IRootPathProvider rootPathProvider, IRequestTracing requestTracing, NancyInternalConfiguration configuration, INancyEnvironment diagnosticsEnvironment, ITypeCatalog typeCatalog, IAssemblyCatalog assemblyCatalog)\r\n        {\r\n            this.container = ConfigureContainer(providers, rootPathProvider, requestTracing, configuration, diagnosticsEnvironment, typeCatalog, assemblyCatalog);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get all NancyModule implementation instances - should be per-request lifetime\r\n        /// </summary>\r\n        /// <param name=\"context\">The current context</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance containing <see cref=\"INancyModule\"/> instances.</returns>\r\n        public IEnumerable<INancyModule> GetAllModules(NancyContext context)\r\n        {\r\n            return this.container.ResolveAll<INancyModule>(false);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Retrieves a specific <see cref=\"INancyModule\"/> implementation - should be per-request lifetime\r\n        /// </summary>\r\n        /// <param name=\"moduleType\">Module type</param>\r\n        /// <param name=\"context\">The current context</param>\r\n        /// <returns>The <see cref=\"INancyModule\"/> instance</returns>\r\n        public INancyModule GetModule(Type moduleType, NancyContext context)\r\n        {\r\n            return this.container.Resolve<INancyModule>(moduleType.FullName);\r\n        }\r\n\r\n        private static TinyIoCContainer ConfigureContainer(IEnumerable<IDiagnosticsProvider> providers, IRootPathProvider rootPathProvider, IRequestTracing requestTracing, NancyInternalConfiguration configuration, INancyEnvironment diagnosticsEnvironment, ITypeCatalog typeCatalog, IAssemblyCatalog assemblyCatalog)\r\n        {\r\n            var diagContainer = new TinyIoCContainer();\r\n\r\n            diagContainer.Register<IInteractiveDiagnostics, InteractiveDiagnostics>();\r\n            diagContainer.Register<IRequestTracing>(requestTracing);\r\n            diagContainer.Register<IRootPathProvider>(rootPathProvider);\r\n            diagContainer.Register<NancyInternalConfiguration>(configuration);\r\n            diagContainer.Register<IModelBinderLocator, DefaultModelBinderLocator>();\r\n            diagContainer.Register<IBinder, DefaultBinder>();\r\n            diagContainer.Register<IFieldNameConverter, DefaultFieldNameConverter>();\r\n            diagContainer.Register<BindingDefaults, BindingDefaults>();\r\n            diagContainer.Register<INancyEnvironment>(diagnosticsEnvironment);\r\n            diagContainer.Register<ISerializer>(new DefaultJsonSerializer(diagnosticsEnvironment));\r\n            diagContainer.Register<ITypeCatalog>(typeCatalog);\r\n            diagContainer.Register<IAssemblyCatalog>(assemblyCatalog);\r\n\r\n\r\n            foreach (var diagnosticsProvider in providers)\r\n            {\r\n                var key = string.Concat(\r\n                    diagnosticsProvider.GetType().FullName,\r\n                    \"_\",\r\n                    diagnosticsProvider.DiagnosticObject.GetType().FullName);\r\n\r\n                diagContainer.Register<IDiagnosticsProvider>(diagnosticsProvider, key);\r\n            }\r\n\r\n            foreach (var moduleType in typeCatalog.GetTypesAssignableTo<DiagnosticModule>())\r\n            {\r\n                diagContainer.Register(typeof(INancyModule), moduleType, moduleType.FullName).AsMultiInstance();\r\n            }\r\n\r\n            return diagContainer;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Diagnostics/DiagnosticsSerializerFactory.cs",
    "content": "namespace Nancy.Diagnostics\r\n{\r\n    using Nancy.Configuration;\r\n    using Nancy.Responses;\r\n    using Nancy.Responses.Negotiation;\r\n\r\n    internal class DiagnosticsSerializerFactory : ISerializerFactory\r\n    {\r\n        private readonly ISerializer serializer;\r\n\r\n        public DiagnosticsSerializerFactory(INancyEnvironment diagnosticsEnvironment)\r\n        {\r\n            this.serializer = new DefaultJsonSerializer(diagnosticsEnvironment);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"ISerializer\"/> implementation that can serialize the provided <paramref name=\"mediaRange\"/>.\r\n        /// </summary>\r\n        /// <param name=\"mediaRange\">The <see cref=\"MediaRange\"/> to get a serializer for.</param>\r\n        /// <returns>An <see cref=\"ISerializer\"/> instance, or <see langword=\"null\" /> if not match was found.</returns>\r\n        public ISerializer GetSerializer(MediaRange mediaRange)\r\n        {\r\n            return this.serializer;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Diagnostics/DiagnosticsSession.cs",
    "content": "namespace Nancy.Diagnostics\r\n{\r\n    using System;\r\n    using System.Security.Cryptography;\r\n    using System.Text;\r\n    \r\n    /// <summary>\r\n    /// Stores the http session information for diagnostics.\r\n    /// </summary>\r\n    \r\n#if !NETSTANDARD1_6\r\n    [Serializable]\r\n#endif\r\n\r\n    public class DiagnosticsSession\r\n    {\r\n        /// <summary>\r\n        /// Gets or sets the hash.\r\n        /// </summary>\r\n        /// <value>The (salted) SHA256 hash.</value>\r\n        public byte[] Hash { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the salt.\r\n        /// </summary>\r\n        /// <value>The salt for the hash value.</value>\r\n        public byte[] Salt { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the expiry.\r\n        /// </summary>\r\n        /// <value>The time when the session will be expired.</value>\r\n        public DateTimeOffset Expiry { get; set; }\r\n\r\n        /// <summary>\r\n        /// Generates a random salt.\r\n        /// </summary>\r\n        /// <returns>A byte array representing the random salt.</returns>\r\n        public static byte[] GenerateRandomSalt()\r\n        {\r\n            var provider = RandomNumberGenerator.Create();\r\n\r\n            var buffer = new byte[32];\r\n            provider.GetBytes(buffer);\r\n\r\n            return buffer;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Generates the salted hash of a byte array.\r\n        /// </summary>\r\n        /// <param name=\"plainText\">The plain text as <see cref=\"byte\"/> array.</param>\r\n        /// <param name=\"salt\">The salt as <see cref=\"byte\"/> array.</param>\r\n        /// <returns>A byte array representing the salted hash.</returns>\r\n        public static byte[] GenerateSaltedHash(byte[] plainText, byte[] salt)\r\n        {\r\n            var algorithm = SHA256.Create();\r\n\r\n            var plainTextWithSaltBytes = new byte[plainText.Length + salt.Length];\r\n\r\n            for (var i = 0; i < plainText.Length; i++)\r\n            {\r\n                plainTextWithSaltBytes[i] = plainText[i];\r\n            }\r\n\r\n            for (var i = 0; i < salt.Length; i++)\r\n            {\r\n                plainTextWithSaltBytes[plainText.Length + i] = salt[i];\r\n            }\r\n\r\n            return algorithm.ComputeHash(plainTextWithSaltBytes);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Generates the salted hash of a <see cref=\"string\"/>.\r\n        /// </summary>\r\n        /// <param name=\"plainText\">The plain text as <see cref=\"string\"/></param>\r\n        /// <param name=\"salt\">The salt as <see cref=\"byte\"/> array.</param>\r\n        /// <returns>A byte array representing the salted hash.</returns>\r\n        public static byte[] GenerateSaltedHash(string plainText, byte[] salt)\r\n        {\r\n            return GenerateSaltedHash(Encoding.UTF8.GetBytes(plainText), salt);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/DiagnosticsViewRenderer.cs",
    "content": "namespace Nancy.Diagnostics\r\n{\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using Configuration;\r\n    using Nancy.Localization;\r\n    using Nancy.Responses;\r\n    using Nancy.Security;\r\n    using Nancy.ViewEngines;\r\n    using Nancy.ViewEngines.SuperSimpleViewEngine;\r\n\r\n    /// <summary>\r\n    /// Renders diagnostics views from embedded resources.\r\n    /// </summary>\r\n    public class DiagnosticsViewRenderer\r\n    {\r\n        private readonly NancyContext context;\r\n        private readonly INancyEnvironment environment;\r\n        private static readonly IViewResolver ViewResolver = new DiagnosticsViewResolver();\r\n        private static readonly IViewEngine Engine = new SuperSimpleViewEngineWrapper(Enumerable.Empty<ISuperSimpleViewEngineMatcher>());\r\n\r\n        /// <summary>\r\n        /// Creates a new instance of the <see cref=\"DiagnosticsViewRenderer\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"context\">A <see cref=\"NancyContext\"/> instance.</param>\r\n        /// <param name=\"environment\">An <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        public DiagnosticsViewRenderer(NancyContext context, INancyEnvironment environment)\r\n        {\r\n            this.context = context;\r\n            this.environment = environment;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Renders the diagnostics view with the provided <paramref name=\"name\"/>.\r\n        /// </summary>\r\n        /// <param name=\"name\">The name of the view to render.</param>\r\n        /// <returns>A <see cref=\"Response\"/> of the rendered view.</returns>\r\n        public Response this[string name]\r\n        {\r\n            get { return this.RenderView(name, null, this.context); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Renders the diagnostics view with the provided <paramref name=\"name\"/> and <paramref name=\"model\"/>.\r\n        /// </summary>\r\n        /// <param name=\"name\">The name of the view to render.</param>\r\n        /// <param name=\"model\">The model that should be passed to the view engine during rendering.</param>\r\n        /// <returns>A <see cref=\"Response\"/> of the rendered view.</returns>\r\n        public Response this[string name, dynamic model]\r\n        {\r\n            get { return RenderView(name, model, this.context); }\r\n        }\r\n\r\n        private Response RenderView(string name, dynamic model, NancyContext context)\r\n        {\r\n            var fullName = string.Concat(name, \".sshtml\");\r\n            var stream = GetBodyStream(fullName);\r\n            var location = GetViewLocationResult(fullName, stream);\r\n            var cache = new DefaultViewCache(this.environment);\r\n\r\n            context.Items.Add(CsrfToken.DEFAULT_CSRF_KEY, \"DIAGNOSTICSTOKEN\");\r\n\r\n            var renderContext =\r\n                new DefaultRenderContext(ViewResolver, cache, new DummyTextResource(), new ViewLocationContext() { Context = context });\r\n\r\n            return Engine.RenderView(location, model, renderContext);\r\n        }\r\n\r\n        private static Stream GetBodyStream(string name)\r\n        {\r\n            var view = new EmbeddedFileResponse(typeof(DiagnosticsViewRenderer).GetTypeInfo().Assembly, \"Nancy.Diagnostics.Views\", name);\r\n\r\n            var stream = new MemoryStream();\r\n\r\n            view.Contents.Invoke(stream);\r\n            stream.Position = 0;\r\n            return stream;\r\n        }\r\n\r\n        private static ViewLocationResult GetViewLocationResult(string name, Stream bodyStream)\r\n        {\r\n            return new ViewLocationResult(\r\n                \"Nancy/Diagnostics/Views\",\r\n                name,\r\n                \"sshtml\",\r\n                () => new StreamReader(bodyStream));\r\n        }\r\n\r\n        internal class DiagnosticsViewResolver : IViewResolver\r\n        {\r\n            /// <summary>\r\n            /// Locates a view based on the provided information.\r\n            /// </summary>\r\n            /// <param name=\"viewName\">The name of the view to locate.</param>\r\n            /// <param name=\"model\">The model that will be used with the view.</param>\r\n            /// <param name=\"viewLocationContext\">A <see cref=\"ViewLocationContext\"/> instance, containing information about the context for which the view is being located.</param>\r\n            /// <returns>A <see cref=\"ViewLocationResult\"/> instance if the view could be found, otherwise <see langword=\"null\"/>.</returns>\r\n            public ViewLocationResult GetViewLocation(string viewName, dynamic model, ViewLocationContext viewLocationContext)\r\n            {\r\n                var fullName = string.Concat(viewName, \".sshtml\");\r\n\r\n                var stream = GetBodyStream(fullName);\r\n\r\n                return GetViewLocationResult(fullName, stream);\r\n            }\r\n        }\r\n\r\n        internal class DummyTextResource : ITextResource\r\n        {\r\n            public string this[string key, NancyContext context]\r\n            {\r\n                get { return string.Empty; }\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Diagnostics/DisabledDiagnostics.cs",
    "content": "namespace Nancy.Diagnostics\r\n{\r\n    using Nancy.Bootstrapper;\r\n\r\n    /// <summary>\r\n    /// Implementation of the <see cref=\"IDiagnostics\"/> interface that does nothing.\r\n    /// </summary>\r\n    public class DisabledDiagnostics : IDiagnostics\r\n    {\r\n        /// <summary>\r\n        /// Initialise diagnostics\r\n        /// </summary>\r\n        /// <param name=\"pipelines\">Application pipelines</param>\r\n        public void Initialize(IPipelines pipelines)\r\n        {\r\n            // Do nothing :-)\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/IDiagnostics.cs",
    "content": "namespace Nancy.Diagnostics\r\n{\r\n    using Nancy.Bootstrapper;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality for Nancy diagnostics.\r\n    /// </summary>\r\n    public interface IDiagnostics\r\n    {\r\n        /// <summary>\r\n        /// Initializes diagnostics\r\n        /// </summary>\r\n        /// <param name=\"pipelines\">Application pipelines</param>\r\n        void Initialize(IPipelines pipelines);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/IDiagnosticsProvider.cs",
    "content": "﻿namespace Nancy.Diagnostics\r\n{\r\n    /// <summary>\r\n    /// Defines the functionality a diagnostics provider.\r\n    /// </summary>\r\n    public interface IDiagnosticsProvider\r\n    {\r\n        /// <summary>\r\n        /// Gets the name of the provider.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the name of the provider.</value>\r\n        string Name { get; }\r\n\r\n        /// <summary>\r\n        /// Gets the description of the provider.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the description of the provider.</value>\r\n        string Description { get; }\r\n\r\n        /// <summary>\r\n        /// Gets the object that contains the interactive diagnostics methods.\r\n        /// </summary>\r\n        /// <value>An instance of the interactive diagnostics object.</value>\r\n        object DiagnosticObject { get; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/IInteractiveDiagnostics.cs",
    "content": "namespace Nancy.Diagnostics\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality for Nancy interactive diagnostics\r\n    /// </summary>\r\n    public interface IInteractiveDiagnostics\r\n    {\r\n        /// <summary>\r\n        /// Gets the list of available <see cref=\"InteractiveDiagnostic\"/>.\r\n        /// </summary>\r\n        /// <value>The available diagnostics. <seealso cref=\"InteractiveDiagnostic\"/></value>\r\n        IEnumerable<InteractiveDiagnostic> AvailableDiagnostics { get; }\r\n\r\n        /// <summary>\r\n        /// Executes the <see cref=\"InteractiveDiagnosticMethod\"/>.\r\n        /// </summary>\r\n        /// <param name=\"interactiveDiagnosticMethod\">The <see cref=\"InteractiveDiagnosticMethod\"/> instance</param>\r\n        /// <param name=\"arguments\">The <see cref=\"InteractiveDiagnosticMethod\"/> arguments.</param>\r\n        /// <returns>The result of the <see cref=\"InteractiveDiagnosticMethod\"/> as <see cref=\"object\"/></returns>\r\n        object ExecuteDiagnostic(InteractiveDiagnosticMethod interactiveDiagnosticMethod, object[] arguments);\r\n\r\n        /// <summary>\r\n        /// Gets the template.\r\n        /// </summary>\r\n        /// <param name=\"interactiveDiagnosticMethod\">The <see cref=\"InteractiveDiagnosticMethod\"/> instance</param>\r\n        /// <returns>The template as <see cref=\"string\"/></returns>\r\n        string GetTemplate(InteractiveDiagnosticMethod interactiveDiagnosticMethod);\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"InteractiveDiagnostic\"/>.\r\n        /// </summary>\r\n        /// <param name=\"providerName\">Name of the provider.</param>\r\n        /// <returns>The <see cref=\"InteractiveDiagnostic\"/> instance.</returns>\r\n        InteractiveDiagnostic GetDiagnostic(string providerName);\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"InteractiveDiagnosticMethod\"/>.\r\n        /// </summary>\r\n        /// <param name=\"providerName\">Name of the provider.</param>\r\n        /// <param name=\"methodName\">Name of the method.</param>\r\n        /// <returns>The <see cref=\"InteractiveDiagnosticMethod\"/> instance</returns>\r\n        InteractiveDiagnosticMethod GetMethod(string providerName, string methodName);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/IRequestTrace.cs",
    "content": "namespace Nancy.Diagnostics\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality for tracing a request.\r\n    /// </summary>\r\n    public interface IRequestTrace\r\n    {\r\n        /// <summary>\r\n        /// Gets or sets the generic item store.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IDictionary{TKey,TValue}\"/> instance containing the items.</value>\r\n        IDictionary<string, object> Items { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the information about the request.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"RequestData\"/> instance.</value>\r\n        RequestData RequestData { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the information about the response.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"ResponseData\"/> instance.</value>\r\n        ResponseData ResponseData { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets the trace log.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"ITraceLog\"/> instance.</value>\r\n        ITraceLog TraceLog { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/IRequestTraceFactory.cs",
    "content": "namespace Nancy.Diagnostics\r\n{\r\n    /// <summary>\r\n    /// Defines the functionality for creating an <see cref=\"IRequestTrace\"/> instance.\r\n    /// </summary>\r\n    public interface IRequestTraceFactory\r\n    {\r\n        /// <summary>\r\n        /// Creates an <see cref=\"IRequestTrace\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"request\">A <see cref=\"Request\"/> instance.</param>\r\n        /// <returns>An <see cref=\"IRequestTrace\"/> instance.</returns>\r\n        IRequestTrace Create(Request request);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/IRequestTracing.cs",
    "content": "﻿namespace Nancy.Diagnostics\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality for request tracing.\r\n    /// </summary>\r\n    public interface IRequestTracing\r\n    {\r\n        /// <summary>\r\n        /// Adds the <see cref=\"IRequestTrace\"/>, of the provided, <see cref=\"NancyContext\"/> to the trace log.\r\n        /// </summary>\r\n        /// <param name=\"sessionId\">The identifier of the trace.</param>\r\n        /// <param name=\"context\">A <see cref=\"NancyContext\"/> instance.</param>\r\n        void AddRequestDiagnosticToSession(Guid sessionId, NancyContext context);\r\n\r\n        /// <summary>\r\n        /// Clears the trace log.\r\n        /// </summary>\r\n        void Clear();\r\n\r\n        /// <summary>\r\n        /// Creates a new trace session.\r\n        /// </summary>\r\n        /// <returns>A <see cref=\"Guid\"/> which represents the identifier of the new trace session.</returns>\r\n        Guid CreateSession();\r\n\r\n        /// <summary>\r\n        /// Gets all the available <see cref=\"RequestTraceSession\"/> instances.\r\n        /// </summary>\r\n        /// <returns></returns>\r\n        IEnumerable<RequestTraceSession> GetSessions();\r\n\r\n        /// <summary>\r\n        /// Checks if the provided <paramref name=\"sessionId\"/> is valid or not.\r\n        /// </summary>\r\n        /// <param name=\"sessionId\">A <see cref=\"Guid\"/> representing the session to check.</param>\r\n        /// <returns><see langword=\"true\"/> if the session is valid, otherwise <see langword=\"false\"/>.</returns>\r\n        bool IsValidSessionId(Guid sessionId);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/ITraceLog.cs",
    "content": "namespace Nancy.Diagnostics\r\n{\r\n    using System;\r\n    using System.Text;\r\n\r\n    /// <summary>\r\n    /// Provides request trace logging.\r\n    /// Uses a delegate to write to the log, rather than creating strings regardless\r\n    /// of whether the log is enabled or not.\r\n    /// </summary>\r\n    public interface ITraceLog\r\n    {\r\n        /// <summary>\r\n        /// Write to the log\r\n        /// </summary>\r\n        /// <param name=\"logDelegate\">Log writing delegate</param>\r\n        void WriteLog(Action<StringBuilder> logDelegate);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/InteractiveDiagnostic.cs",
    "content": "namespace Nancy.Diagnostics\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// An interactive diagnostic instance.\r\n    /// </summary>\r\n    public class InteractiveDiagnostic\r\n    {\r\n        /// <summary>\r\n        /// Gets or sets the diagnostic name.\r\n        /// </summary>\r\n        /// <value>The name of the diagnostic</value>\r\n        public string Name { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the diagnostic description.\r\n        /// </summary>\r\n        /// <value>The description of the diagnostic.</value>\r\n        public string Description { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the diagnostic methods.\r\n        /// </summary>\r\n        /// <value>The collection of diagnostic methods.</value>\r\n        public IEnumerable<InteractiveDiagnosticMethod> Methods { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/InteractiveDiagnosticMethod.cs",
    "content": "namespace Nancy.Diagnostics\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Defines an interactive diagnostic method.\r\n    /// </summary>\r\n    public class InteractiveDiagnosticMethod\r\n    {\r\n        /// <summary>\r\n        /// Gets the parent diagnostic object.\r\n        /// </summary>\r\n        /// <value>The parent diagnostic object.</value>\r\n        public object ParentDiagnosticObject { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the return type\r\n        /// </summary>\r\n        /// <value>The type of the method return type</value>\r\n        public Type ReturnType { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the name of the method.\r\n        /// </summary>\r\n        /// <value>The name of the method.</value>\r\n        public string MethodName { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the description.\r\n        /// </summary>\r\n        /// <value>The description of the method.</value>\r\n        public string Description { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the arguments.\r\n        /// </summary>\r\n        /// <value>The arguments for the method.</value>\r\n        public IEnumerable<Tuple<string, Type>> Arguments { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"InteractiveDiagnosticMethod\"/> class, with\r\n        /// the provided <paramref name=\"parentDiagnostic\"/>, <paramref name=\"returnType\"/>, \r\n        /// <paramref name=\"methodName\"/>, <paramref name=\"arguments\"/> and <paramref name=\"description\"/>.\r\n        /// </summary>\r\n        /// <param name=\"parentDiagnostic\">The parent diagnostic.</param>\r\n        /// <param name=\"returnType\">Type of the return.</param>\r\n        /// <param name=\"methodName\">Name of the method.</param>\r\n        /// <param name=\"arguments\">The arguments.</param>\r\n        /// <param name=\"description\">The description.</param>\r\n        public InteractiveDiagnosticMethod(object parentDiagnostic, Type returnType, string methodName, IEnumerable<Tuple<string, Type>> arguments, string description)\r\n        {\r\n            this.ParentDiagnosticObject = parentDiagnostic;\r\n            this.ReturnType = returnType;\r\n            this.MethodName = methodName;\r\n            this.Arguments = arguments;\r\n            this.Description = description;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/InteractiveDiagnostics.cs",
    "content": "﻿namespace Nancy.Diagnostics\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n\r\n    using Nancy.Routing;\r\n\r\n    /// <summary>\r\n    /// Handles interactive diagnostic instances.\r\n    /// </summary>\r\n    /// <seealso cref=\"Nancy.Diagnostics.IInteractiveDiagnostics\" />\r\n    public class InteractiveDiagnostics : IInteractiveDiagnostics\r\n    {\r\n        private readonly IDiagnosticsProvider[] providers;\r\n\r\n        private const BindingFlags Flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;\r\n\r\n        /// <summary>\r\n        /// Gets the list of available diagnostics.\r\n        /// </summary>\r\n        /// <value>The available diagnostics.</value>\r\n        public IEnumerable<InteractiveDiagnostic> AvailableDiagnostics { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Initializes an <see cref=\"InteractiveDiagnostics\"/> class of <see cref=\"IDiagnosticsProvider\"/> instances.\r\n        /// </summary>\r\n        /// <param name=\"providers\">The providers.</param>\r\n        public InteractiveDiagnostics(IEnumerable<IDiagnosticsProvider> providers)\r\n        {\r\n            var customProvidersAvailable = providers.Any(provider =>\r\n            {\r\n                Type providerType = provider.GetType();\r\n\r\n                return providerType != typeof(TestingDiagnosticProvider) &\r\n                       providerType != typeof(DefaultRouteCacheProvider);\r\n            });\r\n\r\n            if (customProvidersAvailable)\r\n            {\r\n                // Exclude only the TestingDiagnosticProvider\r\n                this.providers = providers.Where(provider => provider.GetType() != typeof(TestingDiagnosticProvider)).ToArray();\r\n            }\r\n            else\r\n            {\r\n                this.providers = providers.ToArray();\r\n            }\r\n\r\n            this.BuildAvailableDiagnostics();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Executes the diagnostic.\r\n        /// </summary>\r\n        /// <param name=\"interactiveDiagnosticMethod\">The interactive diagnostic method.</param>\r\n        /// <param name=\"arguments\">The arguments.</param>\r\n        /// <returns>The result of the <see cref=\"InteractiveDiagnosticMethod\"/> as <see cref=\"object\"/></returns>\r\n        /// <exception cref=\"System.ArgumentException\"></exception>\r\n        public object ExecuteDiagnostic(InteractiveDiagnosticMethod interactiveDiagnosticMethod, object[] arguments)\r\n        {\r\n            var method = GetMethodInfo(interactiveDiagnosticMethod);\r\n\r\n            if (method == null)\r\n            {\r\n                throw new ArgumentException(string.Format(\"Unable to locate method: {0}\", interactiveDiagnosticMethod.MethodName));\r\n            }\r\n\r\n            return method.Invoke(interactiveDiagnosticMethod.ParentDiagnosticObject, arguments);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the template for an interactive diagnostic method instance.\r\n        /// </summary>\r\n        /// <param name=\"interactiveDiagnosticMethod\">The interactive diagnostic method.</param>\r\n        /// <returns>The template as <see cref=\"string\"/></returns>\r\n        public string GetTemplate(InteractiveDiagnosticMethod interactiveDiagnosticMethod)\r\n        {\r\n            var diagObjectType = interactiveDiagnosticMethod.ParentDiagnosticObject.GetType();\r\n\r\n            return GetTemplateFromProperty(interactiveDiagnosticMethod, diagObjectType) ??\r\n                   GetTemplateFromAttribute(interactiveDiagnosticMethod);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the diagnostic for a provider.\r\n        /// </summary>\r\n        /// <param name=\"providerName\">Name of the provider.</param>\r\n        /// <returns>The <see cref=\"InteractiveDiagnostic\"/> instance.</returns>\r\n        public InteractiveDiagnostic GetDiagnostic(string providerName)\r\n        {\r\n            return this.AvailableDiagnostics.FirstOrDefault(d => string.Equals(d.Name, providerName, StringComparison.OrdinalIgnoreCase));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the method instance for a method name and provider.\r\n        /// </summary>\r\n        /// <param name=\"providerName\">Name of the provider.</param>\r\n        /// <param name=\"methodName\">Name of the method.</param>\r\n        /// <returns>The <see cref=\"InteractiveDiagnosticMethod\"/> instance</returns>\r\n        public InteractiveDiagnosticMethod GetMethod(string providerName, string methodName)\r\n        {\r\n            var diagnostic = this.GetDiagnostic(providerName);\r\n\r\n            if (diagnostic == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            return diagnostic.Methods.FirstOrDefault(m => string.Equals(m.MethodName, methodName, StringComparison.OrdinalIgnoreCase));\r\n        }\r\n\r\n        private void BuildAvailableDiagnostics()\r\n        {\r\n            var diags = new List<InteractiveDiagnostic>(this.providers.Length);\r\n\r\n            foreach (var diagnosticsProvider in this.providers)\r\n            {\r\n                diags.Add(new InteractiveDiagnostic\r\n                    {\r\n                        Name = diagnosticsProvider.Name,\r\n                        Description = diagnosticsProvider.Description,\r\n                        Methods = this.GetDiagnosticMethods(diagnosticsProvider)\r\n                    });\r\n            }\r\n\r\n            this.AvailableDiagnostics = diags;\r\n        }\r\n\r\n        private IEnumerable<InteractiveDiagnosticMethod> GetDiagnosticMethods(IDiagnosticsProvider diagnosticsProvider)\r\n        {\r\n            var objectMethods = typeof(object).GetMethods().Select(x => x.Name).ToList();\r\n\r\n            var methods = diagnosticsProvider.DiagnosticObject\r\n                                             .GetType()\r\n                                             .GetMethods(Flags)\r\n                                             .Where(x => !objectMethods.Contains(x.Name))\r\n                                             .Where(mi => !mi.IsSpecialName)\r\n                                             .ToArray();\r\n\r\n            var diagnosticMethods = new List<InteractiveDiagnosticMethod>(methods.Length);\r\n\r\n            foreach (var methodInfo in methods)\r\n            {\r\n                diagnosticMethods.Add(new InteractiveDiagnosticMethod(\r\n                                            diagnosticsProvider.DiagnosticObject,\r\n                                            methodInfo.ReturnType,\r\n                                            methodInfo.Name,\r\n                                            this.GetArguments(methodInfo),\r\n                                            this.GetDescription(diagnosticsProvider, methodInfo)));\r\n            }\r\n\r\n            return diagnosticMethods;\r\n        }\r\n\r\n        private string GetDescription(IDiagnosticsProvider diagnosticsProvider, MethodInfo methodInfo)\r\n        {\r\n            return GetDescriptionFromProperty(diagnosticsProvider, methodInfo) ??\r\n                   GetDescriptionFromAttribute(diagnosticsProvider, methodInfo);\r\n        }\r\n\r\n        private IEnumerable<Tuple<string, Type>> GetArguments(MethodInfo methodInfo)\r\n        {\r\n            var parameters = methodInfo.GetParameters();\r\n            var arguments = new List<Tuple<string, Type>>(parameters.Length);\r\n\r\n            foreach (var parameterInfo in parameters)\r\n            {\r\n                arguments.Add(Tuple.Create(parameterInfo.Name, parameterInfo.ParameterType));\r\n            }\r\n\r\n            return arguments;\r\n        }\r\n\r\n        private static string GetTemplateFromProperty(\r\n            InteractiveDiagnosticMethod interactiveDiagnosticMethod, Type diagObjectType)\r\n        {\r\n            var propertyName = String.Format(\"{0}{1}\", interactiveDiagnosticMethod.MethodName, \"Template\");\r\n            var property = diagObjectType.GetProperty(propertyName);\r\n\r\n            if (property == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            return (string)property.GetValue(interactiveDiagnosticMethod.ParentDiagnosticObject, null);\r\n        }\r\n\r\n        private static string GetTemplateFromAttribute(InteractiveDiagnosticMethod interactiveDiagnosticMethod)\r\n        {\r\n            var method = GetMethodInfo(interactiveDiagnosticMethod);\r\n\r\n            var attribute = (TemplateAttribute)method.GetCustomAttribute(typeof(TemplateAttribute));\r\n\r\n            return attribute != null ? attribute.Template : null;\r\n        }\r\n\r\n        private static string GetDescriptionFromProperty(IDiagnosticsProvider diagnosticsProvider, MethodInfo methodInfo)\r\n        {\r\n            var propertyName = String.Format(\"{0}{1}\", methodInfo.Name, \"Description\");\r\n            var property = diagnosticsProvider.DiagnosticObject.GetType().GetProperty(propertyName);\r\n\r\n            if (property == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            return (string)property.GetValue(diagnosticsProvider.DiagnosticObject, null);\r\n        }\r\n\r\n        private static string GetDescriptionFromAttribute(IDiagnosticsProvider diagnosticsProvider, MethodInfo methodInfo)\r\n        {\r\n            var attribute = (DescriptionAttribute)methodInfo.GetCustomAttribute(typeof(DescriptionAttribute));\r\n\r\n            return attribute != null ? attribute.Description : null;\r\n        }\r\n\r\n        private static MethodInfo GetMethodInfo(InteractiveDiagnosticMethod interactiveDiagnosticMethod)\r\n        {\r\n            var diagObjectType = interactiveDiagnosticMethod.ParentDiagnosticObject.GetType();\r\n\r\n            var method = diagObjectType.GetMethod(interactiveDiagnosticMethod.MethodName, Flags);\r\n\r\n            return method;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/Modules/InfoModule.cs",
    "content": "﻿namespace Nancy.Diagnostics.Modules\r\n{\r\n    using System;\r\n    using System.Collections;\r\n    using System.Collections.Generic;\r\n    using System.Dynamic;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Configuration;\r\n    using Nancy.ViewEngines;\r\n\r\n\r\n    /// <summary>\r\n    /// The information module for diagnostics.\r\n    /// </summary>\r\n    /// <seealso cref=\"Nancy.Diagnostics.DiagnosticModule\" />\r\n    public class InfoModule : DiagnosticModule\r\n    {\r\n        private readonly ITypeCatalog typeCatalog;\r\n        private readonly IAssemblyCatalog assemblyCatalog;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"InfoModule\"/> class, with\r\n        /// the provided <paramref name=\"rootPathProvider\"/>, <paramref name=\"configuration\"/>, \r\n        /// <paramref name=\"environment\"/>, <paramref name=\"typeCatalog\"/> and <paramref name=\"assemblyCatalog\"/>.\r\n        /// </summary>\r\n        /// <param name=\"rootPathProvider\">The root path provider.</param>\r\n        /// <param name=\"configuration\">The configuration.</param>\r\n        /// <param name=\"environment\">The environment.</param>\r\n        /// <param name=\"typeCatalog\">The type catalog.</param>\r\n        /// <param name=\"assemblyCatalog\">The assembly catalog.</param>\r\n        public InfoModule(IRootPathProvider rootPathProvider, NancyInternalConfiguration configuration, INancyEnvironment environment, ITypeCatalog typeCatalog, IAssemblyCatalog assemblyCatalog)\r\n            : base(\"/info\")\r\n        {\r\n            this.typeCatalog = typeCatalog;\r\n            this.assemblyCatalog = assemblyCatalog;\r\n\r\n            Get(\"/\", _ =>\r\n            {\r\n                return View[\"Info\"];\r\n            });\r\n\r\n            Get(\"/data\", _ =>\r\n            {\r\n                dynamic data = new ExpandoObject();\r\n\r\n                data.Nancy = new ExpandoObject();\r\n                data.Nancy.Version = string.Format(\"v{0}\", this.GetType().GetTypeInfo().Assembly.GetName().Version.ToString());\r\n                data.Nancy.TracesDisabled = !environment.GetValue<TraceConfiguration>().DisplayErrorTraces;\r\n                data.Nancy.CaseSensitivity = StaticConfiguration.CaseSensitive ? \"Sensitive\" : \"Insensitive\";\r\n                data.Nancy.RootPath = rootPathProvider.GetRootPath();\r\n                data.Nancy.Hosting = GetHosting();\r\n                data.Nancy.BootstrapperContainer = GetBootstrapperContainer();\r\n                data.Nancy.LocatedBootstrapper = NancyBootstrapperLocator.GetBootstrapperType().ToString();\r\n                data.Nancy.LoadedViewEngines = GetViewEngines();\r\n\r\n                data.Configuration = new Dictionary<string, object>();\r\n                foreach (var propertyInfo in configuration.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))\r\n                {\r\n                    var value =\r\n                        propertyInfo.GetValue(configuration, null);\r\n\r\n                    data.Configuration[propertyInfo.Name] = (!typeof(IEnumerable).IsAssignableFrom(value.GetType())) ?\r\n                        new[] { value.ToString() } :\r\n                        ((IEnumerable<object>)value).Select(x => x.ToString());\r\n                }\r\n\r\n                return this.Response.AsJson((object)data);\r\n            });\r\n        }\r\n\r\n        private string[] GetViewEngines()\r\n        {\r\n            var engines = this.typeCatalog.GetTypesAssignableTo<IViewEngine>();\r\n\r\n            return engines\r\n                .Select(engine => engine.Name.Split(new [] { \"ViewEngine\" }, StringSplitOptions.None)[0])\r\n                .ToArray();\r\n        }\r\n\r\n        private string GetBootstrapperContainer()\r\n        {\r\n            var name = this.assemblyCatalog\r\n                .GetAssemblies()\r\n                .Select(asm => asm.GetName())\r\n                .FirstOrDefault(asmName => asmName.Name != null && asmName.Name.StartsWith(\"Nancy.Bootstrappers.\"));\r\n\r\n            return (name == null) ?\r\n                \"TinyIoC\" :\r\n                string.Format(\"{0} (v{1})\", name.Name.Split('.').Last(), name.Version);\r\n        }\r\n\r\n        private string GetHosting()\r\n        {\r\n            var name = this.assemblyCatalog\r\n                .GetAssemblies()\r\n                .Select(asm => asm.GetName())\r\n                .FirstOrDefault(asmName => asmName.Name != null && asmName.Name.StartsWith(\"Nancy.Hosting.\"));\r\n\r\n            return (name == null) ?\r\n                \"Unknown\" :\r\n                string.Format(\"{0} (v{1})\", name.Name.Split('.').Last(), name.Version);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/Modules/InteractiveModule.cs",
    "content": "﻿namespace Nancy.Diagnostics.Modules\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.ComponentModel;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using Nancy.Helpers;\r\n\r\n    /// <summary>\r\n    /// Nancy module for interactive diagnostics.\r\n    /// </summary>\r\n    /// <seealso cref=\"Nancy.Diagnostics.DiagnosticModule\" />\r\n    public class InteractiveModule : DiagnosticModule\r\n    {\r\n        private readonly IInteractiveDiagnostics interactiveDiagnostics;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"InteractiveModule\"/> class, with\r\n        /// the provided <paramref name=\"interactiveDiagnostics\"/>.\r\n        /// </summary>\r\n        /// <param name=\"interactiveDiagnostics\">The interactive diagnostics.</param>\r\n        public InteractiveModule(IInteractiveDiagnostics interactiveDiagnostics)\r\n            :base (\"/interactive\")\r\n        {\r\n            this.interactiveDiagnostics = interactiveDiagnostics;\r\n\r\n            Get(\"/\", _ =>\r\n            {\r\n                return View[\"InteractiveDiagnostics\"];\r\n            });\r\n\r\n            Get(\"/providers\", _ =>\r\n            {\r\n                var providers = this.interactiveDiagnostics\r\n                    .AvailableDiagnostics\r\n                    .Select(p => new\r\n                        {\r\n                            p.Name,\r\n                            p.Description,\r\n                            Type = p.GetType().Name,\r\n                            p.GetType().Namespace,\r\n                            Assembly = p.GetType().GetTypeInfo().Assembly.GetName().Name\r\n                        })\r\n                    .ToArray();\r\n\r\n                return this.Response.AsJson(providers);\r\n            });\r\n\r\n            Get(\"/providers/{providerName}\", ctx =>\r\n            {\r\n                var providerName =\r\n                    HttpUtility.UrlDecode((string)ctx.providerName);\r\n\r\n                var diagnostic =\r\n                    this.interactiveDiagnostics.GetDiagnostic(providerName);\r\n\r\n                if (diagnostic == null)\r\n                {\r\n                    return HttpStatusCode.NotFound;\r\n                }\r\n\r\n                var methods = diagnostic.Methods\r\n                    .Select(m => new\r\n                    {\r\n                        m.MethodName,\r\n                        ReturnType = m.ReturnType.ToString(),\r\n                        m.Description,\r\n                        Arguments = m.Arguments.Select(a => new\r\n                        {\r\n                            ArgumentName = a.Item1,\r\n                            ArgumentType = a.Item2.ToString()\r\n                        })\r\n                    })\r\n                    .ToArray();\r\n\r\n                return this.Response.AsJson(methods);\r\n            });\r\n\r\n            Get(\"/providers/{providerName}/{methodName}\", ctx =>\r\n            {\r\n                var providerName =\r\n                    HttpUtility.UrlDecode((string)ctx.providerName);\r\n\r\n                var methodName =\r\n                    HttpUtility.UrlDecode((string)ctx.methodName);\r\n\r\n                var method =\r\n                    this.interactiveDiagnostics.GetMethod(providerName, methodName);\r\n\r\n                if (method == null)\r\n                {\r\n                    return HttpStatusCode.NotFound;\r\n                }\r\n\r\n                object[] arguments =\r\n                    GetArguments(method, this.Request.Query);\r\n\r\n                return this.Response.AsJson(new { Result = this.interactiveDiagnostics.ExecuteDiagnostic(method, arguments) });\r\n\r\n            });\r\n\r\n            Get<Response>(\"/templates/{providerName}/{methodName}\", ctx =>\r\n            {\r\n                var providerName =\r\n                    HttpUtility.UrlDecode((string)ctx.providerName);\r\n\r\n                var methodName =\r\n                    HttpUtility.UrlDecode((string)ctx.methodName);\r\n\r\n                var method =\r\n                    this.interactiveDiagnostics.GetMethod(providerName, methodName);\r\n\r\n                if (method == null)\r\n                {\r\n                    return HttpStatusCode.NotFound;\r\n                }\r\n\r\n                var template =\r\n                    this.interactiveDiagnostics.GetTemplate(method);\r\n\r\n                if (template == null)\r\n                {\r\n                    return HttpStatusCode.NotFound;\r\n                }\r\n\r\n                return template;\r\n            });\r\n        }\r\n\r\n        private static object[] GetArguments(InteractiveDiagnosticMethod method, dynamic query)\r\n        {\r\n            var arguments = new List<object>();\r\n\r\n            foreach (var argument in method.Arguments)\r\n            {\r\n                arguments.Add(ConvertArgument((string)query[argument.Item1].Value, argument.Item2));\r\n            }\r\n\r\n            return arguments.ToArray();\r\n        }\r\n\r\n        private static object ConvertArgument(string value, Type destinationType)\r\n        {\r\n            var converter =\r\n                TypeDescriptor.GetConverter(destinationType);\r\n\r\n            if (converter == null || !converter.CanConvertFrom(typeof(string)))\r\n            {\r\n                return null;\r\n            }\r\n\r\n            try\r\n            {\r\n                return converter.ConvertFrom(value);\r\n            }\r\n            catch (FormatException)\r\n            {\r\n                return null;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Diagnostics/Modules/MainModule.cs",
    "content": "﻿namespace Nancy.Diagnostics.Modules\r\n{\r\n    /// <summary>\r\n    /// Main Nancy module for diagnostics.\r\n    /// </summary>\r\n    /// <seealso cref=\"Nancy.Diagnostics.DiagnosticModule\" />\r\n    public class MainModule : DiagnosticModule\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"MainModule\"/> class.\r\n        /// </summary>\r\n        public MainModule()\r\n        {\r\n            Get(\"/\", _ =>\r\n            {\r\n                return View[\"Dashboard\"];\r\n            });\r\n\r\n            Post(\"/\", _ =>\r\n            {\r\n                return this.Response.AsRedirect(\"~/\");\r\n            });\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Diagnostics/Modules/SettingsModule.cs",
    "content": "﻿namespace Nancy.Diagnostics.Modules\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using System.Text.RegularExpressions;\r\n    using Nancy.ModelBinding;\r\n\r\n    /// <summary>\r\n    /// Nancy module for diagnostic settings.\r\n    /// </summary>\r\n    /// <seealso cref=\"Nancy.Diagnostics.DiagnosticModule\" />\r\n    public class SettingsModule : DiagnosticModule\r\n    {\r\n        private static readonly IEnumerable<Type> Types = new[] { typeof(StaticConfiguration) }.Union(\r\n                                                                  typeof(StaticConfiguration).GetNestedTypes(BindingFlags.Static | BindingFlags.Public));\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"SettingsModule\"/> class.\r\n        /// </summary>\r\n        public SettingsModule()\r\n            : base(\"/settings\")\r\n        {\r\n            Get(\"/\", _ =>\r\n            {\r\n                var properties = Types.SelectMany(t => t.GetProperties(BindingFlags.Static | BindingFlags.Public))\r\n                                      .Where(x => x.PropertyType == typeof(bool));\r\n\r\n                var model = from property in properties\r\n                        orderby property.Name\r\n                        let value = (bool) property.GetValue(null, null)\r\n                        let description = GetDescription(property)\r\n                        where !string.IsNullOrEmpty(description)\r\n                        select new {\r\n                            Name = property.Name,\r\n                            Description = description,\r\n                            DisplayName = Regex.Replace(property.Name, \"[A-Z]\", \" $0\"),\r\n                            Value = value,\r\n                            Checked = (value) ? \"checked='checked'\" : string.Empty\r\n                        };\r\n\r\n                return View[\"Settings\", model];\r\n            });\r\n\r\n            Post(\"/\", _ => {\r\n\r\n                var model =\r\n                    this.Bind<SettingsModel>();\r\n\r\n                var property = GetProperty(model);\r\n\r\n                if (property != null)\r\n                {\r\n                    property.SetValue(null, model.Value, null);\r\n                }\r\n\r\n                return HttpStatusCode.OK;\r\n            });\r\n        }\r\n\r\n        private static PropertyInfo GetProperty(SettingsModel model)\r\n        {\r\n            return Types.SelectMany(t => t.GetProperties(BindingFlags.Static | BindingFlags.Public))\r\n                        .SingleOrDefault(x => x.Name.Equals(model.Name, StringComparison.OrdinalIgnoreCase));\r\n        }\r\n\r\n        private static string GetDescription(PropertyInfo property)\r\n        {\r\n            var attributes = property\r\n                .GetCustomAttributes(typeof (DescriptionAttribute), false)\r\n                .Cast<DescriptionAttribute>()\r\n                .ToArray();\r\n\r\n            return (!attributes.Any()) ? string.Empty : attributes.First().Description;\r\n        }\r\n    }\r\n\r\n\r\n    /// <summary>\r\n    /// Data model for settings.\r\n    /// </summary>\r\n    public class SettingsModel\r\n    {\r\n        /// <summary>\r\n        /// Gets or sets the name for the setting.\r\n        /// </summary>\r\n        /// <value>The name of the setting</value>\r\n        public string Name { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the value for this setting.\r\n        /// </summary>\r\n        /// <value><see langword=\"true\"/> or <see langword=\"false\"/></value>\r\n        public bool Value { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/Modules/TraceModule.cs",
    "content": "﻿namespace Nancy.Diagnostics.Modules\r\n{\r\n    using System;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Nancy module for request tracing. Part of diagnostics module.\r\n    /// </summary>\r\n    /// <seealso cref=\"Nancy.Diagnostics.DiagnosticModule\" />\r\n    public class TraceModule : DiagnosticModule\r\n    {\r\n        private readonly IRequestTracing sessionProvider;\r\n\r\n        /// <summary>\r\n        /// Initializes an instance of the <see cref=\"TraceModule\"/> class, with\r\n        /// the provided <paramref name=\"sessionProvider\"/>.\r\n        /// </summary>\r\n        /// <param name=\"sessionProvider\">The session provider.</param>\r\n        public TraceModule(IRequestTracing sessionProvider)\r\n            : base(\"/trace\")\r\n        {\r\n            this.sessionProvider = sessionProvider;\r\n\r\n            Get(\"/\", _ =>\r\n            {\r\n                return View[\"RequestTracing\"];\r\n            });\r\n\r\n            Get(\"/sessions\", _ =>\r\n            {\r\n                return this.Response.AsJson(this.sessionProvider.GetSessions().Select(s => new { Id = s.Id }).ToArray());\r\n            });\r\n\r\n            Get(\"/sessions/{id}\", ctx =>\r\n            {\r\n                Guid id;\r\n                if (!Guid.TryParse(ctx.Id, out id))\r\n                {\r\n                    return HttpStatusCode.NotFound;\r\n                }\r\n\r\n                var session =\r\n                    this.sessionProvider.GetSessions().FirstOrDefault(s => s.Id == id);\r\n\r\n                if (session == null)\r\n                {\r\n                    return HttpStatusCode.NotFound;\r\n                }\r\n\r\n                return this.Response.AsJson(session.RequestTraces.Select(t => new\r\n                    {\r\n                        t.RequestData.Method,\r\n                        RequestUrl = t.RequestData.Url,\r\n                        RequestContentType = t.RequestData.ContentType,\r\n                        ResponseContentType = t.ResponseData.ContentType,\r\n                        RequestHeaders = t.RequestData.Headers,\r\n                        ResponseHeaders = t.ResponseData.Headers,\r\n                        t.ResponseData.StatusCode,\r\n                        Log = t.TraceLog.ToString().Replace(\"\\r\", \"\").Split(new[] { \"\\n\" }, StringSplitOptions.None),\r\n                    }).ToArray());\r\n            });\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Diagnostics/NullLog.cs",
    "content": "namespace Nancy.Diagnostics\r\n{\r\n    using System;\r\n    using System.Text;\r\n\r\n    /// <summary>\r\n    /// Implementation of <see cref=\"ITraceLog\"/> that does not log anything.\r\n    /// </summary>\r\n    public class NullLog : ITraceLog\r\n    {\r\n        /// <summary>\r\n        /// Write to the log\r\n        /// </summary>\r\n        /// <param name=\"logDelegate\">Log writing delegate</param>\r\n        public void WriteLog(Action<StringBuilder> logDelegate)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns a string that represents the current object.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// A string that represents the current object.\r\n        /// </returns>\r\n        public override string ToString()\r\n        {\r\n            return string.Empty;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/RequestData.cs",
    "content": "namespace Nancy.Diagnostics\r\n{\r\n    using Nancy.Responses.Negotiation;\r\n\r\n    /// <summary>\r\n    /// Stores request trace information about the request.\r\n    /// </summary>\r\n    public class RequestData\r\n    {\r\n        /// <summary>\r\n        /// Gets or sets the content type of the request.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"MediaRange\"/> containing the content type.</value>\r\n        public MediaRange ContentType { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the headers of the request.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"RequestHeaders\"/> instance containing the headers.</value>\r\n        public RequestHeaders Headers { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets the HTTP verb of the request.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the HTTP verb.</value>\r\n        public string Method { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the <see cref=\"Url\"/> that was requested.\r\n        /// </summary>\r\n        public Url Url { get; set; }\r\n\r\n        /// <summary>\r\n        /// Implicitly casts a <see cref=\"Request\"/> instance into a <see cref=\"RequestData\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"request\">A <see cref=\"Request\"/> instance.</param>\r\n        /// <returns>A <see cref=\"RequestData\"/> instance.</returns>\r\n        public static implicit operator RequestData(Request request)\r\n        {\r\n            return new RequestData\r\n            {\r\n                ContentType = request.Headers.ContentType,\r\n                Headers = request.Headers,\r\n                Method = request.Method,\r\n                Url = request.Url\r\n            };\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/RequestTraceSession.cs",
    "content": "namespace Nancy.Diagnostics\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Holds trace sessions for a request.\r\n    /// </summary>\r\n    public class RequestTraceSession\r\n    {\r\n        private const int MaxSize = 500;\r\n        private readonly ConcurrentLimitedCollection<IRequestTrace> requestTraces;\r\n\r\n        /// <summary>\r\n        /// Initializes an instance of the <see cref=\"RequestTraceSession\"/> class, with\r\n        /// the provided <paramref name=\"id\"/>.\r\n        /// </summary>\r\n        /// <param name=\"id\">The session identifier.</param>\r\n        public RequestTraceSession(Guid id)\r\n        {\r\n            this.Id = id;\r\n            this.requestTraces = new ConcurrentLimitedCollection<IRequestTrace>(MaxSize);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the identifier.\r\n        /// </summary>\r\n        /// <value>The session identifier.</value>\r\n        public Guid Id { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the request traces.\r\n        /// </summary>\r\n        /// <value>The collection of request traces.</value>\r\n        public IEnumerable<IRequestTrace> RequestTraces\r\n        {\r\n            get\r\n            {\r\n                return this.requestTraces;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds a request trace instance to the collection.\r\n        /// </summary>\r\n        /// <param name=\"trace\">The trace.</param>\r\n        public void AddRequestTrace(IRequestTrace trace)\r\n        {\r\n            this.requestTraces.Add(trace);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/Resources/960.css",
    "content": "body{min-width:960px}.container_12,.container_16{margin-left:auto;margin-right:auto;width:960px}.grid_1,.grid_2,.grid_3,.grid_4,.grid_5,.grid_6,.grid_7,.grid_8,.grid_9,.grid_10,.grid_11,.grid_12,.grid_13,.grid_14,.grid_15,.grid_16{display:inline;float:left;margin-left:10px;margin-right:10px}.push_1,.pull_1,.push_2,.pull_2,.push_3,.pull_3,.push_4,.pull_4,.push_5,.pull_5,.push_6,.pull_6,.push_7,.pull_7,.push_8,.pull_8,.push_9,.pull_9,.push_10,.pull_10,.push_11,.pull_11,.push_12,.pull_12,.push_13,.pull_13,.push_14,.pull_14,.push_15,.pull_15{position:relative}.container_12 .grid_3,.container_16 .grid_4{width:220px}.container_12 .grid_6,.container_16 .grid_8{width:460px}.container_12 .grid_9,.container_16 .grid_12{width:700px}.container_12 .grid_12,.container_16 .grid_16{width:940px}.alpha{margin-left:0}.omega{margin-right:0}.container_12 .grid_1{width:60px}.container_12 .grid_2{width:140px}.container_12 .grid_4{width:300px}.container_12 .grid_5{width:380px}.container_12 .grid_7{width:540px}.container_12 .grid_8{width:620px}.container_12 .grid_10{width:780px}.container_12 .grid_11{width:860px}.container_16 .grid_1{width:40px}.container_16 .grid_2{width:100px}.container_16 .grid_3{width:160px}.container_16 .grid_5{width:280px}.container_16 .grid_6{width:340px}.container_16 .grid_7{width:400px}.container_16 .grid_9{width:520px}.container_16 .grid_10{width:580px}.container_16 .grid_11{width:640px}.container_16 .grid_13{width:760px}.container_16 .grid_14{width:820px}.container_16 .grid_15{width:880px}.container_12 .prefix_3,.container_16 .prefix_4{padding-left:240px}.container_12 .prefix_6,.container_16 .prefix_8{padding-left:480px}.container_12 .prefix_9,.container_16 .prefix_12{padding-left:720px}.container_12 .prefix_1{padding-left:80px}.container_12 .prefix_2{padding-left:160px}.container_12 .prefix_4{padding-left:320px}.container_12 .prefix_5{padding-left:400px}.container_12 .prefix_7{padding-left:560px}.container_12 .prefix_8{padding-left:640px}.container_12 .prefix_10{padding-left:800px}.container_12 .prefix_11{padding-left:880px}.container_16 .prefix_1{padding-left:60px}.container_16 .prefix_2{padding-left:120px}.container_16 .prefix_3{padding-left:180px}.container_16 .prefix_5{padding-left:300px}.container_16 .prefix_6{padding-left:360px}.container_16 .prefix_7{padding-left:420px}.container_16 .prefix_9{padding-left:540px}.container_16 .prefix_10{padding-left:600px}.container_16 .prefix_11{padding-left:660px}.container_16 .prefix_13{padding-left:780px}.container_16 .prefix_14{padding-left:840px}.container_16 .prefix_15{padding-left:900px}.container_12 .suffix_3,.container_16 .suffix_4{padding-right:240px}.container_12 .suffix_6,.container_16 .suffix_8{padding-right:480px}.container_12 .suffix_9,.container_16 .suffix_12{padding-right:720px}.container_12 .suffix_1{padding-right:80px}.container_12 .suffix_2{padding-right:160px}.container_12 .suffix_4{padding-right:320px}.container_12 .suffix_5{padding-right:400px}.container_12 .suffix_7{padding-right:560px}.container_12 .suffix_8{padding-right:640px}.container_12 .suffix_10{padding-right:800px}.container_12 .suffix_11{padding-right:880px}.container_16 .suffix_1{padding-right:60px}.container_16 .suffix_2{padding-right:120px}.container_16 .suffix_3{padding-right:180px}.container_16 .suffix_5{padding-right:300px}.container_16 .suffix_6{padding-right:360px}.container_16 .suffix_7{padding-right:420px}.container_16 .suffix_9{padding-right:540px}.container_16 .suffix_10{padding-right:600px}.container_16 .suffix_11{padding-right:660px}.container_16 .suffix_13{padding-right:780px}.container_16 .suffix_14{padding-right:840px}.container_16 .suffix_15{padding-right:900px}.container_12 .push_3,.container_16 .push_4{left:240px}.container_12 .push_6,.container_16 .push_8{left:480px}.container_12 .push_9,.container_16 .push_12{left:720px}.container_12 .push_1{left:80px}.container_12 .push_2{left:160px}.container_12 .push_4{left:320px}.container_12 .push_5{left:400px}.container_12 .push_7{left:560px}.container_12 .push_8{left:640px}.container_12 .push_10{left:800px}.container_12 .push_11{left:880px}.container_16 .push_1{left:60px}.container_16 .push_2{left:120px}.container_16 .push_3{left:180px}.container_16 .push_5{left:300px}.container_16 .push_6{left:360px}.container_16 .push_7{left:420px}.container_16 .push_9{left:540px}.container_16 .push_10{left:600px}.container_16 .push_11{left:660px}.container_16 .push_13{left:780px}.container_16 .push_14{left:840px}.container_16 .push_15{left:900px}.container_12 .pull_3,.container_16 .pull_4{left:-240px}.container_12 .pull_6,.container_16 .pull_8{left:-480px}.container_12 .pull_9,.container_16 .pull_12{left:-720px}.container_12 .pull_1{left:-80px}.container_12 .pull_2{left:-160px}.container_12 .pull_4{left:-320px}.container_12 .pull_5{left:-400px}.container_12 .pull_7{left:-560px}.container_12 .pull_8{left:-640px}.container_12 .pull_10{left:-800px}.container_12 .pull_11{left:-880px}.container_16 .pull_1{left:-60px}.container_16 .pull_2{left:-120px}.container_16 .pull_3{left:-180px}.container_16 .pull_5{left:-300px}.container_16 .pull_6{left:-360px}.container_16 .pull_7{left:-420px}.container_16 .pull_9{left:-540px}.container_16 .pull_10{left:-600px}.container_16 .pull_11{left:-660px}.container_16 .pull_13{left:-780px}.container_16 .pull_14{left:-840px}.container_16 .pull_15{left:-900px}.clear{clear:both;display:block;overflow:hidden;visibility:hidden;width:0;height:0}.clearfix:before,.clearfix:after,.container_12:before,.container_12:after,.container_16:before,.container_16:after{content:'.';display:block;overflow:hidden;visibility:hidden;font-size:0;line-height:0;width:0;height:0}.clearfix:after,.container_12:after,.container_16:after{clear:both}.clearfix,.container_12,.container_16{zoom:1}"
  },
  {
    "path": "src/Nancy/Diagnostics/Resources/Modules/interactive/methods.js",
    "content": "﻿(function (Method) {\r\n    var app = diagnostics.app;\r\n\r\n    Method.Model = Backbone.Model.extend({});\r\n\r\n    Method.Collection = Backbone.Collection.extend({\r\n        model: Method.Model,\r\n\r\n        initialize: function (opts) {\r\n            this.providerName = opts.providerName;\r\n        },\r\n\r\n        url: function () {\r\n            return Nancy.config.basePath + \"interactive/providers/\" + this.providerName;\r\n        }\r\n    });\r\n\r\n    Method.Views.List = Backbone.View.extend({\r\n        el: '#main',\r\n\r\n        events: {\r\n            'click #back': 'back'\r\n        },\r\n\r\n        initialize: function () {\r\n            this.router = app.router;\r\n            this.template = $(\"#methodList\").html();\r\n            this.providerName = this.model.providerName;\r\n        },\r\n\r\n        render: function () {\r\n            var methods = this.model.toJSON();\r\n\r\n            var html = Handlebars.compile(this.template)({ collection: methods });\r\n\r\n            $(this.el).html(html);\r\n\r\n            _.each(methods, this.renderItem, this);\r\n        },\r\n\r\n        renderItem: function (model) {\r\n            var itemView = new Method.Views.Item({ model: model, providerName: this.providerName });\r\n\r\n            this.$('#root').append(itemView.el);\r\n        },\r\n\r\n        back: function () {\r\n            this.router.navigate(\"\", true);\r\n        }\r\n    });\r\n\r\n    Method.Views.Item = Backbone.View.extend({\r\n        tagName: 'li',\r\n\r\n        events: {\r\n            'focus .method-argument input': 'showTooltip',\r\n            'blur .method-argument input': 'hideTooltip',\r\n            'click input[type=button]': 'executeMethod'\r\n        },\r\n\r\n        initialize: function (args) {\r\n            this.providerName = args.providerName;\r\n            this.app = app;\r\n            this.router = app.router;\r\n            this.template = $(\"#method\").html();\r\n            this.render();\r\n        },\r\n\r\n        render: function () {\r\n            var html = Handlebars.compile(this.template)({ model: this.model });\r\n            $(this.el).append(html);\r\n        },\r\n\r\n        showTooltip: function (e) {\r\n            $(e.currentTarget).parent('.tooltip').addClass(\"tooltip-showing\");\r\n        },\r\n\r\n        hideTooltip: function (e) {\r\n            $(e.currentTarget).parent('.tooltip').removeClass(\"tooltip-showing\");\r\n        },\r\n\r\n        executeMethod: function () {\r\n            var parameters = this.$(\"input\");\r\n\r\n            var executionContext = {};\r\n\r\n            executionContext.providerName = this.providerName;\r\n            executionContext.methodName = this.model.methodName;\r\n            executionContext.arguments = [];\r\n\r\n            _.each(parameters, function (input) {\r\n                if (input.type !== \"submit\" && input.type !== \"button\") {\r\n                    executionContext.arguments.push({ name: input.id, value: this.$(input).val() });\r\n                }\r\n            }, this);\r\n\r\n            this.app.trigger(\"execute\", executionContext);\r\n        }\r\n    });\r\n})(diagnostics.module(\"method\"));"
  },
  {
    "path": "src/Nancy/Diagnostics/Resources/Modules/interactive/providers.js",
    "content": "﻿(function (Provider) {\r\n    var app = diagnostics.app;\r\n\r\n    Provider.Model = Backbone.Model.extend({});\r\n\r\n    Provider.Collection = Backbone.Collection.extend({\r\n        model: Provider.Model,\r\n\r\n        url: function () {\r\n            return Nancy.config.basePath + \"interactive/providers/\";\r\n        }\r\n    });\r\n\r\n    Provider.Views.List = Backbone.View.extend({\r\n        el: '#main',\r\n\r\n        initialize: function () {\r\n            this.template = $(\"#providerList\").html();\r\n        },\r\n\r\n        render: function () {\r\n            var providers = this.model.toJSON();\r\n\r\n            var html = Handlebars.compile(this.template)({ collection: providers });\r\n\r\n            $(this.el).html(html);\r\n\r\n            _.each(providers, this.renderItem, this);\r\n        },\r\n\r\n        renderItem: function (model) {\r\n            var itemView = new Provider.Views.Item({ model: model });\r\n\r\n            $(this.el).append(itemView.el);\r\n        }\r\n    });\r\n\r\n    Provider.Views.Item = Backbone.View.extend({\r\n        className: \"item-list\",\r\n\r\n        events: {\r\n            'click': 'showMethods'\r\n        },\r\n\r\n        initialize: function () {\r\n            this.router = app.router;\r\n            this.template = $(\"#provider\").html();\r\n            this.render();\r\n        },\r\n\r\n        render: function () {\r\n            var html = Handlebars.compile(this.template)({ model: this.model });\r\n            $(this.el).append(html);\r\n        },\r\n\r\n        showMethods: function () {\r\n            this.router.navigate(this.model.name, true);\r\n        }\r\n    });\r\n})(diagnostics.module(\"provider\"))"
  },
  {
    "path": "src/Nancy/Diagnostics/Resources/Modules/interactive/results.js",
    "content": "﻿(function (Results, Handlebars, $) {\r\n    var app = diagnostics.app;\r\n\r\n    Results.Views.Result = Backbone.View.extend({\r\n        el: '#results',\r\n\r\n        initialize: function (opts) {\r\n            this.providerName = opts.providerName;\r\n            this.methodName = opts.methodName;\r\n            this.arguments = opts.arguments;\r\n            this.templatePath = this.providerName + \"/\" + this.methodName;\r\n        },\r\n\r\n        render: function () {\r\n            $.ajax({\r\n                    url: Nancy.config.basePath + \"interactive/templates/\" + this.templatePath,\r\n                    dataType: \"text\",\r\n                    context: this,\r\n\t\t\t\t\tsuccess: this.renderWithTemplate,\r\n\t\t\t\t\terror: this.renderWithoutTemplate\r\n                });\r\n        },\r\n\r\n        renderWithTemplate: function (template) {\r\n            var html = Handlebars.compile(template)({ model: this.model });\r\n            $(this.el).html(html);\r\n        },\r\n\r\n        renderWithoutTemplate: function () {\r\n            $(this.el).html(\"<div class=\\\"modelreport\\\">\" + _.modelreport(this.model) + \"</div>\");\r\n        }\r\n    });\r\n\r\n    Results.execute = function (executionContext) {\r\n        console.log(\"executing: \" + executionContext.providerName + \"/\" + executionContext.methodName);\r\n        console.log(\"Arguments:\");\r\n        _.each(executionContext.arguments, function (arg) {\r\n            console.log(\"Name: \" + arg.name + \" Value:\" + arg.value);\r\n        });\r\n\r\n        $.ajax({\r\n                url: Nancy.config.basePath + \"interactive/providers/\" + executionContext.providerName + \"/\" + executionContext.methodName,\r\n                dataType: \"json\",\r\n                data: executionContext.arguments,\r\n                success: function (data) {\r\n                    var resultsView = new Results.Views.Result({\r\n                        providerName: executionContext.providerName,\r\n                        methodName: executionContext.methodName,\r\n                        model: data\r\n                    });\r\n\r\n                    resultsView.render();\r\n                }\r\n            });\r\n    };\r\n\r\n    app.bind(\"execute\", Results.execute);\r\n})(diagnostics.module(\"results\"), Handlebars, $);"
  },
  {
    "path": "src/Nancy/Diagnostics/Resources/Modules/tracing/sessions.js",
    "content": "﻿(function (Session) {\r\n    var app = diagnostics.app;\r\n\r\n    Session.Model = Backbone.Model.extend({});\r\n\r\n    Session.Collection = Backbone.Collection.extend({\r\n        model: Session.Model,\r\n\r\n        url: function () {\r\n            return Nancy.config.basePath + \"trace/sessions/\";\r\n        }\r\n    });\r\n\r\n    Session.Views.List = Backbone.View.extend({\r\n        el: '#main',\r\n\r\n        initialize: function () {\r\n            this.template = $(\"#sessionList\").html();\r\n        },\r\n\r\n        render: function () {\r\n            var sessions = this.model.toJSON();\r\n\r\n            var html = Handlebars.compile(this.template)({ collection: sessions });\r\n\r\n            $(this.el).html(html);\r\n\r\n            _.each(sessions, this.renderItem, this);\r\n        },\r\n\r\n        renderItem: function (model) {\r\n            var itemView = new Session.Views.Item({ model: model });\r\n\r\n            $(this.el).append(itemView.el);\r\n        }\r\n    });\r\n\r\n    Session.Views.Item = Backbone.View.extend({\r\n        className: \"item-list\",\r\n\r\n        events: {\r\n            'click': 'showSession'\r\n        },\r\n\r\n        initialize: function () {\r\n            this.router = app.router;\r\n            this.template = $(\"#session\").html();\r\n            this.render();\r\n        },\r\n\r\n        render: function () {\r\n            var html = Handlebars.compile(this.template)({ model: this.model });\r\n            $(this.el).append(html);\r\n        },\r\n\r\n        showSession: function () {\r\n            this.router.navigate(this.model.id, true);\r\n        }\r\n    });\r\n})(diagnostics.module(\"session\"))"
  },
  {
    "path": "src/Nancy/Diagnostics/Resources/Modules/tracing/traces.js",
    "content": "﻿(function (Trace) {\r\n    var app = diagnostics.app;\r\n\r\n    Trace.Model = Backbone.Model.extend({});\r\n\r\n    Trace.Collection = Backbone.Collection.extend({\r\n        model: Trace.Model,\r\n\r\n        initialize: function (opts) {\r\n            this.id = opts.id;\r\n        },\r\n\r\n        url: function () {\r\n            return Nancy.config.basePath + \"trace/sessions/\" + this.id;\r\n        }\r\n    });\r\n\r\n    Trace.Views.List = Backbone.View.extend({\r\n        el: '#main',\r\n\r\n        events: {\r\n            'click #back': 'back'\r\n        },\r\n\r\n        initialize: function () {\r\n            this.router = app.router;\r\n            this.template = $(\"#traceList\").html();\r\n        },\r\n\r\n        render: function () {\r\n            var traces = this.model.toJSON();\r\n\r\n            var html = Handlebars.compile(this.template)({ collection: traces });\r\n\r\n            $(this.el).html(html);\r\n\r\n            _.each(traces, this.renderItem, this);\r\n        },\r\n\r\n        renderItem: function (model) {\r\n            var itemView = new Trace.Views.Item({ model: model });\r\n\r\n            this.$('#root').append(itemView.el);\r\n        },\r\n\r\n        back: function () {\r\n            this.router.navigate(\"\", true);\r\n        }\r\n    });\r\n\r\n    Trace.Views.Item = Backbone.View.extend({\r\n        className: 'item-list',\r\n\r\n        events: {\r\n            'click': 'viewDetails'\r\n        },\r\n\r\n        initialize: function (args) {\r\n            this.template = $(\"#trace\").html();\r\n            this.render();\r\n        },\r\n\r\n        render: function () {\r\n            var html = Handlebars.compile(this.template)({ model: this.model });\r\n            $(this.el).append(html);\r\n        },\r\n\r\n        viewDetails: function () {\r\n            var details = new Trace.Views.Details({ model: this.model });\r\n            details.render();\r\n        }\r\n    });\r\n\r\n    Trace.Views.Details = Backbone.View.extend({\r\n        el: '#details',\r\n\r\n        render: function () {\r\n            $(this.el).html(\"<div class=\\\"modelreport\\\">\" + _.modelreport(this.model) + \"</div>\");\r\n        }\r\n    });\r\n})(diagnostics.module(\"trace\"));"
  },
  {
    "path": "src/Nancy/Diagnostics/Resources/backbone-min.js",
    "content": "// Backbone.js 0.5.3\n// (c) 2010 Jeremy Ashkenas, DocumentCloud Inc.\n// Backbone may be freely distributed under the MIT license.\n// For all details and documentation:\n// http://documentcloud.github.com/backbone\n(function(){var h=this,p=h.Backbone,e;e=typeof exports!==\"undefined\"?exports:h.Backbone={};e.VERSION=\"0.5.3\";var f=h._;if(!f&&typeof require!==\"undefined\")f=require(\"underscore\")._;var g=h.jQuery||h.Zepto;e.noConflict=function(){h.Backbone=p;return this};e.emulateHTTP=!1;e.emulateJSON=!1;e.Events={bind:function(a,b,c){var d=this._callbacks||(this._callbacks={});(d[a]||(d[a]=[])).push([b,c]);return this},unbind:function(a,b){var c;if(a){if(c=this._callbacks)if(b){c=c[a];if(!c)return this;for(var d=\n0,e=c.length;d<e;d++)if(c[d]&&b===c[d][0]){c[d]=null;break}}else c[a]=[]}else this._callbacks={};return this},trigger:function(a){var b,c,d,e,f=2;if(!(c=this._callbacks))return this;for(;f--;)if(b=f?a:\"all\",b=c[b])for(var g=0,h=b.length;g<h;g++)(d=b[g])?(e=f?Array.prototype.slice.call(arguments,1):arguments,d[0].apply(d[1]||this,e)):(b.splice(g,1),g--,h--);return this}};e.Model=function(a,b){var c;a||(a={});if(c=this.defaults)f.isFunction(c)&&(c=c.call(this)),a=f.extend({},c,a);this.attributes={};\nthis._escapedAttributes={};this.cid=f.uniqueId(\"c\");this.set(a,{silent:!0});this._changed=!1;this._previousAttributes=f.clone(this.attributes);if(b&&b.collection)this.collection=b.collection;this.initialize(a,b)};f.extend(e.Model.prototype,e.Events,{_previousAttributes:null,_changed:!1,idAttribute:\"id\",initialize:function(){},toJSON:function(){return f.clone(this.attributes)},get:function(a){return this.attributes[a]},escape:function(a){var b;if(b=this._escapedAttributes[a])return b;b=this.attributes[a];\nreturn this._escapedAttributes[a]=(b==null?\"\":\"\"+b).replace(/&(?!\\w+;|#\\d+;|#x[\\da-f]+;)/gi,\"&amp;\").replace(/</g,\"&lt;\").replace(/>/g,\"&gt;\").replace(/\"/g,\"&quot;\").replace(/'/g,\"&#x27;\").replace(/\\//g,\"&#x2F;\")},has:function(a){return this.attributes[a]!=null},set:function(a,b){b||(b={});if(!a)return this;if(a.attributes)a=a.attributes;var c=this.attributes,d=this._escapedAttributes;if(!b.silent&&this.validate&&!this._performValidation(a,b))return!1;if(this.idAttribute in a)this.id=a[this.idAttribute];\nvar e=this._changing;this._changing=!0;for(var g in a){var h=a[g];if(!f.isEqual(c[g],h))c[g]=h,delete d[g],this._changed=!0,b.silent||this.trigger(\"change:\"+g,this,h,b)}!e&&!b.silent&&this._changed&&this.change(b);this._changing=!1;return this},unset:function(a,b){if(!(a in this.attributes))return this;b||(b={});var c={};c[a]=void 0;if(!b.silent&&this.validate&&!this._performValidation(c,b))return!1;delete this.attributes[a];delete this._escapedAttributes[a];a==this.idAttribute&&delete this.id;this._changed=\n!0;b.silent||(this.trigger(\"change:\"+a,this,void 0,b),this.change(b));return this},clear:function(a){a||(a={});var b,c=this.attributes,d={};for(b in c)d[b]=void 0;if(!a.silent&&this.validate&&!this._performValidation(d,a))return!1;this.attributes={};this._escapedAttributes={};this._changed=!0;if(!a.silent){for(b in c)this.trigger(\"change:\"+b,this,void 0,a);this.change(a)}return this},fetch:function(a){a||(a={});var b=this,c=a.success;a.success=function(d,e,f){if(!b.set(b.parse(d,f),a))return!1;c&&\nc(b,d)};a.error=i(a.error,b,a);return(this.sync||e.sync).call(this,\"read\",this,a)},save:function(a,b){b||(b={});if(a&&!this.set(a,b))return!1;var c=this,d=b.success;b.success=function(a,e,f){if(!c.set(c.parse(a,f),b))return!1;d&&d(c,a,f)};b.error=i(b.error,c,b);var f=this.isNew()?\"create\":\"update\";return(this.sync||e.sync).call(this,f,this,b)},destroy:function(a){a||(a={});if(this.isNew())return this.trigger(\"destroy\",this,this.collection,a);var b=this,c=a.success;a.success=function(d){b.trigger(\"destroy\",\nb,b.collection,a);c&&c(b,d)};a.error=i(a.error,b,a);return(this.sync||e.sync).call(this,\"delete\",this,a)},url:function(){var a=k(this.collection)||this.urlRoot||l();if(this.isNew())return a;return a+(a.charAt(a.length-1)==\"/\"?\"\":\"/\")+encodeURIComponent(this.id)},parse:function(a){return a},clone:function(){return new this.constructor(this)},isNew:function(){return this.id==null},change:function(a){this.trigger(\"change\",this,a);this._previousAttributes=f.clone(this.attributes);this._changed=!1},hasChanged:function(a){if(a)return this._previousAttributes[a]!=\nthis.attributes[a];return this._changed},changedAttributes:function(a){a||(a=this.attributes);var b=this._previousAttributes,c=!1,d;for(d in a)f.isEqual(b[d],a[d])||(c=c||{},c[d]=a[d]);return c},previous:function(a){if(!a||!this._previousAttributes)return null;return this._previousAttributes[a]},previousAttributes:function(){return f.clone(this._previousAttributes)},_performValidation:function(a,b){var c=this.validate(a);if(c)return b.error?b.error(this,c,b):this.trigger(\"error\",this,c,b),!1;return!0}});\ne.Collection=function(a,b){b||(b={});if(b.comparator)this.comparator=b.comparator;f.bindAll(this,\"_onModelEvent\",\"_removeReference\");this._reset();a&&this.reset(a,{silent:!0});this.initialize.apply(this,arguments)};f.extend(e.Collection.prototype,e.Events,{model:e.Model,initialize:function(){},toJSON:function(){return this.map(function(a){return a.toJSON()})},add:function(a,b){if(f.isArray(a))for(var c=0,d=a.length;c<d;c++)this._add(a[c],b);else this._add(a,b);return this},remove:function(a,b){if(f.isArray(a))for(var c=\n0,d=a.length;c<d;c++)this._remove(a[c],b);else this._remove(a,b);return this},get:function(a){if(a==null)return null;return this._byId[a.id!=null?a.id:a]},getByCid:function(a){return a&&this._byCid[a.cid||a]},at:function(a){return this.models[a]},sort:function(a){a||(a={});if(!this.comparator)throw Error(\"Cannot sort a set without a comparator\");this.models=this.sortBy(this.comparator);a.silent||this.trigger(\"reset\",this,a);return this},pluck:function(a){return f.map(this.models,function(b){return b.get(a)})},\nreset:function(a,b){a||(a=[]);b||(b={});this.each(this._removeReference);this._reset();this.add(a,{silent:!0});b.silent||this.trigger(\"reset\",this,b);return this},fetch:function(a){a||(a={});var b=this,c=a.success;a.success=function(d,f,e){b[a.add?\"add\":\"reset\"](b.parse(d,e),a);c&&c(b,d)};a.error=i(a.error,b,a);return(this.sync||e.sync).call(this,\"read\",this,a)},create:function(a,b){var c=this;b||(b={});a=this._prepareModel(a,b);if(!a)return!1;var d=b.success;b.success=function(a,e,f){c.add(a,b);\nd&&d(a,e,f)};a.save(null,b);return a},parse:function(a){return a},chain:function(){return f(this.models).chain()},_reset:function(){this.length=0;this.models=[];this._byId={};this._byCid={}},_prepareModel:function(a,b){if(a instanceof e.Model){if(!a.collection)a.collection=this}else{var c=a;a=new this.model(c,{collection:this});a.validate&&!a._performValidation(c,b)&&(a=!1)}return a},_add:function(a,b){b||(b={});a=this._prepareModel(a,b);if(!a)return!1;var c=this.getByCid(a);if(c)throw Error([\"Can't add the same model to a set twice\",\nc.id]);this._byId[a.id]=a;this._byCid[a.cid]=a;this.models.splice(b.at!=null?b.at:this.comparator?this.sortedIndex(a,this.comparator):this.length,0,a);a.bind(\"all\",this._onModelEvent);this.length++;b.silent||a.trigger(\"add\",a,this,b);return a},_remove:function(a,b){b||(b={});a=this.getByCid(a)||this.get(a);if(!a)return null;delete this._byId[a.id];delete this._byCid[a.cid];this.models.splice(this.indexOf(a),1);this.length--;b.silent||a.trigger(\"remove\",a,this,b);this._removeReference(a);return a},\n_removeReference:function(a){this==a.collection&&delete a.collection;a.unbind(\"all\",this._onModelEvent)},_onModelEvent:function(a,b,c,d){(a==\"add\"||a==\"remove\")&&c!=this||(a==\"destroy\"&&this._remove(b,d),b&&a===\"change:\"+b.idAttribute&&(delete this._byId[b.previous(b.idAttribute)],this._byId[b.id]=b),this.trigger.apply(this,arguments))}});f.each([\"forEach\",\"each\",\"map\",\"reduce\",\"reduceRight\",\"find\",\"detect\",\"filter\",\"select\",\"reject\",\"every\",\"all\",\"some\",\"any\",\"include\",\"contains\",\"invoke\",\"max\",\n\"min\",\"sortBy\",\"sortedIndex\",\"toArray\",\"size\",\"first\",\"rest\",\"last\",\"without\",\"indexOf\",\"lastIndexOf\",\"isEmpty\",\"groupBy\"],function(a){e.Collection.prototype[a]=function(){return f[a].apply(f,[this.models].concat(f.toArray(arguments)))}});e.Router=function(a){a||(a={});if(a.routes)this.routes=a.routes;this._bindRoutes();this.initialize.apply(this,arguments)};var q=/:([\\w\\d]+)/g,r=/\\*([\\w\\d]+)/g,s=/[-[\\]{}()+?.,\\\\^$|#\\s]/g;f.extend(e.Router.prototype,e.Events,{initialize:function(){},route:function(a,\nb,c){e.history||(e.history=new e.History);f.isRegExp(a)||(a=this._routeToRegExp(a));e.history.route(a,f.bind(function(d){d=this._extractParameters(a,d);c.apply(this,d);this.trigger.apply(this,[\"route:\"+b].concat(d))},this))},navigate:function(a,b){e.history.navigate(a,b)},_bindRoutes:function(){if(this.routes){var a=[],b;for(b in this.routes)a.unshift([b,this.routes[b]]);b=0;for(var c=a.length;b<c;b++)this.route(a[b][0],a[b][1],this[a[b][1]])}},_routeToRegExp:function(a){a=a.replace(s,\"\\\\$&\").replace(q,\n\"([^/]*)\").replace(r,\"(.*?)\");return RegExp(\"^\"+a+\"$\")},_extractParameters:function(a,b){return a.exec(b).slice(1)}});e.History=function(){this.handlers=[];f.bindAll(this,\"checkUrl\")};var j=/^#*/,t=/msie [\\w.]+/,m=!1;f.extend(e.History.prototype,{interval:50,getFragment:function(a,b){if(a==null)if(this._hasPushState||b){a=window.location.pathname;var c=window.location.search;c&&(a+=c);a.indexOf(this.options.root)==0&&(a=a.substr(this.options.root.length))}else a=window.location.hash;return decodeURIComponent(a.replace(j,\n\"\"))},start:function(a){if(m)throw Error(\"Backbone.history has already been started\");this.options=f.extend({},{root:\"/\"},this.options,a);this._wantsPushState=!!this.options.pushState;this._hasPushState=!(!this.options.pushState||!window.history||!window.history.pushState);a=this.getFragment();var b=document.documentMode;if(b=t.exec(navigator.userAgent.toLowerCase())&&(!b||b<=7))this.iframe=g('<iframe src=\"javascript:0\" tabindex=\"-1\" />').hide().appendTo(\"body\")[0].contentWindow,this.navigate(a);\nthis._hasPushState?g(window).bind(\"popstate\",this.checkUrl):\"onhashchange\"in window&&!b?g(window).bind(\"hashchange\",this.checkUrl):setInterval(this.checkUrl,this.interval);this.fragment=a;m=!0;a=window.location;b=a.pathname==this.options.root;if(this._wantsPushState&&!this._hasPushState&&!b)return this.fragment=this.getFragment(null,!0),window.location.replace(this.options.root+\"#\"+this.fragment),!0;else if(this._wantsPushState&&this._hasPushState&&b&&a.hash)this.fragment=a.hash.replace(j,\"\"),window.history.replaceState({},\ndocument.title,a.protocol+\"//\"+a.host+this.options.root+this.fragment);if(!this.options.silent)return this.loadUrl()},route:function(a,b){this.handlers.unshift({route:a,callback:b})},checkUrl:function(){var a=this.getFragment();a==this.fragment&&this.iframe&&(a=this.getFragment(this.iframe.location.hash));if(a==this.fragment||a==decodeURIComponent(this.fragment))return!1;this.iframe&&this.navigate(a);this.loadUrl()||this.loadUrl(window.location.hash)},loadUrl:function(a){var b=this.fragment=this.getFragment(a);\nreturn f.any(this.handlers,function(a){if(a.route.test(b))return a.callback(b),!0})},navigate:function(a,b){var c=(a||\"\").replace(j,\"\");if(!(this.fragment==c||this.fragment==decodeURIComponent(c))){if(this._hasPushState){var d=window.location;c.indexOf(this.options.root)!=0&&(c=this.options.root+c);this.fragment=c;window.history.pushState({},document.title,d.protocol+\"//\"+d.host+c)}else if(window.location.hash=this.fragment=c,this.iframe&&c!=this.getFragment(this.iframe.location.hash))this.iframe.document.open().close(),\nthis.iframe.location.hash=c;b&&this.loadUrl(a)}}});e.View=function(a){this.cid=f.uniqueId(\"view\");this._configure(a||{});this._ensureElement();this.delegateEvents();this.initialize.apply(this,arguments)};var u=/^(\\S+)\\s*(.*)$/,n=[\"model\",\"collection\",\"el\",\"id\",\"attributes\",\"className\",\"tagName\"];f.extend(e.View.prototype,e.Events,{tagName:\"div\",$:function(a){return g(a,this.el)},initialize:function(){},render:function(){return this},remove:function(){g(this.el).remove();return this},make:function(a,\nb,c){a=document.createElement(a);b&&g(a).attr(b);c&&g(a).html(c);return a},delegateEvents:function(a){if(a||(a=this.events))for(var b in f.isFunction(a)&&(a=a.call(this)),g(this.el).unbind(\".delegateEvents\"+this.cid),a){var c=this[a[b]];if(!c)throw Error('Event \"'+a[b]+'\" does not exist');var d=b.match(u),e=d[1];d=d[2];c=f.bind(c,this);e+=\".delegateEvents\"+this.cid;d===\"\"?g(this.el).bind(e,c):g(this.el).delegate(d,e,c)}},_configure:function(a){this.options&&(a=f.extend({},this.options,a));for(var b=\n0,c=n.length;b<c;b++){var d=n[b];a[d]&&(this[d]=a[d])}this.options=a},_ensureElement:function(){if(this.el){if(f.isString(this.el))this.el=g(this.el).get(0)}else{var a=this.attributes||{};if(this.id)a.id=this.id;if(this.className)a[\"class\"]=this.className;this.el=this.make(this.tagName,a)}}});e.Model.extend=e.Collection.extend=e.Router.extend=e.View.extend=function(a,b){var c=v(this,a,b);c.extend=this.extend;return c};var w={create:\"POST\",update:\"PUT\",\"delete\":\"DELETE\",read:\"GET\"};e.sync=function(a,\nb,c){var d=w[a];c=f.extend({type:d,dataType:\"json\"},c);if(!c.url)c.url=k(b)||l();if(!c.data&&b&&(a==\"create\"||a==\"update\"))c.contentType=\"application/json\",c.data=JSON.stringify(b.toJSON());if(e.emulateJSON)c.contentType=\"application/x-www-form-urlencoded\",c.data=c.data?{model:c.data}:{};if(e.emulateHTTP&&(d===\"PUT\"||d===\"DELETE\")){if(e.emulateJSON)c.data._method=d;c.type=\"POST\";c.beforeSend=function(a){a.setRequestHeader(\"X-HTTP-Method-Override\",d)}}if(c.type!==\"GET\"&&!e.emulateJSON)c.processData=\n!1;return g.ajax(c)};var o=function(){},v=function(a,b,c){var d;d=b&&b.hasOwnProperty(\"constructor\")?b.constructor:function(){return a.apply(this,arguments)};f.extend(d,a);o.prototype=a.prototype;d.prototype=new o;b&&f.extend(d.prototype,b);c&&f.extend(d,c);d.prototype.constructor=d;d.__super__=a.prototype;return d},k=function(a){if(!a||!a.url)return null;return f.isFunction(a.url)?a.url():a.url},l=function(){throw Error('A \"url\" property or function must be specified');},i=function(a,b,c){return function(d){a?\na(b,d,c):b.trigger(\"error\",b,d,c)}}}).call(this);\n"
  },
  {
    "path": "src/Nancy/Diagnostics/Resources/diagnostics.js",
    "content": "diagnostics = {\r\n    // Create this closure to contain the cached modules\r\n    module: (function () {\r\n        // Internal module cache.\r\n        var modules = {};\r\n\r\n        // Create a new module reference scaffold or load an\r\n        // existing module.\r\n        return function (name) {\r\n            // If this module has already been created, return it.\r\n            if (modules[name]) {\r\n                return modules[name];\r\n            }\r\n\r\n            // Create a module and save it under this name\r\n            return (modules[name] = { Views: {} });\r\n        };\r\n    } ()),\r\n\r\n    app: _.extend({}, Backbone.Events)\r\n};\r\n"
  },
  {
    "path": "src/Nancy/Diagnostics/Resources/handlebars.js",
    "content": "// lib/handlebars/base.js\nvar Handlebars = {};\n\nHandlebars.VERSION = \"1.0.beta.2\";\n\nHandlebars.helpers  = {};\nHandlebars.partials = {};\n\nHandlebars.registerHelper = function(name, fn, inverse) {\n  if(inverse) { fn.not = inverse; }\n  this.helpers[name] = fn;\n};\n\nHandlebars.registerPartial = function(name, str) {\n  this.partials[name] = str;\n};\n\nHandlebars.registerHelper('helperMissing', function(arg) {\n  if(arguments.length === 2) {\n    return undefined;\n  } else {\n    throw new Error(\"Could not find property '\" + arg + \"'\");\n  }\n});\n\nHandlebars.registerHelper('blockHelperMissing', function(context, options) {\n  var inverse = options.inverse || function() {}, fn = options.fn;\n\n\n  var ret = \"\";\n  var type = Object.prototype.toString.call(context);\n\n  if(type === \"[object Function]\") {\n    context = context();\n  }\n\n  if(context === true) {\n    return fn(this);\n  } else if(context === false || context == null) {\n    return inverse(this);\n  } else if(type === \"[object Array]\") {\n    if(context.length > 0) {\n      for(var i=0, j=context.length; i<j; i++) {\n        ret = ret + fn(context[i]);\n      }\n    } else {\n      ret = inverse(this);\n    }\n    return ret;\n  } else {\n    return fn(context);\n  }\n});\n\nHandlebars.registerHelper('each', function(context, options) {\n  var fn = options.fn, inverse = options.inverse;\n  var ret = \"\";\n\n  if(context && context.length > 0) {\n    for(var i=0, j=context.length; i<j; i++) {\n      ret = ret + fn(context[i]);\n    }\n  } else {\n    ret = inverse(this);\n  }\n  return ret;\n});\n\nHandlebars.registerHelper('if', function(context, options) {\n  if(!context || Handlebars.Utils.isEmpty(context)) {\n    return options.inverse(this);\n  } else {\n    return options.fn(this);\n  }\n});\n\nHandlebars.registerHelper('unless', function(context, options) {\n  var fn = options.fn, inverse = options.inverse;\n  options.fn = inverse;\n  options.inverse = fn;\n\n  return Handlebars.helpers['if'].call(this, context, options);\n});\n\nHandlebars.registerHelper('with', function(context, options) {\n  return options.fn(context);\n});\n\nHandlebars.registerHelper('log', function(context) {\n  Handlebars.log(context);\n});\n;\n// lib/handlebars/compiler/parser.js\n/* Jison generated parser */\nvar handlebars = (function(){\n\nvar parser = {trace: function trace() { },\nyy: {},\nsymbols_: {\"error\":2,\"root\":3,\"program\":4,\"EOF\":5,\"statements\":6,\"simpleInverse\":7,\"statement\":8,\"openInverse\":9,\"closeBlock\":10,\"openBlock\":11,\"mustache\":12,\"partial\":13,\"CONTENT\":14,\"COMMENT\":15,\"OPEN_BLOCK\":16,\"inMustache\":17,\"CLOSE\":18,\"OPEN_INVERSE\":19,\"OPEN_ENDBLOCK\":20,\"path\":21,\"OPEN\":22,\"OPEN_UNESCAPED\":23,\"OPEN_PARTIAL\":24,\"params\":25,\"hash\":26,\"param\":27,\"STRING\":28,\"INTEGER\":29,\"BOOLEAN\":30,\"hashSegments\":31,\"hashSegment\":32,\"ID\":33,\"EQUALS\":34,\"pathSegments\":35,\"SEP\":36,\"$accept\":0,\"$end\":1},\nterminals_: {2:\"error\",5:\"EOF\",14:\"CONTENT\",15:\"COMMENT\",16:\"OPEN_BLOCK\",18:\"CLOSE\",19:\"OPEN_INVERSE\",20:\"OPEN_ENDBLOCK\",22:\"OPEN\",23:\"OPEN_UNESCAPED\",24:\"OPEN_PARTIAL\",28:\"STRING\",29:\"INTEGER\",30:\"BOOLEAN\",33:\"ID\",34:\"EQUALS\",36:\"SEP\"},\nproductions_: [0,[3,2],[4,3],[4,1],[4,0],[6,1],[6,2],[8,3],[8,3],[8,1],[8,1],[8,1],[8,1],[11,3],[9,3],[10,3],[12,3],[12,3],[13,3],[13,4],[7,2],[17,3],[17,2],[17,2],[17,1],[25,2],[25,1],[27,1],[27,1],[27,1],[27,1],[26,1],[31,2],[31,1],[32,3],[32,3],[32,3],[32,3],[21,1],[35,3],[35,1]],\nperformAction: function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$) {\n\nvar $0 = $$.length - 1;\nswitch (yystate) {\ncase 1: return $$[$0-1] \nbreak;\ncase 2: this.$ = new yy.ProgramNode($$[$0-2], $$[$0]) \nbreak;\ncase 3: this.$ = new yy.ProgramNode($$[$0]) \nbreak;\ncase 4: this.$ = new yy.ProgramNode([]) \nbreak;\ncase 5: this.$ = [$$[$0]] \nbreak;\ncase 6: $$[$0-1].push($$[$0]); this.$ = $$[$0-1] \nbreak;\ncase 7: this.$ = new yy.InverseNode($$[$0-2], $$[$0-1], $$[$0]) \nbreak;\ncase 8: this.$ = new yy.BlockNode($$[$0-2], $$[$0-1], $$[$0]) \nbreak;\ncase 9: this.$ = $$[$0] \nbreak;\ncase 10: this.$ = $$[$0] \nbreak;\ncase 11: this.$ = new yy.ContentNode($$[$0]) \nbreak;\ncase 12: this.$ = new yy.CommentNode($$[$0]) \nbreak;\ncase 13: this.$ = new yy.MustacheNode($$[$0-1][0], $$[$0-1][1]) \nbreak;\ncase 14: this.$ = new yy.MustacheNode($$[$0-1][0], $$[$0-1][1]) \nbreak;\ncase 15: this.$ = $$[$0-1] \nbreak;\ncase 16: this.$ = new yy.MustacheNode($$[$0-1][0], $$[$0-1][1]) \nbreak;\ncase 17: this.$ = new yy.MustacheNode($$[$0-1][0], $$[$0-1][1], true) \nbreak;\ncase 18: this.$ = new yy.PartialNode($$[$0-1]) \nbreak;\ncase 19: this.$ = new yy.PartialNode($$[$0-2], $$[$0-1]) \nbreak;\ncase 20: \nbreak;\ncase 21: this.$ = [[$$[$0-2]].concat($$[$0-1]), $$[$0]] \nbreak;\ncase 22: this.$ = [[$$[$0-1]].concat($$[$0]), null] \nbreak;\ncase 23: this.$ = [[$$[$0-1]], $$[$0]] \nbreak;\ncase 24: this.$ = [[$$[$0]], null] \nbreak;\ncase 25: $$[$0-1].push($$[$0]); this.$ = $$[$0-1]; \nbreak;\ncase 26: this.$ = [$$[$0]] \nbreak;\ncase 27: this.$ = $$[$0] \nbreak;\ncase 28: this.$ = new yy.StringNode($$[$0]) \nbreak;\ncase 29: this.$ = new yy.IntegerNode($$[$0]) \nbreak;\ncase 30: this.$ = new yy.BooleanNode($$[$0]) \nbreak;\ncase 31: this.$ = new yy.HashNode($$[$0]) \nbreak;\ncase 32: $$[$0-1].push($$[$0]); this.$ = $$[$0-1] \nbreak;\ncase 33: this.$ = [$$[$0]] \nbreak;\ncase 34: this.$ = [$$[$0-2], $$[$0]] \nbreak;\ncase 35: this.$ = [$$[$0-2], new yy.StringNode($$[$0])] \nbreak;\ncase 36: this.$ = [$$[$0-2], new yy.IntegerNode($$[$0])] \nbreak;\ncase 37: this.$ = [$$[$0-2], new yy.BooleanNode($$[$0])] \nbreak;\ncase 38: this.$ = new yy.IdNode($$[$0]) \nbreak;\ncase 39: $$[$0-2].push($$[$0]); this.$ = $$[$0-2]; \nbreak;\ncase 40: this.$ = [$$[$0]] \nbreak;\n}\n},\ntable: [{3:1,4:2,5:[2,4],6:3,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],22:[1,13],23:[1,14],24:[1,15]},{1:[3]},{5:[1,16]},{5:[2,3],7:17,8:18,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,19],20:[2,3],22:[1,13],23:[1,14],24:[1,15]},{5:[2,5],14:[2,5],15:[2,5],16:[2,5],19:[2,5],20:[2,5],22:[2,5],23:[2,5],24:[2,5]},{4:20,6:3,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,4],22:[1,13],23:[1,14],24:[1,15]},{4:21,6:3,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,4],22:[1,13],23:[1,14],24:[1,15]},{5:[2,9],14:[2,9],15:[2,9],16:[2,9],19:[2,9],20:[2,9],22:[2,9],23:[2,9],24:[2,9]},{5:[2,10],14:[2,10],15:[2,10],16:[2,10],19:[2,10],20:[2,10],22:[2,10],23:[2,10],24:[2,10]},{5:[2,11],14:[2,11],15:[2,11],16:[2,11],19:[2,11],20:[2,11],22:[2,11],23:[2,11],24:[2,11]},{5:[2,12],14:[2,12],15:[2,12],16:[2,12],19:[2,12],20:[2,12],22:[2,12],23:[2,12],24:[2,12]},{17:22,21:23,33:[1,25],35:24},{17:26,21:23,33:[1,25],35:24},{17:27,21:23,33:[1,25],35:24},{17:28,21:23,33:[1,25],35:24},{21:29,33:[1,25],35:24},{1:[2,1]},{6:30,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],22:[1,13],23:[1,14],24:[1,15]},{5:[2,6],14:[2,6],15:[2,6],16:[2,6],19:[2,6],20:[2,6],22:[2,6],23:[2,6],24:[2,6]},{17:22,18:[1,31],21:23,33:[1,25],35:24},{10:32,20:[1,33]},{10:34,20:[1,33]},{18:[1,35]},{18:[2,24],21:40,25:36,26:37,27:38,28:[1,41],29:[1,42],30:[1,43],31:39,32:44,33:[1,45],35:24},{18:[2,38],28:[2,38],29:[2,38],30:[2,38],33:[2,38],36:[1,46]},{18:[2,40],28:[2,40],29:[2,40],30:[2,40],33:[2,40],36:[2,40]},{18:[1,47]},{18:[1,48]},{18:[1,49]},{18:[1,50],21:51,33:[1,25],35:24},{5:[2,2],8:18,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,2],22:[1,13],23:[1,14],24:[1,15]},{14:[2,20],15:[2,20],16:[2,20],19:[2,20],22:[2,20],23:[2,20],24:[2,20]},{5:[2,7],14:[2,7],15:[2,7],16:[2,7],19:[2,7],20:[2,7],22:[2,7],23:[2,7],24:[2,7]},{21:52,33:[1,25],35:24},{5:[2,8],14:[2,8],15:[2,8],16:[2,8],19:[2,8],20:[2,8],22:[2,8],23:[2,8],24:[2,8]},{14:[2,14],15:[2,14],16:[2,14],19:[2,14],20:[2,14],22:[2,14],23:[2,14],24:[2,14]},{18:[2,22],21:40,26:53,27:54,28:[1,41],29:[1,42],30:[1,43],31:39,32:44,33:[1,45],35:24},{18:[2,23]},{18:[2,26],28:[2,26],29:[2,26],30:[2,26],33:[2,26]},{18:[2,31],32:55,33:[1,56]},{18:[2,27],28:[2,27],29:[2,27],30:[2,27],33:[2,27]},{18:[2,28],28:[2,28],29:[2,28],30:[2,28],33:[2,28]},{18:[2,29],28:[2,29],29:[2,29],30:[2,29],33:[2,29]},{18:[2,30],28:[2,30],29:[2,30],30:[2,30],33:[2,30]},{18:[2,33],33:[2,33]},{18:[2,40],28:[2,40],29:[2,40],30:[2,40],33:[2,40],34:[1,57],36:[2,40]},{33:[1,58]},{14:[2,13],15:[2,13],16:[2,13],19:[2,13],20:[2,13],22:[2,13],23:[2,13],24:[2,13]},{5:[2,16],14:[2,16],15:[2,16],16:[2,16],19:[2,16],20:[2,16],22:[2,16],23:[2,16],24:[2,16]},{5:[2,17],14:[2,17],15:[2,17],16:[2,17],19:[2,17],20:[2,17],22:[2,17],23:[2,17],24:[2,17]},{5:[2,18],14:[2,18],15:[2,18],16:[2,18],19:[2,18],20:[2,18],22:[2,18],23:[2,18],24:[2,18]},{18:[1,59]},{18:[1,60]},{18:[2,21]},{18:[2,25],28:[2,25],29:[2,25],30:[2,25],33:[2,25]},{18:[2,32],33:[2,32]},{34:[1,57]},{21:61,28:[1,62],29:[1,63],30:[1,64],33:[1,25],35:24},{18:[2,39],28:[2,39],29:[2,39],30:[2,39],33:[2,39],36:[2,39]},{5:[2,19],14:[2,19],15:[2,19],16:[2,19],19:[2,19],20:[2,19],22:[2,19],23:[2,19],24:[2,19]},{5:[2,15],14:[2,15],15:[2,15],16:[2,15],19:[2,15],20:[2,15],22:[2,15],23:[2,15],24:[2,15]},{18:[2,34],33:[2,34]},{18:[2,35],33:[2,35]},{18:[2,36],33:[2,36]},{18:[2,37],33:[2,37]}],\ndefaultActions: {16:[2,1],37:[2,23],53:[2,21]},\nparseError: function parseError(str, hash) {\n    throw new Error(str);\n},\nparse: function parse(input) {\n    var self = this,\n        stack = [0],\n        vstack = [null], // semantic value stack\n        lstack = [], // location stack\n        table = this.table,\n        yytext = '',\n        yylineno = 0,\n        yyleng = 0,\n        recovering = 0,\n        TERROR = 2,\n        EOF = 1;\n\n    //this.reductionCount = this.shiftCount = 0;\n\n    this.lexer.setInput(input);\n    this.lexer.yy = this.yy;\n    this.yy.lexer = this.lexer;\n    if (typeof this.lexer.yylloc == 'undefined')\n        this.lexer.yylloc = {};\n    var yyloc = this.lexer.yylloc;\n    lstack.push(yyloc);\n\n    if (typeof this.yy.parseError === 'function')\n        this.parseError = this.yy.parseError;\n\n    function popStack (n) {\n        stack.length = stack.length - 2*n;\n        vstack.length = vstack.length - n;\n        lstack.length = lstack.length - n;\n    }\n\n    function lex() {\n        var token;\n        token = self.lexer.lex() || 1; // $end = 1\n        // if token isn't its numeric value, convert\n        if (typeof token !== 'number') {\n            token = self.symbols_[token] || token;\n        }\n        return token;\n    };\n\n    var symbol, preErrorSymbol, state, action, a, r, yyval={},p,len,newState, expected;\n    while (true) {\n        // retreive state number from top of stack\n        state = stack[stack.length-1];\n\n        // use default actions if available\n        if (this.defaultActions[state]) {\n            action = this.defaultActions[state];\n        } else {\n            if (symbol == null)\n                symbol = lex();\n            // read action for current state and first input\n            action = table[state] && table[state][symbol];\n        }\n\n        // handle parse error\n        if (typeof action === 'undefined' || !action.length || !action[0]) {\n\n            if (!recovering) {\n                // Report error\n                expected = [];\n                for (p in table[state]) if (this.terminals_[p] && p > 2) {\n                    expected.push(\"'\"+this.terminals_[p]+\"'\");\n                }\n                var errStr = '';\n                if (this.lexer.showPosition) {\n                    errStr = 'Parse error on line '+(yylineno+1)+\":\\n\"+this.lexer.showPosition()+'\\nExpecting '+expected.join(', ');\n                } else {\n                    errStr = 'Parse error on line '+(yylineno+1)+\": Unexpected \" +\n                                  (symbol == 1 /*EOF*/ ? \"end of input\" :\n                                              (\"'\"+(this.terminals_[symbol] || symbol)+\"'\"));\n                }\n                this.parseError(errStr,\n                    {text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected});\n            }\n\n            // just recovered from another error\n            if (recovering == 3) {\n                if (symbol == EOF) {\n                    throw new Error(errStr || 'Parsing halted.');\n                }\n\n                // discard current lookahead and grab another\n                yyleng = this.lexer.yyleng;\n                yytext = this.lexer.yytext;\n                yylineno = this.lexer.yylineno;\n                yyloc = this.lexer.yylloc;\n                symbol = lex();\n            }\n\n            // try to recover from error\n            while (1) {\n                // check for error recovery rule in this state\n                if ((TERROR.toString()) in table[state]) {\n                    break;\n                }\n                if (state == 0) {\n                    throw new Error(errStr || 'Parsing halted.');\n                }\n                popStack(1);\n                state = stack[stack.length-1];\n            }\n\n            preErrorSymbol = symbol; // save the lookahead token\n            symbol = TERROR;         // insert generic error symbol as new lookahead\n            state = stack[stack.length-1];\n            action = table[state] && table[state][TERROR];\n            recovering = 3; // allow 3 real symbols to be shifted before reporting a new error\n        }\n\n        // this shouldn't happen, unless resolve defaults are off\n        if (action[0] instanceof Array && action.length > 1) {\n            throw new Error('Parse Error: multiple actions possible at state: '+state+', token: '+symbol);\n        }\n\n        switch (action[0]) {\n\n            case 1: // shift\n                //this.shiftCount++;\n\n                stack.push(symbol);\n                vstack.push(this.lexer.yytext);\n                lstack.push(this.lexer.yylloc);\n                stack.push(action[1]); // push state\n                symbol = null;\n                if (!preErrorSymbol) { // normal execution/no error\n                    yyleng = this.lexer.yyleng;\n                    yytext = this.lexer.yytext;\n                    yylineno = this.lexer.yylineno;\n                    yyloc = this.lexer.yylloc;\n                    if (recovering > 0)\n                        recovering--;\n                } else { // error just occurred, resume old lookahead f/ before error\n                    symbol = preErrorSymbol;\n                    preErrorSymbol = null;\n                }\n                break;\n\n            case 2: // reduce\n                //this.reductionCount++;\n\n                len = this.productions_[action[1]][1];\n\n                // perform semantic action\n                yyval.$ = vstack[vstack.length-len]; // default to $$ = $1\n                // default location, uses first token for firsts, last for lasts\n                yyval._$ = {\n                    first_line: lstack[lstack.length-(len||1)].first_line,\n                    last_line: lstack[lstack.length-1].last_line,\n                    first_column: lstack[lstack.length-(len||1)].first_column,\n                    last_column: lstack[lstack.length-1].last_column\n                };\n                r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);\n\n                if (typeof r !== 'undefined') {\n                    return r;\n                }\n\n                // pop off stack\n                if (len) {\n                    stack = stack.slice(0,-1*len*2);\n                    vstack = vstack.slice(0, -1*len);\n                    lstack = lstack.slice(0, -1*len);\n                }\n\n                stack.push(this.productions_[action[1]][0]);    // push nonterminal (reduce)\n                vstack.push(yyval.$);\n                lstack.push(yyval._$);\n                // goto new state = table[STATE][NONTERMINAL]\n                newState = table[stack[stack.length-2]][stack[stack.length-1]];\n                stack.push(newState);\n                break;\n\n            case 3: // accept\n                return true;\n        }\n\n    }\n\n    return true;\n}};/* Jison generated lexer */\nvar lexer = (function(){\n\nvar lexer = ({EOF:1,\nparseError:function parseError(str, hash) {\n        if (this.yy.parseError) {\n            this.yy.parseError(str, hash);\n        } else {\n            throw new Error(str);\n        }\n    },\nsetInput:function (input) {\n        this._input = input;\n        this._more = this._less = this.done = false;\n        this.yylineno = this.yyleng = 0;\n        this.yytext = this.matched = this.match = '';\n        this.conditionStack = ['INITIAL'];\n        this.yylloc = {first_line:1,first_column:0,last_line:1,last_column:0};\n        return this;\n    },\ninput:function () {\n        var ch = this._input[0];\n        this.yytext+=ch;\n        this.yyleng++;\n        this.match+=ch;\n        this.matched+=ch;\n        var lines = ch.match(/\\n/);\n        if (lines) this.yylineno++;\n        this._input = this._input.slice(1);\n        return ch;\n    },\nunput:function (ch) {\n        this._input = ch + this._input;\n        return this;\n    },\nmore:function () {\n        this._more = true;\n        return this;\n    },\npastInput:function () {\n        var past = this.matched.substr(0, this.matched.length - this.match.length);\n        return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\\n/g, \"\");\n    },\nupcomingInput:function () {\n        var next = this.match;\n        if (next.length < 20) {\n            next += this._input.substr(0, 20-next.length);\n        }\n        return (next.substr(0,20)+(next.length > 20 ? '...':'')).replace(/\\n/g, \"\");\n    },\nshowPosition:function () {\n        var pre = this.pastInput();\n        var c = new Array(pre.length + 1).join(\"-\");\n        return pre + this.upcomingInput() + \"\\n\" + c+\"^\";\n    },\nnext:function () {\n        if (this.done) {\n            return this.EOF;\n        }\n        if (!this._input) this.done = true;\n\n        var token,\n            match,\n            col,\n            lines;\n        if (!this._more) {\n            this.yytext = '';\n            this.match = '';\n        }\n        var rules = this._currentRules();\n        for (var i=0;i < rules.length; i++) {\n            match = this._input.match(this.rules[rules[i]]);\n            if (match) {\n                lines = match[0].match(/\\n.*/g);\n                if (lines) this.yylineno += lines.length;\n                this.yylloc = {first_line: this.yylloc.last_line,\n                               last_line: this.yylineno+1,\n                               first_column: this.yylloc.last_column,\n                               last_column: lines ? lines[lines.length-1].length-1 : this.yylloc.last_column + match[0].length}\n                this.yytext += match[0];\n                this.match += match[0];\n                this.matches = match;\n                this.yyleng = this.yytext.length;\n                this._more = false;\n                this._input = this._input.slice(match[0].length);\n                this.matched += match[0];\n                token = this.performAction.call(this, this.yy, this, rules[i],this.conditionStack[this.conditionStack.length-1]);\n                if (token) return token;\n                else return;\n            }\n        }\n        if (this._input === \"\") {\n            return this.EOF;\n        } else {\n            this.parseError('Lexical error on line '+(this.yylineno+1)+'. Unrecognized text.\\n'+this.showPosition(), \n                    {text: \"\", token: null, line: this.yylineno});\n        }\n    },\nlex:function lex() {\n        var r = this.next();\n        if (typeof r !== 'undefined') {\n            return r;\n        } else {\n            return this.lex();\n        }\n    },\nbegin:function begin(condition) {\n        this.conditionStack.push(condition);\n    },\npopState:function popState() {\n        return this.conditionStack.pop();\n    },\n_currentRules:function _currentRules() {\n        return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules;\n    }});\nlexer.performAction = function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) {\n\nvar YYSTATE=YY_START\nswitch($avoiding_name_collisions) {\ncase 0: this.begin(\"mu\"); if (yy_.yytext) return 14; \nbreak;\ncase 1: return 14; \nbreak;\ncase 2: return 24; \nbreak;\ncase 3: return 16; \nbreak;\ncase 4: return 20; \nbreak;\ncase 5: return 19; \nbreak;\ncase 6: return 19; \nbreak;\ncase 7: return 23; \nbreak;\ncase 8: return 23; \nbreak;\ncase 9: yy_.yytext = yy_.yytext.substr(3,yy_.yyleng-5); this.begin(\"INITIAL\"); return 15; \nbreak;\ncase 10: return 22; \nbreak;\ncase 11: return 34; \nbreak;\ncase 12: return 33; \nbreak;\ncase 13: return 33; \nbreak;\ncase 14: return 36; \nbreak;\ncase 15: /*ignore whitespace*/ \nbreak;\ncase 16: this.begin(\"INITIAL\"); return 18; \nbreak;\ncase 17: this.begin(\"INITIAL\"); return 18; \nbreak;\ncase 18: yy_.yytext = yy_.yytext.substr(1,yy_.yyleng-2).replace(/\\\\\"/g,'\"'); return 28; \nbreak;\ncase 19: return 30; \nbreak;\ncase 20: return 30; \nbreak;\ncase 21: return 29; \nbreak;\ncase 22: return 33; \nbreak;\ncase 23: yy_.yytext = yy_.yytext.substr(1, yy_.yyleng-2); return 33; \nbreak;\ncase 24: return 'INVALID'; \nbreak;\ncase 25: return 5; \nbreak;\n}\n};\nlexer.rules = [/^[^\\x00]*?(?=(\\{\\{))/,/^[^\\x00]+/,/^\\{\\{>/,/^\\{\\{#/,/^\\{\\{\\//,/^\\{\\{\\^/,/^\\{\\{\\s*else\\b/,/^\\{\\{\\{/,/^\\{\\{&/,/^\\{\\{![\\s\\S]*?\\}\\}/,/^\\{\\{/,/^=/,/^\\.(?=[} ])/,/^\\.\\./,/^[/.]/,/^\\s+/,/^\\}\\}\\}/,/^\\}\\}/,/^\"(\\\\[\"]|[^\"])*\"/,/^true(?=[}\\s])/,/^false(?=[}\\s])/,/^[0-9]+(?=[}\\s])/,/^[a-zA-Z0-9_$-]+(?=[=}\\s/.])/,/^\\[.*\\]/,/^./,/^$/];\nlexer.conditions = {\"mu\":{\"rules\":[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25],\"inclusive\":false},\"INITIAL\":{\"rules\":[0,1,25],\"inclusive\":true}};return lexer;})()\nparser.lexer = lexer;\nreturn parser;\n})();\nif (typeof require !== 'undefined' && typeof exports !== 'undefined') {\nexports.parser = handlebars;\nexports.parse = function () { return handlebars.parse.apply(handlebars, arguments); }\nexports.main = function commonjsMain(args) {\n    if (!args[1])\n        throw new Error('Usage: '+args[0]+' FILE');\n    if (typeof process !== 'undefined') {\n        var source = require('fs').readFileSync(require('path').join(process.cwd(), args[1]), \"utf8\");\n    } else {\n        var cwd = require(\"file\").path(require(\"file\").cwd());\n        var source = cwd.join(args[1]).read({charset: \"utf-8\"});\n    }\n    return exports.parser.parse(source);\n}\nif (typeof module !== 'undefined' && require.main === module) {\n  exports.main(typeof process !== 'undefined' ? process.argv.slice(1) : require(\"system\").args);\n}\n};\n;\n// lib/handlebars/compiler/base.js\nHandlebars.Parser = handlebars;\n\nHandlebars.parse = function(string) {\n  Handlebars.Parser.yy = Handlebars.AST;\n  return Handlebars.Parser.parse(string);\n};\n\nHandlebars.print = function(ast) {\n  return new Handlebars.PrintVisitor().accept(ast);\n};\n\nHandlebars.logger = {\n  DEBUG: 0, INFO: 1, WARN: 2, ERROR: 3, level: 3,\n\n  // override in the host environment\n  log: function(level, str) {}\n};\n\nHandlebars.log = function(level, str) { Handlebars.logger.log(level, str); };\n;\n// lib/handlebars/compiler/ast.js\n(function() {\n\n  Handlebars.AST = {};\n\n  Handlebars.AST.ProgramNode = function(statements, inverse) {\n    this.type = \"program\";\n    this.statements = statements;\n    if(inverse) { this.inverse = new Handlebars.AST.ProgramNode(inverse); }\n  };\n\n  Handlebars.AST.MustacheNode = function(params, hash, unescaped) {\n    this.type = \"mustache\";\n    this.id = params[0];\n    this.params = params.slice(1);\n    this.hash = hash;\n    this.escaped = !unescaped;\n  };\n\n  Handlebars.AST.PartialNode = function(id, context) {\n    this.type    = \"partial\";\n\n    // TODO: disallow complex IDs\n\n    this.id      = id;\n    this.context = context;\n  };\n\n  var verifyMatch = function(open, close) {\n    if(open.original !== close.original) {\n      throw new Handlebars.Exception(open.original + \" doesn't match \" + close.original);\n    }\n  };\n\n  Handlebars.AST.BlockNode = function(mustache, program, close) {\n    verifyMatch(mustache.id, close);\n    this.type = \"block\";\n    this.mustache = mustache;\n    this.program  = program;\n  };\n\n  Handlebars.AST.InverseNode = function(mustache, program, close) {\n    verifyMatch(mustache.id, close);\n    this.type = \"inverse\";\n    this.mustache = mustache;\n    this.program  = program;\n  };\n\n  Handlebars.AST.ContentNode = function(string) {\n    this.type = \"content\";\n    this.string = string;\n  };\n\n  Handlebars.AST.HashNode = function(pairs) {\n    this.type = \"hash\";\n    this.pairs = pairs;\n  };\n\n  Handlebars.AST.IdNode = function(parts) {\n    this.type = \"ID\";\n    this.original = parts.join(\".\");\n\n    var dig = [], depth = 0;\n\n    for(var i=0,l=parts.length; i<l; i++) {\n      var part = parts[i];\n\n      if(part === \"..\") { depth++; }\n      else if(part === \".\" || part === \"this\") { this.isScoped = true; }\n      else { dig.push(part); }\n    }\n\n    this.parts    = dig;\n    this.string   = dig.join('.');\n    this.depth    = depth;\n    this.isSimple = (dig.length === 1) && (depth === 0);\n  };\n\n  Handlebars.AST.StringNode = function(string) {\n    this.type = \"STRING\";\n    this.string = string;\n  };\n\n  Handlebars.AST.IntegerNode = function(integer) {\n    this.type = \"INTEGER\";\n    this.integer = integer;\n  };\n\n  Handlebars.AST.BooleanNode = function(bool) {\n    this.type = \"BOOLEAN\";\n    this.bool = bool;\n  };\n\n  Handlebars.AST.CommentNode = function(comment) {\n    this.type = \"comment\";\n    this.comment = comment;\n  };\n\n})();;\n// lib/handlebars/utils.js\nHandlebars.Exception = function(message) {\n  var tmp = Error.prototype.constructor.apply(this, arguments);\n\n  for (var p in tmp) {\n    if (tmp.hasOwnProperty(p)) { this[p] = tmp[p]; }\n  }\n};\nHandlebars.Exception.prototype = new Error;\n\n// Build out our basic SafeString type\nHandlebars.SafeString = function(string) {\n  this.string = string;\n};\nHandlebars.SafeString.prototype.toString = function() {\n  return this.string.toString();\n};\n\n(function() {\n  var escape = {\n    \"<\": \"&lt;\",\n    \">\": \"&gt;\",\n    '\"': \"&quot;\",\n    \"'\": \"&#x27;\",\n    \"`\": \"&#x60;\"\n  };\n\n  var badChars = /&(?!\\w+;)|[<>\"'`]/g;\n  var possible = /[&<>\"'`]/;\n\n  var escapeChar = function(chr) {\n    return escape[chr] || \"&amp;\";\n  };\n\n  Handlebars.Utils = {\n    escapeExpression: function(string) {\n      // don't escape SafeStrings, since they're already safe\n      if (string instanceof Handlebars.SafeString) {\n        return string.toString();\n      } else if (string == null || string === false) {\n        return \"\";\n      }\n\n      if(!possible.test(string)) { return string; }\n      return string.replace(badChars, escapeChar);\n    },\n\n    isEmpty: function(value) {\n      if (typeof value === \"undefined\") {\n        return true;\n      } else if (value === null) {\n        return true;\n      } else if (value === false) {\n        return true;\n      } else if(Object.prototype.toString.call(value) === \"[object Array]\" && value.length === 0) {\n        return true;\n      } else {\n        return false;\n      }\n    }\n  };\n})();;\n// lib/handlebars/compiler/compiler.js\nHandlebars.Compiler = function() {};\nHandlebars.JavaScriptCompiler = function() {};\n\n(function(Compiler, JavaScriptCompiler) {\n  Compiler.OPCODE_MAP = {\n    appendContent: 1,\n    getContext: 2,\n    lookupWithHelpers: 3,\n    lookup: 4,\n    append: 5,\n    invokeMustache: 6,\n    appendEscaped: 7,\n    pushString: 8,\n    truthyOrFallback: 9,\n    functionOrFallback: 10,\n    invokeProgram: 11,\n    invokePartial: 12,\n    push: 13,\n    assignToHash: 15,\n    pushStringParam: 16\n  };\n\n  Compiler.MULTI_PARAM_OPCODES = {\n    appendContent: 1,\n    getContext: 1,\n    lookupWithHelpers: 2,\n    lookup: 1,\n    invokeMustache: 3,\n    pushString: 1,\n    truthyOrFallback: 1,\n    functionOrFallback: 1,\n    invokeProgram: 3,\n    invokePartial: 1,\n    push: 1,\n    assignToHash: 1,\n    pushStringParam: 1\n  };\n\n  Compiler.DISASSEMBLE_MAP = {};\n\n  for(var prop in Compiler.OPCODE_MAP) {\n    var value = Compiler.OPCODE_MAP[prop];\n    Compiler.DISASSEMBLE_MAP[value] = prop;\n  }\n\n  Compiler.multiParamSize = function(code) {\n    return Compiler.MULTI_PARAM_OPCODES[Compiler.DISASSEMBLE_MAP[code]];\n  };\n\n  Compiler.prototype = {\n    compiler: Compiler,\n\n    disassemble: function() {\n      var opcodes = this.opcodes, opcode, nextCode;\n      var out = [], str, name, value;\n\n      for(var i=0, l=opcodes.length; i<l; i++) {\n        opcode = opcodes[i];\n\n        if(opcode === 'DECLARE') {\n          name = opcodes[++i];\n          value = opcodes[++i];\n          out.push(\"DECLARE \" + name + \" = \" + value);\n        } else {\n          str = Compiler.DISASSEMBLE_MAP[opcode];\n\n          var extraParams = Compiler.multiParamSize(opcode);\n          var codes = [];\n\n          for(var j=0; j<extraParams; j++) {\n            nextCode = opcodes[++i];\n\n            if(typeof nextCode === \"string\") {\n              nextCode = \"\\\"\" + nextCode.replace(\"\\n\", \"\\\\n\") + \"\\\"\";\n            }\n\n            codes.push(nextCode);\n          }\n\n          str = str + \" \" + codes.join(\" \");\n\n          out.push(str);\n        }\n      }\n\n      return out.join(\"\\n\");\n    },\n\n    guid: 0,\n\n    compile: function(program, options) {\n      this.children = [];\n      this.depths = {list: []};\n      this.options = options;\n\n      // These changes will propagate to the other compiler components\n      var knownHelpers = this.options.knownHelpers;\n      this.options.knownHelpers = {\n        'helperMissing': true,\n        'blockHelperMissing': true,\n        'each': true,\n        'if': true,\n        'unless': true,\n        'with': true,\n        'log': true\n      };\n      if (knownHelpers) {\n        for (var name in knownHelpers) {\n          this.options.knownHelpers[name] = knownHelpers[name];\n        }\n      }\n\n      return this.program(program);\n    },\n\n    accept: function(node) {\n      return this[node.type](node);\n    },\n\n    program: function(program) {\n      var statements = program.statements, statement;\n      this.opcodes = [];\n\n      for(var i=0, l=statements.length; i<l; i++) {\n        statement = statements[i];\n        this[statement.type](statement);\n      }\n      this.isSimple = l === 1;\n\n      this.depths.list = this.depths.list.sort(function(a, b) {\n        return a - b;\n      });\n\n      return this;\n    },\n\n    compileProgram: function(program) {\n      var result = new this.compiler().compile(program, this.options);\n      var guid = this.guid++;\n\n      this.usePartial = this.usePartial || result.usePartial;\n\n      this.children[guid] = result;\n\n      for(var i=0, l=result.depths.list.length; i<l; i++) {\n        depth = result.depths.list[i];\n\n        if(depth < 2) { continue; }\n        else { this.addDepth(depth - 1); }\n      }\n\n      return guid;\n    },\n\n    block: function(block) {\n      var mustache = block.mustache;\n      var depth, child, inverse, inverseGuid;\n\n      var params = this.setupStackForMustache(mustache);\n\n      var programGuid = this.compileProgram(block.program);\n\n      if(block.program.inverse) {\n        inverseGuid = this.compileProgram(block.program.inverse);\n        this.declare('inverse', inverseGuid);\n      }\n\n      this.opcode('invokeProgram', programGuid, params.length, !!mustache.hash);\n      this.declare('inverse', null);\n      this.opcode('append');\n    },\n\n    inverse: function(block) {\n      var params = this.setupStackForMustache(block.mustache);\n\n      var programGuid = this.compileProgram(block.program);\n\n      this.declare('inverse', programGuid);\n\n      this.opcode('invokeProgram', null, params.length, !!block.mustache.hash);\n      this.opcode('append');\n    },\n\n    hash: function(hash) {\n      var pairs = hash.pairs, pair, val;\n\n      this.opcode('push', '{}');\n\n      for(var i=0, l=pairs.length; i<l; i++) {\n        pair = pairs[i];\n        val  = pair[1];\n\n        this.accept(val);\n        this.opcode('assignToHash', pair[0]);\n      }\n    },\n\n    partial: function(partial) {\n      var id = partial.id;\n      this.usePartial = true;\n\n      if(partial.context) {\n        this.ID(partial.context);\n      } else {\n        this.opcode('push', 'depth0');\n      }\n\n      this.opcode('invokePartial', id.original);\n      this.opcode('append');\n    },\n\n    content: function(content) {\n      this.opcode('appendContent', content.string);\n    },\n\n    mustache: function(mustache) {\n      var params = this.setupStackForMustache(mustache);\n\n      this.opcode('invokeMustache', params.length, mustache.id.original, !!mustache.hash);\n\n      if(mustache.escaped) {\n        this.opcode('appendEscaped');\n      } else {\n        this.opcode('append');\n      }\n    },\n\n    ID: function(id) {\n      this.addDepth(id.depth);\n\n      this.opcode('getContext', id.depth);\n\n      this.opcode('lookupWithHelpers', id.parts[0] || null, id.isScoped || false);\n\n      for(var i=1, l=id.parts.length; i<l; i++) {\n        this.opcode('lookup', id.parts[i]);\n      }\n    },\n\n    STRING: function(string) {\n      this.opcode('pushString', string.string);\n    },\n\n    INTEGER: function(integer) {\n      this.opcode('push', integer.integer);\n    },\n\n    BOOLEAN: function(bool) {\n      this.opcode('push', bool.bool);\n    },\n\n    comment: function() {},\n\n    // HELPERS\n    pushParams: function(params) {\n      var i = params.length, param;\n\n      while(i--) {\n        param = params[i];\n\n        if(this.options.stringParams) {\n          if(param.depth) {\n            this.addDepth(param.depth);\n          }\n\n          this.opcode('getContext', param.depth || 0);\n          this.opcode('pushStringParam', param.string);\n        } else {\n          this[param.type](param);\n        }\n      }\n    },\n\n    opcode: function(name, val1, val2, val3) {\n      this.opcodes.push(Compiler.OPCODE_MAP[name]);\n      if(val1 !== undefined) { this.opcodes.push(val1); }\n      if(val2 !== undefined) { this.opcodes.push(val2); }\n      if(val3 !== undefined) { this.opcodes.push(val3); }\n    },\n\n    declare: function(name, value) {\n      this.opcodes.push('DECLARE');\n      this.opcodes.push(name);\n      this.opcodes.push(value);\n    },\n\n    addDepth: function(depth) {\n      if(depth === 0) { return; }\n\n      if(!this.depths[depth]) {\n        this.depths[depth] = true;\n        this.depths.list.push(depth);\n      }\n    },\n\n    setupStackForMustache: function(mustache) {\n      var params = mustache.params;\n\n      this.pushParams(params);\n\n      if(mustache.hash) {\n        this.hash(mustache.hash);\n      }\n\n      this.ID(mustache.id);\n\n      return params;\n    }\n  };\n\n  JavaScriptCompiler.prototype = {\n    // PUBLIC API: You can override these methods in a subclass to provide\n    // alternative compiled forms for name lookup and buffering semantics\n    nameLookup: function(parent, name, type) {\n\t\t\tif (/^[0-9]+$/.test(name)) {\n        return parent + \"[\" + name + \"]\";\n      } else if (JavaScriptCompiler.isValidJavaScriptVariableName(name)) {\n\t    \treturn parent + \".\" + name;\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn parent + \"['\" + name + \"']\";\n      }\n    },\n\n    appendToBuffer: function(string) {\n      if (this.environment.isSimple) {\n        return \"return \" + string + \";\";\n      } else {\n        return \"buffer += \" + string + \";\";\n      }\n    },\n\n    initializeBuffer: function() {\n      return this.quotedString(\"\");\n    },\n\n    namespace: \"Handlebars\",\n    // END PUBLIC API\n\n    compile: function(environment, options, context, asObject) {\n      this.environment = environment;\n      this.options = options || {};\n\n      this.name = this.environment.name;\n      this.isChild = !!context;\n      this.context = context || {\n        programs: [],\n        aliases: { self: 'this' },\n        registers: {list: []}\n      };\n\n      this.preamble();\n\n      this.stackSlot = 0;\n      this.stackVars = [];\n\n      this.compileChildren(environment, options);\n\n      var opcodes = environment.opcodes, opcode;\n\n      this.i = 0;\n\n      for(l=opcodes.length; this.i<l; this.i++) {\n        opcode = this.nextOpcode(0);\n\n        if(opcode[0] === 'DECLARE') {\n          this.i = this.i + 2;\n          this[opcode[1]] = opcode[2];\n        } else {\n          this.i = this.i + opcode[1].length;\n          this[opcode[0]].apply(this, opcode[1]);\n        }\n      }\n\n      return this.createFunctionContext(asObject);\n    },\n\n    nextOpcode: function(n) {\n      var opcodes = this.environment.opcodes, opcode = opcodes[this.i + n], name, val;\n      var extraParams, codes;\n\n      if(opcode === 'DECLARE') {\n        name = opcodes[this.i + 1];\n        val  = opcodes[this.i + 2];\n        return ['DECLARE', name, val];\n      } else {\n        name = Compiler.DISASSEMBLE_MAP[opcode];\n\n        extraParams = Compiler.multiParamSize(opcode);\n        codes = [];\n\n        for(var j=0; j<extraParams; j++) {\n          codes.push(opcodes[this.i + j + 1 + n]);\n        }\n\n        return [name, codes];\n      }\n    },\n\n    eat: function(opcode) {\n      this.i = this.i + opcode.length;\n    },\n\n    preamble: function() {\n      var out = [];\n\n      if (!this.isChild) {\n        var namespace = this.namespace;\n        var copies = \"helpers = helpers || \" + namespace + \".helpers;\";\n        if(this.environment.usePartial) { copies = copies + \" partials = partials || \" + namespace + \".partials;\"; }\n        out.push(copies);\n      } else {\n        out.push('');\n      }\n\n      if (!this.environment.isSimple) {\n        out.push(\", buffer = \" + this.initializeBuffer());\n      } else {\n        out.push(\"\");\n      }\n\n      // track the last context pushed into place to allow skipping the\n      // getContext opcode when it would be a noop\n      this.lastContext = 0;\n      this.source = out;\n    },\n\n    createFunctionContext: function(asObject) {\n      var locals = this.stackVars;\n      if (!this.isChild) {\n        locals = locals.concat(this.context.registers.list);\n      }\n\n      if(locals.length > 0) {\n        this.source[1] = this.source[1] + \", \" + locals.join(\", \");\n      }\n\n      // Generate minimizer alias mappings\n      if (!this.isChild) {\n        var aliases = []\n        for (var alias in this.context.aliases) {\n          this.source[1] = this.source[1] + ', ' + alias + '=' + this.context.aliases[alias];\n        }\n      }\n\n      if (this.source[1]) {\n        this.source[1] = \"var \" + this.source[1].substring(2) + \";\";\n      }\n\n      // Merge children\n      if (!this.isChild) {\n        this.source[1] += '\\n' + this.context.programs.join('\\n') + '\\n';\n      }\n\n      if (!this.environment.isSimple) {\n        this.source.push(\"return buffer;\");\n      }\n\n      var params = this.isChild ? [\"depth0\", \"data\"] : [\"Handlebars\", \"depth0\", \"helpers\", \"partials\", \"data\"];\n\n      for(var i=0, l=this.environment.depths.list.length; i<l; i++) {\n        params.push(\"depth\" + this.environment.depths.list[i]);\n      }\n\n      if (asObject) {\n        params.push(this.source.join(\"\\n  \"));\n\n        return Function.apply(this, params);\n      } else {\n        var functionSource = 'function ' + (this.name || '') + '(' + params.join(',') + ') {\\n  ' + this.source.join(\"\\n  \") + '}';\n        Handlebars.log(Handlebars.logger.DEBUG, functionSource + \"\\n\\n\");\n        return functionSource;\n      }\n    },\n\n    appendContent: function(content) {\n      this.source.push(this.appendToBuffer(this.quotedString(content)));\n    },\n\n    append: function() {\n      var local = this.popStack();\n      this.source.push(\"if(\" + local + \" || \" + local + \" === 0) { \" + this.appendToBuffer(local) + \" }\");\n      if (this.environment.isSimple) {\n        this.source.push(\"else { \" + this.appendToBuffer(\"''\") + \" }\");\n      }\n    },\n\n    appendEscaped: function() {\n      var opcode = this.nextOpcode(1), extra = \"\";\n      this.context.aliases.escapeExpression = 'this.escapeExpression';\n\n      if(opcode[0] === 'appendContent') {\n        extra = \" + \" + this.quotedString(opcode[1][0]);\n        this.eat(opcode);\n      }\n\n      this.source.push(this.appendToBuffer(\"escapeExpression(\" + this.popStack() + \")\" + extra));\n    },\n\n    getContext: function(depth) {\n      if(this.lastContext !== depth) {\n        this.lastContext = depth;\n      }\n    },\n\n    lookupWithHelpers: function(name, isScoped) {\n      if(name) {\n        var topStack = this.nextStack();\n\n        this.usingKnownHelper = false;\n\n        var toPush;\n        if (!isScoped && this.options.knownHelpers[name]) {\n          toPush = topStack + \" = \" + this.nameLookup('helpers', name, 'helper');\n          this.usingKnownHelper = true;\n        } else if (isScoped || this.options.knownHelpersOnly) {\n          toPush = topStack + \" = \" + this.nameLookup('depth' + this.lastContext, name, 'context');\n        } else {\n          toPush =  topStack + \" = \"\n              + this.nameLookup('helpers', name, 'helper')\n              + \" || \"\n              + this.nameLookup('depth' + this.lastContext, name, 'context');\n        }\n\n        toPush += ';';\n        this.source.push(toPush);\n      } else {\n        this.pushStack('depth' + this.lastContext);\n      }\n    },\n\n    lookup: function(name) {\n      var topStack = this.topStack();\n      this.source.push(topStack + \" = (\" + topStack + \" === null || \" + topStack + \" === undefined || \" + topStack + \" === false ? \" +\n \t\t\t\ttopStack + \" : \" + this.nameLookup(topStack, name, 'context') + \");\");\n    },\n\n    pushStringParam: function(string) {\n      this.pushStack('depth' + this.lastContext);\n      this.pushString(string);\n    },\n\n    pushString: function(string) {\n      this.pushStack(this.quotedString(string));\n    },\n\n    push: function(name) {\n      this.pushStack(name);\n    },\n\n    invokeMustache: function(paramSize, original, hasHash) {\n      this.populateParams(paramSize, this.quotedString(original), \"{}\", null, hasHash, function(nextStack, helperMissingString, id) {\n        if (!this.usingKnownHelper) {\n          this.context.aliases.helperMissing = 'helpers.helperMissing';\n          this.context.aliases.undef = 'void 0';\n          this.source.push(\"else if(\" + id + \"=== undef) { \" + nextStack + \" = helperMissing.call(\" + helperMissingString + \"); }\");\n          if (nextStack !== id) {\n            this.source.push(\"else { \" + nextStack + \" = \" + id + \"; }\");\n          }\n        }\n      });\n    },\n\n    invokeProgram: function(guid, paramSize, hasHash) {\n      var inverse = this.programExpression(this.inverse);\n      var mainProgram = this.programExpression(guid);\n\n      this.populateParams(paramSize, null, mainProgram, inverse, hasHash, function(nextStack, helperMissingString, id) {\n        if (!this.usingKnownHelper) {\n          this.context.aliases.blockHelperMissing = 'helpers.blockHelperMissing';\n          this.source.push(\"else { \" + nextStack + \" = blockHelperMissing.call(\" + helperMissingString + \"); }\");\n        }\n      });\n    },\n\n    populateParams: function(paramSize, helperId, program, inverse, hasHash, fn) {\n      var needsRegister = hasHash || this.options.stringParams || inverse || this.options.data;\n      var id = this.popStack(), nextStack;\n      var params = [], param, stringParam, stringOptions;\n\n      if (needsRegister) {\n        this.register('tmp1', program);\n        stringOptions = 'tmp1';\n      } else {\n        stringOptions = '{ hash: {} }';\n      }\n\n      if (needsRegister) {\n        var hash = (hasHash ? this.popStack() : '{}');\n        this.source.push('tmp1.hash = ' + hash + ';');\n      }\n\n      if(this.options.stringParams) {\n        this.source.push('tmp1.contexts = [];');\n      }\n\n      for(var i=0; i<paramSize; i++) {\n        param = this.popStack();\n        params.push(param);\n\n        if(this.options.stringParams) {\n          this.source.push('tmp1.contexts.push(' + this.popStack() + ');');\n        }\n      }\n\n      if(inverse) {\n        this.source.push('tmp1.fn = tmp1;');\n        this.source.push('tmp1.inverse = ' + inverse + ';');\n      }\n\n      if(this.options.data) {\n        this.source.push('tmp1.data = data;');\n      }\n\n      params.push(stringOptions);\n\n      this.populateCall(params, id, helperId || id, fn);\n    },\n\n    populateCall: function(params, id, helperId, fn) {\n      var paramString = [\"depth0\"].concat(params).join(\", \");\n      var helperMissingString = [\"depth0\"].concat(helperId).concat(params).join(\", \");\n\n      var nextStack = this.nextStack();\n\n      if (this.usingKnownHelper) {\n        this.source.push(nextStack + \" = \" + id + \".call(\" + paramString + \");\");\n      } else {\n        this.context.aliases.functionType = '\"function\"';\n        this.source.push(\"if(typeof \" + id + \" === functionType) { \" + nextStack + \" = \" + id + \".call(\" + paramString + \"); }\");\n      }\n      fn.call(this, nextStack, helperMissingString, id);\n      this.usingKnownHelper = false;\n    },\n\n    invokePartial: function(context) {\n      this.pushStack(\"self.invokePartial(\" + this.nameLookup('partials', context, 'partial') + \", '\" + context + \"', \" + this.popStack() + \", helpers, partials);\");\n    },\n\n    assignToHash: function(key) {\n      var value = this.popStack();\n      var hash = this.topStack();\n\n      this.source.push(hash + \"['\" + key + \"'] = \" + value + \";\");\n    },\n\n    // HELPERS\n\n    compiler: JavaScriptCompiler,\n\n    compileChildren: function(environment, options) {\n      var children = environment.children, child, compiler;\n\n      for(var i=0, l=children.length; i<l; i++) {\n        child = children[i];\n        compiler = new this.compiler();\n\n        this.context.programs.push('');     // Placeholder to prevent name conflicts for nested children\n        var index = this.context.programs.length;\n        child.index = index;\n        child.name = 'program' + index;\n        this.context.programs[index] = compiler.compile(child, options, this.context);\n      }\n    },\n\n    programExpression: function(guid) {\n      if(guid == null) { return \"self.noop\"; }\n\n      var child = this.environment.children[guid],\n          depths = child.depths.list;\n      var programParams = [child.index, child.name, \"data\"];\n\n      for(var i=0, l = depths.length; i<l; i++) {\n        depth = depths[i];\n\n        if(depth === 1) { programParams.push(\"depth0\"); }\n        else { programParams.push(\"depth\" + (depth - 1)); }\n      }\n\n      if(depths.length === 0) {\n        return \"self.program(\" + programParams.join(\", \") + \")\";\n      } else {\n        programParams.shift();\n        return \"self.programWithDepth(\" + programParams.join(\", \") + \")\";\n      }\n    },\n\n    register: function(name, val) {\n      this.useRegister(name);\n      this.source.push(name + \" = \" + val + \";\");\n    },\n\n    useRegister: function(name) {\n      if(!this.context.registers[name]) {\n        this.context.registers[name] = true;\n        this.context.registers.list.push(name);\n      }\n    },\n\n    pushStack: function(item) {\n      this.source.push(this.nextStack() + \" = \" + item + \";\");\n      return \"stack\" + this.stackSlot;\n    },\n\n    nextStack: function() {\n      this.stackSlot++;\n      if(this.stackSlot > this.stackVars.length) { this.stackVars.push(\"stack\" + this.stackSlot); }\n      return \"stack\" + this.stackSlot;\n    },\n\n    popStack: function() {\n      return \"stack\" + this.stackSlot--;\n    },\n\n    topStack: function() {\n      return \"stack\" + this.stackSlot;\n    },\n\n    quotedString: function(str) {\n      return '\"' + str\n        .replace(/\\\\/g, '\\\\\\\\')\n        .replace(/\"/g, '\\\\\"')\n        .replace(/\\n/g, '\\\\n')\n        .replace(/\\r/g, '\\\\r') + '\"';\n    }\n  };\n\n  var reservedWords = (\"break case catch continue default delete do else finally \" +\n                       \"for function if in instanceof new return switch this throw \" +\n                       \"try typeof var void while with null true false\").split(\" \");\n\n  var compilerWords = JavaScriptCompiler.RESERVED_WORDS = {};\n\n  for(var i=0, l=reservedWords.length; i<l; i++) {\n    compilerWords[reservedWords[i]] = true;\n  }\n\n\tJavaScriptCompiler.isValidJavaScriptVariableName = function(name) {\n\t\tif(!JavaScriptCompiler.RESERVED_WORDS[name] && /^[a-zA-Z_$][0-9a-zA-Z_$]+$/.test(name)) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n})(Handlebars.Compiler, Handlebars.JavaScriptCompiler);\n\nHandlebars.precompile = function(string, options) {\n  options = options || {};\n\n  var ast = Handlebars.parse(string);\n  var environment = new Handlebars.Compiler().compile(ast, options);\n  return new Handlebars.JavaScriptCompiler().compile(environment, options);\n};\n\nHandlebars.compile = function(string, options) {\n  options = options || {};\n\n  var compiled;\n  function compile() {\n    var ast = Handlebars.parse(string);\n    var environment = new Handlebars.Compiler().compile(ast, options);\n    var templateSpec = new Handlebars.JavaScriptCompiler().compile(environment, options, undefined, true);\n    return Handlebars.template(templateSpec);\n  }\n\n  // Template is only compiled on first use and cached after that point.\n  return function(context, options) {\n    if (!compiled) {\n      compiled = compile();\n    }\n    return compiled.call(this, context, options);\n  };\n};\n;\n// lib/handlebars/vm.js\nHandlebars.VM = {\n  template: function(templateSpec) {\n    // Just add water\n    var container = {\n      escapeExpression: Handlebars.Utils.escapeExpression,\n      invokePartial: Handlebars.VM.invokePartial,\n      programs: [],\n      program: function(i, fn, data) {\n        var programWrapper = this.programs[i];\n        if(data) {\n          return Handlebars.VM.program(fn, data);\n        } else if(programWrapper) {\n          return programWrapper;\n        } else {\n          programWrapper = this.programs[i] = Handlebars.VM.program(fn);\n          return programWrapper;\n        }\n      },\n      programWithDepth: Handlebars.VM.programWithDepth,\n      noop: Handlebars.VM.noop\n    };\n\n    return function(context, options) {\n      options = options || {};\n      return templateSpec.call(container, Handlebars, context, options.helpers, options.partials, options.data);\n    };\n  },\n\n  programWithDepth: function(fn, data, $depth) {\n    var args = Array.prototype.slice.call(arguments, 2);\n\n    return function(context, options) {\n      options = options || {};\n\n      return fn.apply(this, [context, options.data || data].concat(args));\n    };\n  },\n  program: function(fn, data) {\n    return function(context, options) {\n      options = options || {};\n\n      return fn(context, options.data || data);\n    };\n  },\n  noop: function() { return \"\"; },\n  invokePartial: function(partial, name, context, helpers, partials) {\n    if(partial === undefined) {\n      throw new Handlebars.Exception(\"The partial \" + name + \" could not be found\");\n    } else if(partial instanceof Function) {\n      return partial(context, {helpers: helpers, partials: partials});\n    } else if (!Handlebars.compile) {\n      throw new Handlebars.Exception(\"The partial \" + name + \" could not be compiled when running in vm mode\");\n    } else {\n      partials[name] = Handlebars.compile(partial);\n      return partials[name](context, {helpers: helpers, partials: partials});\n    }\n  }\n};\n\nHandlebars.template = Handlebars.VM.template;\n;\n"
  },
  {
    "path": "src/Nancy/Diagnostics/Resources/interactive-diagnostics.js",
    "content": "﻿$(function () {\r\n    var app = diagnostics.app;\r\n\r\n    var Provider = diagnostics.module(\"provider\");\r\n    var Method = diagnostics.module(\"method\");\r\n    var Results = diagnostics.module(\"results\");\r\n\r\n    var Router = Backbone.Router.extend({\r\n        routes: {\r\n            \"\": \"index\",\r\n            \":providerName\": \"methods\"\r\n        },\r\n\r\n        index: function () {\r\n            var providers = new Provider.Collection();\r\n            providers.fetch().success(function () {\r\n                var list = new Provider.Views.List({ model: providers });\r\n                list.render();\r\n            });\r\n        },\r\n\r\n        methods: function (providerName) {\r\n            var methods = new Method.Collection({ providerName: providerName });\r\n            methods.fetch().success(function () {\r\n                var list = new Method.Views.List({ model: methods });\r\n                list.render();\r\n            });\r\n        }\r\n    });\r\n\r\n    // Start router and trigger first route\r\n    app.router = new Router();\r\n    Backbone.history.start();\r\n});"
  },
  {
    "path": "src/Nancy/Diagnostics/Resources/interactive.css",
    "content": "﻿.method-arguments \r\n{\r\n    margin-bottom: 0px;    \r\n}\r\n\r\n.execute-button\r\n{\r\n    margin-top: 4px;\r\n    width: 100%;\r\n}\r\n\r\n.method-argument\r\n{\r\n    margin-left: 0px;\r\n}\r\n\r\n.method-argument input \r\n{\r\n    width: 252px;    \r\n}\r\n\r\n.tooltip\r\n{\r\n    position: relative;\r\n}\r\n\r\n.tooltip span\r\n{\r\n    margin-left: -999em;\r\n    position: absolute;\r\n}\r\n\r\n.tooltip-showing span\r\n{\r\n    border-radius: 5px 5px;\r\n    -moz-border-radius: 5px;\r\n    -webkit-border-radius: 5px;\r\n    position: absolute;\r\n    left: 280px;\r\n    margin-left: 0px;\r\n    top: 0;\r\n    width: 250px;\r\n    padding: 0.8em 1em;\r\n    background: #ffffff; \r\n}\r\n\r\n.tooltip-showing span:after\r\n{\r\n  content: \"\\25C2\";\r\n  display: block;\r\n  font-size: 28px;\r\n  height: 0;\r\n  line-height: 0;\r\n  position: absolute;\r\n  color: #ffffff;\r\n  left: -12px;\r\n  top: 10px;\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Diagnostics/Resources/jsonreport.js",
    "content": "﻿/**\r\n* Created by demis.bellot@gmail.com\r\n* Open Source under the New BSD Licence: https://github.com/AjaxStack/AjaxStack/blob/master/LICENSE\r\n*/\r\n\r\n//for non-modern browsers i.e: <=IE8\r\n!window.JSON && document.write(unescape('%3Cscript src=\"\"http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js\"\"%3E%3C/script%3E'));\r\n\r\nif (!_) var _ = {};\r\n_.modelreport = (function () {\r\n    var root = this, doc = document,\r\n\t\t\t\t$ = function (id) { return doc.getElementById(id); },\r\n\t\t\t\t$$ = function (sel) { return doc.getElementsByTagName(sel); },\r\n\t\t\t\t$each = function (fn) { for (var i = 0, len = this.length; i < len; i++) fn(i, this[i], this); },\r\n\t\t\t\tisIE = /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);\r\n\r\n    $.each = function (arr, fn) { $each.call(arr, fn); };\r\n\r\n    var splitCase = function (t) { return typeof t != 'string' ? t : t.replace(/([A-Z]|[0-9]+)/g, ' $1').replace(/_/g, ' '); },\r\n\t\t\t\tuniqueKeys = function (m) { var h = {}; for (var i = 0, len = m.length; i < len; i++) for (var k in m[i]) h[k] = k; return h; },\r\n\t\t\t\tkeys = function (o) { var a = []; for (var k in o) a.push(k); return a; }\r\n    var tbls = [];\r\n\r\n    function val(m) {\r\n        if (m == null) return '';\r\n        if (typeof m == 'number') return num(m);\r\n        if (typeof m == 'string') return str(m);\r\n        if (typeof m == 'boolean') return m ? 'true' : 'false';\r\n        return m.length ? arr(m) : obj(m);\r\n    }\r\n    function num(m) { return m; }\r\n    function str(m) {\r\n        return m.substr(0, 6) == '/Date(' ? dfmt(date(m)) : m;\r\n    }\r\n    function date(s) { return new Date(parseFloat(/Date\\(([^)]+)\\)/.exec(s)[1])); }\r\n    function pad(d) { return d < 10 ? '0' + d : d; }\r\n    function dfmt(d) { return d.getFullYear() + '/' + pad(d.getMonth() + 1) + '/' + pad(d.getDate()); }\r\n    function obj(m) {\r\n        var sb = '<dl>';\r\n        for (var k in m) sb += '<dt class=\"ib\">' + splitCase(k) + '</dt><dd>' + val(m[k]) + '</dd>';\r\n        sb += '</dl>';\r\n        return sb;\r\n    }\r\n    function arr(m) {\r\n        if (typeof m[0] == 'string' || typeof m[0] == 'number') return m.join('<br/> ');\r\n        var id = tbls.length, h = uniqueKeys(m);\r\n        var sb = '<table id=\"tbl-' + id + '\"><caption></caption><thead><tr>';\r\n        tbls.push(m);\r\n        var i = 0;\r\n        for (var k in h) sb += '<th id=\"h-' + id + '-' + (i++) + '\"><b></b>' + splitCase(k) + '</th>';\r\n        sb += '</tr></thead><tbody>' + makeRows(h, m) + '</tbody></table>';\r\n        return sb;\r\n    }\r\n\r\n    function makeRows(h, m) {\r\n        var sb = '';\r\n        for (var r = 0, len = m.length; r < len; r++) {\r\n            sb += '<tr>';\r\n            var row = m[r];\r\n            for (var k in h) sb += '<td>' + val(row[k]) + '</td>';\r\n            sb += '</tr>';\r\n        }\r\n        return sb;\r\n    }\r\n\r\n    function setTableBody(tbody, html) {\r\n        if (!isIE) { tbody.innerHTML = html; return; }\r\n        var temp = tbody.ownerDocument.createElement('div');\r\n        temp.innerHTML = '<table>' + html + '</table>';\r\n        tbody.parentNode.replaceChild(temp.firstChild.firstChild, tbody);\r\n    }\r\n\r\n    function clearSel() {\r\n        if (doc.selection && doc.selection.empty) doc.selection.empty();\r\n        else if (root.getSelection) {\r\n            var sel = root.getSelection();\r\n            if (sel && sel.removeAllRanges) sel.removeAllRanges();\r\n        }\r\n    }\r\n\r\n    function cmp(v1, v2) {\r\n        var f1, f2, f1 = parseFloat(v1), f2 = parseFloat(v2);\r\n        if (!isNaN(f1) && !isNaN(f2)) v1 = f1, v2 = f2;\r\n        if (typeof v1 == 'string' && v1.substr(0, 6) == '/Date(') v1 = date(v1), v2 = date(v2);\r\n        if (v1 == v2) return 0;\r\n        return v1 > v2 ? 1 : -1;\r\n    }\r\n\r\n    function enc(html) {\r\n        if (typeof html != 'string') return html;\r\n        return html.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\r\n    }\r\n\r\n    function addEvent(obj, type, fn) {\r\n        if (obj.attachEvent) {\r\n            obj['e' + type + fn] = fn;\r\n            obj[type + fn] = function () { obj['e' + type + fn](root.event); }\r\n            obj.attachEvent('on' + type, obj[type + fn]);\r\n        } else\r\n            obj.addEventListener(type, fn, false);\r\n    }\r\n\r\n    addEvent(doc, 'click', function (e) {\r\n        var e = e || root.event, el = e.target || e.srcElement, cls = el.className;\r\n        if (el.tagName == 'B') el = el.parentNode;\r\n        if (el.tagName != 'TH') return;\r\n        el.className = cls == 'asc' ? 'desc' : (cls == 'desc' ? null : 'asc');\r\n        $.each($$('TH'), function (i, th) { if (th == el) return; th.className = null; });\r\n        clearSel();\r\n        var ids = el.id.split('-'), tId = ids[1], cId = ids[2];\r\n        var tbl = tbls[tId].slice(0), h = uniqueKeys(tbl), col = keys(h)[cId], tbody = el.parentNode.parentNode.nextSibling;\r\n        if (!el.className) { setTableBody(tbody, makeRows(h, tbls[tId])); return; }\r\n        var d = el.className == 'asc' ? 1 : -1;\r\n        tbl.sort(function (a, b) { return cmp(a[col], b[col]) * d; });\r\n        setTableBody(tbody, makeRows(h, tbl));\r\n    });\r\n\r\n    return function (model) {\r\n        return val(model);\r\n    };\r\n})();\r\n"
  },
  {
    "path": "src/Nancy/Diagnostics/Resources/main.css",
    "content": "﻿body\r\n{\r\n    background: black;\r\n    color: white;\r\n    font-family: Arial;\r\n}\r\n\r\nul\r\n{\r\n    list-style: none;\r\n}\r\n\r\nbutton.g-button, a.g-button, input[type=submit].g-button, input[type=button].g-button\r\n{\r\n    padding: 6px 10px;\r\n    -webkit-border-radius: 2px 2px;\r\n    border: solid 1px rgb(153, 153, 153);\r\n    background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(rgb(255, 255, 255)), to(rgb(221, 221, 221)));\r\n    color: #333;\r\n    text-decoration: none;\r\n    cursor: pointer;\r\n    display: inline-block;\r\n    text-align: center;\r\n    text-shadow: 0px 1px 1px rgba(255,255,255,1);\r\n    line-height: 1;\r\n}\r\n\r\n.container_12\r\n{\r\n    padding: 20px 0;\r\n    position: relative;\r\n}\r\n\r\n.header\r\n{\r\n    padding: 0 0 28px 0;\r\n    height: 100px;\r\n    position: relative;\r\n}\r\n\r\n.header h1\r\n{\r\n    font-size: 24pt;\r\n    position: absolute;\r\n    bottom: 0;\r\n    right: 0;\r\n    margin-bottom: 18px;\r\n}\r\n\r\na.icon-block\r\n{\r\n    display: block;\r\n    background-color: white;\r\n    height: 180px;\r\n    line-height: 0;\r\n    font-size: 0;\r\n    color: transparent;\r\n}\r\n\r\na.icon-block:hover\r\n{\r\n    border: 2px solid #555555;\r\n    height: 176px;\r\n    margin-right: 8px;\r\n    margin-left: 8px;\r\n    background-size: auto 150px;\r\n}\r\n\r\ndiv.description-text h2\r\n{\r\n    font-size: 14pt;\r\n    font-weight: bold;\r\n    margin-bottom: 0px;\r\n    margin-top: 5px;\r\n}\r\n\r\n#infoBox\r\n{\r\n    background-image: url(info.png);\r\n    background-position: center center;\r\n    background-repeat: no-repeat;\r\n}\r\n\r\n#interactiveBox\r\n{\r\n    background-image: url(interactive.png);\r\n    background-position: center center;\r\n    background-repeat: no-repeat;\r\n}\r\n\r\n#traceBox\r\n{\r\n    background-image: url(logs.png);\r\n    background-position: center center;\r\n    background-repeat: no-repeat;\r\n}\r\n\r\n#settingsBox\r\n{\r\n    background-image: url(settings.png);\r\n    background-position: center center;\r\n    background-repeat: no-repeat;\r\n}\r\n\r\ndiv.item-list\r\n{\r\n    background: white;\r\n    color: Black;\r\n    width: 95%;\r\n    padding: 7px;\r\n    margin-bottom: 5px;\r\n    min-height: 100px;\r\n    cursor: pointer;\r\n}\r\n\r\ndiv.item-list:hover\r\n{\r\n    padding: 5px;\r\n    border: 2px solid #555555;\r\n}\r\n\r\ndiv.item-list h2\r\n{\r\n    font-size: 14pt;\r\n    font-weight: bold;\r\n    margin-bottom: 0px;\r\n}\r\n\r\n#back \r\n{\r\n    cursor: pointer;\r\n    font-size: 120%;\r\n    margin-bottom: 10px;\r\n    display: block;    \r\n}\r\n\r\n/* JSON Report CSS */\r\n\r\n.ib {\r\n    text-transform: capitalize;\r\n}\r\n\r\n.modelreport TABLE\r\n{\r\n    border-collapse: collapse;\r\n    border: solid 1px #ccc;\r\n    clear: left;\r\n}\r\n\r\n.modelreport TH\r\n{\r\n    text-align: left;\r\n    padding: 4px 8px;\r\n    text-shadow: #fff 1px 1px -1px;\r\n    background: #f1f1f1;\r\n    color: black;\r\n    white-space: nowrap;\r\n    cursor: pointer;\r\n    font-weight: bold;\r\n}\r\n.modelreport TH, .modelreport TD, .modelreport TD DT, .modelreport TD DD\r\n{\r\n    font-size: 11px;\r\n    font-family: Arial;\r\n}\r\n\r\n.modelreport TD\r\n{\r\n    padding: 8px 8px 0 8px;\r\n    vertical-align: top;\r\n}\r\n\r\n.modelreport DL\r\n{\r\n    clear: left;\r\n    margin: 0px;\r\n}\r\n\r\n.modelreport DT\r\n{\r\n/*    margin: 10px 0 5px 0;*/\r\n    font-weight: bold;\r\n    font-size: 13px;\r\n    width: 260px;\r\n    clear: left;\r\n    float: left;\r\n    display: block;\r\n    white-space: nowrap;\r\n    overflow: hidden;\r\n}\r\n\r\n.modelreport DD\r\n{\r\n/*    margin: 5px 10px;*/\r\n    font-weight: bold;\r\n    font-size: 13px;\r\n    display: block;\r\n    float: left;\r\n}\r\n.modelreport DL DL DT\r\n{\r\n    font-weight: bold;\r\n    font-size: 13px;\r\n}\r\n.modelreport DL DL DD\r\n{\r\n    font-size: 13px;\r\n    max-width: 200px;\r\n}\r\n.modelreport HR\r\n{\r\n    display: none;\r\n}\r\n.modelreport TD DL HR\r\n{\r\n    display: block;\r\n    padding: 0;\r\n    clear: left;\r\n    border: none;\r\n}\r\n.modelreport TD DL\r\n{\r\n    padding: 4px;\r\n    margin: 0;\r\n    height: 100%;\r\n    max-width: 700px;\r\n}\r\n.modelreport DL TD DL DT\r\n{\r\n    padding: 2px;\r\n    margin: 0 10px 0 0;\r\n    font-weight: bold;\r\n    font-size: 11px;\r\n    width: 120px;\r\n    overflow: hidden;\r\n    clear: left;\r\n    float: left;\r\n    display: block;\r\n}\r\n.modelreport DL TD DL DD\r\n{\r\n    margin: 0;\r\n    padding: 2px;\r\n    font-size: 8px;\r\n    display: block;\r\n    float: left;\r\n}\r\n.modelreport TBODY > TR:last-child > TD\r\n{\r\n    padding: 8px;\r\n}\r\n.modelreport THEAD\r\n{\r\n    -webkit-user-select: none;\r\n    -moz-user-select: none;\r\n}\r\n.modelreport .desc, .modelreport .asc\r\n{\r\n    background-color: #FAFAD2;\r\n}\r\n.modelreport .desc\r\n{\r\n    background-color: #D4EDC9;\r\n}\r\n.modelreport TH B\r\n{\r\n    display: block;\r\n    float: right;\r\n    margin: 0 0 0 5px;\r\n    width: 0;\r\n    height: 0;\r\n    border-left: 5px solid transparent;\r\n    border-right: 5px solid transparent;\r\n    border-top: 5px solid #ccc;\r\n    border-bottom: none;\r\n}\r\n.modelreport .asc B\r\n{\r\n    border-left: 5px solid transparent;\r\n    border-right: 5px solid transparent;\r\n    border-top: 5px solid #333;\r\n    border-bottom: none;\r\n}\r\n.modelreport .desc B\r\n{\r\n    border-left: 5px solid transparent;\r\n    border-right: 5px solid transparent;\r\n    border-bottom: 5px solid #333;\r\n    border-top: none;\r\n}\r\n.modelreport H3\r\n{\r\n    font-size: 13px;\r\n    margin: 0 0 10px 0;\r\n}\r\n\r\n/* Settings */\r\n\r\n#settings {\r\n    float: left;\r\n}\r\n\r\n#settings li {\r\n    margin-bottom: 10px;\r\n}\r\n\r\n.help p {\r\n    font-size: 14px;\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Diagnostics/Resources/nancy-common.js",
    "content": "﻿"
  },
  {
    "path": "src/Nancy/Diagnostics/Resources/request-tracing.js",
    "content": "﻿$(function () {\r\n    var app = diagnostics.app;\r\n\r\n    var Session = diagnostics.module(\"session\");\r\n    var Trace = diagnostics.module(\"trace\");\r\n\r\n    var Router = Backbone.Router.extend({\r\n        routes: {\r\n            \"\": \"index\",\r\n            \":id\": \"trace\"\r\n        },\r\n\r\n        index: function () {\r\n            var sessions = new Session.Collection();\r\n            sessions.fetch().success(function () {\r\n                var list = new Session.Views.List({ model: sessions });\r\n                list.render();\r\n            });\r\n        },\r\n\r\n        trace: function (id) {\r\n            var traces = new Trace.Collection({ id: id });\r\n            traces.fetch().success(function () {\r\n                var list = new Trace.Views.List({ model: traces });\r\n                list.render();\r\n            });\r\n        }\r\n    });\r\n\r\n    // Start router and trigger first route\r\n    app.router = new Router();\r\n    Backbone.history.start();\r\n});"
  },
  {
    "path": "src/Nancy/Diagnostics/Resources/reset.css",
    "content": "a,abbr,acronym,address,applet,article,aside,audio,b,big,blockquote,body,canvas,caption,center,cite,code,dd,del,details,dfn,dialog,div,dl,dt,em,embed,fieldset,figcaption,figure,font,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,html,i,iframe,img,ins,kbd,label,legend,li,mark,menu,meter,nav,object,ol,output,p,pre,progress,q,rp,rt,ruby,s,samp,section,small,span,strike,strong,sub,summary,sup,table,tbody,td,tfoot,th,thead,time,tr,tt,u,ul,var,video,xmp{border:0;margin:0;padding:0;font-size:100%}html,body{height:100%}article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section{display:block}b,strong{font-weight:bold}img{color:transparent;font-size:0;vertical-align:middle;-ms-interpolation-mode:bicubic}ol,ul{list-style:none}li{display:list-item}table{border-collapse:collapse;border-spacing:0}th,td,caption{font-weight:normal;vertical-align:top;text-align:left}q{quotes:none}q:before,q:after{content:'';content:none}sub,sup,small{font-size:75%}sub,sup{line-height:0;position:relative;vertical-align:baseline}sub{bottom:-0.25em}sup{top:-0.5em}svg{overflow:hidden}"
  },
  {
    "path": "src/Nancy/Diagnostics/Resources/text.css",
    "content": "body{font:13px/1.5 'Helvetica Neue',Arial,'Liberation Sans',FreeSans,sans-serif}pre,code{font-family:'DejaVu Sans Mono',Menlo,Consolas,monospace}hr{border:0 #ccc solid;border-top-width:1px;clear:both;height:0}h1{font-size:25px}h2{font-size:23px}h3{font-size:21px}h4{font-size:19px}h5{font-size:17px}h6{font-size:15px}ol{list-style:decimal}ul{list-style:disc}li{margin-left:30px}p,dl,hr,h1,h2,h3,h4,h5,h6,ol,ul,pre,table,address,fieldset,figure{margin-bottom:20px}"
  },
  {
    "path": "src/Nancy/Diagnostics/Resources/underscore-min.js",
    "content": "// Underscore.js 1.2.2\n// (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.\n// Underscore is freely distributable under the MIT license.\n// Portions of Underscore are inspired or borrowed from Prototype,\n// Oliver Steele's Functional, and John Resig's Micro-Templating.\n// For all details and documentation:\n// http://documentcloud.github.com/underscore\n(function(){function r(a,c,d){if(a===c)return a!==0||1/a==1/c;if(a==null||c==null)return a===c;if(a._chain)a=a._wrapped;if(c._chain)c=c._wrapped;if(b.isFunction(a.isEqual))return a.isEqual(c);if(b.isFunction(c.isEqual))return c.isEqual(a);var e=l.call(a);if(e!=l.call(c))return false;switch(e){case \"[object String]\":return String(a)==String(c);case \"[object Number]\":return a=+a,c=+c,a!=a?c!=c:a==0?1/a==1/c:a==c;case \"[object Date]\":case \"[object Boolean]\":return+a==+c;case \"[object RegExp]\":return a.source==\nc.source&&a.global==c.global&&a.multiline==c.multiline&&a.ignoreCase==c.ignoreCase}if(typeof a!=\"object\"||typeof c!=\"object\")return false;for(var f=d.length;f--;)if(d[f]==a)return true;d.push(a);var f=0,g=true;if(e==\"[object Array]\"){if(f=a.length,g=f==c.length)for(;f--;)if(!(g=f in a==f in c&&r(a[f],c[f],d)))break}else{if(\"constructor\"in a!=\"constructor\"in c||a.constructor!=c.constructor)return false;for(var h in a)if(m.call(a,h)&&(f++,!(g=m.call(c,h)&&r(a[h],c[h],d))))break;if(g){for(h in c)if(m.call(c,\nh)&&!f--)break;g=!f}}d.pop();return g}var s=this,F=s._,o={},k=Array.prototype,p=Object.prototype,i=k.slice,G=k.unshift,l=p.toString,m=p.hasOwnProperty,v=k.forEach,w=k.map,x=k.reduce,y=k.reduceRight,z=k.filter,A=k.every,B=k.some,q=k.indexOf,C=k.lastIndexOf,p=Array.isArray,H=Object.keys,t=Function.prototype.bind,b=function(a){return new n(a)};if(typeof exports!==\"undefined\"){if(typeof module!==\"undefined\"&&module.exports)exports=module.exports=b;exports._=b}else typeof define===\"function\"&&define.amd?\ndefine(\"underscore\",function(){return b}):s._=b;b.VERSION=\"1.2.2\";var j=b.each=b.forEach=function(a,c,b){if(a!=null)if(v&&a.forEach===v)a.forEach(c,b);else if(a.length===+a.length)for(var e=0,f=a.length;e<f;e++){if(e in a&&c.call(b,a[e],e,a)===o)break}else for(e in a)if(m.call(a,e)&&c.call(b,a[e],e,a)===o)break};b.map=function(a,c,b){var e=[];if(a==null)return e;if(w&&a.map===w)return a.map(c,b);j(a,function(a,g,h){e[e.length]=c.call(b,a,g,h)});return e};b.reduce=b.foldl=b.inject=function(a,c,d,e){var f=\nd!==void 0;a==null&&(a=[]);if(x&&a.reduce===x)return e&&(c=b.bind(c,e)),f?a.reduce(c,d):a.reduce(c);j(a,function(a,b,i){f?d=c.call(e,d,a,b,i):(d=a,f=true)});if(!f)throw new TypeError(\"Reduce of empty array with no initial value\");return d};b.reduceRight=b.foldr=function(a,c,d,e){a==null&&(a=[]);if(y&&a.reduceRight===y)return e&&(c=b.bind(c,e)),d!==void 0?a.reduceRight(c,d):a.reduceRight(c);a=(b.isArray(a)?a.slice():b.toArray(a)).reverse();return b.reduce(a,c,d,e)};b.find=b.detect=function(a,c,b){var e;\nD(a,function(a,g,h){if(c.call(b,a,g,h))return e=a,true});return e};b.filter=b.select=function(a,c,b){var e=[];if(a==null)return e;if(z&&a.filter===z)return a.filter(c,b);j(a,function(a,g,h){c.call(b,a,g,h)&&(e[e.length]=a)});return e};b.reject=function(a,c,b){var e=[];if(a==null)return e;j(a,function(a,g,h){c.call(b,a,g,h)||(e[e.length]=a)});return e};b.every=b.all=function(a,c,b){var e=true;if(a==null)return e;if(A&&a.every===A)return a.every(c,b);j(a,function(a,g,h){if(!(e=e&&c.call(b,a,g,h)))return o});\nreturn e};var D=b.some=b.any=function(a,c,d){var c=c||b.identity,e=false;if(a==null)return e;if(B&&a.some===B)return a.some(c,d);j(a,function(a,b,h){if(e||(e=c.call(d,a,b,h)))return o});return!!e};b.include=b.contains=function(a,c){var b=false;if(a==null)return b;return q&&a.indexOf===q?a.indexOf(c)!=-1:b=D(a,function(a){return a===c})};b.invoke=function(a,c){var d=i.call(arguments,2);return b.map(a,function(a){return(c.call?c||a:a[c]).apply(a,d)})};b.pluck=function(a,c){return b.map(a,function(a){return a[c]})};\nb.max=function(a,c,d){if(!c&&b.isArray(a))return Math.max.apply(Math,a);if(!c&&b.isEmpty(a))return-Infinity;var e={computed:-Infinity};j(a,function(a,b,h){b=c?c.call(d,a,b,h):a;b>=e.computed&&(e={value:a,computed:b})});return e.value};b.min=function(a,c,d){if(!c&&b.isArray(a))return Math.min.apply(Math,a);if(!c&&b.isEmpty(a))return Infinity;var e={computed:Infinity};j(a,function(a,b,h){b=c?c.call(d,a,b,h):a;b<e.computed&&(e={value:a,computed:b})});return e.value};b.shuffle=function(a){var c=[],b;\nj(a,function(a,f){f==0?c[0]=a:(b=Math.floor(Math.random()*(f+1)),c[f]=c[b],c[b]=a)});return c};b.sortBy=function(a,c,d){return b.pluck(b.map(a,function(a,b,g){return{value:a,criteria:c.call(d,a,b,g)}}).sort(function(a,c){var b=a.criteria,d=c.criteria;return b<d?-1:b>d?1:0}),\"value\")};b.groupBy=function(a,c){var d={},e=b.isFunction(c)?c:function(a){return a[c]};j(a,function(a,c){var b=e(a,c);(d[b]||(d[b]=[])).push(a)});return d};b.sortedIndex=function(a,c,d){d||(d=b.identity);for(var e=0,f=a.length;e<\nf;){var g=e+f>>1;d(a[g])<d(c)?e=g+1:f=g}return e};b.toArray=function(a){return!a?[]:a.toArray?a.toArray():b.isArray(a)?i.call(a):b.isArguments(a)?i.call(a):b.values(a)};b.size=function(a){return b.toArray(a).length};b.first=b.head=function(a,b,d){return b!=null&&!d?i.call(a,0,b):a[0]};b.initial=function(a,b,d){return i.call(a,0,a.length-(b==null||d?1:b))};b.last=function(a,b,d){return b!=null&&!d?i.call(a,Math.max(a.length-b,0)):a[a.length-1]};b.rest=b.tail=function(a,b,d){return i.call(a,b==null||\nd?1:b)};b.compact=function(a){return b.filter(a,function(a){return!!a})};b.flatten=function(a,c){return b.reduce(a,function(a,e){if(b.isArray(e))return a.concat(c?e:b.flatten(e));a[a.length]=e;return a},[])};b.without=function(a){return b.difference(a,i.call(arguments,1))};b.uniq=b.unique=function(a,c,d){var d=d?b.map(a,d):a,e=[];b.reduce(d,function(d,g,h){if(0==h||(c===true?b.last(d)!=g:!b.include(d,g)))d[d.length]=g,e[e.length]=a[h];return d},[]);return e};b.union=function(){return b.uniq(b.flatten(arguments,\ntrue))};b.intersection=b.intersect=function(a){var c=i.call(arguments,1);return b.filter(b.uniq(a),function(a){return b.every(c,function(c){return b.indexOf(c,a)>=0})})};b.difference=function(a,c){return b.filter(a,function(a){return!b.include(c,a)})};b.zip=function(){for(var a=i.call(arguments),c=b.max(b.pluck(a,\"length\")),d=Array(c),e=0;e<c;e++)d[e]=b.pluck(a,\"\"+e);return d};b.indexOf=function(a,c,d){if(a==null)return-1;var e;if(d)return d=b.sortedIndex(a,c),a[d]===c?d:-1;if(q&&a.indexOf===q)return a.indexOf(c);\nfor(d=0,e=a.length;d<e;d++)if(a[d]===c)return d;return-1};b.lastIndexOf=function(a,b){if(a==null)return-1;if(C&&a.lastIndexOf===C)return a.lastIndexOf(b);for(var d=a.length;d--;)if(a[d]===b)return d;return-1};b.range=function(a,b,d){arguments.length<=1&&(b=a||0,a=0);for(var d=arguments[2]||1,e=Math.max(Math.ceil((b-a)/d),0),f=0,g=Array(e);f<e;)g[f++]=a,a+=d;return g};var E=function(){};b.bind=function(a,c){var d,e;if(a.bind===t&&t)return t.apply(a,i.call(arguments,1));if(!b.isFunction(a))throw new TypeError;\ne=i.call(arguments,2);return d=function(){if(!(this instanceof d))return a.apply(c,e.concat(i.call(arguments)));E.prototype=a.prototype;var b=new E,g=a.apply(b,e.concat(i.call(arguments)));return Object(g)===g?g:b}};b.bindAll=function(a){var c=i.call(arguments,1);c.length==0&&(c=b.functions(a));j(c,function(c){a[c]=b.bind(a[c],a)});return a};b.memoize=function(a,c){var d={};c||(c=b.identity);return function(){var b=c.apply(this,arguments);return m.call(d,b)?d[b]:d[b]=a.apply(this,arguments)}};b.delay=\nfunction(a,b){var d=i.call(arguments,2);return setTimeout(function(){return a.apply(a,d)},b)};b.defer=function(a){return b.delay.apply(b,[a,1].concat(i.call(arguments,1)))};b.throttle=function(a,c){var d,e,f,g,h,i=b.debounce(function(){h=g=false},c);return function(){d=this;e=arguments;var b;f||(f=setTimeout(function(){f=null;h&&a.apply(d,e);i()},c));g?h=true:a.apply(d,e);i();g=true}};b.debounce=function(a,b){var d;return function(){var e=this,f=arguments;clearTimeout(d);d=setTimeout(function(){d=\nnull;a.apply(e,f)},b)}};b.once=function(a){var b=false,d;return function(){if(b)return d;b=true;return d=a.apply(this,arguments)}};b.wrap=function(a,b){return function(){var d=[a].concat(i.call(arguments));return b.apply(this,d)}};b.compose=function(){var a=i.call(arguments);return function(){for(var b=i.call(arguments),d=a.length-1;d>=0;d--)b=[a[d].apply(this,b)];return b[0]}};b.after=function(a,b){return a<=0?b():function(){if(--a<1)return b.apply(this,arguments)}};b.keys=H||function(a){if(a!==\nObject(a))throw new TypeError(\"Invalid object\");var b=[],d;for(d in a)m.call(a,d)&&(b[b.length]=d);return b};b.values=function(a){return b.map(a,b.identity)};b.functions=b.methods=function(a){var c=[],d;for(d in a)b.isFunction(a[d])&&c.push(d);return c.sort()};b.extend=function(a){j(i.call(arguments,1),function(b){for(var d in b)b[d]!==void 0&&(a[d]=b[d])});return a};b.defaults=function(a){j(i.call(arguments,1),function(b){for(var d in b)a[d]==null&&(a[d]=b[d])});return a};b.clone=function(a){return!b.isObject(a)?\na:b.isArray(a)?a.slice():b.extend({},a)};b.tap=function(a,b){b(a);return a};b.isEqual=function(a,b){return r(a,b,[])};b.isEmpty=function(a){if(b.isArray(a)||b.isString(a))return a.length===0;for(var c in a)if(m.call(a,c))return false;return true};b.isElement=function(a){return!!(a&&a.nodeType==1)};b.isArray=p||function(a){return l.call(a)==\"[object Array]\"};b.isObject=function(a){return a===Object(a)};b.isArguments=l.call(arguments)==\"[object Arguments]\"?function(a){return l.call(a)==\"[object Arguments]\"}:\nfunction(a){return!(!a||!m.call(a,\"callee\"))};b.isFunction=function(a){return l.call(a)==\"[object Function]\"};b.isString=function(a){return l.call(a)==\"[object String]\"};b.isNumber=function(a){return l.call(a)==\"[object Number]\"};b.isNaN=function(a){return a!==a};b.isBoolean=function(a){return a===true||a===false||l.call(a)==\"[object Boolean]\"};b.isDate=function(a){return l.call(a)==\"[object Date]\"};b.isRegExp=function(a){return l.call(a)==\"[object RegExp]\"};b.isNull=function(a){return a===null};\nb.isUndefined=function(a){return a===void 0};b.noConflict=function(){s._=F;return this};b.identity=function(a){return a};b.times=function(a,b,d){for(var e=0;e<a;e++)b.call(d,e)};b.escape=function(a){return(\"\"+a).replace(/&/g,\"&amp;\").replace(/</g,\"&lt;\").replace(/>/g,\"&gt;\").replace(/\"/g,\"&quot;\").replace(/'/g,\"&#x27;\").replace(/\\//g,\"&#x2F;\")};b.mixin=function(a){j(b.functions(a),function(c){I(c,b[c]=a[c])})};var J=0;b.uniqueId=function(a){var b=J++;return a?a+b:b};b.templateSettings={evaluate:/<%([\\s\\S]+?)%>/g,\ninterpolate:/<%=([\\s\\S]+?)%>/g,escape:/<%-([\\s\\S]+?)%>/g};b.template=function(a,c){var d=b.templateSettings,d=\"var __p=[],print=function(){__p.push.apply(__p,arguments);};with(obj||{}){__p.push('\"+a.replace(/\\\\/g,\"\\\\\\\\\").replace(/'/g,\"\\\\'\").replace(d.escape,function(a,b){return\"',_.escape(\"+b.replace(/\\\\'/g,\"'\")+\"),'\"}).replace(d.interpolate,function(a,b){return\"',\"+b.replace(/\\\\'/g,\"'\")+\",'\"}).replace(d.evaluate||null,function(a,b){return\"');\"+b.replace(/\\\\'/g,\"'\").replace(/[\\r\\n\\t]/g,\" \")+\";__p.push('\"}).replace(/\\r/g,\n\"\\\\r\").replace(/\\n/g,\"\\\\n\").replace(/\\t/g,\"\\\\t\")+\"');}return __p.join('');\",e=new Function(\"obj\",\"_\",d);return c?e(c,b):function(a){return e(a,b)}};var n=function(a){this._wrapped=a};b.prototype=n.prototype;var u=function(a,c){return c?b(a).chain():a},I=function(a,c){n.prototype[a]=function(){var a=i.call(arguments);G.call(a,this._wrapped);return u(c.apply(b,a),this._chain)}};b.mixin(b);j(\"pop,push,reverse,shift,sort,splice,unshift\".split(\",\"),function(a){var b=k[a];n.prototype[a]=function(){b.apply(this._wrapped,\narguments);return u(this._wrapped,this._chain)}});j([\"concat\",\"join\",\"slice\"],function(a){var b=k[a];n.prototype[a]=function(){return u(b.apply(this._wrapped,arguments),this._chain)}});n.prototype.chain=function(){this._chain=true;return this};n.prototype.value=function(){return this._wrapped}}).call(this);\n"
  },
  {
    "path": "src/Nancy/Diagnostics/ResponseData.cs",
    "content": "namespace Nancy.Diagnostics\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Stores request trace information about the response.\r\n    /// </summary>\r\n    public class ResponseData\r\n    {\r\n        /// <summary>\r\n        /// Gets or sets the content type of the response.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the content type.</value>\r\n        public string ContentType { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the headers of the response.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"IDictionary{TKey,TValue}\"/> instance containing the headers.</value>\r\n        public IDictionary<string, string> Headers { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the <see cref=\"HttpStatusCode\"/> of the response.\r\n        /// </summary>\r\n        public HttpStatusCode StatusCode { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the <see cref=\"Type\"/> of the response.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"Type\"/> instance.</value>\r\n        public Type Type { get; set; }\r\n\r\n        /// <summary>\r\n        /// Implicitly casts a <see cref=\"Response\"/> instance into a <see cref=\"ResponseData\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"response\">A <see cref=\"Response\"/> instance.</param>\r\n        /// <returns>A <see cref=\"ResponseData\"/> instance.</returns>\r\n        public static implicit operator ResponseData(Response response)\r\n        {\r\n            return new ResponseData\r\n            {\r\n                ContentType = response.ContentType,\r\n                Headers = response.Headers,\r\n                StatusCode = response.StatusCode,\r\n                Type = response.GetType()\r\n            };\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/TemplateAttribute.cs",
    "content": "namespace Nancy.Diagnostics\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Attribute for defining an HTML template.\r\n    /// </summary>\r\n    /// <seealso cref=\"System.Attribute\" />\r\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]\r\n    public class TemplateAttribute : Attribute\r\n    {\r\n        /// <summary>\r\n        /// Gets or sets the template.\r\n        /// </summary>\r\n        /// <value>The template as <see cref=\"string\"/>.</value>\r\n        public string Template { get; set; }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"TemplateAttribute\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"template\">The template as <see cref=\"string\"/>.</param>\r\n        public TemplateAttribute(string template)\r\n        {\r\n            this.Template = template;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/TestingDiagnosticProvider.cs",
    "content": "﻿namespace Nancy.Diagnostics\r\n{\r\n    /// <summary>\r\n    /// A dummy diagnostic provider for testing purposes.\r\n    /// </summary>\r\n    /// <seealso cref=\"Nancy.Diagnostics.IDiagnosticsProvider\" />\r\n    public class TestingDiagnosticProvider : IDiagnosticsProvider\r\n    {\r\n        private readonly object diagObject;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"TestingDiagnosticProvider\"/> class.\r\n        /// </summary>\r\n        public TestingDiagnosticProvider()\r\n        {\r\n            this.diagObject = new DiagObject();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the name of the provider.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the name of the provider.</value>\r\n        public string Name\r\n        {\r\n            get { return \"Testing Diagnostic Provider\"; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the description of the provider.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the description of the provider.</value>\r\n        public string Description\r\n        {\r\n            get { return \"Some testing methods that can be called to.. erm.. test things.\"; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the object that contains the interactive diagnostics methods.\r\n        /// </summary>\r\n        /// <value>An instance of the interactive diagnostics object.</value>\r\n        public object DiagnosticObject\r\n        {\r\n            get { return this.diagObject; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Contains dummy diagnostic methods.\r\n        /// </summary>\r\n        public class DiagObject\r\n        {\r\n            /// <summary>\r\n            /// Empty return value\r\n            /// </summary>\r\n            public void NoReturnValue()\r\n            {\r\n\r\n            }\r\n\r\n            /// <summary>\r\n            /// String return value.\r\n            /// </summary>\r\n            /// <returns>A dummy <seealso cref=\"string\"/> value.</returns>\r\n            public string StringReturnValue()\r\n            {\r\n                return \"Hello!\";\r\n            }\r\n\r\n            /// <summary>\r\n            /// Returns hello with a given name.\r\n            /// </summary>\r\n            /// <param name=\"name\">A name.</param>\r\n            /// <returns>A dummy <seealso cref=\"string\"/> value.</returns>\r\n            public string SayHello(string name)\r\n            {\r\n                return string.Format(\"Hello {0}!\", name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Returns the template for the SayHelloWithAge\r\n            /// </summary>\r\n            /// <value>The template for the SayHelloWithAge</value>\r\n            public string SayHelloWithAgeTemplate\r\n            {\r\n                get\r\n                {\r\n                    return \"<h1>Templated Results</h1><p>{{model.result}}</p>\";\r\n                }\r\n            }\r\n\r\n            /// <summary>\r\n            /// Returns the description of the SayHelloWithAgeDescription method\r\n            /// </summary>\r\n            /// <value>Description for the test method</value>\r\n            public string SayHelloWithAgeDescription\r\n            {\r\n                get\r\n                {\r\n                    return \"Simple test method that takes a name and an age and returns a result with a template.\";\r\n                }\r\n            }\r\n\r\n            /// <summary>\r\n            /// Simple test method that takes a name and an age and returns a string.\r\n            /// </summary>\r\n            /// <param name=\"myName\">A name.</param>\r\n            /// <param name=\"myAge\">An age.</param>\r\n            /// <returns>A string with the given name and age.</returns>\r\n            public string SayHelloWithAge(string myName, int myAge)\r\n            {\r\n                return string.Format(\"Hello {0}, you are {1} years old!\", myName, myAge);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Returns a string with a name and an age using built-in attributes.\r\n            /// </summary>\r\n            /// <param name=\"myName\">My name.</param>\r\n            /// <param name=\"myAge\">My age.</param>\r\n            /// <returns>A templated string with the given name and age.</returns>\r\n            [Template(\"<h1>Templated Results</h1><p>{{model.result}}</p>\")]\r\n            [Description(\"Simple test method that takes a name and an age and returns a result with a template.\")]\r\n            public string SayHelloWithAge2(string myName, int myAge)\r\n            {\r\n                return string.Format(\"Hello {0}, you are {1} years old!\", myName, myAge);\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Diagnostics/Views/Dashboard.sshtml",
    "content": "﻿@Master['_DiagnosticsMaster']\r\n\r\n@Section['Title']Dashboard@EndSection\r\n\r\n@Section['Header']\r\n\t<script src=\"@Path['~/Resources/diagnostics.js']\"></script>\r\n@EndSection\r\n\r\n@Section['Page_Title']\r\n\t<h1>Dashboard</h1>\r\n@EndSection\r\n\r\n@Section['Body']\r\n\t<a id=\"infoBox\" class=\"grid_3 icon-block\" href=\"@Path['~/info']\"></a>\r\n\t<a id=\"interactiveBox\" class=\"grid_3 icon-block\" href=\"@Path['~/interactive']\"></a>\r\n\t<a id=\"traceBox\" class=\"grid_3 icon-block\" href=\"@Path['~/trace']\"></a>\r\n\t<a id=\"settingsBox\" class=\"grid_3 icon-block\" href=\"@Path['~/settings']\"></a>\r\n\r\n\t<div class=\"grid_3 description-text\">\r\n\t\t<h2>Information</h2>\r\n\t\t<p>Information about Nancy's current runtime configuration. A useful starting point for diagnosing a misbehaving site.</p>\r\n\t</div>\r\n\r\n\t<div class=\"grid_3 description-text\">\r\n\t\t<h2>Interactive Diagnostics</h2>\r\n\t\t<p>Interactive diagnostics allow you to poke and prod at the guts of your Nancy site, from querying configuration, to clearing caches, through to executing parts of the pipeline and visualising the results.</p>\r\n\t</div>\r\n\r\n\t<div class=\"grid_3 description-text\">\r\n\t\t<h2>Request Tracing</h2>\r\n\t\t<p>Provides tracing information about requests including request/response headers and a tracelog of each request.</p>\r\n\t</div>\r\n\r\n\t<div class=\"grid_3 description-text\">\r\n\t\t<h2>Settings</h2>\r\n\t\t<p>Configure some of Nancy's runtime static configuration.</p>\r\n\t</div>\r\n@EndSection\r\n\r\n\r\n\r\n"
  },
  {
    "path": "src/Nancy/Diagnostics/Views/Info.sshtml",
    "content": "﻿@Master['_DiagnosticsMaster']\r\n\r\n@Section['Title']Info@EndSection\r\n\r\n@Section['Header']\r\n\t<script src=\"@Path['~/Resources/jsonreport.js']\"></script>\r\n@EndSection\r\n\r\n@Section['Page_Title']\r\n\t<h1>Info</h1>\r\n@EndSection\r\n\r\n@Section['Body']\r\n<div id=\"data\" class=\"modelreport\">\r\n</div>\r\n\r\n<script language=\"javascript\" type=\"text/javascript\">\r\n\t$.getJSON(\"@Path['~/Info/Data']\")\r\n\t .success(function (data) {\r\n            $(\"#data\").html(_.modelreport(data));\r\n\t });\r\n\r\n</script>\r\n@EndSection\r\n\r\n\r\n\r\n"
  },
  {
    "path": "src/Nancy/Diagnostics/Views/InteractiveDiagnostics.sshtml",
    "content": "﻿@Master['_DiagnosticsMaster']\r\n\r\n@Section['Title']Interactive Diagnostics@EndSection\r\n\r\n@Section['Header']\r\n\t<script src=\"@Path['~/Resources/jsonreport.js']\"></script>\r\n\t<script src=\"@Path['~/Resources/interactive-diagnostics.js']\"></script>\r\n\t<script src=\"@Path['~/Resources/Modules/interactive/providers.js']\"></script>\r\n\t<script src=\"@Path['~/Resources/Modules/interactive/methods.js']\"></script>\r\n\t<script src=\"@Path['~/Resources/Modules/interactive/results.js']\"></script>\r\n\r\n\t<link href=\"@Path['~/Resources/interactive.css']\" rel=\"Stylesheet\" />\r\n@EndSection\r\n\r\n@Section['Page_Title']\r\n\t<h1>Interactive Diagnostics</h1>\r\n@EndSection\r\n\r\n@Section['Body']\r\n\t<div id=\"main\" class=\"grid_4\">\r\n\t</div>\r\n\r\n\t<div id=\"results\" class=\"grid_8\">\r\n\t</div>\r\n\r\n\t<script id=\"providerList\" type=\"text/x-handlebars-template\">\r\n\t\t{{#if collection.length}}\r\n\t\t{{else}}\r\n\t\t  None providers found.\r\n\t\t{{/if}}\r\n\t</script>\r\n\r\n\t<script id=\"methodList\" type=\"text/x-handlebars-template\">\r\n\t\t<a id=\"back\"><< back</a>\r\n\t\t{{#if collection.length}}\r\n\t\t  <ul id=\"root\">\r\n\t\t  </ul>\r\n\t\t{{else}}\r\n\t\t  None found.\r\n\t\t{{/if}}\r\n\t</script>\r\n\r\n\t<script id=\"provider\" type=\"text/x-handlebars-template\">\r\n\t\t<h2>{{model.name}}</h2>\r\n\t\t<p>{{model.description}}</p>\r\n\t</script>\r\n\r\n\t<script id=\"method\" type=\"text/x-handlebars-template\">\r\n\t\t<div class=\"item-list\">\r\n\t\t\t<strong>{{model.methodName}}</strong><br/>\r\n\t\t\t<em>{{model.description}}</em><br/>\r\n\t\t\t\t{{#if model.arguments.length}}\r\n\t\t\t\t\t<ul class=\"method-arguments\">\r\n\t\t\t\t\t\t{{#each model.arguments}}\r\n\t\t\t\t\t\t\t<li class=\"method-argument\">\r\n\t\t\t\t\t\t\t\t<div class=\"tooltip\">\r\n\t\t\t\t\t\t\t\t\t<input type=\"text\" id=\"{{this.argumentName}}\"/>\r\n\t\t\t\t\t\t\t\t\t<span class=\"method-argument-tooltip\">\r\n\t\t\t\t\t\t\t\t\t\t<strong>{{this.argumentName}}</strong><br/>\r\n\t\t\t\t\t\t\t\t\t\t<em>{{this.argumentType}}</em>\r\n\t\t\t\t\t\t\t\t\t</span>\r\n\t\t\t\t\t\t\t\t</div>\r\n\t\t\t\t\t\t\t</li>\r\n\t\t\t\t\t\t{{/each}}\r\n\t\t\t\t\t</ul>\r\n\t\t\t\t{{else}}\r\n\t\t\t\t\tNone.\r\n\t\t\t\t{{/if}}\r\n\t\t\t<input type=\"button\" value=\"Execute\" class=\"g-button execute-button\"/>\r\n\t\t</div>\r\n\t</script>\r\n@EndSection\r\n\r\n\r\n\r\n"
  },
  {
    "path": "src/Nancy/Diagnostics/Views/RequestTracing.sshtml",
    "content": "﻿@Master['_DiagnosticsMaster']\r\n\r\n@Section['Title']Request Tracing@EndSection\r\n\r\n@Section['Header']\r\n\t<link href=\"@Path['~/Resources/request-tracing.css']\" rel=\"Stylesheet\" />\r\n\r\n\t<script src=\"@Path['~/Resources/jsonreport.js']\"></script>\r\n\t<script src=\"@Path['~/Resources/Modules/tracing/sessions.js']\"></script>\r\n\t<script src=\"@Path['~/Resources/Modules/tracing/traces.js']\"></script>\r\n\r\n\t<script src=\"@Path['~/Resources/request-tracing.js']\"></script>\r\n@EndSection\r\n\r\n@Section['Page_Title']\r\n\t<h1>Request Tracing</h1>\r\n@EndSection\r\n\r\n@Section['Body']\r\n\t<div id=\"main\" class=\"grid_4\">\r\n\t</div>\r\n\r\n\t<div id=\"details\" class=\"grid_8\">\r\n\t</div>\r\n\r\n\t<script id=\"sessionList\" type=\"text/x-handlebars-template\">\r\n\t\t{{#if collection.length}}\r\n\t\t{{else}}\r\n\t\t  No sessions found.\r\n\t\t{{/if}}\r\n\t</script>\r\n\r\n\t<script id=\"traceList\" type=\"text/x-handlebars-template\">\r\n\t\t<a id=\"back\"><< back</a>\r\n\t\t{{#if collection.length}}\r\n\t\t  <div id=\"root\">\r\n\t\t  </div>\r\n\t\t{{else}}\r\n\t\t  None found.\r\n\t\t{{/if}}\r\n\t</script>\r\n\r\n\t<script id=\"session\" type=\"text/x-handlebars-template\">\r\n\t\t{{model.id}}\r\n\t</script>\r\n\r\n\t<script id=\"trace\" type=\"text/x-handlebars-template\">\r\n\t\tStatus: {{model.statusCode}}<br/>\r\n\t\tMethod: {{model.method}}<br/>\r\n\t\tPath: {{model.requestUrl.path}}<br/>\r\n\t\tRequest Type: {{model.requestContentType}}<br/>\r\n\t\tResponse Type: {{model.responseContentType}}\r\n\t</script>\r\n@EndSection\r\n\r\n\r\n\r\n"
  },
  {
    "path": "src/Nancy/Diagnostics/Views/Settings.sshtml",
    "content": "﻿@Master['_DiagnosticsMaster']\r\n\r\n@Section['Title']Settings@EndSection\r\n\r\n@Section['Header']\r\n@EndSection\r\n\r\n@Section['Page_Title']\r\n\t<h1>Settings</h1>\r\n@EndSection\r\n\r\n@Section['Body']\r\n\r\n\t<div id=\"settings\">\r\n\t\t<ul>\r\n\t\t\t@Each\r\n\t\t\t\t<li>\r\n\t\t\t\t\t<label for=\"@Current.Name\">\r\n\t\t\t\t\t\t@Current.DisplayName\r\n\t\t\t\t\t</label>\r\n\t\t\t\t\t<input type=\"checkbox\" value=\"@Current.Name\" @Current.Checked /><br>\r\n\t\t\t\t\t@Current.Description\r\n\t\t\t\t</li>\r\n\t\t\t@EndEach\r\n\t\t</ul>\r\n\t</div>\r\n\r\n\t<script language=\"javascript\" type=\"text/javascript\">\r\n\r\n\t\t$(\"input[type='checkbox']\").click(function() {\r\n\t\t\r\n\t\t\t$.ajax({\r\n\t\t\t\t  type: \"POST\",\r\n\t\t\t\t  data: {Name: $(this).val(), Value:$(this).is(':checked') },\r\n\t\t\t\t  dataType: \"json\",\r\n\t\t\t\t  success: function(){\r\n\t\t\t\t\tconsole.log(\"yay\");\r\n\t\t\t\t  }\r\n\t\t\t});\r\n\r\n\t\t});\r\n\r\n\t</script>\r\n@EndSection"
  },
  {
    "path": "src/Nancy/Diagnostics/Views/_DiagnosticsMaster.sshtml",
    "content": "﻿<!DOCTYPE HTML>\r\n<html>\r\n\t<head>\r\n\t\t<title>@Section['Title'];</title>\r\n\t\t<style type=\"text/css\">\r\n\t\t\tbody \r\n\t\t\t{\r\n\t\t\t\tbackground: black;\r\n\t\t\t}\r\n\t\t</style>\r\n\r\n\t\t<script language=\"javascript\" type=\"text/javascript\">\r\n\t\t\tNancy = { };\r\n\r\n\t\t\tNancy.config = { };\r\n\r\n\t\t\tNancy.config.basePath = \"@Path['~/']\";\r\n\t\t</script>\r\n\t\t<script src=\"@Path['~/Resources/jquery-1.7.1.min.js']\"></script>\r\n\t\t<script src=\"@Path['~/Resources/underscore-min.js']\"></script>\r\n\t\t<script src=\"@Path['~/Resources/backbone-min.js']\"></script>\r\n\t\t<script src=\"@Path['~/Resources/handlebars.js']\"></script>\r\n\t\t<script src=\"@Path['~/Resources/nancy-common.js']\"></script>\r\n\t\t<script src=\"@Path['~/Resources/diagnostics.js']\"></script>\r\n\r\n\t\t<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"@Path['~/Resources/reset.css']\" />\r\n\t\t<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"@Path['~/Resources/text.css']\" />\r\n\t\t<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"@Path['~/Resources/960.css']\" />\r\n\t\t<link rel=\"Stylesheet\" type=\"text/css\" media=\"all\" href=\"@Path['~/Resources/main.css']\"  />\r\n\r\n\t\t@Section['Header'];\r\n\t</head>\r\n\t<body>\r\n\t\t<div class=\"container_12\">\r\n\r\n\t\t\t<div class=\"grid_6 header\">\r\n\t\t\t\t<a href=\"@Path['~/']\">\r\n\t\t\t\t\t<img src=\"@Path['~/Resources/logo.png']\" width=\"380px\" alt=\"Nancy\" />\r\n\t\t\t\t</a>\r\n\t\t\t</div>\r\n\r\n\t\t\t<div class=\"grid_6 header\">\r\n\t\t\t\t@Section['Page_Title'];\r\n\t\t\t</div>\r\n\r\n\t\t\t@Section['Body'];\r\n\t\t</div>\r\n\t</body>\r\n</html>"
  },
  {
    "path": "src/Nancy/Diagnostics/Views/help.sshtml",
    "content": "﻿@Master['_DiagnosticsMaster']\r\n\r\n@Section['Title']Diagnostics Disabled@EndSection\r\n\r\n@Section['Header']\r\n@EndSection\r\n\r\n@Section['Page_Title']\r\n\t<h1>Diagnostics Disabled</h1>\r\n@EndSection\r\n\r\n@Section['Body']\r\n\t<div class=\"grid_2\">&nbsp;</div>\r\n\t<div class=\"grid_8 help\">\r\n\t\t<p>Diagnostics is currently not correctly configured for this website. Please review your diagnostic configuration and try again.</p>\r\n\t</div>\r\n\t<div class=\"grid_2\">&nbsp;</div>\r\n@EndSection\r\n\r\n\r\n\r\n"
  },
  {
    "path": "src/Nancy/Diagnostics/Views/login.sshtml",
    "content": "﻿@Master['_DiagnosticsMaster']\n\n@Section['Title']Login@EndSection\n\n@Section['Header']\n@EndSection\n\n@Section['Page_Title']\n\t<h1>Login</h1>\n@EndSection\n\n@Section['Body']\n\t<div class=\"grid_3\">&nbsp;</div>\n\t<div class=\"grid_2\" id=\"login\">Password:</div>\n\t<div class=\"grid_4\">\n\t\t<form action=\"@Path['~/']\" method=\"post\">\n\t\t\t<input type=\"password\" id=\"Password\" name=\"Password\" />\n\t\t\t<input type=\"submit\" value=\"Go\"/>\n\t\t</form>\n\t</div>\n\t<div class=\"grid_3\">&nbsp;</div>\n\t<script language=\"javascript\" type=\"text/javascript\">\n\t\tdocument.getElementById(\"Password\").focus();\n\t</script>\n@EndSection\n\n\n\n"
  },
  {
    "path": "src/Nancy/DisabledStaticContentProvider.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    /// <summary>\r\n    /// A \"disabled\" static content provider - always returns null\r\n    /// so no content is served.\r\n    /// </summary>\r\n    public class DisabledStaticContentProvider : IStaticContentProvider\r\n    {\r\n        /// <summary>\r\n        /// Gets the static content response, if possible.\r\n        /// </summary>\r\n        /// <param name=\"context\">Current context</param>\r\n        /// <returns>Response if serving content, null otherwise</returns>\r\n        public Response GetContent(NancyContext context)\r\n        {\r\n            return null;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/DynamicDictionary.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using System;\r\n    using System.Collections;\r\n    using System.Collections.Generic;\r\n    using System.Diagnostics;\r\n    using System.Dynamic;\r\n    using System.Linq;\r\n    using System.Text;\r\n\r\n    /// <summary>\r\n    /// A dictionary that supports dynamic access.\r\n    /// </summary>\r\n    [DebuggerDisplay(\"{DebuggerDisplay, nq}\")]\r\n    public class DynamicDictionary : DynamicObject, IEquatable<DynamicDictionary>, IHideObjectMembers, IEnumerable<string>, IDictionary<string, object>\r\n    {\r\n        private readonly GlobalizationConfiguration globalizationConfiguration;\r\n\r\n        private readonly IDictionary<string, dynamic> dictionary =\r\n            new Dictionary<string, dynamic>(StaticConfiguration.CaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase);\r\n\r\n        /// <summary>\r\n        /// Initializes a new istance of the <see cref=\"DynamicDictionary\"/> class.\r\n        /// </summary>\r\n        public DynamicDictionary()\r\n            : this(GlobalizationConfiguration.Default)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new istance of the <see cref=\"DynamicDictionary\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"globalizationConfiguration\">A <see cref=\"GlobalizationConfiguration\"/> instance.</param>\r\n        public DynamicDictionary(GlobalizationConfiguration globalizationConfiguration)\r\n        {\r\n            this.globalizationConfiguration = globalizationConfiguration;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an empty dynamic dictionary.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"DynamicDictionary\"/> instance.</value>\r\n        public static DynamicDictionary Empty\r\n        {\r\n            get { return new DynamicDictionary(); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a dynamic dictionary from an <see cref=\"IDictionary{TKey,TValue}\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"values\">An <see cref=\"IDictionary{TKey,TValue}\"/> instance, that the dynamic dictionary should be created from.</param>\r\n        /// <param name=\"globalizationConfiguration\"></param>\r\n        /// <returns>An <see cref=\"DynamicDictionary\"/> instance.</returns>\r\n        public static DynamicDictionary Create(IDictionary<string, object> values, GlobalizationConfiguration globalizationConfiguration)\r\n        {\r\n            var instance = new DynamicDictionary(globalizationConfiguration);\r\n\r\n            foreach (var key in values.Keys)\r\n            {\r\n                instance[key] = values[key];\r\n            }\r\n\r\n            return instance;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Provides the implementation for operations that set member values. Classes derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class can override this method to specify dynamic behavior for operations such as setting a value for a property.\r\n        /// </summary>\r\n        /// <returns>true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.)</returns>\r\n        /// <param name=\"binder\">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member to which the value is being assigned. For example, for the statement sampleObject.SampleProperty = \"Test\", where sampleObject is an instance of the class derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class, binder.Name returns \"SampleProperty\". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param><param name=\"value\">The value to set to the member. For example, for sampleObject.SampleProperty = \"Test\", where sampleObject is an instance of the class derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class, the <paramref name=\"value\"/> is \"Test\".</param>\r\n        public override bool TrySetMember(SetMemberBinder binder, object value)\r\n        {\r\n            this[binder.Name] = value;\r\n            return true;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Provides the implementation for operations that get member values. Classes derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class can override this method to specify dynamic behavior for operations such as getting a value for a property.\r\n        /// </summary>\r\n        /// <returns>true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a run-time exception is thrown.)</returns>\r\n        /// <param name=\"binder\">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member on which the dynamic operation is performed. For example, for the Console.WriteLine(sampleObject.SampleProperty) statement, where sampleObject is an instance of the class derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class, binder.Name returns \"SampleProperty\". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param><param name=\"result\">The result of the get operation. For example, if the method is called for a property, you can assign the property value to <paramref name=\"result\"/>.</param>\r\n        public override bool TryGetMember(GetMemberBinder binder, out object result)\r\n        {\r\n            if (!this.dictionary.TryGetValue(binder.Name, out result))\r\n            {\r\n                result = new DynamicDictionaryValue(null, this.globalizationConfiguration);\r\n            }\r\n\r\n            return true;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns the enumeration of all dynamic member names.\r\n        /// </summary>\r\n        /// <returns>A <see cref=\"IEnumerable{T}\"/> that contains dynamic member names.</returns>\r\n        public override IEnumerable<string> GetDynamicMemberNames()\r\n        {\r\n            return this.dictionary.Keys;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns the enumeration of all dynamic member names.\r\n        /// </summary>\r\n        /// <returns>A <see cref=\"IEnumerable{T}\"/> that contains dynamic member names.</returns>\r\n        public IEnumerator<string> GetEnumerator()\r\n        {\r\n            return this.dictionary.Keys.GetEnumerator();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns the enumeration of all dynamic member names.\r\n        /// </summary>\r\n        /// <returns>A <see cref=\"IEnumerator\"/> that contains dynamic member names.</returns>\r\n        IEnumerator IEnumerable.GetEnumerator()\r\n        {\r\n            return this.dictionary.Keys.GetEnumerator();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the <see cref=\"DynamicDictionaryValue\"/> with the specified name.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"DynamicDictionaryValue\"/> instance containing a value.</value>\r\n        public dynamic this[string name]\r\n        {\r\n            get\r\n            {\r\n                name = GetNeutralKey(name);\r\n\r\n                dynamic member;\r\n                if (!this.dictionary.TryGetValue(name, out member))\r\n                {\r\n                    member = new DynamicDictionaryValue(null, this.globalizationConfiguration);\r\n                }\r\n\r\n                return member;\r\n            }\r\n            set\r\n            {\r\n                name = GetNeutralKey(name);\r\n\r\n                this.dictionary[name] = value is DynamicDictionaryValue ? value : new DynamicDictionaryValue(value, this.globalizationConfiguration);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Indicates whether the current <see cref=\"DynamicDictionary\"/> is equal to another object of the same type.\r\n        /// </summary>\r\n        /// <returns><see langword=\"true\"/> if the current instance is equal to the <paramref name=\"other\"/> parameter; otherwise, <see langword=\"false\"/>.</returns>\r\n        /// <param name=\"other\">An <see cref=\"DynamicDictionary\"/> instance to compare with this instance.</param>\r\n        public bool Equals(DynamicDictionary other)\r\n        {\r\n            if (ReferenceEquals(null, other))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            return ReferenceEquals(this, other) || Equals(other.dictionary, this.dictionary);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determines whether the specified <see cref=\"System.Object\"/> is equal to this instance.\r\n        /// </summary>\r\n        /// <param name=\"obj\">The <see cref=\"System.Object\"/> to compare with this instance.</param>\r\n        /// <returns><see langword=\"true\"/> if the specified <see cref=\"System.Object\"/> is equal to this instance; otherwise, <see langword=\"false\"/>.</returns>\r\n        public override bool Equals(object obj)\r\n        {\r\n            if (ReferenceEquals(null, obj))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            if (ReferenceEquals(this, obj))\r\n            {\r\n                return true;\r\n            }\r\n\r\n            return obj.GetType() == typeof(DynamicDictionary) && this.Equals((DynamicDictionary)obj);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an enumerator that iterates through the collection.\r\n        /// </summary>\r\n        /// <returns>A <see cref=\"T:System.Collections.Generic.IEnumerator`1\"/> that can be used to iterate through the collection.</returns>\r\n        IEnumerator<KeyValuePair<string, dynamic>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator()\r\n        {\r\n            return this.dictionary.GetEnumerator();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns a hash code for this <see cref=\"DynamicDictionary\"/>.\r\n        /// </summary>\r\n        /// <returns> A hash code for this <see cref=\"DynamicDictionary\"/>, suitable for use in hashing algorithms and data structures like a hash table.</returns>\r\n        public override int GetHashCode()\r\n        {\r\n            return (this.dictionary != null ? this.dictionary.GetHashCode() : 0);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds an element with the provided key and value to the <see cref=\"DynamicDictionary\"/>.\r\n        /// </summary>\r\n        /// <param name=\"key\">The object to use as the key of the element to add.</param>\r\n        /// <param name=\"value\">The object to use as the value of the element to add.</param>\r\n        public void Add(string key, dynamic value)\r\n        {\r\n            this[key] = value;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds an item to the <see cref=\"DynamicDictionary\"/>.\r\n        /// </summary>\r\n        /// <param name=\"item\">The object to add to the <see cref=\"DynamicDictionary\"/>.</param>\r\n        public void Add(KeyValuePair<string, dynamic> item)\r\n        {\r\n            this[item.Key] = item.Value;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determines whether the <see cref=\"DynamicDictionary\"/> contains an element with the specified key.\r\n        /// </summary>\r\n        /// <returns><see langword=\"true\" /> if the <see cref=\"DynamicDictionary\"/> contains an element with the key; otherwise, <see langword=\"false\" />.\r\n        /// </returns>\r\n        /// <param name=\"key\">The key to locate in the <see cref=\"DynamicDictionary\"/>.</param>\r\n        public bool ContainsKey(string key)\r\n        {\r\n            key = GetNeutralKey(key);\r\n            return this.dictionary.ContainsKey(key);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets an <see cref=\"T:System.Collections.Generic.ICollection`1\"/> containing the keys of the <see cref=\"DynamicDictionary\"/>.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"T:System.Collections.Generic.ICollection`1\"/> containing the keys of the <see cref=\"DynamicDictionary\"/>.</returns>\r\n        public ICollection<string> Keys\r\n        {\r\n            get { return this.dictionary.Keys; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the value associated with the specified key.\r\n        /// </summary>\r\n        /// <returns><see langword=\"true\" /> if the <see cref=\"DynamicDictionary\"/> contains an element with the specified key; otherwise, <see langword=\"false\" />.</returns>\r\n        /// <param name=\"key\">The key whose value to get.</param>\r\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 <paramref name=\"value\"/> parameter. This parameter is passed uninitialized.</param>\r\n        public bool TryGetValue(string key, out dynamic value)\r\n        {\r\n            key = GetNeutralKey(key);\r\n            return this.dictionary.TryGetValue(key, out value);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Removes all items from the <see cref=\"DynamicDictionary\"/>.\r\n        /// </summary>\r\n        public void Clear()\r\n        {\r\n            this.dictionary.Clear();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the number of elements contained in the <see cref=\"DynamicDictionary\"/>.\r\n        /// </summary>\r\n        /// <returns>The number of elements contained in the <see cref=\"DynamicDictionary\"/>.</returns>\r\n        public int Count\r\n        {\r\n            get { return this.dictionary.Count; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determines whether the <see cref=\"DynamicDictionary\"/> contains a specific value.\r\n        /// </summary>\r\n        /// <returns><see langword=\"true\" /> if <paramref name=\"item\"/> is found in the <see cref=\"DynamicDictionary\"/>; otherwise, <see langword=\"false\" />.\r\n        /// </returns>\r\n        /// <param name=\"item\">The object to locate in the <see cref=\"DynamicDictionary\"/>.</param>\r\n        public bool Contains(KeyValuePair<string, dynamic> item)\r\n        {\r\n            var dynamicValueKeyValuePair =\r\n                this.GetDynamicKeyValuePair(item);\r\n\r\n            return this.dictionary.Contains(dynamicValueKeyValuePair);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Copies the elements of the <see cref=\"DynamicDictionary\"/> to an <see cref=\"T:System.Array\"/>, starting at a particular <see cref=\"T:System.Array\"/> index.\r\n        /// </summary>\r\n        /// <param name=\"array\">The one-dimensional <see cref=\"T:System.Array\"/> that is the destination of the elements copied from the <see cref=\"DynamicDictionary\"/>. The <see cref=\"T:System.Array\"/> must have zero-based indexing.</param>\r\n        /// <param name=\"arrayIndex\">The zero-based index in <paramref name=\"array\"/> at which copying begins.</param>\r\n        public void CopyTo(KeyValuePair<string, dynamic>[] array, int arrayIndex)\r\n        {\r\n            this.dictionary.CopyTo(array, arrayIndex);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether the <see cref=\"DynamicDictionary\"/> is read-only.\r\n        /// </summary>\r\n        /// <returns>Always returns <see langword=\"false\" />.</returns>\r\n        public bool IsReadOnly\r\n        {\r\n            get { return false; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Removes the element with the specified key from the <see cref=\"DynamicDictionary\"/>.\r\n        /// </summary>\r\n        /// <returns><see langword=\"true\" /> if the element is successfully removed; otherwise, <see langword=\"false\" />.</returns>\r\n        /// <param name=\"key\">The key of the element to remove.</param>\r\n        public bool Remove(string key)\r\n        {\r\n            key = GetNeutralKey(key);\r\n            return this.dictionary.Remove(key);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Removes the first occurrence of a specific object from the <see cref=\"DynamicDictionary\"/>.\r\n        /// </summary>\r\n        /// <returns><see langword=\"true\" /> if <paramref name=\"item\"/> was successfully removed from the <see cref=\"DynamicDictionary\"/>; otherwise, <see langword=\"false\" />.</returns>\r\n        /// <param name=\"item\">The object to remove from the <see cref=\"DynamicDictionary\"/>.</param>\r\n        public bool Remove(KeyValuePair<string, dynamic> item)\r\n        {\r\n            var dynamicValueKeyValuePair =\r\n                this.GetDynamicKeyValuePair(item);\r\n\r\n            return this.dictionary.Remove(dynamicValueKeyValuePair);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets an <see cref=\"T:System.Collections.Generic.ICollection`1\"/> containing the values in the <see cref=\"DynamicDictionary\"/>.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"T:System.Collections.Generic.ICollection`1\"/> containing the values in the <see cref=\"DynamicDictionary\"/>.</returns>\r\n        public ICollection<dynamic> Values\r\n        {\r\n            get\r\n            {\r\n                return this.dictionary.Values;\r\n            }\r\n        }\r\n\r\n        private KeyValuePair<string, dynamic> GetDynamicKeyValuePair(KeyValuePair<string, dynamic> item)\r\n        {\r\n            var dynamicValueKeyValuePair =\r\n                new KeyValuePair<string, dynamic>(item.Key, new DynamicDictionaryValue(item.Value, this.globalizationConfiguration));\r\n            return dynamicValueKeyValuePair;\r\n        }\r\n\r\n        private static string GetNeutralKey(string key)\r\n        {\r\n            return key.Replace(\"-\", string.Empty);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a typed Dictionary of <see cref=\"T:Dictionary{String, Object}\" /> from <see cref=\"DynamicDictionary\"/>\r\n        /// </summary>\r\n        /// <returns>Gets a typed Dictionary of <see cref=\"T:Dictionary{String, Object}\" /> from <see cref=\"DynamicDictionary\"/></returns>\r\n        public Dictionary<string, object> ToDictionary()\r\n        {\r\n            var data = new Dictionary<string, object>();\r\n\r\n            foreach (var item in this.dictionary)\r\n            {\r\n                var newKey = item.Key;\r\n                var newValue = ((DynamicDictionaryValue)item.Value).Value;\r\n\r\n                data.Add(newKey, newValue);\r\n            }\r\n\r\n            return data;\r\n        }\r\n\r\n        private string DebuggerDisplay\r\n        {\r\n            get\r\n            {\r\n                var builder = new StringBuilder();\r\n                var maxItems = Math.Min(this.dictionary.Count, 5);\r\n\r\n                builder.Append(\"{\");\r\n\r\n                for (var i = 0; i < maxItems; i++)\r\n                {\r\n                    var item = this.dictionary.ElementAt(i);\r\n\r\n                    builder.AppendFormat(\" {0} = {1}{2}\", item.Key, item.Value, i < maxItems - 1 ? \",\" : string.Empty);\r\n                }\r\n\r\n                if (maxItems < this.dictionary.Count)\r\n                {\r\n                    builder.Append(\"...\");\r\n                }\r\n\r\n                builder.Append(\" }\");\r\n\r\n                return builder.ToString();\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/DynamicDictionaryValue.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using System;\r\n    using System.ComponentModel;\r\n    using System.Dynamic;\r\n    using System.Globalization;\r\n    using System.Linq.Expressions;\r\n    using System.Reflection;\r\n\r\n    using Microsoft.CSharp.RuntimeBinder;\r\n    using Extensions;\r\n\r\n    using Binder = Microsoft.CSharp.RuntimeBinder.Binder;\r\n\r\n    /// <summary>\r\n    /// A value that is stored inside a <see cref=\"DynamicDictionary\"/> instance.\r\n    /// </summary>\r\n    public class DynamicDictionaryValue : DynamicObject, IEquatable<DynamicDictionaryValue>, IHideObjectMembers, IConvertible\r\n    {\r\n        private readonly object value;\r\n        private readonly GlobalizationConfiguration globalizationConfiguration;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DynamicDictionaryValue\"/> class, with\r\n        /// the provided <paramref name=\"value\"/>.\r\n        /// </summary>\r\n        /// <param name=\"value\">The value to store in the instance</param>\r\n        public DynamicDictionaryValue(object value)\r\n            : this(value, GlobalizationConfiguration.Default)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DynamicDictionaryValue\"/> class, with\r\n        /// the provided <paramref name=\"value\"/> and <paramref name=\"globalizationConfiguration\"/>.\r\n        /// </summary>\r\n        /// <param name=\"value\">The value to store in the instance</param>\r\n        /// <param name=\"globalizationConfiguration\">A <see cref=\"GlobalizationConfiguration\"/> instance.</param>\r\n        public DynamicDictionaryValue(object value, GlobalizationConfiguration globalizationConfiguration)\r\n        {\r\n            this.value = value;\r\n            this.globalizationConfiguration = globalizationConfiguration;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether this instance has value.\r\n        /// </summary>\r\n        /// <value><see langword=\"true\"/>  if this instance has value; otherwise, <see langword=\"false\"/> .</value>\r\n        /// <remarks><see langword=\"null\"/> is considered as not being a value.</remarks>\r\n        public bool HasValue\r\n        {\r\n            get { return (this.value != null); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the inner value\r\n        /// </summary>\r\n        public object Value\r\n        {\r\n            get { return this.value; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns a default value if Value is null\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">When no default value is supplied, required to supply the default type</typeparam>\r\n        /// <param name=\"defaultValue\">Optional parameter for default value, if not given it returns default of type T</param>\r\n        /// <returns>If value is not null, value is returned, else default value is returned</returns>\r\n        public T Default<T>(T defaultValue = default(T))\r\n        {\r\n            if (this.HasValue)\r\n            {\r\n                try\r\n                {\r\n                    return (T)this.value;\r\n                }\r\n                catch\r\n                {\r\n                    var typeName = this.value.GetType().Name;\r\n                    var message = string.Format(\"Cannot convert value of type '{0}' to type '{1}'\", typeName, typeof(T).Name);\r\n\r\n                    throw new InvalidCastException(message);\r\n                }\r\n            }\r\n\r\n            return defaultValue;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to convert the value to type of T, failing to do so will return the defaultValue.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">When no default value is supplied, required to supply the default type</typeparam>\r\n        /// <param name=\"defaultValue\">Optional parameter for default value, if not given it returns default of type T</param>\r\n        /// <returns>If value is not null, value is returned, else default value is returned</returns>\r\n        public T TryParse<T>(T defaultValue = default (T))\r\n        {\r\n            if (this.HasValue)\r\n            {\r\n                try\r\n                {\r\n                    var valueType = this.value.GetType();\r\n                    var parseType = typeof(T);\r\n\r\n                    // check for direct cast\r\n                    if (valueType.IsAssignableFrom(parseType))\r\n                    {\r\n                        return (T)this.value;\r\n                    }\r\n\r\n                    var stringValue = this.value as string;\r\n                    if (parseType == typeof(DateTime))\r\n                    {\r\n                        DateTime result;\r\n\r\n                        if (DateTime.TryParse(stringValue, CultureInfo.InvariantCulture, this.globalizationConfiguration.DateTimeStyles, out result))\r\n                        {\r\n                            return (T)((object)result);\r\n                        }\r\n\r\n                        return defaultValue;\r\n                    }\r\n\r\n                    if (stringValue != null)\r\n                    {\r\n                        var converter = TypeDescriptor.GetConverter(parseType);\r\n\r\n                        if (converter.CanConvertFrom(typeof(string)))\r\n                        {\r\n                            return (T) converter.ConvertFromInvariantString(stringValue);\r\n                        }\r\n\r\n                        return defaultValue;\r\n                    }\r\n\r\n                    var underlyingType = Nullable.GetUnderlyingType(parseType) ?? parseType;\r\n\r\n                    return (T)Convert.ChangeType(this.value, underlyingType, CultureInfo.InvariantCulture);\r\n                }\r\n                catch\r\n                {\r\n                    return defaultValue;\r\n                }\r\n            }\r\n\r\n            return defaultValue;\r\n        }\r\n\r\n        /// <summary>\r\n        /// == operator for <see cref=\"DynamicDictionaryValue\"/>\r\n        /// </summary>\r\n        /// <param name=\"dynamicValue\"><see cref=\"DynamicDictionaryValue\"/></param>\r\n        /// <param name=\"compareValue\"><see cref=\"object\"/> value to compare to</param>\r\n        /// <returns><see langword=\"true\"/> if equal,<see langword=\"false\"/> otherwise</returns>\r\n        public static bool operator ==(DynamicDictionaryValue dynamicValue, object compareValue)\r\n        {\r\n            if (ReferenceEquals(null, dynamicValue))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            if (dynamicValue.value == null && compareValue == null)\r\n            {\r\n                return true;\r\n            }\r\n\r\n            return dynamicValue.value != null && dynamicValue.value.Equals(compareValue);\r\n        }\r\n\r\n        /// <summary>\r\n        /// != operator for <see cref=\"DynamicDictionaryValue\"/>\r\n        /// </summary>\r\n        /// <param name=\"dynamicValue\"><see cref=\"DynamicDictionaryValue\"/></param>\r\n        /// <param name=\"compareValue\"><see cref=\"object\"/> value to compare to</param>\r\n        /// <returns><see langword=\"true\"/> if not equal,<see langword=\"false\"/> otherwise</returns>\r\n        public static bool operator !=(DynamicDictionaryValue dynamicValue, object compareValue)\r\n        {\r\n            return !(dynamicValue == compareValue);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Indicates whether the current object is equal to another object of the same type.\r\n        /// </summary>\r\n        /// <returns><see langword=\"true\"/> if the current object is equal to the <paramref name=\"compareValue\"/> parameter; otherwise, <see langword=\"false\"/>.\r\n        /// </returns>\r\n        /// <param name=\"compareValue\">An <see cref=\"DynamicDictionaryValue\"/> to compare with this instance.</param>\r\n        public bool Equals(DynamicDictionaryValue compareValue)\r\n        {\r\n            if (ReferenceEquals(null, compareValue))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            return ReferenceEquals(this, compareValue) || Equals(compareValue.value, this.value);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determines whether the specified <see cref=\"object\"/> is equal to the current <see cref=\"object\"/>.\r\n        /// </summary>\r\n        /// <returns><see langword=\"true\"/> if the specified <see cref=\"object\"/> is equal to the current <see cref=\"DynamicDictionaryValue\"/>; otherwise, <see langword=\"false\"/>.</returns>\r\n        /// <param name=\"compareValue\">The <see cref=\"object\"/> to compare with the current <see cref=\"DynamicDictionaryValue\"/>.</param>\r\n        public override bool Equals(object compareValue)\r\n        {\r\n            if (ReferenceEquals(null, compareValue))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            if (ReferenceEquals(this, compareValue))\r\n            {\r\n                return true;\r\n            }\r\n\r\n            return compareValue.GetType() == typeof(DynamicDictionaryValue) && this.Equals((DynamicDictionaryValue)compareValue);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Serves as a hash function for a particular type.\r\n        /// </summary>\r\n        /// <returns>A hash code for the current instance.</returns>\r\n        public override int GetHashCode()\r\n        {\r\n            return (this.value != null ? this.value.GetHashCode() : 0);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Provides implementation for binary operations. Classes derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class can override this method to specify dynamic behavior for operations such as addition and multiplication.\r\n        /// </summary>\r\n        /// <returns><see langword=\"true\"/>  if the operation is successful; otherwise, <see langword=\"false\"/>. If this method returns <see langword=\"false\"/>, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.)</returns>\r\n        /// <param name=\"binder\">Provides information about the binary operation. The binder.Operation property returns an <see cref=\"T:System.Linq.Expressions.ExpressionType\"/> object. For example, for the sum = first + second statement, where first and second are derived from the DynamicObject class, binder.Operation returns ExpressionType.Add.</param><param name=\"arg\">The right operand for the binary operation. For example, for the sum = first + second statement, where first and second are derived from the DynamicObject class, <paramref name=\"arg\"/> is equal to second.</param><param name=\"result\">The result of the binary operation.</param>\r\n        public override bool TryBinaryOperation(BinaryOperationBinder binder, object arg, out object result)\r\n        {\r\n            object resultOfCast;\r\n            result = null;\r\n\r\n            if (binder.Operation != ExpressionType.Equal)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            var convert =\r\n                Binder.Convert(CSharpBinderFlags.None, arg.GetType(), typeof(DynamicDictionaryValue));\r\n\r\n            if (!this.TryConvert((ConvertBinder)convert, out resultOfCast))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            result = (resultOfCast == null) ?\r\n                Equals(arg, resultOfCast) :\r\n                resultOfCast.Equals(arg);\r\n\r\n            return true;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Provides implementation for type conversion operations. Classes derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class can override this method to specify dynamic behavior for operations that convert an object from one type to another.\r\n        /// </summary>\r\n        /// <returns><see langword=\"true\"/>  if the operation is successful; otherwise, <see langword=\"false\"/>. If this method returns <see langword=\"false\"/>, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.)</returns>\r\n        /// <param name=\"binder\">Provides information about the conversion operation. The binder.Type property provides the type to which the object must be converted. For example, for the statement (String)sampleObject in C# (CType(sampleObject, Type) in Visual Basic), where sampleObject is an instance of the class derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class, binder.Type returns the <see cref=\"T:System.String\"/> type. The binder.Explicit property provides information about the kind of conversion that occurs. It returns true for explicit conversion and false for implicit conversion.</param><param name=\"result\">The result of the type conversion operation.</param>\r\n        public override bool TryConvert(ConvertBinder binder, out object result)\r\n        {\r\n            result = null;\r\n\r\n            if (this.value == null)\r\n            {\r\n                return true;\r\n            }\r\n\r\n            var binderType = binder.Type;\r\n            if (binderType == typeof(string))\r\n            {\r\n                result = Convert.ToString(this.value);\r\n                return true;\r\n            }\r\n\r\n            if (binderType == typeof(Guid) || binderType == typeof(Guid?))\r\n            {\r\n                Guid guid;\r\n                if (Guid.TryParse(Convert.ToString(this.value), out guid))\r\n                {\r\n                    result = guid;\r\n                    return true;\r\n                }\r\n            }\r\n            else if (binderType == typeof(TimeSpan) || binderType == typeof(TimeSpan?))\r\n            {\r\n                TimeSpan timespan;\r\n                if (TimeSpan.TryParse(Convert.ToString(this.value), out timespan))\r\n                {\r\n                    result = timespan;\r\n                    return true;\r\n                }\r\n            }\r\n            else if (binderType.GetTypeInfo().IsEnum)\r\n            {\r\n                // handles enum to enum assignments\r\n                if (this.value.GetType().GetTypeInfo().IsEnum)\r\n                {\r\n                    if (binderType == this.value.GetType())\r\n                    {\r\n                        result = this.value;\r\n                        return true;\r\n                    }\r\n\r\n                    return false;\r\n                }\r\n\r\n                // handles number to enum assignments\r\n                if (Enum.GetUnderlyingType(binderType) == this.value.GetType())\r\n                {\r\n                    result = Enum.ToObject(binderType, this.value);\r\n                    return true;\r\n                }\r\n\r\n                return false;\r\n            }\r\n            else\r\n            {\r\n                if (binderType.GetTypeInfo().IsGenericType && binderType.GetGenericTypeDefinition() == typeof(Nullable<>))\r\n                {\r\n                    binderType = binderType.GetGenericArguments()[0];\r\n                }\r\n\r\n                var typeCode = binderType.GetTypeCode();\r\n\r\n                if (typeCode == TypeCode.Object)\r\n                {\r\n                    if (binderType.IsAssignableFrom(this.value.GetType()))\r\n                    {\r\n                        result = this.value;\r\n                        return true;\r\n                    }\r\n                    else\r\n                    {\r\n                        return false;\r\n                    }\r\n                }\r\n\r\n#if !NETSTANDARD1_6\r\n                result = Convert.ChangeType(this.value, typeCode);\r\n#else\r\n                result = Convert.ChangeType(this.value, binderType);\r\n#endif\r\n\r\n                return true;\r\n            }\r\n            return base.TryConvert(binder, out result);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns a <see cref=\"System.String\" /> that represents a <see cref=\"DynamicDictionaryValue\"/> instance.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// A <see cref=\"System.String\" /> that represents this instance.\r\n        /// </returns>\r\n        public override string ToString()\r\n        {\r\n            return this.value == null ? base.ToString() : Convert.ToString(this.value);\r\n        }\r\n\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"DynamicDictionaryValue\"/> to <see cref=\"Nullable{T}\"/>.\r\n        /// </summary>\r\n        /// <param name=\"dynamicValue\">The <see cref=\"DynamicDictionaryValue\"/> instance</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator bool?(DynamicDictionaryValue dynamicValue)\r\n        {\r\n            if (!dynamicValue.HasValue)\r\n            {\r\n                return default(bool?);\r\n            }\r\n\r\n            return (bool)dynamicValue;\r\n        }\r\n\r\n\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"DynamicDictionaryValue\"/> to <see cref=\"System.Boolean\"/>.\r\n        /// </summary>\r\n        /// <param name=\"dynamicValue\">The <see cref=\"DynamicDictionaryValue\"/> instance</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator bool(DynamicDictionaryValue dynamicValue)\r\n        {\r\n            if (!dynamicValue.HasValue)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            if (dynamicValue.value.GetType().GetTypeInfo().IsValueType)\r\n            {\r\n                return (Convert.ToBoolean(dynamicValue.value));\r\n            }\r\n\r\n            bool result;\r\n            if (bool.TryParse(dynamicValue.ToString(), out result))\r\n            {\r\n                return result;\r\n            }\r\n\r\n            return true;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"DynamicDictionaryValue\"/> to <see cref=\"System.String\"/>.\r\n        /// </summary>\r\n        /// <param name=\"dynamicValue\">The <see cref=\"DynamicDictionaryValue\"/> instance</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator string(DynamicDictionaryValue dynamicValue)\r\n        {\r\n            return dynamicValue.HasValue\r\n                       ? Convert.ToString(dynamicValue.value)\r\n                       : null;\r\n        }\r\n\r\n\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"DynamicDictionaryValue\"/> to <see cref=\"Nullable{T}\"/>.\r\n        /// </summary>\r\n        /// <param name=\"dynamicValue\">The <see cref=\"DynamicDictionaryValue\"/> instance</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator int?(DynamicDictionaryValue dynamicValue)\r\n        {\r\n            if (!dynamicValue.HasValue)\r\n            {\r\n                return default(int?);\r\n            }\r\n\r\n            return (int)dynamicValue;\r\n        }\r\n\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"DynamicDictionaryValue\"/> to <see cref=\"System.Int32\"/>.\r\n        /// </summary>\r\n        /// <param name=\"dynamicValue\">The <see cref=\"DynamicDictionaryValue\"/> instance</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator int(DynamicDictionaryValue dynamicValue)\r\n        {\r\n            if (!dynamicValue.HasValue)\r\n            {\r\n                return default(int);\r\n            }\r\n\r\n            if (dynamicValue.value.GetType().GetTypeInfo().IsValueType)\r\n            {\r\n                return Convert.ToInt32(dynamicValue.value);\r\n            }\r\n\r\n            return int.Parse(dynamicValue.ToString());\r\n        }\r\n\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"DynamicDictionaryValue\"/> to <see cref=\"System.Nullable{Guid}\"/>.\r\n        /// </summary>\r\n        /// <param name=\"dynamicValue\">The <see cref=\"DynamicDictionaryValue\"/> instance</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator Guid?(DynamicDictionaryValue dynamicValue)\r\n        {\r\n            if (!dynamicValue.HasValue)\r\n            {\r\n                return default(Guid?);\r\n            }\r\n\r\n            return (Guid)dynamicValue;\r\n        }\r\n\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"DynamicDictionaryValue\"/> to <see cref=\"Guid\"/>.\r\n        /// </summary>\r\n        /// <param name=\"dynamicValue\">The <see cref=\"DynamicDictionaryValue\"/> instance</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator Guid(DynamicDictionaryValue dynamicValue)\r\n        {\r\n            if (!dynamicValue.HasValue)\r\n            {\r\n                return default(Guid);\r\n            }\r\n\r\n            if (dynamicValue.value is Guid)\r\n            {\r\n                return (Guid)dynamicValue.value;\r\n            }\r\n\r\n            return Guid.Parse(dynamicValue.ToString());\r\n        }\r\n\r\n\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"DynamicDictionaryValue\"/> to <see cref=\"System.Nullable{DateTime}\"/>.\r\n        /// </summary>\r\n        /// <param name=\"dynamicValue\">The <see cref=\"DynamicDictionaryValue\"/> instance</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator DateTime?(DynamicDictionaryValue dynamicValue)\r\n        {\r\n            if (!dynamicValue.HasValue)\r\n            {\r\n                return default(DateTime?);\r\n            }\r\n\r\n            return (DateTime)dynamicValue;\r\n        }\r\n\r\n\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"DynamicDictionaryValue\"/> to <see cref=\"DateTime\"/>.\r\n        /// </summary>\r\n        /// <param name=\"dynamicValue\">The <see cref=\"DynamicDictionaryValue\"/> instance</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator DateTime(DynamicDictionaryValue dynamicValue)\r\n        {\r\n            if (!dynamicValue.HasValue)\r\n            {\r\n                return default(DateTime);\r\n            }\r\n\r\n            if (dynamicValue.value is DateTime)\r\n            {\r\n                return (DateTime)dynamicValue.value;\r\n            }\r\n\r\n            return DateTime.Parse(dynamicValue.ToString(), CultureInfo.InvariantCulture, dynamicValue.globalizationConfiguration.DateTimeStyles);\r\n        }\r\n\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"DynamicDictionaryValue\"/> to <see cref=\"System.Nullable{TimeSpan}\"/>.\r\n        /// </summary>\r\n        /// <param name=\"dynamicValue\">The <see cref=\"DynamicDictionaryValue\"/> instance</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator TimeSpan?(DynamicDictionaryValue dynamicValue)\r\n        {\r\n            if (!dynamicValue.HasValue)\r\n            {\r\n                return default(TimeSpan?);\r\n            }\r\n\r\n            return (TimeSpan)dynamicValue;\r\n        }\r\n\r\n\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"DynamicDictionaryValue\"/> to <see cref=\"TimeSpan\"/>.\r\n        /// </summary>\r\n        /// <param name=\"dynamicValue\">The <see cref=\"DynamicDictionaryValue\"/> instance</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator TimeSpan(DynamicDictionaryValue dynamicValue)\r\n        {\r\n            if (!dynamicValue.HasValue)\r\n            {\r\n                return default(TimeSpan);\r\n            }\r\n\r\n            if (dynamicValue.value is TimeSpan)\r\n            {\r\n                return (TimeSpan)dynamicValue.value;\r\n            }\r\n\r\n            return TimeSpan.Parse(dynamicValue.ToString());\r\n        }\r\n\r\n\r\n        /// <summary>\r\n        /// Implicit type conversion operator from <see cref=\"DynamicDictionaryValue\"/> to long?\r\n        /// </summary>\r\n        /// <param name=\"dynamicValue\"><see cref=\"DynamicDictionaryValue\"/></param>\r\n        public static implicit operator long?(DynamicDictionaryValue dynamicValue)\r\n        {\r\n            if (!dynamicValue.HasValue)\r\n            {\r\n                return default(long?);\r\n            }\r\n\r\n            return (long)dynamicValue;\r\n        }\r\n\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"DynamicDictionaryValue\"/> to <see cref=\"System.Int64\"/>.\r\n        /// </summary>\r\n        /// <param name=\"dynamicValue\">The <see cref=\"DynamicDictionaryValue\"/> instance</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator long(DynamicDictionaryValue dynamicValue)\r\n        {\r\n            if (!dynamicValue.HasValue)\r\n            {\r\n                return default(long);\r\n            }\r\n\r\n            if (dynamicValue.value.GetType().GetTypeInfo().IsValueType)\r\n            {\r\n                return Convert.ToInt64(dynamicValue.value);\r\n            }\r\n\r\n            return long.Parse(dynamicValue.ToString());\r\n        }\r\n\r\n\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"DynamicDictionaryValue\"/> to <see cref=\"Nullable{T}\"/>.\r\n        /// </summary>\r\n        /// <param name=\"dynamicValue\">The <see cref=\"DynamicDictionaryValue\"/> instance</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator float?(DynamicDictionaryValue dynamicValue)\r\n        {\r\n            if (!dynamicValue.HasValue)\r\n            {\r\n                return default(float?);\r\n            }\r\n\r\n            return (float)dynamicValue;\r\n        }\r\n\r\n\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"DynamicDictionaryValue\"/> to <see cref=\"System.Single\"/>.\r\n        /// </summary>\r\n        /// <param name=\"dynamicValue\">The <see cref=\"DynamicDictionaryValue\"/> instance</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator float(DynamicDictionaryValue dynamicValue)\r\n        {\r\n            if (!dynamicValue.HasValue)\r\n            {\r\n                return default(float);\r\n            }\r\n\r\n            if (dynamicValue.value.GetType().GetTypeInfo().IsValueType)\r\n            {\r\n                return Convert.ToSingle(dynamicValue.value);\r\n            }\r\n\r\n            return float.Parse(dynamicValue.ToString());\r\n        }\r\n\r\n\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"DynamicDictionaryValue\"/> to <see cref=\"Nullable{T}\"/>.\r\n        /// </summary>\r\n        /// <param name=\"dynamicValue\">The <see cref=\"DynamicDictionaryValue\"/> instance</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator decimal?(DynamicDictionaryValue dynamicValue)\r\n        {\r\n            if (!dynamicValue.HasValue)\r\n            {\r\n                return default(decimal?);\r\n            }\r\n\r\n            return (decimal)dynamicValue;\r\n        }\r\n\r\n\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"DynamicDictionaryValue\"/> to <see cref=\"System.Decimal\"/>.\r\n        /// </summary>\r\n        /// <param name=\"dynamicValue\">The <see cref=\"DynamicDictionaryValue\"/> instance</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator decimal(DynamicDictionaryValue dynamicValue)\r\n        {\r\n            if (!dynamicValue.HasValue)\r\n            {\r\n                return default(decimal);\r\n            }\r\n\r\n            if (dynamicValue.value.GetType().GetTypeInfo().IsValueType)\r\n            {\r\n                return Convert.ToDecimal(dynamicValue.value);\r\n            }\r\n\r\n            return decimal.Parse(dynamicValue.ToString());\r\n        }\r\n\r\n\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"DynamicDictionaryValue\"/> to <see cref=\"Nullable{T}\"/>.\r\n        /// </summary>\r\n        /// <param name=\"dynamicValue\">The <see cref=\"DynamicDictionaryValue\"/> instance</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator double?(DynamicDictionaryValue dynamicValue)\r\n        {\r\n            if (!dynamicValue.HasValue)\r\n            {\r\n                return default(double?);\r\n            }\r\n\r\n            return (double)dynamicValue;\r\n        }\r\n\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"DynamicDictionaryValue\"/> to <see cref=\"System.Double\"/>.\r\n        /// </summary>\r\n        /// <param name=\"dynamicValue\">The <see cref=\"DynamicDictionaryValue\"/> instance</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator double(DynamicDictionaryValue dynamicValue)\r\n        {\r\n            if (!dynamicValue.HasValue)\r\n            {\r\n                return default(double);\r\n            }\r\n\r\n            if (dynamicValue.value.GetType().GetTypeInfo().IsValueType)\r\n            {\r\n                return Convert.ToDouble(dynamicValue.value);\r\n            }\r\n\r\n            return double.Parse(dynamicValue.ToString());\r\n        }\r\n\r\n#region Implementation of IConvertible\r\n\r\n        /// <summary>\r\n        /// Returns the <see cref=\"T:System.TypeCode\"/> for this instance.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// The enumerated constant that is the <see cref=\"T:System.TypeCode\"/> of the class or value type that implements this interface.\r\n        /// </returns>\r\n        /// <filterpriority>2</filterpriority>\r\n        public TypeCode GetTypeCode()\r\n        {\r\n            if (this.value == null)\r\n            {\r\n                return TypeCode.Empty;\r\n            }\r\n\r\n            return this.value.GetType().GetTypeCode();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Converts the value of this instance to an equivalent Boolean value using the specified culture-specific formatting information.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// A Boolean value equivalent to the value of this instance.\r\n        /// </returns>\r\n        /// <param name=\"provider\">An <see cref=\"T:System.IFormatProvider\"/> interface implementation that supplies culture-specific formatting information. </param><filterpriority>2</filterpriority>\r\n        public bool ToBoolean(IFormatProvider provider)\r\n        {\r\n            return Convert.ToBoolean(this.value, provider);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Converts the value of this instance to an equivalent Unicode character using the specified culture-specific formatting information.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// A Unicode character equivalent to the value of this instance.\r\n        /// </returns>\r\n        /// <param name=\"provider\">An <see cref=\"T:System.IFormatProvider\"/> interface implementation that supplies culture-specific formatting information. </param><filterpriority>2</filterpriority>\r\n        public char ToChar(IFormatProvider provider)\r\n        {\r\n            return Convert.ToChar(this.value, provider);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Converts the value of this instance to an equivalent 8-bit signed integer using the specified culture-specific formatting information.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// An 8-bit signed integer equivalent to the value of this instance.\r\n        /// </returns>\r\n        /// <param name=\"provider\">An <see cref=\"T:System.IFormatProvider\"/> interface implementation that supplies culture-specific formatting information. </param><filterpriority>2</filterpriority>\r\n        public sbyte ToSByte(IFormatProvider provider)\r\n        {\r\n            return Convert.ToSByte(this.value, provider);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Converts the value of this instance to an equivalent 8-bit unsigned integer using the specified culture-specific formatting information.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// An 8-bit unsigned integer equivalent to the value of this instance.\r\n        /// </returns>\r\n        /// <param name=\"provider\">An <see cref=\"T:System.IFormatProvider\"/> interface implementation that supplies culture-specific formatting information. </param><filterpriority>2</filterpriority>\r\n        public byte ToByte(IFormatProvider provider)\r\n        {\r\n            return Convert.ToByte(this.value, provider);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Converts the value of this instance to an equivalent 16-bit signed integer using the specified culture-specific formatting information.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// An 16-bit signed integer equivalent to the value of this instance.\r\n        /// </returns>\r\n        /// <param name=\"provider\">An <see cref=\"T:System.IFormatProvider\"/> interface implementation that supplies culture-specific formatting information. </param><filterpriority>2</filterpriority>\r\n        public short ToInt16(IFormatProvider provider)\r\n        {\r\n            return Convert.ToInt16(this.value, provider);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Converts the value of this instance to an equivalent 16-bit unsigned integer using the specified culture-specific formatting information.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// An 16-bit unsigned integer equivalent to the value of this instance.\r\n        /// </returns>\r\n        /// <param name=\"provider\">An <see cref=\"T:System.IFormatProvider\"/> interface implementation that supplies culture-specific formatting information. </param><filterpriority>2</filterpriority>\r\n        public ushort ToUInt16(IFormatProvider provider)\r\n        {\r\n            return Convert.ToUInt16(this.value, provider);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Converts the value of this instance to an equivalent 32-bit signed integer using the specified culture-specific formatting information.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// An 32-bit signed integer equivalent to the value of this instance.\r\n        /// </returns>\r\n        /// <param name=\"provider\">An <see cref=\"T:System.IFormatProvider\"/> interface implementation that supplies culture-specific formatting information. </param><filterpriority>2</filterpriority>\r\n        public int ToInt32(IFormatProvider provider)\r\n        {\r\n            return Convert.ToInt32(this.value, provider);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Converts the value of this instance to an equivalent 32-bit unsigned integer using the specified culture-specific formatting information.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// An 32-bit unsigned integer equivalent to the value of this instance.\r\n        /// </returns>\r\n        /// <param name=\"provider\">An <see cref=\"T:System.IFormatProvider\"/> interface implementation that supplies culture-specific formatting information. </param><filterpriority>2</filterpriority>\r\n        public uint ToUInt32(IFormatProvider provider)\r\n        {\r\n            return Convert.ToUInt32(this.value, provider);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Converts the value of this instance to an equivalent 64-bit signed integer using the specified culture-specific formatting information.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// An 64-bit signed integer equivalent to the value of this instance.\r\n        /// </returns>\r\n        /// <param name=\"provider\">An <see cref=\"T:System.IFormatProvider\"/> interface implementation that supplies culture-specific formatting information. </param><filterpriority>2</filterpriority>\r\n        public long ToInt64(IFormatProvider provider)\r\n        {\r\n            return Convert.ToInt64(this.value, provider);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Converts the value of this instance to an equivalent 64-bit unsigned integer using the specified culture-specific formatting information.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// An 64-bit unsigned integer equivalent to the value of this instance.\r\n        /// </returns>\r\n        /// <param name=\"provider\">An <see cref=\"T:System.IFormatProvider\"/> interface implementation that supplies culture-specific formatting information. </param><filterpriority>2</filterpriority>\r\n        public ulong ToUInt64(IFormatProvider provider)\r\n        {\r\n            return Convert.ToUInt64(this.value, provider);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Converts the value of this instance to an equivalent single-precision floating-point number using the specified culture-specific formatting information.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// A single-precision floating-point number equivalent to the value of this instance.\r\n        /// </returns>\r\n        /// <param name=\"provider\">An <see cref=\"T:System.IFormatProvider\"/> interface implementation that supplies culture-specific formatting information. </param><filterpriority>2</filterpriority>\r\n        public float ToSingle(IFormatProvider provider)\r\n        {\r\n            return Convert.ToSingle(this.value, provider);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Converts the value of this instance to an equivalent double-precision floating-point number using the specified culture-specific formatting information.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// A double-precision floating-point number equivalent to the value of this instance.\r\n        /// </returns>\r\n        /// <param name=\"provider\">An <see cref=\"T:System.IFormatProvider\"/> interface implementation that supplies culture-specific formatting information. </param><filterpriority>2</filterpriority>\r\n        public double ToDouble(IFormatProvider provider)\r\n        {\r\n            return Convert.ToDouble(this.value, provider);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Converts the value of this instance to an equivalent <see cref=\"T:System.Decimal\"/> number using the specified culture-specific formatting information.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// A <see cref=\"T:System.Decimal\"/> number equivalent to the value of this instance.\r\n        /// </returns>\r\n        /// <param name=\"provider\">An <see cref=\"T:System.IFormatProvider\"/> interface implementation that supplies culture-specific formatting information. </param><filterpriority>2</filterpriority>\r\n        public decimal ToDecimal(IFormatProvider provider)\r\n        {\r\n            return Convert.ToDecimal(this.value, provider);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Converts the value of this instance to an equivalent <see cref=\"T:System.DateTime\"/> using the specified culture-specific formatting information.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// A <see cref=\"T:System.DateTime\"/> instance equivalent to the value of this instance.\r\n        /// </returns>\r\n        /// <param name=\"provider\">An <see cref=\"T:System.IFormatProvider\"/> interface implementation that supplies culture-specific formatting information. </param><filterpriority>2</filterpriority>\r\n        public DateTime ToDateTime(IFormatProvider provider)\r\n        {\r\n            return Convert.ToDateTime(this.value, provider);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Converts the value of this instance to an equivalent <see cref=\"T:System.String\"/> using the specified culture-specific formatting information.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// A <see cref=\"T:System.String\"/> instance equivalent to the value of this instance.\r\n        /// </returns>\r\n        /// <param name=\"provider\">An <see cref=\"T:System.IFormatProvider\"/> interface implementation that supplies culture-specific formatting information. </param><filterpriority>2</filterpriority>\r\n        public string ToString(IFormatProvider provider)\r\n        {\r\n            return Convert.ToString(this.value, provider);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Converts the value of this instance to an <see cref=\"T:System.Object\"/> of the specified <see cref=\"T:System.Type\"/> that has an equivalent value, using the specified culture-specific formatting information.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// An <see cref=\"T:System.Object\"/> instance of type <paramref name=\"conversionType\"/> whose value is equivalent to the value of this instance.\r\n        /// </returns>\r\n        /// <param name=\"conversionType\">The <see cref=\"T:System.Type\"/> to which the value of this instance is converted. </param><param name=\"provider\">An <see cref=\"T:System.IFormatProvider\"/> interface implementation that supplies culture-specific formatting information. </param><filterpriority>2</filterpriority>\r\n        public object ToType(Type conversionType, IFormatProvider provider)\r\n        {\r\n            return Convert.ChangeType(this.value, conversionType, provider);\r\n        }\r\n\r\n#endregion\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ErrorHandling/DefaultStatusCodeHandler.cs",
    "content": "namespace Nancy.ErrorHandling\r\n{\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using System.Text;\r\n    using Nancy.Configuration;\r\n    using Nancy.Extensions;\r\n    using Nancy.IO;\r\n    using Nancy.Responses.Negotiation;\r\n    using Nancy.ViewEngines;\r\n\r\n    /// <summary>\r\n    /// Default error handler\r\n    /// </summary>\r\n    public class DefaultStatusCodeHandler : IStatusCodeHandler\r\n    {\r\n        private const string DisplayErrorTracesFalseMessage = \"Error details are currently disabled.<br />To enable it, please set <strong>TraceConfiguration.DisplayErrorTraces</strong> to <strong>true</strong>.<br />For example by overriding your Bootstrapper's <strong>Configure</strong> method and calling<br/> <strong>environment.Tracing(enabled: false, displayErrorTraces: true);</strong>.\";\r\n\r\n        private readonly IDictionary<HttpStatusCode, string> errorMessages;\r\n        private readonly IDictionary<HttpStatusCode, string> errorPages;\r\n        private readonly IResponseNegotiator responseNegotiator;\r\n        private readonly HttpStatusCode[] supportedStatusCodes = { HttpStatusCode.NotFound, HttpStatusCode.InternalServerError };\r\n        private readonly TraceConfiguration configuration;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultStatusCodeHandler\"/> type.\r\n        /// </summary>\r\n        /// <param name=\"responseNegotiator\">The response negotiator.</param>\r\n        /// <param name=\"environment\">An <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        public DefaultStatusCodeHandler(IResponseNegotiator responseNegotiator, INancyEnvironment environment)\r\n        {\r\n            this.errorMessages = new Dictionary<HttpStatusCode, string>\r\n            {\r\n                { HttpStatusCode.NotFound, \"The resource you have requested cannot be found.\" },\r\n                { HttpStatusCode.InternalServerError, \"Something went horribly, horribly wrong while servicing your request.\" }\r\n            };\r\n\r\n            this.errorPages = new Dictionary<HttpStatusCode, string>\r\n            {\r\n                { HttpStatusCode.NotFound, LoadResource(\"404.html\") },\r\n                { HttpStatusCode.InternalServerError, LoadResource(\"500.html\") }\r\n            };\r\n\r\n            this.responseNegotiator = responseNegotiator;\r\n            this.configuration = environment.GetValue<TraceConfiguration>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Whether the status code is handled\r\n        /// </summary>\r\n        /// <param name=\"statusCode\">Status code</param>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> instance of the current request.</param>\r\n        /// <returns>True if handled, false otherwise</returns>\r\n        public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context)\r\n        {\r\n            return this.supportedStatusCodes.Any(s => s == statusCode);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Handle the error code\r\n        /// </summary>\r\n        /// <param name=\"statusCode\">Status code</param>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> instance of the current request.</param>\r\n        /// <returns>Nancy Response</returns>\r\n        public void Handle(HttpStatusCode statusCode, NancyContext context)\r\n        {\r\n            if (context.Response != null && context.Response.Contents != null && !ReferenceEquals(context.Response.Contents, Response.NoBody))\r\n            {\r\n                return;\r\n            }\r\n\r\n            if (!this.errorMessages.ContainsKey(statusCode) || !this.errorPages.ContainsKey(statusCode))\r\n            {\r\n                return;\r\n            }\r\n\r\n            Response existingResponse = null;\r\n\r\n            if (context.Response != null)\r\n            {\r\n                existingResponse = context.Response;\r\n            }\r\n\r\n            // Reset negotiation context to avoid any downstream cast exceptions\r\n            // from swapping a view model with a `DefaultStatusCodeHandlerResult`\r\n            context.NegotiationContext = new NegotiationContext();\r\n\r\n            var details = !this.configuration.DisplayErrorTraces\r\n                ? DisplayErrorTracesFalseMessage\r\n                : string.Concat(\"<pre>\", context.GetExceptionDetails().Replace(\"<\", \"&gt;\").Replace(\">\", \"&lt;\"), \"</pre>\");\r\n\r\n            var result = new DefaultStatusCodeHandlerResult\r\n            {\r\n                Details = details,\r\n                Message = this.errorMessages[statusCode],\r\n                StatusCode = statusCode\r\n            };\r\n            \r\n            try\r\n            {\r\n                context.Response = this.responseNegotiator.NegotiateResponse(result, context);\r\n                context.Response.StatusCode = statusCode;\r\n\r\n                if (existingResponse != null)\r\n                {\r\n                    context.Response.ReasonPhrase = existingResponse.ReasonPhrase;\r\n                }\r\n                return;\r\n            }\r\n            catch (ViewNotFoundException)\r\n            {\r\n                // No view will be found for `DefaultStatusCodeHandlerResult`\r\n                // because it is rendered from embedded resources below\r\n            }\r\n\r\n            this.ModifyResponse(statusCode, context, result);\r\n        }\r\n\r\n        private void ModifyResponse(HttpStatusCode statusCode, NancyContext context, DefaultStatusCodeHandlerResult result)\r\n        {\r\n            if (context.Response == null)\r\n            {\r\n                context.Response = new Response { StatusCode = statusCode };\r\n            }\r\n\r\n            var contents = this.errorPages[statusCode];\r\n\r\n            if (!string.IsNullOrEmpty(contents))\r\n            {\r\n                contents = contents.Replace(\"[DETAILS]\", result.Details);\r\n            }\r\n\r\n            context.Response.ContentType = \"text/html\";\r\n            context.Response.Contents = s =>\r\n            {\r\n                using (var writer = new StreamWriter(new UnclosableStreamWrapper(s), Encoding.UTF8))\r\n                {\r\n                    writer.Write(contents);\r\n                }\r\n            };\r\n        }\r\n\r\n        private static string LoadResource(string filename)\r\n        {\r\n            var resourceStream = typeof(INancyEngine).GetTypeInfo().Assembly.GetManifestResourceStream(string.Format(\"Nancy.ErrorHandling.Resources.{0}\", filename));\r\n\r\n\r\n            if (resourceStream == null)\r\n            {\r\n                return string.Empty;\r\n            }\r\n\r\n            using (var reader = new StreamReader(resourceStream))\r\n            {\r\n                return reader.ReadToEnd();\r\n            }\r\n        }\r\n\r\n        public class DefaultStatusCodeHandlerResult\r\n        {\r\n            public HttpStatusCode StatusCode { get; set; }\r\n\r\n            public string Message { get; set; }\r\n\r\n            public string Details { get; set; }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/ErrorHandling/Resources/404.html",
    "content": "<!DOCTYPE html>\r\n<html>\r\n<head>\r\n    <title>Nancy - 404 Not Found</title>\r\n    <style>\r\n        html {\r\n            height: 100%;\r\n        }\r\n\r\n        body {\r\n            background: linear-gradient(-180deg, #000000, #434343) #000 fixed;\r\n            color: #333;\r\n            display: table;\r\n            font-family: sans-serif;\r\n            height: 100%;\r\n            margin: 0;\r\n            width: 100%;\r\n        }\r\n\r\n        img {\r\n            float: left;\r\n            margin-right: 40px;\r\n        }\r\n\r\n        h1 {\r\n            font-family: sans-serif;\r\n            margin-bottom: 5px;\r\n        }\r\n\r\n        h1, h2 {\r\n            color: #333;\r\n        }\r\n\r\n        .container {\r\n            display: table-cell;\r\n            vertical-align: middle;\r\n            padding: 20px;\r\n        }\r\n\r\n        .box {\r\n            background-color: #f6f8f8;\r\n            border-radius: 4px;\r\n            box-shadow: 0 2px 4px 0 rgba(0, 0, 0, .3);\r\n            margin: 0 auto;\r\n            max-width: 960px;\r\n            padding: 25px;\r\n        }\r\n\r\n        .header {\r\n            overflow: hidden;\r\n            vertical-align: middle;\r\n        }\r\n\r\n        .header div {\r\n            float: left;\r\n        }\r\n\r\n        footer {\r\n            color: #f6f8f8;\r\n            font-size: 12px;\r\n            margin-top: 10px;\r\n            text-align: center;\r\n        }\r\n\r\n        footer a,\r\n        footer a:hover,\r\n        footer a:visited {\r\n            color: #6daf00;\r\n        }\r\n    </style>\r\n</head>\r\n<body>\r\n    <div class=\"container\">\r\n        <div class=\"box\">\r\n            <div class=\"header\">\r\n                <img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHcAAACWCAYAAADkIRetAABL10lEQVR4Xu2dBVhU2f//D0iqhITdAnZ3YHas3bW6tqtrd2EGFgKCqKgoZmAXdoDd3bm75rp2wuf//sw5cmdnqGH/X7Z+Ps/rmctlZpi5r/P5nL6Kv9u/oduFFag9eJtYPmirODh0m9macXtSjZ99JFOH+Sfyea46Xy3b3lt9Uz9+c9qCiMzE//37ZzF4q0jdd5No9GOY2Ndng/gwZJtZ1Lg9KV54H7Q97xeZZlXwqRyD116sWv3Sk0UZiMjq/yT/w2iwQNg2WSSqt14qDnReLaIGbhE0JlzQlP1mn30iLF7MO5Hq4tKz2UPCb37f+O5v213ffPzZ/P8E/INwHSwsS0wT5eoEimMtl4jonusFDdkmaPQuQZP2C5oTKWjeiRSfgk44r1l1vnrWpAgYv1f8pVHPWWf7tSFmw3dYWKA6sgG2wOK/INcs+yjhWGG2GFg7ULxssURQLwhGfUzDdwgat1eQ71FBc4+leDb3aIZWv74+Z26KVOAC3IFlcgsFFjuu93X0jXAv5LU7dc2h28T3KLh9IbYHyPGfiN60Q0SKYlNF8Wr+4nitABHVfLGg7usEDdgiBU89yHLFV58I20XzjxdzSKRYG1Ad+IC6wOJ/LzTa7O2nXyyuPAl12Hm9c8H5J3J3m3HIbvmEvZbHhu8wu9l/s3iM73QOBbcf5Lr8Z9JzvgnCvpqfmFjdX7yGZKo7T1CbpYJ6bxA0CinaJwIpOsL8/sxDDlXnHy9lHo/UlKAKWAF+ASP4nH40M4mIegtglRgBL95dNzv6wMt1183WldZeLDNwwckMu2YfsXw19YCgsbsF9dssqMsa8bXTSrQtVgnPtstkQfvPkGO0sKzsKxrWmCtuVvUVVNVPEKKYWoYI+mmjoMmof30jxfvpB63HzDyUPlUcQuzAD+AkeA/WgezATOEMCrDseKSag4wq2nMmRkDYpSauIWfcRy0+7Xwi4Lj1b9MPmUVPQHUyYqcg9AYIDcboZovF5aaLRJ1S3v8xsUy6IcKs9HSRE0K3IIKjqkBwNT9zqjfPkr5fYUWjdlrS7IgU0d4HLXZP3pcqZyxSUoHe4A74Cm6CWsBGRXNlEADaABsl21oJLwnqAA8ldQ0YC5wSErDv1jCLgGOZmwQet3zof9QsCoUQjUFuFMq2A1cx9YPE03pBYkj5WSK1+K/+Kz89r027pTn7/7im+JvJu9pTyDEv2nZpIe2/EUqRd4Lp6L3pdOCW129Xft02/d37d/XfvHlT6OXvL9IvO1k37fi9ZsMh4wUgEAXOg4VgKdgNXqs0vQCMBMPBanAfrActQaB6j40gm4piR+AGUhpEt83k/bZWAUdzZPONsFkdcFx8ZbHDtss0jK4dNQ7WZZ8v380X65CRcv5nxX769Mni3ce3xe88vzL/xpNT71++e0pfo75QdHS0jqioKPr69St9/vIp+vPnj2/w/LsfPnyIhOCQc/fX+QZEFLo9cZ9lNMtNBF/BJxANPoMLIBK8BY9BHyW1LBgHOqjMYAsKg4ag+qR9lulnH3as7RuZ4sacSNk26IMqpN1yQRBKEEp15olX6MsPrOgjC8d/js+fP1t/+fKlCQQeBa+j2Wbc/2Jk4zXRkPzp5eun76883B214WwP8j7gQohiIEyBJUep4w/gHAhT0X8WVABFwUxVCCaDPNMPOjnOPGQzwTfS7MMURG2vMEEtQhCtgVylSBotFLdQ15Z0GyvM/oti0yAiB0LW89idJiwZ70Fv376lp08f07GrKynwcBmauNdKivvzPAYrJuw1vzblQKpLvhE5Qo49mFUSfzfn0fszPeefyHk+4JgTDd5iQ02CzQitfaqiGoQsufkSsbjYNGH9nxP7/v17a4j5AYJu60WryYI5XX/8+JF+//13evjoPh0+v4z8DxQjCPn/Itj7oGP0irN1Xp9+NP/Iqw8PN0ZHR23F3939/tOLiOvPwj6eeuhHK0/3p6GbqlPTBekh1pyjllPzO7SSm7sO/o9F7atXr8wgpARS6xnIjdJ0JU2wFr1P6cbNq7Tj+Gyatjfdn5KKBhMtOe1JFx8vp5fv70R/iUIJIvoEvoIotAaioqI/0+ev7+nNh9/owfMbFHlzO03e3oGaLEgT3STY/BDScrb/XNS+fv3aEXKXIupis2WyYH4fZAJ68eIF3bt3j86cO0EhBzogei2TJNbnSGY6fHcSvfn0OLEfIaaKePnqBR25svn9kkOjZi/ZPeO/1/1BK7cy2kL3jYL2C4Lj2j7J2+cmXVi0nunly5f04MEDunjxIm09FEBT95gevTMOuVDEPW96//lFkqoIfA4Usudf7967c+X8+fMNFy9e/N9Jy48fP7ZGCp0EuR/5giC7Ef16lejZHSS9d0QH5hL5f0cU0pno0QUO5cTIjal3Hz16RJcuXaJ9h7fSnN2lTWo9Tz2QmnZd70fvPj1LchWBqoZQeOnXX3+NunLlyskjR46U3LRp039juvK3337LhcjdA7myHfXzJaKgFvTp5Dp6//Y1/fzoIV0+fpA+bp5ItKA10dNbLDjRch8+fKiTe/DwPgre1R6pOUWixHIDbPnZOvTi3S0TlRp/Fq4inj9/Tjdu3Ph8/PjxFXv37s3yn5CLL10Wde4VyKVornP3+VFUaE86uGMTBQcH09q1a6lFixZ0PHwj0bKuRMeWEX39HJ/bmHSIghOTlg8eOkAhO/vRhD1WiYxaOzrxYC7e67Op8QqjX5BlzhPdiqCoD6+5oOmqiDt37kSfPHnyLuQ23bp16787ehFV5s+ePWsIuY90cnEhaHU/+rBzFg0bOpRy5MhBVatWpTRp0tDsGdPpS/gsok1jiD6+TSgVxkTL3bt36dy5c7R//34K3TGcJu1JlSi5AUfz09PX1/j9Ei/191+JbkcQvf+dvu6aSVGj81L0qp/o07MHnEV0jbtTp059hty5YWFhtv9quUhTKVAntkeEPeFI+/rxHdH6ofRp8wSaCZkuLi5kZmZGTk5OtDR4PkVt8SLa5U30+X28AxlcUFBgCPU5Xb9+nU6cOEG7d++mZdtGQa59ouRuvNiZ3n14mXi53D7YPJaeD8xBpzYtoSPrgymwbjp62iUlfVk7hF4/eajLIqdPn6Y9e/acR72b+V8t9+rVqynwhdshep+8e/cOEfeZok+souj5LelmxHYaPmwo1a9fn8Z5edGDwxuIgpoTXdlNFPU1NrFa1MpuUExKjoiIoB07dtDizYNp4u7ERK4ZHbg5Gen0HSW62/37LxQ1syptrGVGNcoWoX59+1K+7BkprJY5fZ1eiV7fOqOTe+bMGZb7+/r16wv/q+XiwpujHmr4yy+/PMJAhq5u+vr7Y6K1gyhqYTv6/dAy+vn4Dnp9YBFFsdit44mQuuMZX+a6VpcC8Z7cgOE0SPv27aNNmzdS0MYeNH63FY3bE7/ciegPH70dCLkfEi/3xX36MrEEBXkKsrNJQY6OjmRtZUmBnmb0FedfXz+mH7lRkFtL/Nv/Xb58uTQEX8JoUjR3GTilfn31lKIPzSda1IFobgOipT8QnVgOsW+MpaoZIn4dRz83XFjszZs36ezZs3To0CHavn07LV+7mKasr4YVleYsVxGH3H1WFHEzEO/3lt87cXLfvcTn7Eo32lhS0xyC3B0E1csq6FobK/oS/D39/uC6rv5Hg4rCw8NpxYoVHf71ctccHlXs5MV9p+7fvx/NDSApGBHMKfHlzxTNXZ9XiOYvn1imQpPKo0AcrTzcyK1jFnvr1i3CgIEuHe/atYvWhq2hGUtHUb/VmbEiQi538dojMRbN3SALOnBlNjLASy40iYteVBVcZURNLU+32lnRwYbmOtGfJxSnD+e20/OnT3QF7ujRo7oqYlnosi7/arFYm5xyyBbbkaEH+724dOW8Lm2h/uXGEAvjaORUyxJjwM8slFN4jFROw4h87tNyKubWMYvVRUjYxvXkv8yHegRVoc4rLXmRHaJXCgbGopXkLWeH0OMnv5BsC3xJXMOKR9Tun6boDSMoan4rilo3mL7cOEKvf3vBhU7X395/YD+t37SW5i8O+vfK7b9JmGMF4HcDNotHXtty0Y6IUDp/8Rz3BXk0hziKWRpHMgvki8zwMctnodxoevLkCUvlaOWLx2mPU7EuYtdvWEe+S2dRz4DG1HiePXVbKxC5LJeJX/LCI7Xoxp0L/Dm4gcaCOYITJRnPickq/Pn5M/LnwwAGrd+6lvxCZ9OkoBGd/rVy+20SWcFWSI4esNmKZm1rSVsPhNHxM8fo+o3rhDRNP//8M8vjqOSIZviYuzj8O+436qRiWI9boZzyuPHEdSxSMS7i0tnUO6A1NfDLSE0xv9p3o6CRO+UqidEKCNbQEz19XzaKPLeRPwcXIo5glUk0ySDeqoILIX9eLrCcTcL3hZP/Sh8as2AwjV5dgpfZ2vzrxGIFoy0u9BDwCoKJGbTBlWas70nLtgfTvsg9dO78OUJXSVdP3b59myOaYZncd9UJvXDhgq41HBkZSQcOHNCl4c1bNtGKtctp1uJp1NO/OdX3zUB1A82p40peqMZywS4WrDE6HBhIHrfbhpYf7ENnz5+mu/fusiTOFiw5psrQR1UT/HuWqisQqv6XDbvDB2lp2GIaOq8vDQhqRWO2Od5Uy27/PSNV2OhlDmpC8CUQDcEkMaN+a9PT8NDmNG2lF4VuW0LhB3ZSxLEIHoRgiQwf6yIUA/AslLsV3EBBV2cTrVq3kgKW+dPIoJ+orW95quVrT7UDeM2zLEBc345gdjKaaKCJ1pM9cYcbLQ/3piMnDtPVa1c5U7AwFs3y9OH0zee5SuG2AxdKriZ0qXjP3j20YmMojVwwkLrMaUH9lxajseEpPqkFe/+ewYzeYcIFcheDD0C3iOwnRZ8N5vTjKlfqFVyVBi3sTlOXj6NFG+bT+u1raVv4Vtq1eyfYRTt37aRtO7ZxlOrq1dA1yyhwmR+NXzicuvs3pEZzclFNXxvClhRqFSIIfxNRy3I1RiiMJWuM3IE+8YZytGDTTNp5cDudPH2S0HXjRltMNkH3hh/5Zz7PGYVTMBdCROsh2rFrB4WsW0zjFo6kH3xaUJfAijRkgxPX69EQexe0/FdEL9bumv24XnwHwU8BZP4BJdiMuqxMSe2C3Km9fzU0htrR8IUDaHKIF81ZPoMCVvrRvBVzKWC5H80JmUGTg8ci1fWgzn61qfEcN6oxJxVV9zMjrA2mtsvkLgXs+yVs2aBhGppoJdg4muXxEKyHGry8Ik1dMYqWbl5M4fuRTSIjOCI5k3ADjkXyz7rq4fDhw7p6f+fOnbRhcxjNXxlIw4MGUKfZLandnIrUB4V3dHjMkp8vYA1w+MfL7blOpIfgXYB+ZMJkVBmK5nNdVgtqsciKvvN3pfqz3ajxrGLUYrYntfapQm1AK59y1MSnINXzyUI1fOyoqq85L0jDwnVB2CFIXddwKpZiBwNEroJFxyXbOG3z44BNFtQ9JDf9GNSMvBYPo4DVfrR84zLasHU9bdm+mbZu30Jbtm2mjRgFW8eZZG0oBYb604SFY6iXbydqPasmtfQrSN1XpuaMIMVqvAE1/9Fie6wVlpD7A3jOcjVYsrFoPKLrIuvLBvPNqZa/JVXztaZqcyRV5/DPKVioLv02XCBT8A+r5GvRzSLe4zsIQK6GJhkkTjKf+2mDBX0f4kxtA4pSF/9G1D+wG41ZOISmLB5HM5ZMAVPJe/EkCB1NwwL7Uk/fttRudg1qOqcAtQxypa6rrPA+ZnGNii0Cqf6xcruvFbl6rBNbwFcIJh3rgSbZKJoBzssV++1CBTVbzGt/JY2DeXuGlN9phSAUHqRgjlYpdsAWRgmOXzIEK+KSDIYBfu8OoRboMztQA9/MuszRwqc0skkFZBNPZJOy1NynGOp8N6rvl5YaBKaiNiEp8J3ke3jFPeR5HZQD/7wlOEiRlojC3uAZJBPTg4Hg2ET/GLdo9Xz1PBXlaG1DqhIrgWAlWQHJjCZbE51g2oZkBb9Ofu42y7iQyR2ItQPMqE6gGaoEXsIqC2GH5fiM69Tm8XD9QRJgPOT5FkwE9v84uag/M0HwLvC12xopV5MsgTAN47StSd4ADBphTF+JoWglOe5oVpI14qublWA84jwXGv68siroBLqu5s/OEa71qUcbjIbFITkK7AMF/lFisQfVDDSG4FeQSwrqxqyNRXR8ktVjz7V8bNzS1kQnIpoNI5mJv24GUi5vyZx1RND0Q5AVDtlapCP9stQEBkliH/L8FbTD8T+nW4RS7QC5mwAxkBzDH2QbStZEKzTBXVciWpbzOS2qWbBG3KIZY9EGso1EK9k4HgNZcyJ0+4Np/B5ucMXRrYpzgCTOIc8oEAK5/4xNYhjyM8MO8hrgESSTsWBgHM3AOJqVaIgEENx+iaCOoUrwenXeSHT80dwvobp5qwYL7x+GqIUgv6OCJu2TMrXUzXLj7FIZS1boS8bjXTxm/2fIXSHsIHg65H4AxLBkTXTc0dwtjmjm6B0ICV1XCGo6T1CHpfg9nhtP3zlh0caSVSRr/ASxPUMETYWEmYdZWHz9ZhOjWZP8FTT524tFa9Hs+xWiJDgFydGAGBYch2jIjVM0UJLXSQFDEUlNfAUV7wxaCSrXUVDFboKq9hZUs7+gukMFNRiD50wS1NxbUKuZAl0WgTFnRH2AoO+D8LcX4u8sxnsvhbgViPo1kLge4sOUfEXvdXgtj1FPgdj9Mh1DqundqsRFdAiO/947AdsvF5agHyS/+H45LqaSayR5laHkhOtmjsKxu/CI93X3FGRhLbG0kVjZgpSCrFOB1IJs7QWldhbkkEGQc1ZBad0EZcwnKGsRQTlLCfLAe+SvLqhIPUElm6KgtBNUuSsKSV9B9YYLqjVaUIkOgloMEzR9PwsyqRGmiU4gbSvRp4DH31ouBh2c24eK9RD8FYJJQcaigRbJiYlm1LOylE/eK6jK9xBrJUiI/z+YmQtKYYlCggJiYycolRMKRjpBLtkQ6RPxN/dJccatbSX4z0fzI9AYmP995S4TZcETSCamvUITzZKBgWSQYNpGikbLVXZFusyCAEcW878lbRbUyUHcZeFqIYFu1db4IjrBaH4LJgC7v6VY3I7HHMOCIzArEwWoHROq0d4gkuNN28YRDcHcCJI3HBuO4wzuiF4LC0qbNi2lTp2azM3NKWXKlGRtba1b1J4iRQqysrLiY4aP+TksjX/H53Q/W1paxjwfx5pcM6TwvBCzlLtCqqVtQt8ZJCxZi+YvIAxk/VvKxQC+PQTvBdRG0RawaEPZ7RMj20A0C+4TJu8H6YVIyVfBjLJly0b9+vWjbt26UZEiRahVq1bUuHFjcnd3pwoVKugWt7u5uemoW7cueXh46LaplCpVigoUKEC5cuXirSu6x+LFi1ONGjV0v7ezsyPHNI6Us7AZDQ6V0WU8GgaMRZueujXRZ0Cpv6vcquARIBasSdYEA8g1lGwsumMcknuFyZEiL0RE8boWVLt+VVq3fTFFXthFKzYH0bodi2nL3tXkt2A6BQTPppVhS8hn3jSaNHMULVo1l3zmT6ah43tT4NIZFLI+gOaGeFPYzmUUun4BrdywGFs+d9L4SWPpx949afiIYVS0kgv9tAgCtsUyGrbJlG6VYcqOVfIT0B78vSYSWiwWNphPHQ7eslzGWDJjHMnt45K8Ql+0lNs7TA66D1krqCC2cFTu7kxdFrpRtxBM8s/LSs1mZ6AGk9JT1SFpyLOfPVXs7wgcyHOAHVUZ6kDVR6eh2uOdqOG09NTSNzu1C8iF1xegXotLUv9QTxq9th6NXNaABvk2pF7DW1CB0mmp4yyI2MJZI3F9Z000MK1u/gImAIu/lVxMw2UEqyD5C991taXiD6Ljieh2ccjuoAHBPL+KqN0N0b5Iy3UF1fEWmGYTVBsCqk8XVHWaoMpTBFWaLKnIaMfqPD9HUmWqoGrT5GtrzsT7zMb7zRH0HR6rjzCnLEUE1e0HQRsTPRpm+vg2C9ZYB/4+Q5HNFgkzTHeVB5cgmFooDCWbGtFa2paPHZfLwYWB6wSVbi2oQEtBNWZoQlme5yRBFSYqJshHT2aSRJOtmGIg2huSZ0Coj6AGPFjSQVCh2qgOQiHVcLZqgwmTGEbRHGdD7Dbkuv5t5OIGWilAD0h+BgiCFcaSGU1wApJDlWgpXUZumBx9cueBhwGQN05QeWa8lFke6MRO0hMKjKLWGMjVBNdQgqt7IUPUx3eYCqk81r3WlCFPkJBk47r5I8j/t5HbJFjYAF/wuWmwIIgmSJYYigaa6ASjWYOX0kBul1AIGimoaF9B5cZC4njFBC1CIRMRKanMwphpHOEKbwiMF5WmOSvgvUr2xbnhgjovhdw1SnC8K0kMRIPEzlSBaMj++4wzY+lLRnAEcolhwcaSExXRxlHN55bgEXzPqyD8IHC8vkB9kSxPyZkho68m6uJazGyuTxU+itn6yOcB1L3acVW8bymILT4Y3yFAUE8lFxgvFzISneS554k4/nu0mLHspCh42litcWqiYSyZ0QQnKJlpuRiPoMUCSJgpo6oa482PSiQLUeLqzhFUzxeNIhSEBnMBpDQEjQJjgc+r3/Nzv/OXr6uv4OM6s2WBqgvp3VdB5LrELTBguUq0cUt7Q7xTkqv7hv1NtpxgBWIL8BUQ08hAciIjWok2lt18EVgoZdSZIwVCpCbTFyJYylwlcR7+fhD+Dmi2gJGvb8EExwp+D/i58+Xrmsxj+FieawjxdSH5e7XYvUecc8+K+NO2cWOM0aL6AGarMkKAOfjrIrh+kDBrMF/4AaqLKKmOCEIEQ6YxJqdtBcttukBK+y6AJTIqIr+JZDEsiGUt4mhnVEqHkDZ68KhZOwmOFXxe/h5VAFis0WaJ/F3LYDziXHc1DdmNSWi5UAL0NDgG/D5XOywQlVI66aLXQkkWyQ5W+KeE4AOAqs6QDRtI0zBVMmC5GvJcUy4wENh4PsPHkmbBLF8J1WQyxiNjoL3+ZAazHGjHfF5jGSN/9z3DfW3QeZXxvHN3w+hdbxp4Hd5DvleXVeJl2wVilEcVkR4CUgLLvySCsawzJwRfqYuU6Sn7kLHLMcCEiJaPwQYsUlIX69XTJg+SJDyRoaGNcSu5CpZtIHd9kuSioMj36rRcfGm7UGwr2VaUgtI0EGADUvwVcuuAX2ojTZb2ElRzNgtNLEq8JhgpXdIESMnGNI93kETJZanfxrDlsCaOjTCejoxtSjKemaoOiOzWC+XyVghSmC6WI/aHlTJDtOXvs0A8qtxP9DK30M0SOQDLZBWL7Rwp6gSKnuBVjTmCSo4WVH+uJi5JkhfqCwYJpG0lWQmWUtvz/DBfrHUQgKjoEgbw2HkdBK2BuJUGsuOJ5I7xzTuDltxYm6elZgWEmSaXC0dHJZYbfs3ni0/VRwp/CxuRFwJcgE3yyg0QKcEESH5fdZagUqO5gZN0uZpgSaMFLDmR3Spu9LCMNZpQpusGjW4bgTpm0R1Xsdg4hzyNZRuKxmPTADNqPd+Ceqy2pl5rUlHvtfb00zonjGbZJlouF4bOXOCWykZbE9Varz1R7ECjqgQEZAApk7XerRUg0oGQWnPFZ89pgsqOk40dyDKdRSnQKLJAa9cSrV4rdE2s8WiDn23RUEqJhlIqtGJTo+Vqh5arPVq6DrgYjlgF6USdQl2xYD099ducGcN32TD4ngMrNtxo2LbcNHJ7Phq9syDWXhUlr13FafyuUjQxvCxN3uNJU/dUoam7qtPkbXXJe3tjmr2rFfnv6UiBe7vT/L29afGBQRR6aBStiZxIG47PpM3H/WjbiSAKP7WUDpxdS0fOb6bDZ7bTkdM7dBw6sYMORG6nPYe20pxtbdCwMktU1LLY1otYrOx6NVRdunre4oJ9JuEJAZlBqmSVW9Nf5Kw5V+zC49eyauiv6UKTxUKYLfVfWYLGrKtLEzY0oUkbW5L3lnY0c1tn8t3ZiwL39MPFHkTB+4bTkgNjKPTwBFp1ZBqti5xFYUd9cdEDacfpBbT7XAjtu7CCDl5YQ4cvhFHkpS10/PJOOnV1L529dpDOX4+ki9dP0JWbZ+n6rUt0+84NunP3FoPN1Hewg/4u3b9/D9znXfIx4MYq+vDtfhk+5ufyJmzeUR+zAZv37Abs7JxouTys2ghC6/lIsQ2+yZ0hrjlmFRX/Erk1/EVBcLK6n4guPU4O/zULNl1ul9CMtCx8Kh08Fk7Hzhyi0xeO0vkrp+jKjfN07dZlunnnKt26e51u371Jd+7dpnv379D9B1KA/gVXj3xTlBj4dgf68O0NFHwDFX34JisSdbMVDe3GKyDOm7CoWybo7hY3b2d3lpvo+rZJoKBKCJAa3ixYDtjUmy7OOmQWZZI9LWN/rBmoBm5UQYkrOQYfbJbW4DGFrsuzUNjBIN2NTK5fl3dcgygWYHBXGw2+F4UCAp7Qzds36OSZE3Th8nn69fGvfOOxmPtV8DHfYY755ddf+Ll8jm9k8gdwq0J9+AYm+vDth/SJuXUS/x3+rBzF/Pn5Rmfzd/VhuYmuc9uHQCyqtnJj5JAnRsW+1PQSy6zttQZVssmt6ivMQYtqfuJhpZmCSowSVNcvafVt59BMtOFwEF29eoVTHEcfS+UbirCQOC82wPnfKfLEEZriM57GTx9FE2aOoU07wugFbvB149Y12r5nCx/H3MuKb38w1XcCPX32lM/p7jX19t1bho9jwB1q4kTdwUa+Vt3sDJHMnzvmvlgLw/tqchNZ7zYLElRxghw/bxoonlUcIAabW4osEGCfrF2hKlJuV/CsPEpcKURug3lJlZuRNh6ZTzdu3uCI5VTHkcXyWAgLMEYJuP/wHo2D1BXrl9HVG1cg+jB5eY+kY6ci6cixg9S8cwM6d+msvLH177/RiEmDqWXXRvTk6WPduTv3b1NQyFxau2klvX7zmm8/xPeTioHvP8XoH+ufY8kcxfx5OXo563Ddu3jPYEgzM6mf+/0yWe9WnYpr6SN+rj5CdE5hJZySfRCjyhyRAgyr7CPelvTiudSkNaY4jf+wNCNtjlzIUcv1Iqc5FssC5cU2vrAx/4/Qqg2hNG+JH0cenwNfKOL4IV0kH4jYSzWaVYDs4fTbyxdI2Wepbc9m1GtIF/r515918geN7UOha5fQpasX6POXz3zDsNiI9cZiDAvmCObMwtmG695r167R0r0jMAZtzuISL3it3ANV31cXuU+azxWdUjols1im4mxhUclHTPacKT4XGSmo2gwWxZgmlgtEp5BMkBusu6mXitrE3LkNQt/QdP9JtPdQ+B8EPH3+BOl5NK3ZvJL6jepFIyYOoj0Hd9HilQt050dPGUpXrl9CARhHW8M3Jv4ejwBijW4HrC+X612Wu2zvaOq6yhz1qekjVWrC4jcMaHTOUEBYJPu4coUZwspzlphTbpqIKjREUB1fNWQYzNISL5b7xR0WSbn30A3BBeI6jKOBoyLe+y7+/vp3mjhzDNLuGf3TSK+vyNtvImTOp3EzRtG6LasQoT9R3xE9aMe+rbp6+fDRAzRswgB6+MsDSuI/I7lovMXIXb5vAro45twSNlkwRr54wuI1BjV6Fm78F0z7oeuTqvx0saTEOBFdaDDqCJ74lrM1SnD8w4yNee43CHXMXJTSoEyoc4O5j8kXKPFyX72kibPG0oUr5/RPowH1nLymj6TQdUvw+zH06NeHNNZ7BI2cPJgeQSaL37QzjEZMHkTPXjxFXX2Z0zs3tHSv+fDxQ9LlqhZz6N7J1C7EXDeL1EUKhriExQJ+Po9Zf2gdLAakzfMXzAiVGC0cykwVqwuPEFRsGOoJnmdlwUEcwSwxAbHzINZfUE0fSPfn1rLpcvH/59LsIG+k5V1/eM6Z86d0qXfX/u0cpVwI0D++RTduX9c1mmbP86atuzfROBSA8ygYXDdzyh41ZQiNnzEast79abkr9nljxMmc54Gl4FWcclle/FN+amaI5X5uMU+MsM8gbJO9zoXQNCUnio35BgkqPUZ2gyALEczyWKKxXJxDdMsJ9zp+cgapijdk+2SisEOmy/0a9ZV27N1KU+eMR0v4he7cq9evdD+vDFtGR08egaxR9AppmuUzXCDmBvtQ+IEdtHTNIpoZOI2jV8eMgCm0eecGlmaSXLSYY+TywArLXbXPB+PD5jwJwJMBCUawvthOK3RpOQr7kMfbOgr75J7PNSvYV6QtOkbs8ujNLWUZgbXmsGAWGLvcZsEyYmtzc3+aXIJazgsFA6v/1+wP4uE/k+QyHz99pGVrF9OQcX0pePk8XcQuWhFE7z+81zWa5syfTm/evvnD81ciBe89HK4rCPNC/LnRpUvZcxbM4Mg2uc7VbsOryV25Zw6W5ZhjgbscfUKKRTRqU4PGLWUWK6f82i+Vqz/qe4vpVqlEWtUVMk82uXl7iHSFRohwjx/lBH31mTxCJSOyoUzNRlNzrXhqjifq58n1SJUnIepHIYInpqVVewJNl6vgVvOR4we54cSPUpCqk6/dvExf0D3SF/Lw5wd8N3Q+AfGv6eTZ4xRx4hBHL0d3kuViICNG7opwf4w4paDaM5CZ5kJWME/CQ+SauCbqVcQula1lTCLwrNBsS1vdWqqUySrXvZNIn3+ICM/dW8qtOl12h2r7ytRsXO+qVROgDejI8654rINCUX8a5O5NulztLuWGXZpoTZbJJF0u38V17b4AauJngelA7sdDIK+aXKvddslQbhcVtYhYiJWL9Wp4CT/M52aDgNTJWe+a5WwrMubuL/bk+UnKrTyN609Zj9afy/Vu/I2qNiH8peRyzr6rXWljRECS5CYs/X8nGO9rJPfRo4d09fYJWn60HQ0IM6c+nIINb8NkIJdTMnd/2oVA7EJtBWa10WIe5OaCAPtklZujncjs0VcczNcPcr8tDJ8q07Osd+PvDjGtl8ovNmRrSgqN7IWZn6sm9XP1IwgDFzxKZdCafqtrCW/bvZnuPrhj2FCKkf7p8yf6FWkaov603NsPz9LWC31p0l573daX7qv179ATd0pGgwsZjcVqy2qrjRGLUOe6Q4BDssrN3lZkce8jDufvz5HLaOm5DqfmeYkb0GDBPAY7ZmdmzMUGJ1ruKwxgrN64HNJuc78WgxUjaee+rTH/H9BnCOPx4vL1ilGxqnmoVbfGdOLs0Rihl69dpA3b1+oKxKnzJ3QDGnfv3/5Tch8/u0/hl0fSlH2u2DVghokD/SWvcc8IqX4t0rGU2igwRu4Sq9TC7S+Rm6u3OFxAya2gdtdx9Nb0kf1eLTUnLJi/5OTwYnT5XiTkvkxQ7oOf71PN5p486K8bhKjUsBSt3byS5UJgFEag9lPVJmW5Hwypx+jHYV2pVotKugmFKPyeBy1q4PVnL56mhWhlN2hfE/3ga0n+j5BfvnpG+65PprHhqbCwXD8y4xm00FIyuksctdrOBwjmTWhLbRx0adkueeUiLUOuilwWK3fYecqWs0GXKH5aLJFrlPpvtKOt573p+W+PE5KLgf9H9F27GuSP3fPnMetTpk4Rnt7j5/MgBEaoRlDbHk3RMr7PEnj2hycNeKKAhy0xLbieqjctT6fOHac5QdOp6Q/1MMN0Nylykf7f0KVHm2jWQTddG6KXqQvj8N1bIQgaB8rtLA0AH9eYIFamdBY5k71Blb0D5H5Ly1MgFnLLjudH2bCqPUemZq3VHD+tQrjuMSffAw3o4dPrCUfuo/scibqBiNPnT1LZOoVp/5E9uqh88uwxNf6+DvdxuT6NqZc5Quu3rU5Xb17RRW691lXp0rULNM13IqYBG9LPjx8lKS3//NsFWnrqO6zdsjBJbHcVtej+oHXMEav2Jym5NSeLtXYZdLcNTJWsXaFc3UQmt74iIm9fLXLLjINgUFGLXvR5ExW9QK5CHLE1L118sJ9HkuKVe+vuDdSnxTkV6/qpZWoXQp27jS+2bqixauNytG7zKpYdI2Pf4XCeAkRqjtBNEzbsUAsDHRdpmt9EzPt+x40u7jyZJPfdx99o86X+NGy7DfYDmSZWdX8QtWpZjS9vYlNyebBnmtiUJodu3bJt8vZzfxKZ3QeK4x59tDqX5fLC9HITZNeolo8catTSM0dx/NE7cGM2OnVnM6b8EpCLxW2lahWi9r2a09Dx/citVEbqP/pHrLe6Tvcf3aPqkMhDkPot5F2Qz/Xs8TNHUVf7U/Hq+WiwV19q9kN9KlEjPwUtncsDIibJffDbSZq234N+2pR4sUw3OWih6lq1m9BH0nCuWto6Q+xMm1+3OM46WScPcg8SmXIPFcdz9mK5jIzaUmNZMsuWLefavppgpGijLSOqRQ3kIEf/DbnozN0dCcp9iyHFZUjJXQd0QJSWpfT57alem2p0HhPyz188o9bdmnBE8nBjjIyFofOoLlLxlRuXdJE/afZY3fMKV/agLIWdsUpjEI9DmyR3363pNGSbNaLWNLGdV6l1yrw+O0DtXpzNcuXPTYJwPEscyFxGZEz23Qb5RoqMeUeJY9kht4wXRypHrJRbcjSfk4KrTJet57pclwTy2DII0keKb6yLbjPy2laFbv9yPh65xvBSGxa7YFkAr6bg1+mO67epTmcvnNK9xzMI79inNVZhdOYxZX1HSO2r0PKuqM0LmyB3+ZnO/P8iyU1cce/8w7HW7flhhSa2sUrHtdTmb6RlRK2UizH4k+71RLpknxXKN0ZkyDdWHMvZT1ChwRylst4tLeUCGcGeLHga18FyYqGOL/CDbMZfUn+uHLJssdCWQiJG0JPnP5s0iPHol4fUqENt8l0wE2JlA+ompvfadG/Ckc2rMHSt6iqNyvA8rtFgxuZdGzj6UXcfM1nuyjM/QmAKXf3ZObablGqPaDxxy1huHW0VLOvVen4yYmuqzeP15cpH/h1fp8uF2gvXZN/CmX+cyAhOegwTlOtH7t+CKZyapdgSo7QILie7SPL+FN7fxqHBTCVdRXafFYXpzI39WPH4m0lynz57Qh16t8T03VQszZFyvyCCDx87AOl1qEL9Euj2VKD5iObYZn0OoU/MkXvsdKTJcndcmUbdVltCmhyIQERCHj/yz4pQ7XdtFnMhlvLqa2KBVt+2WCALex1/ca/sAOGS7JP1+caLzOBc3jGCcvQVVGQop2aZikt7SbHFRynJY2REQzxEc3eJn6eEq6huNS8jhUUG8Lpik4cfuYXMLebrt65qrWPFi5fP0VU6wV0n/Yg1Wpaz/8heXkRnstwrv+6jH9c6QZxs9UIcIo+R3ZsWjN6u/UaqL8vpt+YsecsHgJTMsmU6br6QxYK54kWVCcJZJPe/vJCbl+VCpDui162PVveyvDJSsMYYro+l+DJSMgTLiK89y4qmhHVEn/MsLw81WW7yo8l99voeRtYq8YoLbfhQjTIBtT0EqHttoH5V0arETpf384BsvE5GdaN5kM3VFjbYIVW7JL/ccSIzOJcHonJDXM5BENwX0sazYBmVZcdLyaUlONai11OJ5RT9na89LQmfggXdN/9xcj98ekc7L/tgSs85Rm7DAI5CKawO46PdLacmqKGkKrGQLaMZkY33kG2T2v46uZ/rBojMyS4XUjMDndw8XhCM6Mw1BJIhuOgIrZ7V4Ehl1Dke1cJjaU7Tkxxo/o7p2Jh1O0mzQh+w6uKj8aI2vFaOVmHokVPvnyokGGbkmSOeaDAaoXr6+wNafnwgdVnugMiTghGtiFIpF9EHqTJaayhwDNnaoEXT+TKF1/WFcFA7AMfzxFfgluxyPbxE5txe4hwgHUi5HhDsxg2sgThGJOdHPVwEoouNgnAFr3EuBArgfL6RAOdKQe6CXTN4p53JciGQ61vu8hhFFY84zcfABC+74ZUWakVGkuCG2OIV83npTiwTB+/pwdOrtCxyIP20JisaTRZ69auS7COpDbTbKckobxrEdbI8V42j21/Kxab2ryB/sst1HysygpOQTBIleAyAMLcRLBoMBUMUOObWdW6IzQOp3BjLx+l6qgP21mhyeX8QbyPhAQWOlGfPn8rIVNIwMCHFq8hcuiYYLOLn8bmY1vKmHeswrbeOG1W8lYTHmfHaD9zo4mNeVhMT4TxtyFH54eN7HvrE5MUz3XPUeg7+mZfJcnfJSC7vfHgD+Y8e36VjV7bSikNeNGpdJWoeaEsN/ATQ6l/IBGpaL0iKbRQg72pXmVM1N7TwvFoBOsFR2Nhe9K+Qmx4cBcTESB6rGKMYrcHncoM8YyF2HMSC/OORmqchciH3DuRyncs7Dp5g5x4vXuNlqMyK9Ut5JogXlfO4MEcktnqexHjxbuo3sif1HtaVj6UQtTaKn8dDkBx1vLaZF6kHLvbVzR5dvHKeV0GyWH6ubmnrEWxDCcRrfDDhwCsh12JNFheKyJOH8Vn8qPugjnT8dGQcct/wxjXeDKbbyrknYjs1nJqHiqJAFwelUKDL47tXmgCRqI6qTIFMrqbwcxm+Ix53DyG2hr+SKwVHg+SX6zZGpAeRgAAL1oBkw4gGqJvBOBargNh8oBQid/6u6XTr9q2YvUK/Pv4FwrrRjLlTsMjtik5UyKpgmhU4TTeStPvATp2oXx7/TBsxfcezPLyYnCOJhXH9OA4bwsZMHaZbr+wPkSyfZ5ACIJin/Lz9J+E1PBf7kvwWzqKD6O92H9iRBfPwJP9tfh4XAl7RoXuvgxH7WKr+dhJ9ubxXV7fTb/+xXdRqbgEqDYEl8L2LjgRcRYHi37qHkFqOxwdmQrgv5Pohcv01wSAaJL/cnKNFWnAgF8QyboyxaE2wAnIVmuCSkDtv5zQsLLvOu/w4NePxASYE+vPoki5dbti2lheYY+51BqLppa6RNBPRdRePvPic5ervzuM53e27t1DI6mAuAFwoeFKfhx554xciOpSjU/e7Bxi+7DW0C23ZtZF+GtGdV2nopK1EthgNoWuwooMnI/oM744toDti9i8havV3+nGhjJF78EQ4tZtfkDxnITpnghkKRKgnqIhzlXgFKKK1ihSr5GpAcjT4S+S6gN2AAAQr4pQct+gSk+1p7tYp2Pp4mbdAcmrTLZYLWOTLm6m5gYVUuhVTeKt58J+lgmm0CoI4WvYcCufxYR6PjoHr7BOnj9LG7et5CYxukMLbbxL5L5xNfgtmIRtc1UW7H36eM3+mbnZo+boQPuasoYvGreGbMUYdiHMzyBfnewzqRAfwPvgdj4QxLDZmjy4v7uPCyWmZ5XZYUJg8IbCiAZV8IJVhsQBRCzTBeqKjQIFkl5tjlEgDtgICEKxPYkRrkotMTEWzN3rR+QvneVkoC9YtEb10+SJEP+SFZ7wbnsFmsbsUefwIdhNEcHRz/cznsQXzIjfE9HfKsyRMKtznYzS2nmHFxjneqM3P53OI+juc3jFMeZALEf+eUziLYmH8e91tGk6dPUH7D+9Bi/w0PXz0IGbTNh45YlksFzJuL8Rs4TxwLJw6LizOcjXBPpJKjJKrBCvJRqK/Avdkl5ttpHAA67NDrAKSwWiQKMma6EITUpL3upF06tRJ3pWuW9R9+/ZtvlCG97mI8/4WgNP5H3lqfG8LoH/bBaOfIYkLjBHqvH4B4uOY2zPw1lMukJySL1++TPsidyJyi1MFTsss2FiyJlon2UC2lPwZZP4r5KYCISAaUHagSWYSH8kFx9vSpFVDKSIyAoJP6e4Ic/HiRbp69SqL5mjmVMfwxWNYfgy8aZvhiFdwBAF5ZxqF8d1pVMFRxHuTFMiLFf4dv5bfn8XyZ+Z7Yuw+vJ06LihN5SEX6EuOO5qNBb8HyT+2nGWEsAGBWUeIKEAsWENJTmQ05x9nQwOCO9Gqbcto854w2n1oJx3CjE4EuiC8JObEmWN0Eqnx1LkTdPrcKeziO40UeYbOXTxL5y+epwuXLtDFSxd1EXMZ9TbftuDK1St8oTlFxsAFRRUWxuRCg8JiVGhwnp8bc6siFnvy5EnauX8LdVpQlsrNFEAKVhhHc9yinwLH5Jc7XFgCbwj+AojJyowE+pLjFK1Jdh9jTsUnOmOsOQdVm+6Oobq8VD+wEFZrFMfOhPL0Q2gN6rnqO+qzqikNXNOGRqzvTOM29aYpWwbSjC3DyXf7OAoK96Yle/0odN88Wrl/Ia09GIJtoStoy5E1tD1iPe2M3ER7jm2n/cfD0djZQ0dOHqCjKDgnUXBOnz1JZ86hwJw/SxdQ73PW4OpBIQsNgDyGozMGPsfP4TvxnDlzhk6cOEERERHYIrqBOgaVpbIzBMOCEy/aJ4ZbEO2Q7HIzDxcpMg0TI8E7HBOTBcQlOru+6IRSN7ek8aXz+SKq9SjgJymoKOSvUXiupKi/OZWYa0VlAlNRhSAHqhTkTNXmp6NaCzLTd4tyUuMleajZkvzUMqQItkmWwjqmCtRlZRUM/NekPmvq08B1TWlYWBsaub4DjV7dlSas6UPTwgbRrI0jyHeTF81Dq37Rztm0LDyAVuwOojV7FtH6vctow94VtGHPSgrbtYLW7VhOSzfNo/bzSlEZiFXEK7pC7KJPQHDqZJebcZhIAfpA7m+AMkGsvmSTotlAsNsEyMWXyztHkg8YSdZEa4IZPdFF9CgKiimKBwgqoSgZyJhRKVAa+2nLBFlQuSBLKhdoRaVn2FCZaSmp3HQ79E/tyXOGIwYcnKjKLBeqNjst1ZidHkt4M2OMODuGGHNSIz8PauqXl1rMLUQt5xbGc5yp9HTBxC45HtFK8i6QMtnlZhgqzEF7CP4FEJNJkRnEI1qTHIfoXBMF5YbcPHM0pOTER7Mm2lgyUJKNRGvgXFFIKTJZo+gUjWJTNYpPw+sVJaeZ6SjlzQgNJRkkOprBcoi2/ivkmqUfImqBWzgmBRmI1iQbiwbGjTAm1yRBHrPAbOAD0QpNtJJtIDmetK1FdFzRbBjRoAhEFJqE10zWMBRdzFC0kWxF0kTPAhYsINmB2BLgPKD0Uq5kmJFkTXQCkrODnJDrPlMKVpIhV8M4mhMQbSjYWLJx2lZyC05iwfFINhAdr2RvA8kAghVKsMZXiB0JzP8SuWkHC/d0g8U+EJWOBeuR5GiG3BwTEb34gm4Q7D4LaJJjFZ03dtGa4Lii2Vg00CQX8obciRpKcsLRnBTRxtH8FvQCybc4DpPJZnXnitTYHZADg9plIGUDJH8BxLDkP4geChIWDTTJ2bwQvdMheKbETaFFs3FEG9fPjMn1sybaH0IhIf8EvIaZCIxFKxKXtoubJvoxaAWST27mhsLao6NoXWGU2ItF1ccbLhAP8MGj0FqGXI10ivSGET2Y5RpIHqrBjbEsXPdORQTPgGSJgWRgIBkkrm7GueI8GzNPUPVgQRUXcAOKhRqkbj+IhZh8ExhNMlCSFbFJnmRy3QyMUvYtSK4N/udyzRizFMLcubLI4lpTrMjYQHwu1ltQs7lyAXb9IJ7hkWJdwR9E9we9cNwJgjtAzEi9tM3SB4EBOMZjpiEyirOOg9zpLFihSdZEmyoZ5IYct66Cyo+QC8O78R3b1uPzL0UkBbJgBT9/Ik9JSvLxo5dcRZJvNERONIxmMAGM50ejaIZgk6P5HCj9PxUKzEEKYGHpKKycq4gmLtXFHZdqkFgDEdZUUE18oV5q20TZmTJiXfqCbqAVaAhqg+qQXEdQOYjLPgLHEOraR5BzT/wOpOurRXYmrn8RAdm88VyWLIlTtPs3jEVr4FzWH/E3a6Gg1ca5Dnyrefm/aw7dLv9PhHLzZcrOP0MuLvCAzFwonNm64HO1xGdsgL/XA3XidI5mlg540IVXmYzE42geTmX5caVskEAjDERD8gGQ+38llLEAlsAK2NhmE45OVYSPczXxMU15QU6VIQbCMuMLV4aMrssQCYjivAMhqxmk1QbVQVU8tyIjC0QFRG6x8TjfXZBjR0EO3wtK0xWiITf9YK1uzjwaMiZrgiWGkkGsdbOxZDe8V/rm/HkY+VmyoXBWhZAeK6XgTojiEr4QyG2Azvgs+B5p6+L71ATV8DqAjedUZbYU6DFKrvrM0V/iPgyyx3L6TkIjTEvbXyA6DOey/H8Uq0WpEmoNbEEqYGeXX3ggcs+yLIdSEAOcKkl5GXABSiIKq3CjqCFfBCW1EsSVhcDiEFlaniv+k1ze6YrISd0CcvHo1BNyB6h6Wq9LlQmCs0yBZG+WzBhKjlu0u4HobJDgWkcWMsdyEFVFyspYD2l6EN+xXf4HyKUgNl0jyKyhfY80nqCcLNCZGstViiUgMFtf/NwDdJfH7nhtXsjNP96EBphx6v4IsQsKY7WL8vLnU69+lIKUIDVwAE7A1aGkaA25n1mYQwlB9kXxWBJiPOWFcqnK8DGoDKnlpVT7IowsDM6QnbejXP3nhnrYrhXEdoPYfvqNsT+2tjMiOjJPguRpLDkO0QlEdC5vSOwoZTlVwOcpxoVNK5xpEZn5voeIzhBbS56DfHw3fh4/HxTnn2VK9+RN5pCUDq9J24EFywjOPUZbI8YpW2uIaaJBQqLfFJkovNy7xtzoxFxzZZpYLVI1qXYgDXAG6UBGMyuRDbIWsDSW6VBMkwbRUnAlBUdGGSkfUjW5JeXvcraQu+7LTIDUbrJ+TjuIxRoLTqcEZxiJ6JgAwVOBt6HkBOpmkN0LEhqpQleOPxujsk/FOApnOVU4iyqKy4LhWh1RO1Derj4j5GZAgcgxAGJHcaNLitUEG7S2pVyN2NP204JjxA/2eUQqFXAWJgg2ilZrPamOSmp6kAlkBTltMojS+GInWZ4TRySLK6zhWEKeh2RIVEIL6SOj2NlT1dGIwmq+EABxrgP1xRpJBkoyd5/G4vWTZRSrSE44mkGWgSrNcjXBBa+IQUZhwZUVFfk5Rt8RguV3dIH8/F3lWuTcKJhZUR25jzAUG6fkhKN5griC2y5WNjPX+bBVfizZV/yCjaPVFqRWUl1BBpAZ5ABuIA9ekT91XtEF8n6GPHxxKdSukD4sHBSTx8awXHlx0tWUu/8q+vDwHUdonHKNu1UseTgkeyGSJ0H0VCBFxxnN2aYgujpq4lD4pCyt4GmFs4LR7zWKQG45WUBytpFbPzynysX2ueVa7IQZH4doPcn5R4mVdrl1NzpxAY7Kj60WxVJyrBFrEK32MelXk+oO8oECoIi5lSgNmdMg5rX88kpYQZOAeHlxXFHy8/Xnjrps/mcbGZ9cMChuyRnGQPR4iJ4MyVNYsrHoLNz/biLFQh4+hybM7huF1XmAY5wzBnLROJTZKUsTuUugpj/EjNWiNnGC45YM3mXvKDqamUGu9JEWOAF7JdhKP00birVQYlMBB71ozRoTqUoqKA5KWdiL6hCzCmI+OZVV0VkgDvLHDUc2v55Tc87uKi0h+tzGJhy9LoMkSrQmm+tlHuIcAdGjVURPgOiJqhEG6Rn59bVYrKpvi3BhSwKFOWvJ98lYX252q+HP664NBSZNNIjOM1wcSpVLlFEecoEsyo+LEpzSWLAm1sogDWcGOUFuA6mlQVlQ3jqdaIFoPQa5UWlKq5Sc33QcOK2VltGbsS0Ej5BrqHKxlGEsKx7BLHcgC45TtDbkybKHQbYibSfVzy4POaVVxBZIAoUgV31+rlqKDpfrncrOkFEHWUkHYtEgu5mpqfgJI4El2IPy4aGyaSYl2EEFppXWkpYHso7VxGZSpSMvKPQtUr9JBZ6gYsqsomeaUuKWE0ptGu4CcYTmk8KMH+PGoZCSWxZCGiPSBqjBCk6vQ+OVC6RQZxas0CQzhmlbwc9pIcVCCupW/pxJpCDklpKfP21VWbWU5VkcUHhS0sWqPc4vsnUWc2wyihpwUAaUBMVAQZBHBWBGPcE2mmAZtTYqal3UE3MYiC0DyoEKLBVUQtBXTuUuvCD3KaIWqVXJymsCeeSjPV+ckqA0qAvJvTVZUlLC0es8AJIkODaSbSwaApzrsRBQRmYPVQhNpwAXbvk+LpXkMGSxydxukP3TfEkQmxtg41xUjt5iHa5zQ1zviiqwyoLSBoKzqxTtrKLXWnqVllOqqE0PsqlUXBiUYLFKquc3sYCb41UhMwhSPgIZtXmShr3u4oBSoBqiqAfoj2NmQOLkpumH1/TFI+BjJ4YFApbtItGE/wgZVaQQRJ3KOvGQNx4gOE1xUFpmgmwd5DiymkBAnWlixHqJaPfR4nX2PmJLyuwQi2BSVFQeyivBxVUAeoCsIB1w0OpfaTm1sp4ZuIH8ehFbXpMqxTJoKddwKCg2Qmy0Y3EZtUmWm19dnJKA68CuKvK01nC8uECgQy/QUz1CnGNvRR/IA04/AYh3Zlh8J5yvIMU6FNMyCYgjw8TzHSDYsRi/l4zezC217ahJwX2UeJalm1iKdN+SM6QQCuVACS6nF8H5QC5VnabRolfWtXbARdnPrcK9pEoBFQzFMilsRV3HQuIoR5wjp+TcCg/TseeSX0wJ5sGATtrIVIJw1EKmXWc9uuA9u4JuoDvkAV02gPw032gOysgC5VBYSkoyeTmtq+yD98vYiGeBkiQ2GreZeJKpg5hjm0M0RHasook1ElxB+SmpfLmDLMBZBavNN7n2wFXl7jwqJZdWpcNTE6thYScaOhYR11kIJJOde9KxzwtBRZTg0pDbPvFynRGRqfH8lK30aCMoVVvQDrSXpO4AvocIhWMdJaO4zBwomEknDxcQJRekr8vTfKaLxWvuZWwuxprbiGosMi4MoreUQWp2AXbGcrX6tpB6kSYXGMht7FhY3GchSM9GwlKDhM6ldlPnEAGOfHGKyuh1aZ04ua79IQDibBqC7xQN1M+IHtvGoAloCppJUjYHeLSvIsUi66BwJTHzuCtyc4tfyz5pa/BtIEyTizT+JntXsRCt4noJi9WXqyJXk+usyZWG7dTJLCq8Cxg0pozqXJaLL/QA0UsOBVhUIsgVO4gARD8LBhDs0jJhuSzfESnYup4gK1xMS4UVUxPUUtTGc5g6oK7EBsf25aQMfH4p1f1P4CELOAonkCNtHoNNrGcHi0hcz5YCqThhsTEt5zLKU37gBjIDJ5WWrYXeqFQavW5QHlBEq3eNBVukFg0h9TqESLm5TCCnPkpuQSUYODeNXy5PKDh2kcIsqwqyqAwqgYqKSorKiioQr4cVztmVkiLw+SGHM0gicIsDd74GXFAkzhUga0AixXqJr7mHi+vO5cUPCUasai0b1LeFVbbNDtIDR/3WsqVeak6r7OdSpaGonuDy+t2hFDaiLtJZpE4IdyPcWFTSsDdBrusAGbG2DSCqupHchIF0S08IKSHFIlpYrpZZ3ExGk1tYyS0jyK1/ouRGYe3VDYw+jTK3jqueNe4GSR8xo1X5QE6QCbhqKRleDcaUnZT9rMBDCpYRbDCQ4WluIaohJa2H2GhA9h5KVg7T4dc65gcFmLjlsliHLrIeRXpFylUpmCVXk6IVWqRWNoDlVlRyC4GCSm7OpMOCHfJrhdOpFOT2S1guhhUfZ24lJli7ijqxCjWO1nLsQYtYiNVayelU9tXGmA0mDVKrJ6RTgt30RqqK/UGymaiQKpuY5JBP/MZi7PMoudlNxyE3y1UUhNwWBnIHio/O3cS91E3FFdt64p5NffEEjaeX4C34CD5Z1xefUf9+gfSvIMqqjoiOobasf/VJXVaTgczxp+TafZNbUOJUAnL7xpuKPyIVX0tfXwzEeEHVeKKUKa8ntYTKpoUMJhDSsjetrlWTB9o8rkrP2mqL9HpTfblVFBcGxb9JtkkrOjrkERcgONqBW5y5pCxITyyQKy8u3kOCtObSNkZutGtfDG+2Ftut3cQ4MxsxyDyN8LLIImZb5hYLLAuJlVYlxCarMiLcqoI4ZF1RHLeuLM5aVxWXrKuJa9bVxS1w17qGuI/Hh3h8BH5hUpUVLyAiijMFPrtMyTnikZgjbliuYz4t88Qnl1vFiOqdaFH/qImVQvWj1GCosSQorhetuZWXzCoQHbW+rTYrZLD6QpukV4JdQUaQPbZpP4uUoiqEhkLwR0D27kpa1sSDi4PIBXkYuS7JtatO7lcMEV6yrw+R6UVnfMq2Qoj2oCPoDLriXA98ld5m1qKfWSox2MxOjDB3EKO5AJg7iYnmLmKKuavwNk8rZpqnE7PN04s5wBf4WWcRa1CYXiNbsBhVMOMmVZyoyM2n4Vwq9joXy1xf5uguFqMAt0IdW0UTCjSh5QykFlNSC+hFazblxTVmREqrZ80VQkMJNqiD7YGTKh2Z1JvmUpGcDxSycRVNUWeehRhIYllKXJbEYZ9LyQWc2pwbiY+uvcWdNG1EkFU20QzTXLUgkqkD6oL6oAFoCBqDJqAZaAFagtagDWinCkMHVSA6gR9AZyaFtegLKacgIwqg3leyspmOnTtHv4arpyCPIdrgBKL1ldtAsS99PdHXIhWk6kenFqFlQClQQgktAgqqSPVQUrOyVL00bGcwUaCJNUJZN1hqk0pv/VRaPck5gQeGyPJD5mAHD/GcBdlz6zGbnsDM2iOjnZPPc3AD7sADDbMSSMEtxCa76qKfeWrdFFcVPaoqqoHqipqMkl9brwDUU4XgO9BArzA0UjTG526WMpPwRaF8BSGqYJooNqt8tPfQxHImyFBP3cPSS3zGqNPtHN1EIOaKm6CgykaRJrN0LEILqSowj5KaU0nNpKQ6a3O3BiswQGKXtKqF5yqKtUVyLiqSM6o/mgN93iJ2OYQ/JL0Aumi04/pUX2qmP5Ia0W2fE7jF8Gvq/GKaVU7RCCsqK2v96liprKhiQFU9qukVhBp61PyGpYPogL97AmKjAD63SVkHqAahh5Z9nIoLytFFV7d+dB8odmdsIvrZZsTnMNOTqepQA6EFQF6VFd1ADr1ITaekOioPKYG18QrIpK9bttarj+1BGn3RmEhwg8T2ELsfol6BKBxL0TlBDkV2fpTnldTP+P1F2/RioCrZZUE5RXlFBT0846CiqSB6K9umFT+hrXAbYqIhCZ/NQGDmONGqFQ8J6u7oTI3E75B6MnNrMcTaRXiamRmJLKzSbX4l0wO4qwjNprd8Jq3eQjh7kNp4xaOSCv70niADyVo0q8XpeHZ623SiHAROhcAjiMyXgOIgCjyH7J24wF3NLUUZdRFKqJJdSlFaUUZRVo9yRgVBHRtQIdZHgL9bBaImo3p4iKwTjUjmAqiyjnHm0cTK59mragVEORUT1zK3EHNcKovG5laqIaSiUk9mbiUzl150ZlZC0wFXdT0d9OpU29gi1RSxJqdrgx0I9sARgp2t7EX2lOlFRaTevpC30j67OAue2OcQr8ETnDtvl1WE4mINsnYUNRCx8gLIEs3HhVUpLwqKMZp4JR8YFQJjyiRAaQajbVUhzguF7QZkReuyisw2srWcTSFb+DjWso8iClxCBuhum0mUwvfRF+kRh8yMIL1ehKYxiNKU2pIZY6nJssPPYKuJrZ5sO4h2RAl2QZcpo2UqkcUytciO4+y4mNnNLERW/D6LSkXZQQ51AdyAu7oweRR5QT5V+gsoCioKKQobUCSRFGaQPouiUNaAwACIvQ7eKmkUD1/BM4heZ+uKhpx5TF2ZXU9ippio1EQ6KZladGoyrfUaSSmSnH6TLliTbCTaOKpTfZMNHPTSuLNKQWnVF8+gSnMmeVGMxOeU8rUCoPAAufXIY0DeOMgTC7nRRSqMrNMGmcUX0g4j0zyE6HcgGhCIwrk34A6k7sbzRto4IXOYyWg0EOkKnJVMRz2ZqWPSrSbU0iBCGWOpyY8m2nhHoLYrkDGQba8nPI2S7gJcFekU6Q3kawVAkhVk0yO7yWivzYqGVnZkmbzow1dEum6L+ncAJI4DU8FY/NwX55uhrVAK/VbOQPoS0+iJtDeITE2mfrpV0cn8xSKTHtkKSwPpWjo3inStABgUAsZJD2eFSyy4xoNLLDgrnPRIA4FpzMwgDeiLM4jElAobI4nAONUm3DD6p4g2Fg7iEA408YxhAVCkVtjpYR8LDkYYP8dOX5YeqQzE2So0gcAUkckv9K+PcGPpGpYKq7gKgQG2JqNkxSNNidPkaQI1iX+niPx/x8i1Ueg1gHIAAAAASUVORK5CYII=\" width=\"115\" height=\"150\" alt=\"Error Image\" />\r\n                <div>\r\n                    <h1>404 - Not Found</h1>\r\n                    <p>The resource you have requested cannot be found.</p>\r\n                    <p>We're sorry &#9785;</p>\r\n                </div>\r\n            </div>\r\n        </div>\r\n\r\n        <footer>\r\n            Powered by <a href=\"http://nancyfx.org\" target=\"_blank\">Nancy</a>. Graphics courtesy of the awesome <a href=\"http://theoatmeal.com/\" target=\"_blank\">Matthew Inman</a>\r\n        </footer>\r\n    </div>\r\n</body>\r\n</html>\r\n"
  },
  {
    "path": "src/Nancy/ErrorHandling/Resources/500.html",
    "content": "<!DOCTYPE html>\r\n<html>\r\n<head>\r\n    <title>Nancy - 500 Internal Server Error</title>\r\n    <style>\r\n        html {\r\n            height: 100%;\r\n        }\r\n\r\n        body {\r\n            background: linear-gradient(-180deg, #000000, #434343) #000 fixed;\r\n            color: #333;\r\n            display: table;\r\n            font-family: sans-serif;\r\n            height: 100%;\r\n            margin: 0;\r\n            width: 100%;\r\n        }\r\n\r\n        img {\r\n            float: left;\r\n            margin-right: 40px;\r\n        }\r\n\r\n        h1 {\r\n            font-family: sans-serif;\r\n            margin-bottom: 5px;\r\n        }\r\n\r\n        h1, h2 {\r\n            color: #333;\r\n        }\r\n\r\n        .container {\r\n            display: table-cell;\r\n            vertical-align: middle;\r\n            padding: 20px;\r\n        }\r\n\r\n        .box {\r\n            background-color: #f6f8f8;\r\n            border-radius: 4px;\r\n            box-shadow: 0 2px 4px 0 rgba(0, 0, 0, .3);\r\n            margin: 0 auto;\r\n            max-width: 960px;\r\n            padding: 25px;\r\n        }\r\n\r\n        .header {\r\n            border-bottom: #ccc 1px dotted;\r\n            padding-bottom: 20px;\r\n            overflow: hidden;\r\n            vertical-align: middle;\r\n        }\r\n\r\n        .header div {\r\n            float: left;\r\n        }\r\n\r\n        footer {\r\n            color: #f6f8f8;\r\n            font-size: 12px;\r\n            margin-top: 10px;\r\n            text-align: center;\r\n        }\r\n\r\n        pre {\r\n            background-image: -webkit-repeating-linear-gradient(top, #efefef 0px, #efefef 22px, #e0e0e0 22px, #e0e0e0 44px);\r\n            background-image: -moz-repeating-linear-gradient(top, #efefef 0px, #efefef 22px, #e0e0e0 22px, #e0e0e0 44px);\r\n            background-image: -ms-repeating-linear-gradient(top, #efefef 0px, #efefef 22px, #e0e0e0 22px, #e0e0e0 44px);\r\n            background-image: -o-repeating-linear-gradient(top, #efefef 0px, #efefef 22px, #e0e0e0 22px, #e0e0e0 44px);\r\n            background-image: repeating-linear-gradient(top, #efefef 0px, #efefef 22px, #e0e0e0 22px, #e0e0e0 44px);\r\n            color: #555;\r\n            display:block;\r\n            font: normal 14px/22px Monaco, Monospace;\r\n            margin-bottom: 0;\r\n            overflow: auto;\r\n            padding: 0 1em;\r\n            white-space: pre-wrap;\r\n        }\r\n\r\n        footer a,\r\n        footer a:hover,\r\n        footer a:visited {\r\n            color: #6daf00;\r\n        }\r\n\r\n        a,\r\n        a:hover,\r\n        a:visited {\r\n            color: #e74c3c;\r\n        }\r\n    </style>\r\n</head>\r\n<body>\r\n    <div class=\"container\">\r\n        <div class=\"box\">\r\n            <div class=\"header\">\r\n                <img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHMAAACWCAYAAADtyrfXAAAwR0lEQVR4Xu2cB1gUVxeG71LEhmCldxQUFRBQQLpUC6IIghUbKAiKXRAr1l5i7SUmlth77/HXmGg0iUlMNJpijUZNTCzs+b87M+sCCyxo1IA7ed5nZ4dieXPKPfci01waNGjQUFJs3No4NG3Va2FYXFqERkAxsbKyqmlra3uidu3aIxwcHHTetUQ7j7b6th5ts12bdb4XHt/vRbN2KTl+UUkZ3i16amlsqcHCwkLP0tLyjI2NDdnb238CqZXfhcTaTdpp2zeJ7lC7SdvrzoEd/w6LT8sJjkkh/6jeBJFyj9CEeS5BnXQ1xtRghsvc3Px7a2trsrOzOwmhNd+myDpeMc51PNsdcvCKka+a4EjzsnxyQmIhsg1EtuxJHmEJ5BLUmer7xW/G51TWGFODiYmJNZxeQZQS0u639rjetETHprHVHb1j50LQU0ABUXHy71eb0j+LGa3p25B8W/WkxuHdCCmXiySIJKTgU5YukbU0xtRgbGxsBamXkXoJafcmorTxm5BYzydOt55P+551m7a/A6EEodSmvx+lrDSg2JQOdHqEHT0dyKh/VCA1ataFGvh3ED4H9ZQsXSPJpH7z72o4hNbWGFODkZGRCaReQNolNEePEKWR/6ZIRJiPk2/cGUAQShBKnpGtqUtWlLzjSl3yHlee/DpH0rBof3IP6UJezXsQF27XuC1ZubYm43qhVN0+gAztmv2mbx3Y5L2UdPLkyYrnz58P/uyzzwacOHFi8r59+8Zs2bKl/dKlSw3yC6hZs2Z1SD1hampKSLtPUUuTXldiw4COxoiwFfX9O7yAUHICXKh/bBQN3VyB2o1rQM1TYsl2aHmq1cGa3CCySXh3Cm/fT4hKq0atycQpnKrZ+lIVS2/St/J/AZkd3huBX3/9tezGjRuev/zyy+qff/750fXr1+nH7y7TV5cu0pkzZ+jQoUO0ffv23z/++OMeAwcOlOUTWhlsR9olpF05hGYj9ZZ4eYAOVM85sNNAdKgPIJQgVIALDWzZlnqnxlHnWY7UbDajeilW5BYdTS6h8eQbmUj884Papgip1rR+BFW386MqVlyknxwi098bkXfu3HH9/fffd//xxx85jx49osfXv6an00MoJ1Wfng63oxs75xGiVBC6bds2+dq1a6fNmjUrj6zq1avrQehyRCkh7fIoXQmp5YsjsVFwFxkalxB0oV9DKEEo6AhBnA7kFtyZLqwxp1srytOg3m2pcT9XMuypT87hscQ/PzQ2jRqHdRNEeiPV1qwTQAZcpKUvQeRkICvzEm/dulXh4cOHk/7888+nf//9Nz179oxycnJIfnAmnYivRq2sGE31ZJTTR49+PLlTiND9+/fT5s2b5atXrx6eXwqEaoEJtWrVkktpdy8wLEqkW0hXO7fgLp9AaA6EEie3ULfQjhSf4UMZg+PowdwK9CBLh4bHhZBLWBx5RnTndVJIsQGte5Otexuq4xFJhtZNIdKHi1wJtMu8yAcPHjj89ddf5//55x96/vy5KFEuJyKQ85x++ukahYSEEPIpfdmO0f0NWfTVV18Raijt3LmT1q9f/ww1VKWpqFq1qqxatWp9a9So8Rxpl0fpFxBqkV8i1oOVwCj30K5/QihBKDXiKIUKJIwKobTNjCLGWFGP7nH0XZ9q1L1lmCC9acteFBzdF8uQWCxNEsnWtYUkElgH7gR6ZV7k48ePQxCJ9/JKlK67V0nez5Cca+kSBFBFHUY3OjB6tHsm/fjjj3Tu3DkhOjdt2kRr1qw53K1btwJTGKRGIUr/5GkXa9JrqKUN+PMmEd21moR3i8aa8AfIJA6EEoRy8gj1bZ1EkQkDqO0YD3KbKCOzxFpIo53JHfKD2/UVainqJJqjeKqNiETDA5HeEBnwKUTql3mRiMa2T58+ffLixQuFxLzIc4hmh9OPcYyyPRidjGQkH25Dj27fIDRHdOnSJTp27BivnYRmSL5o0SIXVshlaGjojSi9hbRLSLu/13Zyi/Ns3n0/hMohlCCU1zpJKEcp1AdNTfOO/SkkNpX4qK5RTz+yjHaDaDFqw9qnCanYIwQTH/84qmrjoxB5GSLL/qDgyZMnYaiL/+SLRlX+fkS0JYNoWgDRh0n04s5VwtcSGiX67rvv6NNPP6Vdu3bxVEsrVqwYw8UVIbQOovSykbEpuQXFCDUOQglCOQUKxQ6IIDK0fSoFtu1DPniPz+WpGO+TCYMERGhPPoclK5eWZFQnULEE+Rki7d4HkXUh8gEXWdKLy+e1FR0vT7VCI7R3717auHEjrVq1ar/aea5VHXNX/zaPvVsKAiShILdQAKGSyHQKjYPI6GQhQj0lkYhEHpHCvSPqpGdYAkQGKETeh0iXMi8S9bEcRJ6VovGVZCI104MH9+nK1W/o6JmNtH7/GFq8oxfN3trizthDbBKYCIaCOFAbCEsXrAG1IWQll8R5KbRFXqFIu2hoxIjEviQFQaRv60QhipF6+TJFnABF9ECzk0RmDZqTab1gSaTfE4gMZO/DBZFdpYgsMX8+vUVf3VpHO7/pQwtPu9DEI5UIotSRA86OOSgL8GudlA2h5MMpRCiEKUXGQ2S7FKH5QQQLaRdLFGGch60vquMZQ03xteZOIYq15HOIjGHvy4Vm50Rx5cnx3+3HF+nY1bG09Kw7ZR/W4XJeicRZTs+xWSyHUMgpXKhHSAcKjEyglp0HUDOIxNcIz1FDhdSKUR4ktiMbtygyb9iSrJ0jIFJYS+ZAZPJ7IxJ1Thsy76uT+Mff1+nkT5No4ZmGNO6QFpfxWqQttULNS+QbxoKcPEIBhArR2CSsC5lb25OFpRX5RsSjc+0LyYp9SYXIGLLBQMDcuSWmO4G515JjVKY7ZXw4IEOa/bGgepkjf0FX7u2idV+2ovFH9F5LXvYhPRq/3p3aj2LUb0UtCo7rSQHoRAOwaewPIFUSChRCEZ1eobFU08iUjIxNyCssnnevgkjXoFz7khBp4dyKajkEcZGKJcgiiCybx0OG7mYyoFVIJ5sNocTBOpPu379Pt27fpNNfr6edZ8fT1k9H0cdH+9PS/R1p9p4AGr+/WolEDlytT+e/30MY8VGFSlXIp2WC0MBgGSEJ7SMKVUYpZPairon9aPPWHeTqGUgOrn7kj8gtYIOZLFwiycgxWLmWtArYApFl71jIsD3MIPswGzD7FPt6+gl2e+R+thVSmyvEXr16tdpvv/02/Pbt2zk3b94kzGMF+P2vv/5K2CmhH374gS5evEinTp0SlhxrNi6noevq05hiiOw4qhIdOrJfWK6cPPUpoqsDNYtJ4bVPFMopQGh42y702dkzdOH4JtqzsD91a+lBPmFxGBiobjAb1w3NJdL/GERWKlMSh+9hlcYfZoPnfMpuLTzLCCJp5klGS88xmnqcybP26R//+daVifdxYZhOGOERBupCZAJ+LzzDTgkfBmAW+5Mg9Pjx47R9x3bqPbcrJa4xKlJoTIYubd26ha5cuUK6uuWoZVwSBcf25XVPKbRdMqRKQqW0GxKTTF1SR9G+TUvp3pDqdDrGkD5rjWF+fGVq5hcubDDbN44WNphN6oXl2pf0uwiR1cuMxFH7K2hPPirrMusku8oFjj7AaNhuRkMlRuxjtPh/9enqrc+EqQ0W+0J6xRz2JWiIFPfCxyGVCxUi9OzZs4TNaBq3LIvaTvOmlM0Fi+wxS0YzZk2l06dP044dO6mRbwthYhPCKVRoMjVpBkk2dhTQqjM179CPhoyYQP6tUCMDO9DiuHq0JLCaEJHYYOb7krlF/gSRlmVG5OSjFf3HH5b9b+xBRohMyFNl0ekg+uPxbUEgpCkG6YWiGAggQoWUe+HCBTp8+DAtWbeQYqc2p8gF5WnUgbwih29llJgWK3z/YcOGUXSn3sJCH+QVCl4KBWGY6ljaOhD2PamOUyNBOtaSL4cCndsG0dHWumTeIBwimys3mC1970KkU9mpjbtlgRC4EMKWgQ3gCLgGnipEzjnhTo/+uidIVMhSd0Eoj1Ah7aK28m0uYZC+ccsG6jg9iiJm16C0rXlltkk2FcTfu3eP4rr2pghEGA4hUxhQCAXikFwSiugU15HRSWTv5IFmpxfvaKWhQCdh3to7pintaq4rNDs17P2loYDPY4j0VRFQRjvYmqBV9iHTTbf++JaKHKI/vEX00znwmXgvyYR8XkeFxuibb74R6ua2bVup+6x4aj7LlLp+pBTZbxWjTZs3EM4JUaeERIrsOhAy+3PyCpWk8qbHwTuGzLDYx0BdEOsnHlYmj9Dca8l2NL+7A41vXFkSKawln2EJEsnepwvRUv7e46urixzZ3bxMdOdHLk6A7l0j+uVioTJx3oeS53YTZMauVMocvSBSSMtLlq+BvFRq0SkdYziOUigQRCLqxCbGqTnVcAijqnbBGMlF8+mOciiAJQgONpO9RxRdTtOnIDtjxVoyByJ7vG8ia88+afW/f549piKvJw+FbhUHrfhxDmEJQr9+RfK/HijSrLBcwcGul/uVaR/0oohZtSh6uShy1C492rt/O3Xu2o1GTl4gpE0gCgUKoYhGYWmB9aEgsiZE4rgjn9hwUA9b8HlrnqFAu4imdLmzFlUxqsdFyrGWzHzfRLYD93d/27dY9ZEf1poxYwbJZDJydnYmykFtRdqFTKGjxbpT2Hw+cuQIlhxbqe/cnhQ+R5/aQeYYNF0J2dVoz74D1KxtDyG9tuoyMI9QRKRwCgByChGppHrtEL78ENeSkL6rjzGlN6xI+uaefC05p0xNd76986HOzJOVWmAIEImlhwPqol4uiTpgEsgB9NXN9UVbvPUd0fN/qFmzZsQYEwgMDBSeyX/+Mk83i/OydPDgQdTFTdRrVgcK/UCb2qNOjtzHyKKuHo2bOp9aJwyCTBGFUESjsEWlXqQSA9sgIUqb+fvQjV5aVLOWLUT6rYNInTIjcsMlF7u1XxoeWXWe0YovGC04w+QzTrCHGBJ8inXk3Kz9bC8i5WUdu/HgVNEyIY2uf0Hff/89RUVFUZs2bYR7unaWcp4+Iex3Kjae+ZFKYZ25buM6ipsRRCHzmNAARQ3RxhqxDbXpNpiiQOuEwYJMdLLCIWQ0MEqR9RUig7m0orH0pe2J1WmoSwWqZOZ1AM8qlBmRC85UbLfyvPbvfKoz+RijaScYYcpD/P2yzxktB5OPMsrcq5R57fcj6tPs/RtEP18Qj4SgftLV/xH9fv1lvcS4j7799ls+0hOOhCz+cAG1muFAwR8w6rSQkVd4CLXpPoQDmUOoNUT6YZbq5BenKtJRvcjKln5UydyLQrzq0dVuMjKpWutjPK9aJiRm7dPWnX1KNmXJOZYzEbKG5RsKDN7FaNBOcViA1JtH5rmfF6mXycl5LqZcgHvhaxQpFqfYhQbp6NGjQvMzatFwCp1dhYJmM/KP8xRFSoTHpQoHk+v5llwk6iEkeiMKm1A1S48X5/tWlA+tx65AQMUyIRKpswrmqjtnneKSlAKHQGDSRkZtlzEKRbprNpcJaa8N3vffppT58flIUj1tpx7FkuTu3bt5RnnrkWI7zgiloDky8updj6dVQWKrzunYtupOzgEdJZExKiKrFibSKoAqWzTlEgVsfes+39rP4OMzUSynii5rVyZEQl4NpM3TYw9KEYjo67eVUbd1jFouZhQ4p2DC5jPKkKIz+7Au3fzjKz4wKPEhLUSlcIQSkx9hfblz5w4atzSLwmeYUZM0S2rdbYAgM7hdH3SqnbGkKLFIpFQfCPQUJNao60rhQ2tQ1gYZPRrC/m5hxnZAgKwsTHDKI23+j6fUvpsZFudiBAZxYWrA5yHlKqNz9blQ+vufJ+oiNM88FssRoVZi14NHpXC4edm6JRQ7vRm59q1FLRNSKSKuL3lGdBGaHIgUpzXS2tBSENlCFGkfXEhdFCXqWzYm93grSvxQm/ptRgeO9D3bmz2AAOuyMo4bz+eecavYi4gF7BcIuoiI+xE8RUotVCT/WPImUSK6WoHR4MC3I4XOVHlSXXWoDtmiSGmnBPudfDkirC3XbfkYI7w4ckm0opBO3ck3MgEjOOFgslKkp3qRlYW66EWBLRMUKZXiZ1fk/8MKbF7J6FIfRn5j2Z8eU1gft8lMq7SLdEVNPJm6hSVCqDlqozZ/DrFaSL1BGXvYUy464WMmTGCaLxSjscUiRikQOfoAkCSOOqBAiw59O1EQBal5tr5wzyUK22LY3xQi8tq1a/Tll18KPz+yftvHlDinEzVIsKPG0S3IK7KzeF4VItVHpGpd5OdZt+zYR55da1DyRpnwe04G01A+7g1i1GOs2Au4T2bkOomtd57ADEqzTBugVcBUxwpcB6RgjCQM60u85hGIzlYki7OPI6ONXyTS7bu/kWJTGgjTH9RHodlBjeSpVdjuOn7iOC3+ZAF1mx1Lfpm2VDWwIjUKiS62yCo2XCSX6CNIrGoNmaaNqXPPAfTT9Z+o83wtQWIfkLGB0Z3RjLIGMuoJqe0RoYhKcpnIqOF4drF+Niv0NLrJUFbXeCgbCzYaD2HZ1fyYoYHdf7jWQlwVcEEpkZNPXgECR0hkcvaKjdG0w/XozLcb6ZdffxHGdBAonCaARN7sCDVy896NNHx5OrWfGUyhM2tS8wWMbAMZaePUgJ1zoDqRUl30fVkXK+P1g4WrSEdPX1irbt27mnojKnt/wigdIq9OYbQ4hVGnVYwS8b7DakaNJjFCVFKD8YzqjWO/OY5lbrkFmCYwe7PhbBVkPodIMh7MqFoQy4HItaDDf1IkpOmALYI8dQJV5EmgIRougREgkNGMQ+605fQYOvn5Tjp77jQdPLGflm9fSENX9KEOHzSlmIXmqNlawhIofTuj1E8YOTWTkba2NtW0dOLryIJFSnUREqWI9CKXxoHCAGLOnDm0Z88e8kuoJHzfFIi7OIvR9t6MYlEmeuF9z/WQ+iFSLI9KyERUUl2kXocx7EHtUczXJJjZmISzHWbJ7LnpMEgcKlK9FSNI5DwBV8F/r95C3uhCBXJ5xRSoXKOKDObs5Mho8PaK1G9TZUrdVJ7StmhhrcoFSuB+wHYtmnioLs087kX9Z/pQfRcHMqhpgZ3/CDJViLRrJtTFKhZefPMYIhtTFWNHWrV6DbVq1Uqoz5+e/pT8OhlSLwhLhrhzaNgOJzGKmStK7LFOpNMaCMxEVEKk0zhGiEqqgzRsl8H+MIlgv1mkMTIfzshEIXMII8OGokyJB6Dcf0ok5DUHzxUCs4onEPKKFjhIYuAOkQGc7XkFQijWtSIj9hrTnJMBOLEgMmFbAIW19SC9igY4HedNhjb+PJWK0xsbH8oYMw0ptQrVrVtX6JLnzZtH5z4/RyGJNQVpfcA5dN/HEhlFzxIFdpfo9jFkIs2adkc0Qmg9MSoJUUlW6HQtOHhuNlwZlUb9INA+j8zHoPx/RiTkmYPbRQrk8tQJ3JlL4I7iC0yTQFdN4w7UESTOPh5AsySmHwkgz1ZGJNPSpvLVagsi+w+fSBZ2zkINjoiIoPbt2xMuQWT0UGuhuekLLs5kdEgUCXkiCZyPOKLMKpEQ1QMSM8WotOcyUwDem2cwyp1iayYItZJy8fA/IxPSdCBw36sIHKxeoFJeEQI5fTmbGWUfqCcInJmbYwGUscOGTOoyYkxGOhVr0HVslQ0YMIAuX74sNFSLFy/GgP4k9ZjgLETfQIi6gmZnC0S2naMQqKQr6LKWUUfIrBrBqGJzRF03RjYQZzeSkTWi0VKMSmWKBTWi2Yt8Mu8Anf/KKC+1yAZGKU+9QC6uJAI3i6QAaQ2IyKz/UmDmbivK2mNPkw970Yjd9tQ8U9wH1dXV5cscYe/z888/J1zY+/yEek12R2rVptFoam4iwhb3hsj5XBxYK74mb4NoZKAB+8RxZYdVLMc8jD00DGFUAVKrd0I0DkBUIiIt8kUlp3pzlci88k6XJ4gILRAGtkDKPyoNjDqBatInKEgenmnToO361H+rXh6BfTifCCAyG9KMowE0Zp+T0IUmcjbIBLpDSAUDRpUrVxZmuriEIf3CxfModpwxUqsuLVjB6N5glIs0RjFLefSJdEVk9tsDkQdEBkBo8nZhafK3ZTPmYxzEvqgeiggNZ6TfBhGItGuUyqhWGu5TQQpEJiOKA5k8n8yj71KkKdgN5P22vW4Do14gQNeqQ6P22tDEgy40ap89vt4gj8DeHEhLAuMPuNG0IwH4miqK5QNQdqAmTozwI+18miQsQUaNy6TYidWpF6JuD6LwpxR8HqIpfiWjzmvBhyKpu7hAkXREZX+QiowTv5r92X4F09O3Z5WM/Fj/msHsW8NQlqMPsQaI1MqgfBgjvRAA0VU8JYlKZr8rkWbgCiAASSoCS9bAFCEQ6RMRWJ4G76gK4ZXxTLcwgVL0cWQ06VBTCPXILRAou0/rJoiSGjWEnysJCPGi9tMMaNAaRt9NZnS4F9LqeNTBNXz9CNaI9z0/UQrsJ5EG+u4RZtK/YwqkrRCgU4lV1LdjnpDbr5ITW1u5MfuqSiD7C1DFAMj0UpEZ/C5E6oGTgABkvJkGJgUM2m5I4w82pAmHXPBMN4/ApHwCe0lwccmfVKQphwNQJ524PKDagZo5M+EwmH5NLWo1kdEHPK2ils3ow6j1XKVAgBQq0neXJFAida9Iym5hl+hG7IoCa54OMAT2uPPVrc0SDbzZ7Gr+7IxUJy+BNCB7FzKng7/BXwDCCmpgwKs3MECGdGqP5sUfC383vNdB9BUqUCX6hqJjnQyZY/e55xKobGC6INr0jZFmrSBrFqMjkPcDJPYYgvq4TCkwXgRRB7kf5RXIozEFJIPekNxuBbtQDAEyoA10ytdkOlVsmeydSJREhoNJoB24D0HFqn9AkldkBwrEyBuy04hmHAtAdHlBpF6xBHYXQVRWoez9nhDZGLXVnxLXVxIFSnQGMQsY2TRllInXn8cw2tSTUeREiFuVW6ASpE/qtjGvwD6c3SK9kHWil7H9rLRckFEONAC+4CGgdHUNjHqBBda/zN22NA2daPrWapJA1QYGSweIq4wGpyY+zwSY0fCdjjThgB+2qaoiErVo5J5GGPvVlhoYZf3rAlnrFzK63Q81PhVpdX4egZAnEstZAfmg5xYuLi+9QRJIQEZps5StKK4AItIF1e79eaecZaae1rsS6gn+ABBW5ARGosDoU9fAoFaaCM2LagTKqP8WI0hyRtT5oskJoEkHRSZKZO12VUQg5rYmNG6fD95rv6x//SHrazQ5p3ohNWZxWYULbAcQcdQWIKKFdB2/Bs9XAi6dDww2gY14v1xnXHFF3v3ztya9P2m+0Hqk7vdGKewXg9osE+k2Esjelsg64BYg8PoCC69/EFYd0emgMv/M2OWoEAjZPjRshwOObZgipXrRBOGZHyLZ8GUE9v3EFCk3gJLW1xBq4GxIuYsmZ2YSoxYzChYIIEYkGkAkok6UmYwITEMWStmKSIXADnjWGqLDkK4jFlT8PGZZ7YSFJ0YaEpGsEJFaJ67udGuxzOpCnfHiRKiquET5B9wE3m9DpD64CEhJMeofkOSVpIFB6qyBpYi1SgeavsWcMnbWo7TNpniu8zJ9dvuoHKRaYmfDQBGBQAuf64bIDKB+G0xoH5qcq30QXQMgZ7FqBCoFKqJREglaL0FNXczfi5GZgCzRi3fUm/GKyOyKzBGDNB2+iJH/HJ1bgXMMJscuc7HML2DF2Sl2AQuqXnJCZjDLYGSUojJsn/E2ZM4HBJ6Bf1ugSgQO3GZBA7Za5O1AJZT1TyLf8gG1D891acj2BjQWIufsbELXJpej3T0YNR8LecuLFthGImopXiUiIbPlIh59/CShSMRC8cRhFARH87QLmdGr8AzvA+cx8pgqe9JoUvn5/jPNBKnp6+MNm0yv+JkrMoJlljjSq5Wksta8BGRvOr1yiUfANYgsoANVKxDiihYIII+/ymj0XneePlUFKuSpCpTQot6IwqzdXjRmbwCt2dyQfs/UpamJEDFTjUBIixJBJIpEqciUzvx+IB5G85vFyAfftykEeQMvznRGTYDbFEYNJjByGi977DhCZ4pVN60dfFvMdrRy4G6UrCLzKajxJmVOAXPAVgCRhdY/IMlTK1BlCwkS9LlA1Epnof712VhdvUBlB4q6aESZu5rQaEgcvSeAdn1kT7f6QW4qo1YLcslTIxDpVKAViFoiycR9i9wykbIDJJlcpOc0Ro0hzxXynFELGwKnbH50RHy1gziLnohI1T1NuYG9yoy22ZsSWRGkgQFSelVtYIonMH/9U0mhSRsMMCjwQBMTACGeWNhrqwhUXf+JJKytwgUKjNntT6dWmNP3vSFvMGQsKZlAgCjkSKIVMpFWw3PLnM3Id6ZSpiuk2faDuHRIHC2KdBwj7mvaDIZIPLfIyC0TDIJIB5Xdk9Q3JbMCqA+eAKTUktc/VYGF1j/ca0FqdQjWK1Kgagcqo/TNTjRqpzedX1iLziAKIrK4uDwCIa5ogS04C0WaA4XMVgqZ88UfqQjKJdN7OqISDY19f4hoI2LaC++RSh1GiacNbDNUtsKUR0dcVCJz+pvc4joAKBVAYkkFlryBKUKgUp5q/YuDtNMzZXQYjU7IWEhQIxDyVAVy+DJDIopL54JxHw6JIZAo/PARJPogGptMYtRoLKQNQsqMZ1QjlJE+qBjBqGp7RGEyonIoGAGZmUqZRojUWuniVpihj0rdXPymZIYCuRiVxWtg1AtUW/+ASvQV2YHGgE+R7g50Rwoc9+oCwzlStxrMT9tzYaMhDCKcIaE+IqnuQKTONERbslgHTTpBThSiLJjdN6jLthr5s3s1ghlVChFPHRjEMKrZAx/vK+5rVucdbGcIx9fohUF+gIrMjDclczcggLT6GgLVNzCQV5TAwhuYaHCID8u5yLG55JVYoMQ8sS4G8hSaLUqsAwnWSJ3mXSCvPcS0AS1xH4FnkGKNX9sujWVCQHVdA+Zc05tNN27GbguRGs4jVRSrj1dDPKsShHt/RpX9xGcGdQSJcnAKVH4TIs3B3wDbUiodqKpApbzXF7ico74D5WlwA5YJXyBCAkcWKlApT41ATgi+XzAQfj5mNqSvFO99URe9xoqR6olXb55iIdtpDNtXP1s4YumRS4AW9jINa/mwSETq+Jp+bGX1JmxllXpsvp4jW6RbFzRgc8u7sYlVm7Ksqo1Zd0hsBHTeVFR2At8DND0FC+ysRmC8AjUNTLviCsyXPmdAytVkyBiSS+DC4glUylMKFCUqCYbctigvbUCURGvOJ4hwlJuG4un1tuAqKOpknTYoByqAShzpXhdovY2pjw/4GiAi/6UGBsQUS6D6BiYN4u4OQiT3FaSpFzhPvcCgOSKBnNmQvTSvwEiJVmgE/ZdwkQLOYMJ/fcsrEMiRYtU2MOo70OKM0IrfgcaB60h1Q3pAzhy19U9V4NzCBQZI+IOINZLAjaLAlqAFaL4BKXaaIPIZqAq8/usy1wAMCP6NBgYUbwID1DcwB9GcrOvKyG/SvywQjZSfBJfZcoNCINggSowAgSteRuXPQAZ0/ssi9cFjwDvYnFcVWPIRmvoGZhokfdubkU9G4QJV658kML+8PAIBOlhfiaBFkKcQKBEOwtYrolJgV2k4VRANCDxENN587QZGTfosbgeaAO4MQ+RDZugH6hoYSV4xBfpwZjBqKhH6YV6BnFDgu0yQeAUQyCwNMpeAi9ji8oTAe+9OoDKFRkDc2SmMZnWBgKlqGhg1An0LEeg9XcR3riRPImSdSDAaQdcpgsQ1IAc0Kg0yLwBviDMBL4rVwCz9F0ZoRdS/6ZB2sRcjz4xXEDhTvUCvaSKeADVRKVCS2Ax4LxJEPgIjwXGg9V8XqQPOAS3Icy25wJJOYNQ3MO3B7eHIAolcnJoGRp3A6QUL5DSZivezuDylwCAQCALQ0TtPEmTuARNB09IQlVpgNL+HvJDXbWCUAlXSZ7EbmL2IlmWdETkT8wr0L6ZAbzUCG3OmiPgtlwRKBHA+wsfmcZECvUEbICstxyq1+SsEtnu9DlSdQPUNTCpeb/SFgPRiNjBqBEKeikAPzmQ8n62U5y/hh4j0WfVy2vMnqAV0WWm7IK9zCfYAX38Ck68DDQaXsxn17wJhM4rfwHgBUZ56ge7ATcJ3lVIgxxf4oKttNPNlVC5mpfWCwE5qGpjXEKi+gZmIZ5/1YNQoozgNjHqBkjylQD4sl/Ccz+WBD0WBTSUaLxa6Vjn4C9iUWpkQGPP6DYwkr4QTmAjwaxaanu5c3qsJ9ChSIEANdgVukN90jVKgt4TnKvai4ST2VBqkj2Cl+YLAsFdqYNQKVN/ALAQ70fS4jlLfwADIUydQkifhMkEC954rlAK9INUTNF7JyFlcU54HY4F2qZaJ6HN9fYEln8BE4P7WMER8TzUNzCsKdJbgp+g8FioFNuGsxjPIbSiKzAFhQIuV9gsCa0Hg8+LvAf47E5hlYF0nRM3oEgjk4ooWCHlKGmRD8GwuT6SxhMcqiFbOXreWCZEcCNSBvN9UBL7BCUwY7m8PRWT3VNPAqBHoXIhATn3AhTWGOA9JoDtw46yUXcTh5euQ+FDR8JQZIHCfuIX0JgSq1r9FeL6+IwSMKm4DAyYUQyA/kCxRH8LdV0gCJRpxVrLf3OeXawSJv4MerKxdkDcKvMYIrfgNTCBebw1H5Hd/tfrHgQRRXj6B9ThjAU+vSyV5wHWlAtljt+W6jSFxGpgHZGVOJgT65JGnRmBTtQILr39TIHtHJwjILIZAlegrXGBdzhjx1XmBUqALcOasYE9dluq0hEDOVKDLyuIFgeUg8GbJRmgln8B4gmv8FDpfjhTWwKgXKMlTCnSUcBgN0bPzCKSGnOXsecMlWp24AIXEMg0Ezv1XJjCcQurfAEg/h/RaZ2DJBNZTI5BTB9SdKskDDZaL1F8GydmyCex9uiDRBQJz3tQEhnMaUpLjIC27cIFOxRRYR6L2KJE6PJKXSQIliU5LGFmhYzbCmVb2vl2Qt//1BRacPqMg+ee+kNEHAtU0MOoFKrEfCSDYaRHgApciikHdxYwsu3ORAt/joLLsvZIJgX6Ql6N+hFbyDnQlJM+KhaCRBQtUlVe0QDsJW+A4VxK4RMRhISOLrpJIYBzInhgHs8rvlUzIkyH6Nr2eQNX06QZ+G4Z63OXVBNrnF5glYgNqT4PMJSIOiyF+HiOzeElkAEQ2Y2QSxnJMmzMj9r5dEGgLgQ/V1L8SNTBpiOITiBSbAYULVI2+QgSOELEGtuO5QEkisEcXbtoWEv15NEJiCN5HQG4r9sK8NavB3scLAhPzC3QBorySd6D7uNAYLk2l/qkVaJNHIMhkZAWsufSFYJGIzSQIbCFGo0kwJIZDYkvxJ7gsotkDixhW/r2UCYkyCPyo4PRZsgamCV7vDoTgbuoFQp4SpUxI5AJFLDMAXu3mQDxk2i0Q3xuHgCCIDIXI5hAZCZGIUstYyI9np9j7fEGiPgSeKcEEBqimz1RE9L5OEDGwaIFSBOI+b3PDn1uNECVacIZD7hRRou0HkJYiSFSNxnYQGQeRnfD5XdlI9r5fkGgEgV9D4Ct3oMshPysacrJAIQIB0ifg91wmFz5aBEIhUxRpDpEWYyF4Pp5Nh8B43uAoo9E8EhIV0dgBErvgc7uzpzY9hJ0RzQWJZhB4Sf0EBhSQPs9DRIt4FYHK+idhKb5CpiixzlgwDmJxb41n5pBpxj9nDu4h17hlngaHzNtAZAxEQrBVZ0hEWrftCZLYMo3FXEBgDQg8AnklamBc8ex2OgR1K1SgMn1KtdAGX1ebp+vxHPHeeiSXCbIhMFGsjyZhENkCz1rzBgcS20NiRyGlEiKRSyS7FHbHPoWZaQzmAxLLQ+I8CJRDXLHqXwJS7FFEiWlaIQKHQ0YuLBQyIa3uJJE62ULnCtHa31l20Z2OaHxWUDRaK6KxFyT2QXSnsmf2/VhLjblCgDwZiIW8O6oCVZcQC5Amx/H0NwwUINBsmIiphDmXCXEOiEinKSIO6KLdp9bctefrTdbPXzzTs2ylE4Ro/LawaEQkUu1+7O/a6ayzxlgxgEQzCFwLgTlKgarRdxGvYTGqAhXyTIaKGAMThUxeg9EB1+dndNDk1JuMbnpy5QtPnv1lRkQVgBY61UroVFMRjV8jGnNsExGNyUI0voDEw9iVcddYKgEQKINAP0TgqYLqnzvk3kyFtK6FCQRDGBmJ4L0o03YsBCIiXWeB2ZA6VUi7Oakb2wcRUUWgpRCATlULIm0gMhgig2v3ZxYaM68BJMogMQwCDyHyXiiiLx0p9pNYRrXSChE4GB+T4O9N8XVWI8W06jwDqXUuIzfQcLq4veU53WwsEVVSyNTwBoFEGSQ2AFMh7uFO1L6eUVyeEqP8KFOssOyw5uM+PjZEVHrMAx9wsaLMutmVdhNRZaCtEfAWcRjKzt8ZhBrWHqIGAy6zUKR6mSF2rY6TCpA5ge9Z6n4jJ7m+RuZbJnU0u3wUXWaNXhA1qAAG58UUQs2HicsSR4hzgUCPuSLO08Xu1naU9q/Pc55rZL5tLoxhn/dvCUnpYKAqJrmBXFNgLv3LkI7ZkDkVImeLOOPegU+CRmpfl8tzNDLfJrSIGfw1iN13bMtl5mNAwZhDpiVk2o0Q576uENh4JmQC58mQOQaM0jujqZlvGZrH4g/GoUvtxsisfyGkKzEfCJFItbbDIWykuEPjDplNuMzpkDmRi8TrWMOlmm72LSMfy/YMcGc3zdKwTEmDrH4iZvkwh1QLRKU1otIO9dIxi1GDsdL5Wkj04jKnigehHfCxyLmNYqWhgUwj4O2kWNsHyeypQxWWYZ7KDgJSIU3EEjJt+B4n0ms9yHIZB3mTxFOBTSHSa7p4/qgBP3mXVe6Hy79dMCGicnK5XCPzbUAz2NjVPuwJbi0s+rIgIAeUH0vItIZM+8EQmYEaCWGNkU69p0mHryHSc4r4b73WQx2NmtMomYgMgI5GwNuJygovhrFfo8zZRsUzi2S2EZBAihIrRKgt6qXDENRIRKU7pHlNhsipEAk8EaEe2eLHPEYbHLj76KYpEZXXpNi3BH3AupyKZDm6WixQ8cyyDzMGNwC9BGKtEZ12iMy6iEznEZA5FgLHgwmI0GyAlNtyARdZ7uqK4zMaEtFbXJJoolJHPpKd71Obnc3/rx5b9mZeVr3Zc7ySQBKj+gMhbjREDhNpjG41EJEZPotRi7mMIvgaM0vn56EfJngTURWgqxHwlqD5LOrr9iynii5rn1+0VRLTtkpkP1tDog1k4p4sEhCVyRA6nJEfRAagZjZDRIagbvrivVPfcmd6Tox2f/jwYWUu8m02PZqoHMW+SHVgX+FtgQ2KdS92vG4/RFsmmhpEYn3US/s+ENudkXk8o+ohjGqEQXKc7J5TT8OsmcsnGf3xxx+8Rmq/XZGaWtn1i3ZCVLYrdO+zF1vuivoYjm41At1qECLQi2938c42ATKbyW7U8is3JayXt/Xdu3f1eNf69ocDmqjUfzGcXe9iw04po1IV2x4swxnRGMZ/DB7NjWcmhPJzuP0RnV1ZTjV3nRhHR8cqT58+1Xp3kahZV075JIg91ZExj6IE2PVgsc5Is01HIMUiGp1SxFpZP1U4hLVDR0/7HTc4mqbH904Se+pajU1Ve1QzsZxb3SQ0PWiA7LqxXx0T2Q13dLSOSeyxbTfmqBHwbtOr0YsMdq1PHfYN3lZUJ8Cum6yabQJ7BpaDGhC6vHYPllO7u+xdn6DTTHrk2ezgMm/2EAMCt+IIgEAZ8Mn1figYoBHwbkWWp0ls494w9sy4PIt9VQEQWVEj4N2KrC4fz3YfCGfPrSqxJI2A0ilRi+ay1i+GsmurfNhD4wqsvUZA6ZFXiRYwR/lM1oKy2YicIez8VzEsJ9GeHSynxeppBPzXI28+c0dTky0fzD79J5k9+gFz1sOh7J/V3uzHvnXYyup6rJligK7hvypxDouWD2fnfohnOUs82U/9HNmC+oasA4YAThBQGZSCaYxGpCkicfdFzFTTHNj+auVYCB6XwimMRqTNi0x2ZaEnu4/lRVzpTZ8akZXlo9n5aW7sFlKpi0ZAKYZmssyDWCdW0mHhGgGlfHqDteJvLc3YRk1jU7qp9GM2C74Ux+RIr2EaAaWXyitWrFj4+eJ2X3wUoPVcR0fHViOglFKjRo0Gu3btenBt32Q6lu5N6enpfLdCc2yxNJGRkVFOT09PJyUlJX3r1q20a+cO+ujD1TRixIhxiiMeGkoBFSpUkH3//fcHjx8/vn/VqlVnt2/fTqdOnaKVK1fSoEGDJmtkliK2bdtmceXKlaeff/45bdiwgf73v//RsWPHaO3atfJOnTpFaQYFpYgvvvgi6aeffqLPPvvsGU+xly5dor1799L8+fMvowGqpRFQijhw4EDTX3/9Vb579+5vDh8+zKUSl5qZmZkNAeU0AkoR+/fvr3727NnkLFxffvml/MSJE/TRRx/91aRJE2fNwKB0Ips0aVKL8+fP30KkyufMmbNT2NbSXKUWXTMzM3OsLVslJSV5aKKy9PF/RWUQ1GVh9WcAAAAASUVORK5CYII=\" width=\"115\" height=\"150\" alt=\"Error Image\" />\r\n                <div>\r\n                    <h1>500 - Internal Server Error</h1>\r\n                    <p>Something went horribly, horribly wrong while servicing your request.</p>\r\n                    <p>We're sorry &#9785;</p>\r\n                </div>\r\n            </div>\r\n\r\n            <div>\r\n                <h2>Error Details</h2>\r\n                [DETAILS]\r\n            </div>\r\n        </div>\r\n        <footer>\r\n            Powered by <a href=\"http://nancyfx.org\" target=\"_blank\">Nancy</a>. Graphics courtesy of the awesome <a href=\"http://theoatmeal.com/\" target=\"_blank\">Matthew Inman</a>\r\n        </footer>\r\n    </div>\r\n</body>\r\n</html>\r\n"
  },
  {
    "path": "src/Nancy/ErrorHandling/RouteExecutionEarlyExitException.cs",
    "content": "﻿namespace Nancy.ErrorHandling\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Here Be Dragons - Using an exception for flow control to hotwire route execution.\r\n    /// It can be useful to call a method inside a route definition and have that method\r\n    /// immediately return a response (such as for authentication). This exception is used\r\n    /// to allow that flow.\r\n    /// </summary>\r\n    public class RouteExecutionEarlyExitException : Exception\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"RouteExecutionEarlyExitException\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"response\">\r\n        /// The response.\r\n        /// </param>\r\n        /// <param name=\"reason\">\r\n        /// The reason for the early exit.\r\n        /// </param>\r\n        public RouteExecutionEarlyExitException(Response response, string reason = null)\r\n        {\r\n            this.Response = response;\r\n            this.Reason = reason ?? \"(none)\";\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the reason for the early exit\r\n        /// </summary>\r\n        public string Reason { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the response\r\n        /// </summary>\r\n        public Response Response { get; protected set; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ErrorPipeline.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// A simple pipeline for on-error hooks.\r\n    /// Hooks will be executed until either a hook returns a response, or every\r\n    /// hook has been executed.\r\n    /// Can be implictly cast to/from the on-error hook delegate signature\r\n    /// (Func NancyContext, Exception, Response) for assigning to NancyEngine or for building\r\n    /// composite pipelines.\r\n    /// </summary>\r\n    /// <seealso>\r\n    ///     <cref>Nancy.NamedPipelineBase{System.Func{Nancy.NancyContext, System.Exception, dynamic}}</cref>\r\n    /// </seealso>\r\n    public class ErrorPipeline : NamedPipelineBase<Func<NancyContext, Exception, dynamic>>\r\n    {\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ErrorPipeline\"/> class.\r\n        /// </summary>\r\n        public ErrorPipeline()\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ErrorPipeline\"/> class, with\r\n        /// the provided <paramref name=\"capacity\"/>.\r\n        /// </summary>\r\n        /// <param name=\"capacity\">The number of pipeline delegates.</param>\r\n        public ErrorPipeline(int capacity) : base(capacity)\r\n        {\r\n        }\r\n\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"ErrorPipeline\"/> to <see cref=\"Func{NancyContext, Exception, dynamic}\"/>.\r\n        /// </summary>\r\n        /// <param name=\"pipeline\">The pipeline.</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator Func<NancyContext, Exception, dynamic>(ErrorPipeline pipeline)\r\n        {\r\n            return pipeline.Invoke;\r\n        }\r\n\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"Func{NancyContext, Exception, dynamic}\"/> to <see cref=\"ErrorPipeline\"/>.\r\n        /// </summary>\r\n        /// <param name=\"func\">The function.</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator ErrorPipeline(Func<NancyContext, Exception, dynamic> func)\r\n        {\r\n            var pipeline = new ErrorPipeline();\r\n            pipeline.AddItemToEndOfPipeline(func);\r\n            return pipeline;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Appends a new func to the ErrorPipeline.\r\n        /// </summary>\r\n        /// <param name=\"pipeline\">The pipeline.</param>\r\n        /// <param name=\"func\">The function.</param>\r\n        /// <returns>\r\n        /// The result of the operator.\r\n        /// </returns>\r\n        public static ErrorPipeline operator +(ErrorPipeline pipeline, Func<NancyContext, Exception, dynamic> func)\r\n        {\r\n            pipeline.AddItemToEndOfPipeline(func);\r\n            return pipeline;\r\n        }\r\n\r\n\r\n        /// <summary>\r\n        /// Appends the items of an ErrorPipeline to the other.\r\n        /// </summary>\r\n        /// <param name=\"pipelineToAddTo\">The pipeline to add to.</param>\r\n        /// <param name=\"pipelineToAdd\">The pipeline to add.</param>\r\n        /// <returns>\r\n        /// The result of the operator.\r\n        /// </returns>\r\n        public static ErrorPipeline operator +(ErrorPipeline pipelineToAddTo, ErrorPipeline pipelineToAdd)\r\n        {\r\n            foreach (var pipelineItem in pipelineToAdd.PipelineItems)\r\n            {\r\n                pipelineToAddTo.AddItemToEndOfPipeline(pipelineItem);\r\n            }\r\n\r\n            return pipelineToAddTo;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Invoke the pipeline. Each item will be invoked in turn until either an\r\n        /// item returns a Response, or all items have been invoked.\r\n        /// </summary>\r\n        /// <param name=\"context\">\r\n        /// The current context to pass to the items.\r\n        /// </param>\r\n        /// <param name=\"ex\">\r\n        /// The exception currently being handled by the error pipeline\r\n        /// </param>\r\n        /// <returns>\r\n        /// Response from an item invocation, or null if no response was generated.\r\n        /// </returns>\r\n        public dynamic Invoke(NancyContext context, Exception ex)\r\n        {\r\n            dynamic returnValue = null;\r\n\r\n            using (var enumerator = this.PipelineDelegates.GetEnumerator())\r\n            {\r\n                while (returnValue == null && enumerator.MoveNext())\r\n                {\r\n                    returnValue = enumerator.Current.Invoke(context, ex);\r\n                }\r\n            }\r\n\r\n            return returnValue;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Extensions/AssemblyExtensions.cs",
    "content": "namespace Nancy.Extensions\r\n{\r\n    using System;\r\n    using System.IO;\r\n    using System.Reflection;\r\n\r\n    /// <summary>\r\n    /// Assembly extension methods\r\n    /// </summary>\r\n    public static class AssemblyExtensions\r\n    {\r\n        /// <summary>\r\n        /// Gets exported types from an assembly and catches common errors\r\n        /// that occur when running under test runners.\r\n        /// </summary>\r\n        /// <param name=\"assembly\">Assembly to retrieve from</param>\r\n        /// <returns>An array of types</returns>\r\n        public static Type[] SafeGetExportedTypes(this Assembly assembly)\r\n        {\r\n            Type[] types;\r\n\r\n            try\r\n            {\r\n                types = assembly.GetExportedTypes();\r\n            }\r\n            catch (FileNotFoundException)\r\n            {\r\n                types = ArrayCache.Empty<Type>();\r\n            }\r\n            catch (NotSupportedException)\r\n            {\r\n                types = ArrayCache.Empty<Type>();\r\n            }\r\n            catch (FileLoadException) {\r\n                // probably assembly version conflict\r\n                types = ArrayCache.Empty<Type>();\r\n            }\r\n            return types;\r\n        }\r\n\r\n#if !CORE\r\n        /// <summary>\r\n        /// Indicates if a given assembly references another which is identified by its name.\r\n        /// </summary>\r\n        /// <param name=\"assembly\">The assembly which will be probed.</param>\r\n        /// <param name=\"referenceName\">The reference assembly name.</param>\r\n        /// <returns>A boolean value indicating if there is a reference.</returns>\r\n        public static bool IsReferencing(this Assembly assembly, AssemblyName referenceName)\r\n        {\r\n            if (AssemblyName.ReferenceMatchesDefinition(assembly.GetName(), referenceName))\r\n            {\r\n                return true;\r\n            }\r\n\r\n            foreach (var referencedAssemblyName in assembly.GetReferencedAssemblies())\r\n            {\r\n                if (AssemblyName.ReferenceMatchesDefinition(referencedAssemblyName, referenceName))\r\n                {\r\n                    return true;\r\n                }\r\n            }\r\n\r\n            return false;\r\n        }\r\n#endif\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Extensions/CollectionExtensions.cs",
    "content": "﻿namespace Nancy.Extensions\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Collections.Specialized;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Containing extensions for the collection objects.\r\n    /// </summary>\r\n    public static class CollectionExtensions\r\n    {\r\n        /// <summary>\r\n        /// Converts a <see cref=\"NameValueCollection\"/> to a <see cref=\"IDictionary{TKey,TValue}\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"source\">The <see cref=\"NameValueCollection\"/> to convert.</param>\r\n        /// <returns>An <see cref=\"IDictionary{TKey,TValue}\"/> instance.</returns>\r\n        public static IDictionary<string, IEnumerable<string>> ToDictionary(this NameValueCollection source)\r\n        {\r\n            return source.AllKeys.ToDictionary<string, string, IEnumerable<string>>(key => key, source.GetValues);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Converts an <see cref=\"IDictionary{TKey,TValue}\"/> instance to a <see cref=\"NameValueCollection\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"source\">The <see cref=\"IDictionary{TKey,TValue}\"/> instance to convert.</param>\r\n        /// <returns>A <see cref=\"NameValueCollection\"/> instance.</returns>\r\n        public static NameValueCollection ToNameValueCollection(this IDictionary<string, IEnumerable<string>> source)\r\n        {\r\n            var collection = new NameValueCollection();\r\n\r\n            foreach (var key in source.Keys)\r\n            {\r\n                foreach (var value in source[key])\r\n                {\r\n                    collection.Add(key, value);\r\n                }\r\n            }\r\n\r\n            return collection;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Merges a collection of <see cref=\"IDictionary{TKey,TValue}\"/> instances into a single one.\r\n        /// </summary>\r\n        /// <param name=\"dictionaries\">The list of <see cref=\"IDictionary{TKey,TValue}\"/> instances to merge.</param>\r\n        /// <returns>An <see cref=\"IDictionary{TKey,TValue}\"/> instance containing the keys and values from the other instances.</returns>\r\n        public static IDictionary<string, string> Merge(this IEnumerable<IDictionary<string, string>> dictionaries)\r\n        {\r\n            var output =\r\n                new Dictionary<string, string>(StaticConfiguration.CaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase);\r\n\r\n            foreach (var dictionary in dictionaries.Where(d => d != null))\r\n            {\r\n                foreach (var kvp in dictionary)\r\n                {\r\n                    if (!output.ContainsKey(kvp.Key))\r\n                    {\r\n                        output.Add(kvp.Key, kvp.Value);\r\n                    }\r\n                }\r\n            }\r\n\r\n            return output;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Filters a collection based on a provided key selector.\r\n        /// </summary>\r\n        /// <param name=\"source\">The collection filter.</param>\r\n        /// <param name=\"keySelector\">The predicate to filter by.</param>\r\n        /// <typeparam name=\"TSource\">The type of the collection to filter.</typeparam>\r\n        /// <typeparam name=\"TKey\">The type of the key to filter by.</typeparam>\r\n        /// <returns>A <see cref=\"IEnumerable{T}\"/> instance with the filtered values.</returns>\r\n        public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)\r\n        {\r\n            var knownKeys = new HashSet<TKey>();\r\n\r\n            foreach (TSource element in source)\r\n            {\r\n                if (knownKeys.Add(keySelector(element)))\r\n                {\r\n                    yield return element;\r\n                }\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Extensions/ContextExtensions.cs",
    "content": "namespace Nancy.Extensions\r\n{\r\n    using System;\r\n    using System.Text;\r\n\r\n    using Nancy.Responses;\r\n\r\n    /// <summary>\r\n    /// Containing extensions for the <see cref=\"NancyContext\"/> object\r\n    /// </summary>\r\n    public static class ContextExtensions\r\n    {\r\n        /// <summary>\r\n        /// Ascertains if a request originated from an Ajax request or not.\r\n        /// </summary>\r\n        /// <param name=\"context\">The current nancy context</param>\r\n        /// <returns>True if the request was done using ajax, false otherwise</returns>\r\n        public static bool IsAjaxRequest(this NancyContext context)\r\n        {\r\n            return context.Request != null && context.Request.IsAjaxRequest();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Expands a path to take into account a base path (if any)\r\n        /// </summary>\r\n        /// <param name=\"context\">Nancy context</param>\r\n        /// <param name=\"path\">Path to expand</param>\r\n        /// <returns>Expanded path</returns>\r\n        public static string ToFullPath(this NancyContext context, string path)\r\n        {\r\n            if (string.IsNullOrEmpty(path))\r\n            {\r\n                return path;\r\n            }\r\n\r\n            if (context.Request == null)\r\n            {\r\n                return path.TrimStart('~');\r\n            }\r\n\r\n            if (string.IsNullOrEmpty(context.Request.Url.BasePath))\r\n            {\r\n                return path.TrimStart('~');\r\n            }\r\n\r\n            if (!path.StartsWith(\"~/\"))\r\n            {\r\n                return path;\r\n            }\r\n\r\n            return string.Format(\"{0}{1}\", context.Request.Url.BasePath, path.TrimStart('~'));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns a redirect response with the redirect path expanded to take into\r\n        /// account a base path (if any)\r\n        /// </summary>\r\n        /// <param name=\"context\">Nancy context</param>\r\n        /// <param name=\"path\">Path to redirect to</param>\r\n        /// <returns>Redirect response</returns>\r\n        public static RedirectResponse GetRedirect(this NancyContext context, string path)\r\n        {\r\n            return new RedirectResponse(context.ToFullPath(path));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Retrieves exception details from the context, if any exist\r\n        /// </summary>\r\n        /// <param name=\"context\">Nancy context</param>\r\n        /// <returns>Exception details</returns>\r\n        public static string GetExceptionDetails(this NancyContext context)\r\n        {\r\n            object errorObject;\r\n            context.Items.TryGetValue(NancyEngine.ERROR_KEY, out errorObject);\r\n\r\n            return (errorObject as string) ?? string.Empty;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get a thrown exception from the context.\r\n        /// </summary>\r\n        /// <param name=\"context\">The context.</param>\r\n        /// <returns>The thrown exception or <c>null</c> if not exception has been thrown.</returns>\r\n        public static Exception GetException(this NancyContext context)\r\n        {\r\n            return GetException<Exception>(context);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get a thrown exception of the given type from the context.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The type of exception to get.</typeparam>\r\n        /// <param name=\"context\">The context.</param>\r\n        /// <returns>The thrown exception or <c>null</c> if not exception has been thrown.</returns>\r\n        public static T GetException<T>(this NancyContext context) where T : Exception\r\n        {\r\n            T exception;\r\n            return TryGetException(context, out exception) ? exception : null;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tries to get a thrown exception from the context.\r\n        /// </summary>\r\n        /// <param name=\"context\">The context.</param>\r\n        /// <param name=\"exception\">The thrown exception.</param>\r\n        /// <returns><c>true</c> if an exception has been thrown during the request, <c>false</c> otherwise.</returns>\r\n        public static bool TryGetException(this NancyContext context, out Exception exception)\r\n        {\r\n            return TryGetException<Exception>(context, out exception);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tries to get a thrown exception of the given type from the context.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The type of exception to get.</typeparam>\r\n        /// <param name=\"context\">The context.</param>\r\n        /// <param name=\"exception\">The thrown exception.</param>\r\n        /// <returns><c>true</c> if an exception of the given type has been thrown during the request, <c>false</c> otherwise.</returns>\r\n        public static bool TryGetException<T>(this NancyContext context, out T exception) where T : Exception\r\n        {\r\n            object exceptionObject;\r\n            if (context.Items.TryGetValue(NancyEngine.ERROR_EXCEPTION, out exceptionObject) && exceptionObject is T)\r\n            {\r\n                exception = exceptionObject as T;\r\n                return true;\r\n            }\r\n\r\n            exception = null;\r\n            return false;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Shortcut extension method for writing trace information\r\n        /// </summary>\r\n        /// <param name=\"context\">Nancy context</param>\r\n        /// <param name=\"logDelegate\">Log delegate</param>\r\n        public static void WriteTraceLog(this NancyContext context, Action<StringBuilder> logDelegate)\r\n        {\r\n            context.Trace.TraceLog.WriteLog(logDelegate);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns a boolean indicating whether a given url string is local or not\r\n        /// </summary>\r\n        /// <param name=\"context\">Nancy context</param>\r\n        /// <param name=\"url\">Url string (relative or absolute)</param>\r\n        /// <returns>True if local, false otherwise</returns>\r\n        public static bool IsLocalUrl(this NancyContext context, string url)\r\n        {\r\n            if (string.IsNullOrEmpty(url))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            if (!Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            Uri uri;\r\n            if (Uri.TryCreate(url, UriKind.Absolute, out uri))\r\n            {\r\n                var currentHostName = context.Request.Url.HostName;\r\n\r\n                // Mono does not populate the uri.Host correctly when url\r\n                // is in //hostname format causing the simple check to fail.\r\n                if (uri.Scheme.Equals(\"file\"))\r\n                {\r\n                    var localFormat = string.Format(\"//{0}\", currentHostName);\r\n                    return !url.StartsWith(\"//\") || url.StartsWith(localFormat);\r\n                }\r\n\r\n                return uri.Host == currentHostName;\r\n            }\r\n\r\n            return Uri.TryCreate(url, UriKind.Relative, out uri);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Extensions/MemoryStreamExtensions.cs",
    "content": "﻿namespace Nancy.Extensions\r\n{\r\n    using System;\r\n    using System.IO;\r\n\r\n    /// <summary>\r\n    /// Extensions for <see cref=\"MemoryStream\"/>\r\n    /// </summary>\r\n    public static class MemoryStreamExtensions\r\n    {\r\n        /// <summary>\r\n        /// Gets the buffer segment.\r\n        /// </summary>\r\n        /// <param name=\"stream\">The memory stream.</param>\r\n        /// <returns>Buffer segment as bytes</returns>\r\n        public static ArraySegment<byte> GetBufferSegment(this MemoryStream stream)\r\n        {\r\n#if NETSTANDARD2_0\r\n            ArraySegment<byte> buffer;\r\n            if (stream.TryGetBuffer(out buffer))\r\n            {\r\n                return buffer;\r\n            }\r\n#endif\r\n            var bytes = stream.GetBytes();\r\n\r\n            return new ArraySegment<byte>(bytes, 0, bytes.Length);\r\n        }\r\n\r\n        private static byte[] GetBytes(this MemoryStream stream)\r\n        {\r\n#if NETSTANDARD2_0\r\n            return stream.ToArray(); // This is all we have if TryGetBuffer fails in GetBufferSegment\r\n#else\r\n            return stream.GetBuffer();\r\n#endif\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Extensions/ModelValidationErrorExtensions.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using Nancy.Validation;\r\n\r\n    /// <summary>\r\n    /// Containing extensions for the <see cref=\"ModelValidationResult.Errors\"/> property.\r\n    /// </summary>\r\n    public static class ModelValidationResultExtensions\r\n    {\r\n        /// <summary>\r\n        /// Adds a new <see cref=\"ModelValidationError\"/> to the validation results.\r\n        /// </summary>\r\n        /// <param name=\"errors\">A reference to the <see cref=\"ModelValidationResult.Errors\"/> property.</param>\r\n        /// <param name=\"name\">The name of the property.</param>\r\n        /// <param name=\"errorMessage\">The validation error message.</param>\r\n        /// <returns>A reference to the <see cref=\"ModelValidationResult.Errors\"/> property.</returns>\r\n        public static IDictionary<string, IList<ModelValidationError>> Add(this IDictionary<string, IList<ModelValidationError>> errors, string name, string errorMessage)\r\n        {\r\n            IList<ModelValidationError> value;\r\n            if (!errors.TryGetValue(name, out value))\r\n            {\r\n                value = new List<ModelValidationError>();\r\n                errors[name] = value;\r\n            }\r\n\r\n            value.Add(new ModelValidationError(name, errorMessage));\r\n\r\n            return errors;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Extensions/ModuleExtensions.cs",
    "content": "namespace Nancy.Extensions\r\n{\r\n    using System;\r\n    using Nancy.ErrorHandling;\r\n\r\n    /// <summary>\r\n    /// Containing extensions for <see cref=\"INancyModule\"/> implementations.\r\n    /// </summary>\r\n    public static class ModuleExtensions\r\n    {\r\n        /// <summary>\r\n        /// Extracts the friendly name of a Nancy module given its type.\r\n        /// </summary>\r\n        /// <param name=\"module\">The module instance</param>\r\n        /// <returns>A string containing the name of the parameter.</returns>\r\n        public static string GetModuleName(this INancyModule module)\r\n        {\r\n            var typeName = module.GetType().Name;\r\n\r\n            var offset = typeName.LastIndexOf(\"Module\", StringComparison.Ordinal);\r\n\r\n            if (offset <= 0)\r\n            {\r\n                return typeName;\r\n            }\r\n\r\n            return typeName.Substring(0, offset);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns a boolean indicating whether the route is executing, or whether the module is\r\n        /// being constructed.\r\n        /// </summary>\r\n        /// <param name=\"module\">The module instance</param>\r\n        /// <returns>True if the route is being executed, false if the module is being constructed</returns>\r\n        public static bool RouteExecuting(this INancyModule module)\r\n        {\r\n            return module.Context != null;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds the before delegate to the Before pipeline if the module is not currently executing,\r\n        /// or executes the delegate directly and returns any response returned if it is.\r\n        /// Uses <see cref=\"RouteExecutionEarlyExitException\"/>\r\n        /// </summary>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <param name=\"beforeDelegate\">Delegate to add or execute</param>\r\n        /// <param name=\"earlyExitReason\">Optional reason for the early exit (if necessary)</param>\r\n        public static void AddBeforeHookOrExecute(this INancyModule module, Func<NancyContext, Response> beforeDelegate, string earlyExitReason = null)\r\n        {\r\n            if (module.RouteExecuting())\r\n            {\r\n                var result = beforeDelegate.Invoke(module.Context);\r\n\r\n                if (result != null)\r\n                {\r\n                    throw new RouteExecutionEarlyExitException(result, earlyExitReason);\r\n                }\r\n            }\r\n            else\r\n            {\r\n                module.Before.AddItemToEndOfPipeline(beforeDelegate);\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Extensions/ObjectExtensions.cs",
    "content": "namespace Nancy.Extensions\r\n{\r\n    using System.Collections.Generic;\r\n    using System.Dynamic;\r\n    using System.Reflection;\r\n\r\n    /// <summary>\r\n    /// Contains extensions to <see cref=\"object\"/> class.\r\n    /// </summary>\r\n    public static class ObjectExtensions\r\n    {\r\n        /// <summary>\r\n        /// Convert an object to a dynamic type\r\n        /// </summary>\r\n        /// <param name=\"value\">An object to convert to dynamic</param>\r\n        /// <returns>Returns a dynamic version of the specified type</returns>\r\n        public static dynamic ToDynamic(this object value)\r\n        {\r\n            var expando = new ExpandoObject() as IDictionary<string, object>;\r\n\r\n            foreach (var property in value.GetType().GetTypeInfo().DeclaredProperties)\r\n            {\r\n                expando.Add(property.Name, property.GetValue(value));\r\n            }\r\n\r\n            return (ExpandoObject)expando;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Extensions/RequestExtensions.cs",
    "content": "﻿namespace Nancy.Extensions\r\n{\r\n    using System;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Containing extensions for the <see cref=\"Request\"/> object\r\n    /// </summary>\r\n    public static class RequestExtensions\r\n    {\r\n        /// <summary>\r\n        /// An extension method making it easy to check if the request was done using ajax\r\n        /// </summary>\r\n        /// <param name=\"request\">The request made by client</param>\r\n        /// <returns><see langword=\"true\" /> if the request was done using ajax, otherwise <see langword=\"false\"/>.</returns>\r\n        public static bool IsAjaxRequest(this Request request)\r\n        {\r\n            const string ajaxRequestHeaderKey = \"X-Requested-With\";\r\n            const string ajaxRequestHeaderValue = \"XMLHttpRequest\";\r\n\r\n            return request.Headers[ajaxRequestHeaderKey].Contains(ajaxRequestHeaderValue);\r\n        }\r\n        /// <summary>\r\n        /// Gets a value indicating whether the request is local.\r\n        /// </summary>\r\n        /// <param name=\"request\">The request made by client</param>\r\n        /// <returns><see langword=\"true\" /> if the request is local, otherwise <see langword=\"false\"/>.</returns>\r\n        public static bool IsLocal(this Request request)\r\n        {\r\n            var userHostAddress = request.UserHostAddress;\r\n\r\n            if (!string.IsNullOrEmpty(userHostAddress))\r\n            {\r\n                if (userHostAddress.Equals(\"127.0.0.1\"))\r\n                {\r\n                    return true;\r\n                }\r\n\r\n                if (userHostAddress.Equals(\"::1\"))\r\n                {\r\n                    return true;\r\n                }\r\n            }\r\n\r\n            var url = request.Url;\r\n\r\n            if (string.IsNullOrEmpty(url))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            Uri uri;\r\n            if (Uri.TryCreate(url, UriKind.Absolute, out uri))\r\n            {\r\n                return uri.IsLoopback;\r\n            }\r\n\r\n            // Invalid or relative Request.Url string\r\n            return false;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Extensions/StreamExtensions.cs",
    "content": "﻿namespace Nancy.Extensions\r\n{\r\n    using System.IO;\r\n    using System.Text;\r\n\r\n    /// <summary>\r\n    /// Extensions for Stream.\r\n    /// </summary>\r\n    public static class StreamExtensions\r\n    {\r\n        internal const int BufferSize = 4096;\r\n\r\n        /// <summary>\r\n        /// Gets the request body as a string.\r\n        /// </summary>\r\n        /// <param name=\"stream\">The request body stream.</param>\r\n        /// <param name=\"encoding\">The encoding to use, <see cref=\"Encoding.UTF8\"/> by default.</param>\r\n        /// <returns>The request body as a <see cref=\"string\"/>.</returns>\r\n        public static string AsString(this Stream stream, Encoding encoding = null)\r\n        {\r\n            using (var reader = new StreamReader(stream, encoding ?? Encoding.UTF8, true, BufferSize, true))\r\n            {\r\n                if (stream.CanSeek)\r\n                {\r\n                    var initialPosition = stream.Position;\r\n\r\n                    stream.Position = 0;\r\n\r\n                    var content = reader.ReadToEnd();\r\n\r\n                    stream.Position = initialPosition;\r\n\r\n                    return content;\r\n                }\r\n                return string.Empty;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Extensions/StringExtensions.cs",
    "content": "namespace Nancy.Extensions\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Diagnostics;\r\n    using System.Linq;\r\n    using System.Text.RegularExpressions;\r\n\r\n    using Nancy.Helpers;\r\n    using Nancy.Routing;\r\n\r\n    /// <summary>\r\n    /// Containing extensions for the <see cref=\"string\"/> object.\r\n    /// </summary>\r\n    public static class StringExtensions\r\n    {\r\n        /// <summary>\r\n        /// A regular expression used to manipulate parameterized route segments.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"Regex\"/> object.</value>\r\n        [DebuggerBrowsable(DebuggerBrowsableState.Never)]\r\n        private static readonly Regex ParameterExpression =\r\n            new Regex(@\"{(?<name>[A-Za-z0-9_]*)(?:\\?(?<default>[A-Za-z0-9_-]*))?}\", RegexOptions.Compiled);\r\n\r\n        /// <summary>\r\n        /// Extracts information about the parameters in the <paramref name=\"segment\"/>.\r\n        /// </summary>\r\n        /// <param name=\"segment\">The segment that the information should be extracted from.</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/>, containing <see cref=\"ParameterSegmentInformation\"/> instances for the parameters in the segment.</returns>\r\n        public static IEnumerable<ParameterSegmentInformation> GetParameterDetails(this string segment)\r\n        {\r\n            var matches = ParameterExpression\r\n                .Matches(segment);\r\n\r\n            var nameMatch = matches\r\n                .Cast<Match>()\r\n                .ToList();\r\n\r\n            return nameMatch.Select(x => new ParameterSegmentInformation(x.Groups[\"name\"].Value, x.Groups[\"default\"].Value, x.Groups[\"default\"].Success));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Checks if a segment contains any parameters.\r\n        /// </summary>\r\n        /// <param name=\"segment\">The segment to check for parameters.</param>\r\n        /// <returns>true if the segment contains a parameter; otherwise false.</returns>\r\n        /// <remarks>A parameter is defined as a string which is surrounded by a pair of curly brackets.</remarks>\r\n        /// <exception cref=\"ArgumentException\">The provided value for the segment parameter was null or empty.</exception>\r\n        public static bool IsParameterized(this string segment)\r\n        {\r\n            var parameterMatch =\r\n                ParameterExpression.Match(segment);\r\n\r\n            return parameterMatch.Success;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a dynamic dictionary back from a Uri query string\r\n        /// </summary>\r\n        /// <param name=\"queryString\">The query string to extract values from</param>\r\n        /// <returns>A dynamic dictionary containing the query string values</returns>\r\n        public static DynamicDictionary AsQueryDictionary(this string queryString)\r\n        {\r\n            var coll = HttpUtility.ParseQueryString(queryString);\r\n            var ret = new DynamicDictionary(GlobalizationConfiguration.Default);\r\n\r\n            var found = 0;\r\n            foreach (var key in coll.AllKeys.Where(key => key != null))\r\n            {\r\n                ret[key] = coll[key];\r\n\r\n                found++;\r\n\r\n                if (found >= StaticConfiguration.RequestQueryFormMultipartLimit)\r\n                {\r\n                    break;\r\n                }\r\n            }\r\n\r\n            return ret;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Converts the value from PascalCase to camelCase.\r\n        /// </summary>\r\n        /// <param name=\"value\">The value.</param>\r\n        /// <returns>System.String.</returns>\r\n        public static string ToCamelCase(this string value)\r\n        {\r\n            return value.ConvertFirstCharacter(x => x.ToLowerInvariant());\r\n        }\r\n\r\n        /// <summary>\r\n        /// Converts the value from camelCase to PascalCase.\r\n        /// </summary>\r\n        /// <param name=\"value\">The value.</param>\r\n        /// <returns>System.String.</returns>\r\n        public static string ToPascalCase(this string value)\r\n        {\r\n            return value.ConvertFirstCharacter(x => x.ToUpperInvariant());\r\n        }\r\n\r\n        private static string ConvertFirstCharacter(this string value, Func<string, string> converter)\r\n        {\r\n            if (string.IsNullOrEmpty(value))\r\n            {\r\n                return string.Empty;\r\n            }\r\n\r\n            return string.Concat(converter(value.Substring(0, 1)), value.Substring(1));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Extensions/TypeExtensions.cs",
    "content": "﻿namespace Nancy.Extensions\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    \r\n    /// <summary>\r\n    /// Containing extensions for the <see cref=\"Type\"/> object.\r\n    /// </summary>\r\n    public static class TypeExtensions\r\n    {\r\n        /// <summary>\r\n        /// Creates an instance of <paramref name=\"type\"/> and cast it to <typeparamref name=\"T\"/>.\r\n        /// </summary>\r\n        /// <param name=\"type\">The type to create an instance of.</param>\r\n        /// <param name=\"nonPublic\"><see langword=\"true\"/> if a non-public constructor can be used, otherwise <see langword=\"false\"/>.</param>\r\n        public static T CreateInstance<T>(this Type type, bool nonPublic = false)\r\n        {\r\n            if (!typeof(T).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()))\r\n            {\r\n                throw new InvalidOperationException(\"Unable to create instance of \" + type.GetTypeInfo().FullName + \"since it can't be cast to \" + typeof(T).GetTypeInfo().FullName);\r\n            }\r\n\r\n            return (T)CreateInstance(type, nonPublic);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates an instance of <paramref name=\"type\"/>.\r\n        /// </summary>\r\n        /// <param name=\"type\">The type to create an instance of.</param>\r\n        /// <param name=\"nonPublic\"><see langword=\"true\"/> if a non-public constructor can be used, otherwise <see langword=\"false\"/>.</param>\r\n        public static object CreateInstance(this Type type, bool nonPublic = false)\r\n        {\r\n            return CreateInstanceInternal(type, nonPublic);\r\n        }\r\n\r\n        /// <summary>\r\n        /// returns the assembly that the type belongs to\r\n        /// </summary>\r\n        /// <param name=\"source\"></param>\r\n        /// <returns> The assembly that contains the type </returns>\r\n        public static Assembly GetAssembly(this Type source)\r\n        {\r\n            return source.GetTypeInfo().Assembly;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Checks if a type is an array or not\r\n        /// </summary>\r\n        /// <param name=\"source\">The type to check.</param>\r\n        /// <returns><see langword=\"true\" /> if the type is an array, otherwise <see langword=\"false\" />.</returns>\r\n        public static bool IsArray(this Type source)\r\n        {\r\n\r\n            return source.GetTypeInfo().BaseType == typeof(Array);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determines whether the <paramref name=\"genericType\"/> is assignable from\r\n        /// <paramref name=\"givenType\"/> taking into account generic definitions\r\n        /// </summary>\r\n        /// <remarks>\r\n        /// Borrowed from: http://tmont.com/blargh/2011/3/determining-if-an-open-generic-type-isassignablefrom-a-type\r\n        /// </remarks>\r\n        public static bool IsAssignableToGenericType(this Type givenType, Type genericType)\r\n        {\r\n            if (givenType == null || genericType == null)\r\n            {\r\n                return false;\r\n            }\r\n            return givenType == genericType\r\n                || givenType.MapsToGenericTypeDefinition(genericType)\r\n                || givenType.HasInterfaceThatMapsToGenericTypeDefinition(genericType)\r\n                || givenType.GetTypeInfo().BaseType.IsAssignableToGenericType(genericType);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Checks if a type is an collection or not\r\n        /// </summary>\r\n        /// <param name=\"source\">The type to check.</param>\r\n        /// <returns><see langword=\"true\" /> if the type is an collection, otherwise <see langword=\"false\" />.</returns>\r\n        public static bool IsCollection(this Type source)\r\n        {\r\n            var collectionType = typeof(ICollection<>);\r\n\r\n            return source.GetTypeInfo().IsGenericType && source\r\n                .GetInterfaces()\r\n                .Any(i => i.GetTypeInfo().IsGenericType && i.GetGenericTypeDefinition() == collectionType);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Checks if a type is enumerable or not\r\n        /// </summary>\r\n        /// <param name=\"source\">The type to check.</param>\r\n        /// <returns><see langword=\"true\" /> if the type is an enumerable, otherwise <see langword=\"false\" />.</returns>\r\n        public static bool IsEnumerable(this Type source)\r\n        {\r\n            var enumerableType = typeof(IEnumerable<>);\r\n\r\n            return source.GetTypeInfo().IsGenericType && source.GetGenericTypeDefinition() == enumerableType;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determines if a type is numeric.  Nullable numeric types are considered numeric.\r\n        /// </summary>\r\n        /// <remarks>\r\n        /// Boolean is not considered numeric.\r\n        /// </remarks>\r\n        public static bool IsNumeric(this Type source)\r\n        {\r\n            if (source == null)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            var underlyingType = Nullable.GetUnderlyingType(source) ?? source;\r\n\r\n            if (underlyingType.GetTypeInfo().IsEnum)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            switch (underlyingType.GetTypeCode())\r\n            {\r\n                case TypeCode.Byte:\r\n                case TypeCode.Decimal:\r\n                case TypeCode.Double:\r\n                case TypeCode.Int16:\r\n                case TypeCode.Int32:\r\n                case TypeCode.Int64:\r\n                case TypeCode.SByte:\r\n                case TypeCode.Single:\r\n                case TypeCode.UInt16:\r\n                case TypeCode.UInt32:\r\n                case TypeCode.UInt64:\r\n                    return true;\r\n                default:\r\n                    return false;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Filters our all types not assignable to <typeparamref name=\"TType\"/>.\r\n        /// </summary>\r\n        /// <typeparam name=\"TType\">The type that all resulting <see cref=\"Type\"/> should be assignable to.</typeparam>\r\n        /// <param name=\"types\">An <see cref=\"IEnumerable{T}\"/> of <see cref=\"Type\"/> instances that should be filtered.</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"Type\"/> instances.</returns>\r\n        public static IEnumerable<Type> NotOfType<TType>(this IEnumerable<Type> types)\r\n        {\r\n            return types.Where(t => !typeof(TType).IsAssignableFrom(t));\r\n        }\r\n\r\n        private static bool HasInterfaceThatMapsToGenericTypeDefinition(this Type givenType, Type genericType)\r\n        {\r\n            return givenType\r\n                .GetInterfaces()\r\n                .Where(it => it.GetTypeInfo().IsGenericType)\r\n                .Any(it => it.GetGenericTypeDefinition() == genericType);\r\n        }\r\n\r\n        private static bool MapsToGenericTypeDefinition(this Type givenType, Type genericType)\r\n        {\r\n            return genericType.GetTypeInfo().IsGenericTypeDefinition\r\n                && givenType.GetTypeInfo().IsGenericType\r\n                && givenType.GetGenericTypeDefinition() == genericType;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the enum for type code.\r\n        /// </summary>\r\n        /// <param name=\"type\">The type.</param>\r\n        /// <returns>An enum value representing the type code.</returns>\r\n        public static TypeCode GetTypeCode(this Type type)\r\n        {\r\n            if (type == typeof(bool))\r\n                return TypeCode.Boolean;\r\n            else if (type == typeof(char))\r\n                return TypeCode.Char;\r\n            else if (type == typeof(sbyte))\r\n                return TypeCode.SByte;\r\n            else if (type == typeof(byte))\r\n                return TypeCode.Byte;\r\n            else if (type == typeof(short))\r\n                return TypeCode.Int16;\r\n            else if (type == typeof(ushort))\r\n                return TypeCode.UInt16;\r\n            else if (type == typeof(int))\r\n                return TypeCode.Int32;\r\n            else if (type == typeof(uint))\r\n                return TypeCode.UInt32;\r\n            else if (type == typeof(long))\r\n                return TypeCode.Int64;\r\n            else if (type == typeof(ulong))\r\n                return TypeCode.UInt64;\r\n            else if (type == typeof(float))\r\n                return TypeCode.Single;\r\n            else if (type == typeof(double))\r\n                return TypeCode.Double;\r\n            else if (type == typeof(decimal))\r\n                return TypeCode.Decimal;\r\n            else if (type == typeof(DateTime))\r\n                return TypeCode.DateTime;\r\n            else if (type == typeof(string))\r\n                return TypeCode.String;\r\n            else if (type.GetTypeInfo().IsEnum)\r\n                return GetTypeCode(Enum.GetUnderlyingType(type));\r\n            else\r\n                return TypeCode.Object;\r\n        }\r\n\r\n        private static object CreateInstanceInternal(Type type, bool nonPublic = false)\r\n        {\r\n#if !NETSTANDARD1_5\r\n            return Activator.CreateInstance(type, nonPublic);\r\n        }\r\n#else\r\n            var constructor = type.GetDefaultConstructor(nonPublic);\r\n\r\n            if (constructor == null)\r\n            {\r\n                throw new MissingMethodException(\"No parameterless constructor defined for this object.\");\r\n            }\r\n\r\n            return constructor.Invoke(Array.Empty<object>());\r\n        }\r\n\r\n        private static ConstructorInfo GetDefaultConstructor(this Type type, bool nonPublic = false)\r\n        {\r\n            var typeInfo = type.GetTypeInfo();\r\n\r\n            var constructors = typeInfo.DeclaredConstructors;\r\n\r\n            foreach (var constructor in constructors)\r\n            {\r\n                var parameters = constructor.GetParameters();\r\n\r\n                if (parameters.Length > 0)\r\n                {\r\n                    continue;\r\n                }\r\n\r\n                if (!constructor.IsPrivate || nonPublic)\r\n                {\r\n                    return constructor;\r\n                }\r\n            }\r\n\r\n            return null;\r\n        }\r\n#endif\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/FormatterExtensions.cs",
    "content": "namespace Nancy\r\n{\r\n    using System;\r\n    using System.IO;\r\n    using System.Text;\r\n    using Extensions;\r\n    using Responses;\r\n\r\n    /// <summary>\r\n    /// Various extensions to return different responses form a <see cref=\"NancyModule\"/>.\r\n    /// </summary>\r\n    public static class FormatterExtensions\r\n    {\r\n        private static ISerializer jsonSerializer;\r\n\r\n        private static ISerializer xmlSerializer;\r\n\r\n        /// <summary>\r\n        /// Sends the file at <paramref name=\"applicationRelativeFilePath\"/> to the\r\n        /// agent, using <paramref name=\"contentType\"/> for the <c>Content-Type</c> header.\r\n        /// </summary>\r\n        /// <param name=\"formatter\">The formatter.</param>\r\n        /// <param name=\"applicationRelativeFilePath\">The application relative file path.</param>\r\n        /// <param name=\"contentType\">Value for the <c>Content-Type</c> header.</param>\r\n        public static Response AsFile(this IResponseFormatter formatter, string applicationRelativeFilePath, string contentType)\r\n        {\r\n            return new GenericFileResponse(applicationRelativeFilePath, contentType, formatter.Context);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Sends the file at <paramref name=\"applicationRelativeFilePath\"/> to the\r\n        /// agent, using the file extension and <see cref=\"MimeTypes.GetMimeType\"/>\r\n        /// to determine the <c>Content-Type</c> header.\r\n        /// </summary>\r\n        /// <param name=\"formatter\">The formatter.</param>\r\n        /// <param name=\"applicationRelativeFilePath\">The application relative file path.</param>\r\n        public static Response AsFile(this IResponseFormatter formatter, string applicationRelativeFilePath)\r\n        {\r\n            return new GenericFileResponse(applicationRelativeFilePath, formatter.Context);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns the <paramref name=\"contents\"/> string to the\r\n        /// agent, using <paramref name=\"contentType\"/> and <paramref name=\"encoding\"/>\r\n        /// for the <c>Content-Type</c> header.\r\n        /// </summary>\r\n        /// <param name=\"formatter\">The formatter.</param>\r\n        /// <param name=\"contents\">The contents of the response.</param>\r\n        /// <param name=\"contentType\">Value for the <c>Content-Type</c> header.</param>\r\n        /// <param name=\"encoding\">The encoding to use.</param>\r\n        public static Response AsText(this IResponseFormatter formatter, string contents, string contentType, Encoding encoding)\r\n        {\r\n            return new TextResponse(contents, contentType, encoding);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns the <paramref name=\"contents\"/> string to the\r\n        /// agent, using <c>text/plain</c> and <paramref name=\"encoding\"/>\r\n        /// for the <c>Content-Type</c> header.\r\n        /// </summary>\r\n        /// <param name=\"formatter\">The formatter.</param>\r\n        /// <param name=\"contents\">The contents of the response.</param>\r\n        /// <param name=\"encoding\">The encoding to use.</param>\r\n        public static Response AsText(this IResponseFormatter formatter, string contents, Encoding encoding)\r\n        {\r\n            return new TextResponse(contents, encoding: encoding);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns the <paramref name=\"contents\"/> string to the\r\n        /// agent, using <paramref name=\"contentType\"/> for the <c>Content-Type</c> header.\r\n        /// </summary>\r\n        /// <param name=\"formatter\">The formatter.</param>\r\n        /// <param name=\"contents\">The contents of the response.</param>\r\n        /// <param name=\"contentType\">Value for the <c>Content-Type</c> header.</param>\r\n        public static Response AsText(this IResponseFormatter formatter, string contents, string contentType)\r\n        {\r\n            return new TextResponse(contents, contentType);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns the <paramref name=\"contents\"/> string as a <c>text/plain</c> response to the agent.\r\n        /// </summary>\r\n        /// <param name=\"formatter\">The formatter.</param>\r\n        /// <param name=\"contents\">The contents of the response.</param>\r\n        public static Response AsText(this IResponseFormatter formatter, string contents)\r\n        {\r\n            return new TextResponse(contents);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Serializes the <paramref name=\"model\"/> to JSON and returns it to the\r\n        /// agent, optionally using the <paramref name=\"statusCode\"/>.\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">The type of the model.</typeparam>\r\n        /// <param name=\"formatter\">The formatter.</param>\r\n        /// <param name=\"model\">The model to serialize.</param>\r\n        /// <param name=\"statusCode\">The HTTP status code. Defaults to <see cref=\"HttpStatusCode.OK\"/>.</param>\r\n        public static Response AsJson<TModel>(this IResponseFormatter formatter, TModel model, HttpStatusCode statusCode = HttpStatusCode.OK)\r\n        {\r\n            var serializer = jsonSerializer ?? (jsonSerializer = formatter.SerializerFactory.GetSerializer(\"application/json\"));\r\n\r\n            return new JsonResponse<TModel>(model, serializer, formatter.Environment)\r\n            {\r\n                StatusCode = statusCode\r\n            };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns a redirect response to the agent.\r\n        /// </summary>\r\n        /// <param name=\"formatter\">The formatter.</param>\r\n        /// <param name=\"location\">The location to redirect to.</param>\r\n        /// <param name=\"type\">The redirect type. See <see cref=\"RedirectResponse.RedirectType\"/>.</param>\r\n        public static Response AsRedirect(this IResponseFormatter formatter, string location, RedirectResponse.RedirectType type = RedirectResponse.RedirectType.SeeOther)\r\n        {\r\n            return new RedirectResponse(formatter.Context.ToFullPath(location), type);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Serializes the <paramref name=\"model\"/> to XML and returns it to the\r\n        /// agent, optionally using the <paramref name=\"statusCode\"/>.\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">The type of the model.</typeparam>\r\n        /// <param name=\"formatter\">The formatter.</param>\r\n        /// <param name=\"model\">The model to serialize.</param>\r\n        /// <param name=\"statusCode\">The HTTP status code. Defaults to <see cref=\"HttpStatusCode.OK\"/>.</param>\r\n        public static Response AsXml<TModel>(this IResponseFormatter formatter, TModel model, HttpStatusCode statusCode = HttpStatusCode.OK)\r\n        {\r\n            var serializer = xmlSerializer ?? (xmlSerializer = formatter.SerializerFactory.GetSerializer(\"application/xml\"));\r\n\r\n            return new XmlResponse<TModel>(model, serializer, formatter.Environment);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Writes the data from the given <paramref name=\"stream\"/> to the\r\n        /// agent, using <paramref name=\"contentType\"/> for the <c>Content-Type</c> header.\r\n        /// </summary>\r\n        /// <param name=\"formatter\">The formatter.</param>\r\n        /// <param name=\"stream\">The stream to copy from.</param>\r\n        /// <param name=\"contentType\">Value for the <c>Content-Type</c> header.</param>\r\n        public static Response FromStream(this IResponseFormatter formatter, Stream stream, string contentType)\r\n        {\r\n            return new StreamResponse(() => stream, contentType);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Invokes the given <paramref name=\"streamDelegate\"/> to write the stream data to the\r\n        /// agent, using <paramref name=\"contentType\"/> for the <c>Content-Type</c> header.\r\n        /// </summary>\r\n        /// <param name=\"formatter\">The formatter.</param>\r\n        /// <param name=\"streamDelegate\">A delegate returning a stream to copy from.</param>\r\n        /// <param name=\"contentType\">Value for the <c>Content-Type</c> header.</param>\r\n        public static Response FromStream(this IResponseFormatter formatter, Func<Stream> streamDelegate, string contentType)\r\n        {\r\n            return new StreamResponse(streamDelegate, contentType);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/GlobalizationConfiguration.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Globalization;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Globalization configuration\r\n    /// </summary>\r\n    public class GlobalizationConfiguration\r\n    {\r\n        /// <summary>\r\n        /// A default instance of the <see cref=\"GlobalizationConfiguration\"/> class\r\n        /// </summary>\r\n        public static readonly GlobalizationConfiguration Default = new GlobalizationConfiguration\r\n        {\r\n            SupportedCultureNames = new[] { CultureInfo.CurrentCulture.Name },\r\n            DefaultCulture = CultureInfo.CurrentCulture.Name,\r\n            DateTimeStyles = DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal\r\n        };\r\n\r\n        private GlobalizationConfiguration()\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"GlobalizationConfiguration\"/> class\r\n        /// </summary>\r\n        /// <param name=\"supportedCultureNames\">An array of supported cultures</param>\r\n        /// <param name=\"defaultCulture\">The default culture of the application</param>\r\n        /// <param name=\"dateTimeStyles\">The <see cref=\"DateTimeStyles\"/> that should be used for date parsing.</param>\r\n        public GlobalizationConfiguration(IEnumerable<string> supportedCultureNames, string defaultCulture = null, DateTimeStyles? dateTimeStyles = null)\r\n        {\r\n            if (supportedCultureNames == null)\r\n            {\r\n                throw new ConfigurationException(\"Invalid Globalization configuration. You must support at least one culture\");\r\n            }\r\n\r\n            supportedCultureNames = supportedCultureNames.Where(cultureName => !string.IsNullOrEmpty(cultureName)).ToArray();\r\n\r\n            if (!supportedCultureNames.Any())\r\n            {\r\n                throw new ConfigurationException(\"Invalid Globalization configuration. You must support at least one culture\");\r\n            }\r\n\r\n            if (string.IsNullOrEmpty(defaultCulture))\r\n            {\r\n                defaultCulture = supportedCultureNames.First();\r\n            }\r\n\r\n            if (!supportedCultureNames.Contains(defaultCulture, StringComparer.OrdinalIgnoreCase))\r\n            {\r\n                throw new ConfigurationException(\"Invalid Globalization configuration. \" + defaultCulture + \" does not exist in the supported culture names\");\r\n            }\r\n\r\n            this.DateTimeStyles = dateTimeStyles ?? Default.DateTimeStyles;\r\n            this.DefaultCulture = defaultCulture;\r\n            this.SupportedCultureNames = supportedCultureNames;\r\n        }\r\n\r\n        /// <summary>\r\n        /// The <see cref=\"DateTimeStyles\"/> that should be used for date parsing.\r\n        /// </summary>\r\n        public DateTimeStyles DateTimeStyles { get; private set; }\r\n\r\n        /// <summary>\r\n        /// The default culture for the application\r\n        /// </summary>\r\n        public string DefaultCulture { get; private set; }\r\n\r\n        /// <summary>\r\n        /// A set of supported cultures\r\n        /// </summary>\r\n        public IEnumerable<string> SupportedCultureNames { get; private set; }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/GlobalizationConfigurationExtensions.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using System.Collections.Generic;\r\n    using System.Globalization;\r\n    using Nancy.Configuration;\r\n\r\n    /// <summary>\r\n    /// Contains <see cref=\"GlobalizationConfiguration\"/> configuration extensions for <see cref=\"INancyEnvironment\"/>.\r\n    /// </summary>\r\n    public static class GlobalizationConfigurationExtensions\r\n    {\r\n        /// <summary>\r\n        /// Configures <see cref=\"GlobalizationConfiguration\"/>\r\n        /// </summary>\r\n        /// <param name=\"environment\">An <see cref=\"INancyEnvironment\"/> that should be configured.</param>\r\n        /// <param name=\"supportedCultureNames\">Cultures that the application can accept</param>\r\n        /// <param name=\"defaultCulture\">Used to set a default culture for the application</param>\r\n        /// <param name=\"dateTimeStyles\">The <see cref=\"DateTimeStyles\"/> that should be used for date parsing.</param>\r\n        /// <remarks>If defaultCulture not specified the first supported culture is used</remarks>\r\n        public static void Globalization(this INancyEnvironment environment, IEnumerable<string> supportedCultureNames, string defaultCulture = null, DateTimeStyles? dateTimeStyles = null)\r\n        {\r\n            environment.AddValue(new GlobalizationConfiguration(\r\n                supportedCultureNames: supportedCultureNames,\r\n                defaultCulture: defaultCulture,\r\n                dateTimeStyles: dateTimeStyles));\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/HeadResponse.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using System;\r\n    using System.Globalization;\r\n    using System.IO;\r\n    using System.Threading.Tasks;\r\n\r\n \t/// <summary>\r\n    /// Represents a HEAD only response.\r\n    /// </summary>\r\n    public class HeadResponse : Response\r\n    {\r\n        private const string ContentLength = \"Content-Length\";\r\n        private readonly Response innerResponse;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"HeadResponse\"/> class, with\r\n        /// the provided <paramref name=\"response\"/>.\r\n        /// </summary>\r\n        /// <param name=\"response\">\r\n        /// The full response to create the head response from.\r\n        /// </param>\r\n        public HeadResponse(Response response)\r\n        {\r\n            this.innerResponse = response;\r\n            this.Contents = stream =>\r\n            {\r\n                this.CheckAndSetContentLength(this.innerResponse);\r\n                GetStringContents(string.Empty)(stream);\r\n            };\r\n            this.ContentType = response.ContentType;\r\n            this.Headers = response.Headers;\r\n            this.StatusCode = response.StatusCode;\r\n            this.ReasonPhrase = response.ReasonPhrase;\r\n        }\r\n\r\n\r\n        /// <summary>\r\n        /// Executes at the end of the nancy execution pipeline and before control is passed back to the hosting.\r\n        /// Can be used to pre-render/validate views while still inside the main pipeline/error handling.\r\n        /// </summary>\r\n        /// <param name=\"context\">Nancy context</param>\r\n        /// <returns>\r\n        /// Task for completion/erroring\r\n        /// </returns>\r\n        public override Task PreExecute(NancyContext context)\r\n        {\r\n            return this.innerResponse.PreExecute(context);\r\n        }\r\n\r\n        private void CheckAndSetContentLength(Response response)\r\n        {\r\n            if (this.Headers.ContainsKey(ContentLength))\r\n            {\r\n                return;\r\n            }\r\n\r\n            using (var nullStream = new NullStream())\r\n            {\r\n                response.Contents.Invoke(nullStream);\r\n\r\n                this.Headers[ContentLength] = nullStream.Length.ToString(CultureInfo.InvariantCulture);\r\n            }\r\n\r\n        }\r\n\r\n        private sealed class NullStream : Stream\r\n        {\r\n            private int bytesWritten;\r\n\r\n            public override void Flush()\r\n            {\r\n            }\r\n\r\n#if !NETSTANDARD1_6\r\n            public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)\r\n            {\r\n                throw new NotSupportedException();\r\n            }\r\n\r\n            public override int EndRead(IAsyncResult asyncResult)\r\n            {\r\n                throw new NotSupportedException();\r\n            }\r\n#endif\r\n\r\n            public override long Seek(long offset, SeekOrigin origin)\r\n            {\r\n                throw new NotSupportedException();\r\n            }\r\n\r\n            public override void SetLength(long value)\r\n            {\r\n                throw new NotSupportedException();\r\n            }\r\n\r\n            public override int Read(byte[] buffer, int offset, int count)\r\n            {\r\n                throw new NotSupportedException();\r\n            }\r\n\r\n            public override int ReadByte()\r\n            {\r\n                throw new NotSupportedException();\r\n            }\r\n\r\n            public override void Write(byte[] buffer, int offset, int count)\r\n            {\r\n                // We assume we can't seek and can't overwrite, but don't throw just in case.\r\n                this.bytesWritten += count;\r\n            }\r\n\r\n            public override bool CanRead\r\n            {\r\n                get { return false; }\r\n            }\r\n\r\n            public override bool CanSeek\r\n            {\r\n                get { return false; }\r\n            }\r\n\r\n            public override bool CanTimeout\r\n            {\r\n                get { return false; }\r\n            }\r\n\r\n            public override bool CanWrite\r\n            {\r\n                get { return true; }\r\n            }\r\n\r\n            public override long Length\r\n            {\r\n                get { return this.bytesWritten; }\r\n            }\r\n\r\n            public override long Position\r\n            {\r\n                get { throw new NotSupportedException(); }\r\n                set { throw new NotSupportedException(); }\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Helpers/CacheHelpers.cs",
    "content": "﻿namespace Nancy.Helpers\r\n{\r\n    using System;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Helper class for caching related functions\r\n    /// </summary>\r\n    public static class CacheHelpers\r\n    {\r\n        /// <summary>\r\n        /// Returns whether to return a not modified response, based on the etag and last modified date\r\n        /// of the resource, and the current nancy context\r\n        /// </summary>\r\n        /// <param name=\"etag\">Current resource etag, or null</param>\r\n        /// <param name=\"lastModified\">Current resource last modified, or null</param>\r\n        /// <param name=\"context\">Current nancy context</param>\r\n        /// <returns>True if not modified should be sent, false otherwise</returns>\r\n        public static bool ReturnNotModified(string etag, DateTime? lastModified, NancyContext context)\r\n        {\r\n            if (context == null || context.Request == null)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            var requestEtag = context.Request.Headers.IfNoneMatch.FirstOrDefault();\r\n\r\n            if (requestEtag != null && !string.IsNullOrEmpty(etag))\r\n            {\r\n                return requestEtag.Equals(etag, StringComparison.Ordinal);\r\n            }\r\n\r\n            var requestDate = context.Request.Headers.IfModifiedSince;\r\n\r\n            if (requestDate.HasValue && lastModified.HasValue && ((int)(lastModified.Value - requestDate.Value).TotalSeconds) <= 0)\r\n            {\r\n                return true;\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Helpers/ExceptionExtensions.cs",
    "content": "﻿namespace Nancy.Helpers\r\n{\r\n    using System;\r\n\r\n    internal static class ExceptionExtensions\r\n    {\r\n        internal static Exception FlattenInnerExceptions(this Exception exception)\r\n        {\r\n            var aggregateException = exception as AggregateException;\r\n            if (aggregateException != null)\r\n            {\r\n                var flattenedAggregateException = aggregateException.Flatten();\r\n\r\n                //If we have more than one exception in the AggregateException\r\n                //we have to send all exceptions back in order not to swallow any exceptions.\r\n                if (flattenedAggregateException.InnerExceptions.Count > 1)\r\n                {\r\n                    return flattenedAggregateException;\r\n                }\r\n\r\n                return flattenedAggregateException.InnerException;\r\n            }\r\n\r\n            return exception;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Helpers/HttpEncoder.cs",
    "content": "//\r\n// Authors:\r\n//   Patrik Torstensson (Patrik.Torstensson@labs2.com)\r\n//   Wictor Wilén (decode/encode functions) (wictor@ibizkit.se)\r\n//   Tim Coleman (tim@timcoleman.com)\r\n//   Gonzalo Paniagua Javier (gonzalo@ximian.com)\r\n\r\n//   Marek Habersack <mhabersack@novell.com>\r\n//\r\n// (C) 2005-2010 Novell, Inc (http://novell.com/)\r\n//\r\n\r\n//\r\n// Permission is hereby granted, free of charge, to any person obtaining\r\n// a copy of this software and associated documentation files (the\r\n// \"Software\"), to deal in the Software without restriction, including\r\n// without limitation the rights to use, copy, modify, merge, publish,\r\n// distribute, sublicense, and/or sell copies of the Software, and to\r\n// permit persons to whom the Software is furnished to do so, subject to\r\n// the following conditions:\r\n//\r\n// The above copyright notice and this permission notice shall be\r\n// included in all copies or substantial portions of the Software.\r\n//\r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\r\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\r\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\r\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\r\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n//\r\n\r\nnamespace Nancy.Helpers\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Globalization;\r\n    using System.IO;\r\n    using System.Text;\r\n\r\n#if NET_4_0\r\n\tpublic\r\n#endif\r\n    class HttpEncoder\r\n    {\r\n        static char[] hexChars = \"0123456789abcdef\".ToCharArray();\r\n        static object entitiesLock = new object();\r\n        static SortedDictionary<string, char> entities;\r\n#if NET_4_0\r\n\t\tstatic Lazy <HttpEncoder> defaultEncoder;\r\n\t\tstatic Lazy <HttpEncoder> currentEncoderLazy;\r\n#else\r\n        static HttpEncoder defaultEncoder;\r\n#endif\r\n        static HttpEncoder currentEncoder;\r\n\r\n        static IDictionary<string, char> Entities\r\n        {\r\n            get\r\n            {\r\n                lock (entitiesLock)\r\n                {\r\n                    if (entities == null)\r\n                        InitEntities();\r\n\r\n                    return entities;\r\n                }\r\n            }\r\n        }\r\n\r\n        public static HttpEncoder Current\r\n        {\r\n            get\r\n            {\r\n#if NET_4_0\r\n\t\t\t\tif (currentEncoder == null)\r\n\t\t\t\t\tcurrentEncoder = currentEncoderLazy.Value;\r\n#endif\r\n                return currentEncoder;\r\n            }\r\n#if NET_4_0\r\n\t\t\tset {\r\n\t\t\t\tif (value == null)\r\n\t\t\t\t\tthrow new ArgumentNullException (\"value\");\r\n\t\t\t\tcurrentEncoder = value;\r\n\t\t\t}\r\n#endif\r\n        }\r\n\r\n        public static HttpEncoder Default\r\n        {\r\n            get\r\n            {\r\n#if NET_4_0\r\n\t\t\t\treturn defaultEncoder.Value;\r\n#else\r\n                return defaultEncoder;\r\n#endif\r\n            }\r\n        }\r\n\r\n        static HttpEncoder()\r\n        {\r\n#if NET_4_0\r\n\t\t\tdefaultEncoder = new Lazy <HttpEncoder> (() => new HttpEncoder ());\r\n\t\t\tcurrentEncoderLazy = new Lazy <HttpEncoder> (new Func <HttpEncoder> (GetCustomEncoderFromConfig));\r\n#else\r\n            defaultEncoder = new HttpEncoder();\r\n            currentEncoder = defaultEncoder;\r\n#endif\r\n        }\r\n\r\n        public HttpEncoder()\r\n        {\r\n        }\r\n#if NET_4_0\r\n\t\tprotected internal virtual\r\n#else\r\n        internal static\r\n#endif\r\n void HeaderNameValueEncode(string headerName, string headerValue, out string encodedHeaderName, out string encodedHeaderValue)\r\n        {\r\n            if (string.IsNullOrEmpty(headerName))\r\n                encodedHeaderName = headerName;\r\n            else\r\n                encodedHeaderName = EncodeHeaderString(headerName);\r\n\r\n            if (string.IsNullOrEmpty(headerValue))\r\n                encodedHeaderValue = headerValue;\r\n            else\r\n                encodedHeaderValue = EncodeHeaderString(headerValue);\r\n        }\r\n\r\n        static void StringBuilderAppend(string s, ref StringBuilder sb)\r\n        {\r\n            if (sb == null)\r\n                sb = new StringBuilder(s);\r\n            else\r\n                sb.Append(s);\r\n        }\r\n\r\n        static string EncodeHeaderString(string input)\r\n        {\r\n            StringBuilder sb = null;\r\n            char ch;\r\n\r\n            for (int i = 0; i < input.Length; i++)\r\n            {\r\n                ch = input[i];\r\n\r\n                if ((ch < 32 && ch != 9) || ch == 127)\r\n                    StringBuilderAppend(String.Format(\"%{0:x2}\", (int)ch), ref sb);\r\n            }\r\n\r\n            if (sb != null)\r\n                return sb.ToString();\r\n\r\n            return input;\r\n        }\r\n#if NET_4_0\r\n\t\tprotected internal virtual void HtmlAttributeEncode (string value, TextWriter output)\r\n\t\t{\r\n\r\n\t\t\tif (output == null)\r\n\t\t\t\tthrow new ArgumentNullException (\"output\");\r\n\r\n\t\t\tif (string.IsNullOrEmpty (value))\r\n\t\t\t\treturn;\r\n\r\n\t\t\toutput.Write (HtmlAttributeEncode (value));\r\n\t\t}\r\n\r\n\t\tprotected internal virtual void HtmlDecode (string value, TextWriter output)\r\n\t\t{\r\n\t\t\tif (output == null)\r\n\t\t\t\tthrow new ArgumentNullException (\"output\");\r\n\r\n\t\t\toutput.Write (HtmlDecode (value));\r\n\t\t}\r\n\r\n\t\tprotected internal virtual void HtmlEncode (string value, TextWriter output)\r\n\t\t{\r\n\t\t\tif (output == null)\r\n\t\t\t\tthrow new ArgumentNullException (\"output\");\r\n\r\n\t\t\toutput.Write (HtmlEncode (value));\r\n\t\t}\r\n\r\n\t\tprotected internal virtual byte[] UrlEncode (byte[] bytes, int offset, int count)\r\n\t\t{\r\n\t\t\treturn UrlEncodeToBytes (bytes, offset, count);\r\n\t\t}\r\n\r\n\t\tstatic HttpEncoder GetCustomEncoderFromConfig ()\r\n\t\t{\r\n\t\t\tvar cfg = HttpRuntime.Section;\r\n\t\t\tstring typeName = cfg.EncoderType;\r\n\r\n\t\t\tif (String.Compare (typeName, \"System.Web.Util.HttpEncoder\", StringComparison.OrdinalIgnoreCase) == 0)\r\n\t\t\t\treturn Default;\r\n\r\n\t\t\tType t = Type.GetType (typeName, false);\r\n\t\t\tif (t == null)\r\n\t\t\t\tthrow new ConfigurationErrorsException (String.Format (\"Could not load type '{0}'.\", typeName));\r\n\r\n\t\t\tif (!typeof (HttpEncoder).IsAssignableFrom (t))\r\n\t\t\t\tthrow new ConfigurationErrorsException (\r\n\t\t\t\t\tString.Format (\"'{0}' is not allowed here because it does not extend class 'System.Web.Util.HttpEncoder'.\", typeName)\r\n\t\t\t\t);\r\n\r\n\t\t\treturn Activator.CreateInstance (t, false) as HttpEncoder;\r\n\t\t}\r\n#endif\r\n#if NET_4_0\r\n\t\tprotected internal virtual\r\n#else\r\n        internal static\r\n#endif\r\n        string UrlPathEncode(string value)\r\n        {\r\n            if (string.IsNullOrEmpty(value))\r\n                return value;\r\n\r\n            MemoryStream result = new MemoryStream();\r\n            int length = value.Length;\r\n            for (int i = 0; i < length; i++)\r\n                UrlPathEncodeChar(value[i], result);\r\n\r\n            return Encoding.ASCII.GetString(result.ToArray());\r\n        }\r\n\r\n        internal static byte[] UrlEncodeToBytes(byte[] bytes, int offset, int count)\r\n        {\r\n            if (bytes == null)\r\n                throw new ArgumentNullException(\"bytes\");\r\n\r\n            int blen = bytes.Length;\r\n            if (blen == 0)\r\n                return ArrayCache.Empty<byte>();\r\n\r\n            if (offset < 0 || offset >= blen)\r\n                throw new ArgumentOutOfRangeException(\"offset\");\r\n\r\n            if (count < 0 || count > blen - offset)\r\n                throw new ArgumentOutOfRangeException(\"count\");\r\n\r\n            MemoryStream result = new MemoryStream(count);\r\n            int end = offset + count;\r\n            for (int i = offset; i < end; i++)\r\n                UrlEncodeChar((char)bytes[i], result, false);\r\n\r\n            return result.ToArray();\r\n        }\r\n\r\n        internal static string HtmlEncode(string s)\r\n        {\r\n            if (s == null)\r\n                return null;\r\n\r\n            if (s.Length == 0)\r\n                return String.Empty;\r\n\r\n            bool needEncode = false;\r\n            for (int i = 0; i < s.Length; i++)\r\n            {\r\n                char c = s[i];\r\n                if (c == '&' || c == '\"' || c == '<' || c == '>' || c > 159\r\n#if NET_4_0\r\n\t\t\t\t    || c == '\\''\r\n#endif\r\n)\r\n                {\r\n                    needEncode = true;\r\n                    break;\r\n                }\r\n            }\r\n\r\n            if (!needEncode)\r\n                return s;\r\n\r\n            StringBuilder output = new StringBuilder();\r\n            char ch;\r\n            int len = s.Length;\r\n\r\n            for (int i = 0; i < len; i++)\r\n            {\r\n                switch (s[i])\r\n                {\r\n                    case '&':\r\n                        output.Append(\"&amp;\");\r\n                        break;\r\n                    case '>':\r\n                        output.Append(\"&gt;\");\r\n                        break;\r\n                    case '<':\r\n                        output.Append(\"&lt;\");\r\n                        break;\r\n                    case '\"':\r\n                        output.Append(\"&quot;\");\r\n                        break;\r\n#if NET_4_0\r\n\t\t\t\t\tcase '\\'':\r\n\t\t\t\t\t\toutput.Append (\"&#39;\");\r\n\t\t\t\t\t\tbreak;\r\n#endif\r\n                    case '\\uff1c':\r\n                        output.Append(\"&#65308;\");\r\n                        break;\r\n\r\n                    case '\\uff1e':\r\n                        output.Append(\"&#65310;\");\r\n                        break;\r\n\r\n                    default:\r\n                        ch = s[i];\r\n                        if (ch > 159 && ch < 256)\r\n                        {\r\n                            output.Append(\"&#\");\r\n                            output.Append(((int)ch).ToString(CultureInfo.InvariantCulture));\r\n                            output.Append(\";\");\r\n                        }\r\n                        else\r\n                            output.Append(ch);\r\n                        break;\r\n                }\r\n            }\r\n\r\n            return output.ToString();\r\n        }\r\n\r\n        internal static string HtmlAttributeEncode(string s)\r\n        {\r\n#if NET_4_0\r\n\t\t\tif (string.IsNullOrEmpty (s))\r\n\t\t\t\treturn String.Empty;\r\n#else\r\n            if (s == null)\r\n                return null;\r\n\r\n            if (s.Length == 0)\r\n                return String.Empty;\r\n#endif\r\n            bool needEncode = false;\r\n            for (int i = 0; i < s.Length; i++)\r\n            {\r\n                char c = s[i];\r\n                if (c == '&' || c == '\"' || c == '<'\r\n#if NET_4_0\r\n\t\t\t\t    || c == '\\''\r\n#endif\r\n)\r\n                {\r\n                    needEncode = true;\r\n                    break;\r\n                }\r\n            }\r\n\r\n            if (!needEncode)\r\n                return s;\r\n\r\n            StringBuilder output = new StringBuilder();\r\n            int len = s.Length;\r\n            for (int i = 0; i < len; i++)\r\n                switch (s[i])\r\n                {\r\n                    case '&':\r\n                        output.Append(\"&amp;\");\r\n                        break;\r\n                    case '\"':\r\n                        output.Append(\"&quot;\");\r\n                        break;\r\n                    case '<':\r\n                        output.Append(\"&lt;\");\r\n                        break;\r\n#if NET_4_0\r\n\t\t\t\tcase '\\'':\r\n\t\t\t\t\toutput.Append (\"&#39;\");\r\n\t\t\t\t\tbreak;\r\n#endif\r\n                    default:\r\n                        output.Append(s[i]);\r\n                        break;\r\n                }\r\n\r\n            return output.ToString();\r\n        }\r\n\r\n        internal static string HtmlDecode(string s)\r\n        {\r\n            if (s == null)\r\n                return null;\r\n\r\n            if (s.Length == 0)\r\n                return String.Empty;\r\n\r\n            if (s.IndexOf('&') == -1)\r\n                return s;\r\n#if NET_4_0\r\n\t\t\tStringBuilder rawEntity = new StringBuilder ();\r\n#endif\r\n            StringBuilder entity = new StringBuilder();\r\n            StringBuilder output = new StringBuilder();\r\n            int len = s.Length;\r\n            // 0 -> nothing,\r\n            // 1 -> right after '&'\r\n            // 2 -> between '&' and ';' but no '#'\r\n            // 3 -> '#' found after '&' and getting numbers\r\n            int state = 0;\r\n            int number = 0;\r\n            bool is_hex_value = false;\r\n            bool have_trailing_digits = false;\r\n\r\n            for (int i = 0; i < len; i++)\r\n            {\r\n                char c = s[i];\r\n                if (state == 0)\r\n                {\r\n                    if (c == '&')\r\n                    {\r\n                        entity.Append(c);\r\n#if NET_4_0\r\n\t\t\t\t\t\trawEntity.Append (c);\r\n#endif\r\n                        state = 1;\r\n                    }\r\n                    else\r\n                    {\r\n                        output.Append(c);\r\n                    }\r\n                    continue;\r\n                }\r\n\r\n                if (c == '&')\r\n                {\r\n                    state = 1;\r\n                    if (have_trailing_digits)\r\n                    {\r\n                        entity.Append(number.ToString(CultureInfo.InvariantCulture));\r\n                        have_trailing_digits = false;\r\n                    }\r\n\r\n                    output.Append(entity.ToString());\r\n                    entity.Length = 0;\r\n                    entity.Append('&');\r\n                    continue;\r\n                }\r\n\r\n                if (state == 1)\r\n                {\r\n                    if (c == ';')\r\n                    {\r\n                        state = 0;\r\n                        output.Append(entity.ToString());\r\n                        output.Append(c);\r\n                        entity.Length = 0;\r\n                    }\r\n                    else\r\n                    {\r\n                        number = 0;\r\n                        is_hex_value = false;\r\n                        if (c != '#')\r\n                        {\r\n                            state = 2;\r\n                        }\r\n                        else\r\n                        {\r\n                            state = 3;\r\n                        }\r\n                        entity.Append(c);\r\n#if NET_4_0\r\n\t\t\t\t\t\trawEntity.Append (c);\r\n#endif\r\n                    }\r\n                }\r\n                else if (state == 2)\r\n                {\r\n                    entity.Append(c);\r\n                    if (c == ';')\r\n                    {\r\n                        string key = entity.ToString();\r\n                        char value;\r\n                        if (key.Length > 1 && Entities.TryGetValue(key.Substring(1, key.Length - 2), out value))\r\n                            key = value.ToString();\r\n\r\n                        output.Append(key);\r\n                        state = 0;\r\n                        entity.Length = 0;\r\n#if NET_4_0\r\n\t\t\t\t\t\trawEntity.Length = 0;\r\n#endif\r\n                    }\r\n                }\r\n                else if (state == 3)\r\n                {\r\n                    if (c == ';')\r\n                    {\r\n#if NET_4_0\r\n\t\t\t\t\t\tif (number == 0)\r\n\t\t\t\t\t\t\toutput.Append (rawEntity.ToString () + \";\");\r\n\t\t\t\t\t\telse\r\n#endif\r\n                        if (number > 65535)\r\n                        {\r\n                            output.Append(\"&#\");\r\n                            output.Append(number.ToString(CultureInfo.InvariantCulture));\r\n                            output.Append(\";\");\r\n                        }\r\n                        else\r\n                        {\r\n                            output.Append((char)number);\r\n                        }\r\n                        state = 0;\r\n                        entity.Length = 0;\r\n#if NET_4_0\r\n\t\t\t\t\t\trawEntity.Length = 0;\r\n#endif\r\n                        have_trailing_digits = false;\r\n                    }\r\n                    else if (is_hex_value && IsHexDigit(c))\r\n                    {\r\n                        number = number * 16 + FromHex(c);\r\n                        have_trailing_digits = true;\r\n#if NET_4_0\r\n\t\t\t\t\t\trawEntity.Append (c);\r\n#endif\r\n                    }\r\n                    else if (Char.IsDigit(c))\r\n                    {\r\n                        number = number * 10 + ((int)c - '0');\r\n                        have_trailing_digits = true;\r\n#if NET_4_0\r\n\t\t\t\t\t\trawEntity.Append (c);\r\n#endif\r\n                    }\r\n                    else if (number == 0 && (c == 'x' || c == 'X'))\r\n                    {\r\n                        is_hex_value = true;\r\n#if NET_4_0\r\n\t\t\t\t\t\trawEntity.Append (c);\r\n#endif\r\n                    }\r\n                    else\r\n                    {\r\n                        state = 2;\r\n                        if (have_trailing_digits)\r\n                        {\r\n                            entity.Append(number.ToString(CultureInfo.InvariantCulture));\r\n                            have_trailing_digits = false;\r\n                        }\r\n                        entity.Append(c);\r\n                    }\r\n                }\r\n            }\r\n\r\n            if (entity.Length > 0)\r\n            {\r\n                output.Append(entity.ToString());\r\n            }\r\n            else if (have_trailing_digits)\r\n            {\r\n                output.Append(number.ToString(CultureInfo.InvariantCulture));\r\n            }\r\n            return output.ToString();\r\n        }\r\n\r\n        internal static bool IsHexDigit(char character)\r\n        {\r\n            //implementation from https://github.com/dotnet/corefx/blob/ac67ffac987d0c27236c4a6cf1255c2bcbc7fe7d/src/System.Private.Uri/src/System/Uri.cs#L1366\r\n            return ((character >= '0') && (character <= '9'))\r\n                || ((character >= 'A') && (character <= 'F'))\r\n                || ((character >= 'a') && (character <= 'f'));\r\n        }\r\n\r\n        internal static int FromHex(char digit)\r\n        {\r\n            //implementation from https://github.com/dotnet/corefx/blob/ac67ffac987d0c27236c4a6cf1255c2bcbc7fe7d/src/System.Private.Uri/src/System/Uri.cs#L1379\r\n            if (((digit >= '0') && (digit <= '9'))\r\n                || ((digit >= 'A') && (digit <= 'F'))\r\n                || ((digit >= 'a') && (digit <= 'f')))\r\n            {\r\n                return (digit <= '9')\r\n                    ? ((int)digit - (int)'0')\r\n                    : (((digit <= 'F')\r\n                    ? ((int)digit - (int)'A')\r\n                    : ((int)digit - (int)'a'))\r\n                    + 10);\r\n            }\r\n            throw new ArgumentException(\"digit\");\r\n        }\r\n\r\n\r\n        internal static bool NotEncoded(char c)\r\n        {\r\n            return (c == '!' || c == '(' || c == ')' || c == '*' || c == '-' || c == '.' || c == '_'\r\n#if !NET_4_0\r\n || c == '\\''\r\n#endif\r\n);\r\n        }\r\n\r\n        internal static void UrlEncodeChar(char c, Stream result, bool isUnicode)\r\n        {\r\n            if (c > 255)\r\n            {\r\n                //FIXME: what happens when there is an internal error?\r\n                //if (!isUnicode)\r\n                //\tthrow new ArgumentOutOfRangeException (\"c\", c, \"c must be less than 256\");\r\n                int idx;\r\n                int i = (int)c;\r\n\r\n                result.WriteByte((byte)'%');\r\n                result.WriteByte((byte)'u');\r\n                idx = i >> 12;\r\n                result.WriteByte((byte)hexChars[idx]);\r\n                idx = (i >> 8) & 0x0F;\r\n                result.WriteByte((byte)hexChars[idx]);\r\n                idx = (i >> 4) & 0x0F;\r\n                result.WriteByte((byte)hexChars[idx]);\r\n                idx = i & 0x0F;\r\n                result.WriteByte((byte)hexChars[idx]);\r\n                return;\r\n            }\r\n\r\n            if (c > ' ' && NotEncoded(c))\r\n            {\r\n                result.WriteByte((byte)c);\r\n                return;\r\n            }\r\n            if (c == ' ')\r\n            {\r\n                result.WriteByte((byte)'+');\r\n                return;\r\n            }\r\n            if ((c < '0') ||\r\n                (c < 'A' && c > '9') ||\r\n                (c > 'Z' && c < 'a') ||\r\n                (c > 'z'))\r\n            {\r\n                if (isUnicode && c > 127)\r\n                {\r\n                    result.WriteByte((byte)'%');\r\n                    result.WriteByte((byte)'u');\r\n                    result.WriteByte((byte)'0');\r\n                    result.WriteByte((byte)'0');\r\n                }\r\n                else\r\n                    result.WriteByte((byte)'%');\r\n\r\n                int idx = ((int)c) >> 4;\r\n                result.WriteByte((byte)hexChars[idx]);\r\n                idx = ((int)c) & 0x0F;\r\n                result.WriteByte((byte)hexChars[idx]);\r\n            }\r\n            else\r\n                result.WriteByte((byte)c);\r\n        }\r\n\r\n        internal static void UrlPathEncodeChar(char c, Stream result)\r\n        {\r\n            if (c < 33 || c > 126)\r\n            {\r\n                byte[] bIn = Encoding.UTF8.GetBytes(c.ToString());\r\n                for (int i = 0; i < bIn.Length; i++)\r\n                {\r\n                    result.WriteByte((byte)'%');\r\n                    int idx = ((int)bIn[i]) >> 4;\r\n                    result.WriteByte((byte)hexChars[idx]);\r\n                    idx = ((int)bIn[i]) & 0x0F;\r\n                    result.WriteByte((byte)hexChars[idx]);\r\n                }\r\n            }\r\n            else if (c == ' ')\r\n            {\r\n                result.WriteByte((byte)'%');\r\n                result.WriteByte((byte)'2');\r\n                result.WriteByte((byte)'0');\r\n            }\r\n            else\r\n                result.WriteByte((byte)c);\r\n        }\r\n\r\n        static void InitEntities()\r\n        {\r\n            // Build the hash table of HTML entity references.  This list comes\r\n            // from the HTML 4.01 W3C recommendation.\r\n            entities = new SortedDictionary<string, char>(StringComparer.Ordinal);\r\n\r\n            entities.Add(\"nbsp\", '\\u00A0');\r\n            entities.Add(\"iexcl\", '\\u00A1');\r\n            entities.Add(\"cent\", '\\u00A2');\r\n            entities.Add(\"pound\", '\\u00A3');\r\n            entities.Add(\"curren\", '\\u00A4');\r\n            entities.Add(\"yen\", '\\u00A5');\r\n            entities.Add(\"brvbar\", '\\u00A6');\r\n            entities.Add(\"sect\", '\\u00A7');\r\n            entities.Add(\"uml\", '\\u00A8');\r\n            entities.Add(\"copy\", '\\u00A9');\r\n            entities.Add(\"ordf\", '\\u00AA');\r\n            entities.Add(\"laquo\", '\\u00AB');\r\n            entities.Add(\"not\", '\\u00AC');\r\n            entities.Add(\"shy\", '\\u00AD');\r\n            entities.Add(\"reg\", '\\u00AE');\r\n            entities.Add(\"macr\", '\\u00AF');\r\n            entities.Add(\"deg\", '\\u00B0');\r\n            entities.Add(\"plusmn\", '\\u00B1');\r\n            entities.Add(\"sup2\", '\\u00B2');\r\n            entities.Add(\"sup3\", '\\u00B3');\r\n            entities.Add(\"acute\", '\\u00B4');\r\n            entities.Add(\"micro\", '\\u00B5');\r\n            entities.Add(\"para\", '\\u00B6');\r\n            entities.Add(\"middot\", '\\u00B7');\r\n            entities.Add(\"cedil\", '\\u00B8');\r\n            entities.Add(\"sup1\", '\\u00B9');\r\n            entities.Add(\"ordm\", '\\u00BA');\r\n            entities.Add(\"raquo\", '\\u00BB');\r\n            entities.Add(\"frac14\", '\\u00BC');\r\n            entities.Add(\"frac12\", '\\u00BD');\r\n            entities.Add(\"frac34\", '\\u00BE');\r\n            entities.Add(\"iquest\", '\\u00BF');\r\n            entities.Add(\"Agrave\", '\\u00C0');\r\n            entities.Add(\"Aacute\", '\\u00C1');\r\n            entities.Add(\"Acirc\", '\\u00C2');\r\n            entities.Add(\"Atilde\", '\\u00C3');\r\n            entities.Add(\"Auml\", '\\u00C4');\r\n            entities.Add(\"Aring\", '\\u00C5');\r\n            entities.Add(\"AElig\", '\\u00C6');\r\n            entities.Add(\"Ccedil\", '\\u00C7');\r\n            entities.Add(\"Egrave\", '\\u00C8');\r\n            entities.Add(\"Eacute\", '\\u00C9');\r\n            entities.Add(\"Ecirc\", '\\u00CA');\r\n            entities.Add(\"Euml\", '\\u00CB');\r\n            entities.Add(\"Igrave\", '\\u00CC');\r\n            entities.Add(\"Iacute\", '\\u00CD');\r\n            entities.Add(\"Icirc\", '\\u00CE');\r\n            entities.Add(\"Iuml\", '\\u00CF');\r\n            entities.Add(\"ETH\", '\\u00D0');\r\n            entities.Add(\"Ntilde\", '\\u00D1');\r\n            entities.Add(\"Ograve\", '\\u00D2');\r\n            entities.Add(\"Oacute\", '\\u00D3');\r\n            entities.Add(\"Ocirc\", '\\u00D4');\r\n            entities.Add(\"Otilde\", '\\u00D5');\r\n            entities.Add(\"Ouml\", '\\u00D6');\r\n            entities.Add(\"times\", '\\u00D7');\r\n            entities.Add(\"Oslash\", '\\u00D8');\r\n            entities.Add(\"Ugrave\", '\\u00D9');\r\n            entities.Add(\"Uacute\", '\\u00DA');\r\n            entities.Add(\"Ucirc\", '\\u00DB');\r\n            entities.Add(\"Uuml\", '\\u00DC');\r\n            entities.Add(\"Yacute\", '\\u00DD');\r\n            entities.Add(\"THORN\", '\\u00DE');\r\n            entities.Add(\"szlig\", '\\u00DF');\r\n            entities.Add(\"agrave\", '\\u00E0');\r\n            entities.Add(\"aacute\", '\\u00E1');\r\n            entities.Add(\"acirc\", '\\u00E2');\r\n            entities.Add(\"atilde\", '\\u00E3');\r\n            entities.Add(\"auml\", '\\u00E4');\r\n            entities.Add(\"aring\", '\\u00E5');\r\n            entities.Add(\"aelig\", '\\u00E6');\r\n            entities.Add(\"ccedil\", '\\u00E7');\r\n            entities.Add(\"egrave\", '\\u00E8');\r\n            entities.Add(\"eacute\", '\\u00E9');\r\n            entities.Add(\"ecirc\", '\\u00EA');\r\n            entities.Add(\"euml\", '\\u00EB');\r\n            entities.Add(\"igrave\", '\\u00EC');\r\n            entities.Add(\"iacute\", '\\u00ED');\r\n            entities.Add(\"icirc\", '\\u00EE');\r\n            entities.Add(\"iuml\", '\\u00EF');\r\n            entities.Add(\"eth\", '\\u00F0');\r\n            entities.Add(\"ntilde\", '\\u00F1');\r\n            entities.Add(\"ograve\", '\\u00F2');\r\n            entities.Add(\"oacute\", '\\u00F3');\r\n            entities.Add(\"ocirc\", '\\u00F4');\r\n            entities.Add(\"otilde\", '\\u00F5');\r\n            entities.Add(\"ouml\", '\\u00F6');\r\n            entities.Add(\"divide\", '\\u00F7');\r\n            entities.Add(\"oslash\", '\\u00F8');\r\n            entities.Add(\"ugrave\", '\\u00F9');\r\n            entities.Add(\"uacute\", '\\u00FA');\r\n            entities.Add(\"ucirc\", '\\u00FB');\r\n            entities.Add(\"uuml\", '\\u00FC');\r\n            entities.Add(\"yacute\", '\\u00FD');\r\n            entities.Add(\"thorn\", '\\u00FE');\r\n            entities.Add(\"yuml\", '\\u00FF');\r\n            entities.Add(\"fnof\", '\\u0192');\r\n            entities.Add(\"Alpha\", '\\u0391');\r\n            entities.Add(\"Beta\", '\\u0392');\r\n            entities.Add(\"Gamma\", '\\u0393');\r\n            entities.Add(\"Delta\", '\\u0394');\r\n            entities.Add(\"Epsilon\", '\\u0395');\r\n            entities.Add(\"Zeta\", '\\u0396');\r\n            entities.Add(\"Eta\", '\\u0397');\r\n            entities.Add(\"Theta\", '\\u0398');\r\n            entities.Add(\"Iota\", '\\u0399');\r\n            entities.Add(\"Kappa\", '\\u039A');\r\n            entities.Add(\"Lambda\", '\\u039B');\r\n            entities.Add(\"Mu\", '\\u039C');\r\n            entities.Add(\"Nu\", '\\u039D');\r\n            entities.Add(\"Xi\", '\\u039E');\r\n            entities.Add(\"Omicron\", '\\u039F');\r\n            entities.Add(\"Pi\", '\\u03A0');\r\n            entities.Add(\"Rho\", '\\u03A1');\r\n            entities.Add(\"Sigma\", '\\u03A3');\r\n            entities.Add(\"Tau\", '\\u03A4');\r\n            entities.Add(\"Upsilon\", '\\u03A5');\r\n            entities.Add(\"Phi\", '\\u03A6');\r\n            entities.Add(\"Chi\", '\\u03A7');\r\n            entities.Add(\"Psi\", '\\u03A8');\r\n            entities.Add(\"Omega\", '\\u03A9');\r\n            entities.Add(\"alpha\", '\\u03B1');\r\n            entities.Add(\"beta\", '\\u03B2');\r\n            entities.Add(\"gamma\", '\\u03B3');\r\n            entities.Add(\"delta\", '\\u03B4');\r\n            entities.Add(\"epsilon\", '\\u03B5');\r\n            entities.Add(\"zeta\", '\\u03B6');\r\n            entities.Add(\"eta\", '\\u03B7');\r\n            entities.Add(\"theta\", '\\u03B8');\r\n            entities.Add(\"iota\", '\\u03B9');\r\n            entities.Add(\"kappa\", '\\u03BA');\r\n            entities.Add(\"lambda\", '\\u03BB');\r\n            entities.Add(\"mu\", '\\u03BC');\r\n            entities.Add(\"nu\", '\\u03BD');\r\n            entities.Add(\"xi\", '\\u03BE');\r\n            entities.Add(\"omicron\", '\\u03BF');\r\n            entities.Add(\"pi\", '\\u03C0');\r\n            entities.Add(\"rho\", '\\u03C1');\r\n            entities.Add(\"sigmaf\", '\\u03C2');\r\n            entities.Add(\"sigma\", '\\u03C3');\r\n            entities.Add(\"tau\", '\\u03C4');\r\n            entities.Add(\"upsilon\", '\\u03C5');\r\n            entities.Add(\"phi\", '\\u03C6');\r\n            entities.Add(\"chi\", '\\u03C7');\r\n            entities.Add(\"psi\", '\\u03C8');\r\n            entities.Add(\"omega\", '\\u03C9');\r\n            entities.Add(\"thetasym\", '\\u03D1');\r\n            entities.Add(\"upsih\", '\\u03D2');\r\n            entities.Add(\"piv\", '\\u03D6');\r\n            entities.Add(\"bull\", '\\u2022');\r\n            entities.Add(\"hellip\", '\\u2026');\r\n            entities.Add(\"prime\", '\\u2032');\r\n            entities.Add(\"Prime\", '\\u2033');\r\n            entities.Add(\"oline\", '\\u203E');\r\n            entities.Add(\"frasl\", '\\u2044');\r\n            entities.Add(\"weierp\", '\\u2118');\r\n            entities.Add(\"image\", '\\u2111');\r\n            entities.Add(\"real\", '\\u211C');\r\n            entities.Add(\"trade\", '\\u2122');\r\n            entities.Add(\"alefsym\", '\\u2135');\r\n            entities.Add(\"larr\", '\\u2190');\r\n            entities.Add(\"uarr\", '\\u2191');\r\n            entities.Add(\"rarr\", '\\u2192');\r\n            entities.Add(\"darr\", '\\u2193');\r\n            entities.Add(\"harr\", '\\u2194');\r\n            entities.Add(\"crarr\", '\\u21B5');\r\n            entities.Add(\"lArr\", '\\u21D0');\r\n            entities.Add(\"uArr\", '\\u21D1');\r\n            entities.Add(\"rArr\", '\\u21D2');\r\n            entities.Add(\"dArr\", '\\u21D3');\r\n            entities.Add(\"hArr\", '\\u21D4');\r\n            entities.Add(\"forall\", '\\u2200');\r\n            entities.Add(\"part\", '\\u2202');\r\n            entities.Add(\"exist\", '\\u2203');\r\n            entities.Add(\"empty\", '\\u2205');\r\n            entities.Add(\"nabla\", '\\u2207');\r\n            entities.Add(\"isin\", '\\u2208');\r\n            entities.Add(\"notin\", '\\u2209');\r\n            entities.Add(\"ni\", '\\u220B');\r\n            entities.Add(\"prod\", '\\u220F');\r\n            entities.Add(\"sum\", '\\u2211');\r\n            entities.Add(\"minus\", '\\u2212');\r\n            entities.Add(\"lowast\", '\\u2217');\r\n            entities.Add(\"radic\", '\\u221A');\r\n            entities.Add(\"prop\", '\\u221D');\r\n            entities.Add(\"infin\", '\\u221E');\r\n            entities.Add(\"ang\", '\\u2220');\r\n            entities.Add(\"and\", '\\u2227');\r\n            entities.Add(\"or\", '\\u2228');\r\n            entities.Add(\"cap\", '\\u2229');\r\n            entities.Add(\"cup\", '\\u222A');\r\n            entities.Add(\"int\", '\\u222B');\r\n            entities.Add(\"there4\", '\\u2234');\r\n            entities.Add(\"sim\", '\\u223C');\r\n            entities.Add(\"cong\", '\\u2245');\r\n            entities.Add(\"asymp\", '\\u2248');\r\n            entities.Add(\"ne\", '\\u2260');\r\n            entities.Add(\"equiv\", '\\u2261');\r\n            entities.Add(\"le\", '\\u2264');\r\n            entities.Add(\"ge\", '\\u2265');\r\n            entities.Add(\"sub\", '\\u2282');\r\n            entities.Add(\"sup\", '\\u2283');\r\n            entities.Add(\"nsub\", '\\u2284');\r\n            entities.Add(\"sube\", '\\u2286');\r\n            entities.Add(\"supe\", '\\u2287');\r\n            entities.Add(\"oplus\", '\\u2295');\r\n            entities.Add(\"otimes\", '\\u2297');\r\n            entities.Add(\"perp\", '\\u22A5');\r\n            entities.Add(\"sdot\", '\\u22C5');\r\n            entities.Add(\"lceil\", '\\u2308');\r\n            entities.Add(\"rceil\", '\\u2309');\r\n            entities.Add(\"lfloor\", '\\u230A');\r\n            entities.Add(\"rfloor\", '\\u230B');\r\n            entities.Add(\"lang\", '\\u2329');\r\n            entities.Add(\"rang\", '\\u232A');\r\n            entities.Add(\"loz\", '\\u25CA');\r\n            entities.Add(\"spades\", '\\u2660');\r\n            entities.Add(\"clubs\", '\\u2663');\r\n            entities.Add(\"hearts\", '\\u2665');\r\n            entities.Add(\"diams\", '\\u2666');\r\n            entities.Add(\"quot\", '\\u0022');\r\n            entities.Add(\"amp\", '\\u0026');\r\n            entities.Add(\"lt\", '\\u003C');\r\n            entities.Add(\"gt\", '\\u003E');\r\n            entities.Add(\"OElig\", '\\u0152');\r\n            entities.Add(\"oelig\", '\\u0153');\r\n            entities.Add(\"Scaron\", '\\u0160');\r\n            entities.Add(\"scaron\", '\\u0161');\r\n            entities.Add(\"Yuml\", '\\u0178');\r\n            entities.Add(\"circ\", '\\u02C6');\r\n            entities.Add(\"tilde\", '\\u02DC');\r\n            entities.Add(\"ensp\", '\\u2002');\r\n            entities.Add(\"emsp\", '\\u2003');\r\n            entities.Add(\"thinsp\", '\\u2009');\r\n            entities.Add(\"zwnj\", '\\u200C');\r\n            entities.Add(\"zwj\", '\\u200D');\r\n            entities.Add(\"lrm\", '\\u200E');\r\n            entities.Add(\"rlm\", '\\u200F');\r\n            entities.Add(\"ndash\", '\\u2013');\r\n            entities.Add(\"mdash\", '\\u2014');\r\n            entities.Add(\"lsquo\", '\\u2018');\r\n            entities.Add(\"rsquo\", '\\u2019');\r\n            entities.Add(\"sbquo\", '\\u201A');\r\n            entities.Add(\"ldquo\", '\\u201C');\r\n            entities.Add(\"rdquo\", '\\u201D');\r\n            entities.Add(\"bdquo\", '\\u201E');\r\n            entities.Add(\"dagger\", '\\u2020');\r\n            entities.Add(\"Dagger\", '\\u2021');\r\n            entities.Add(\"permil\", '\\u2030');\r\n            entities.Add(\"lsaquo\", '\\u2039');\r\n            entities.Add(\"rsaquo\", '\\u203A');\r\n            entities.Add(\"euro\", '\\u20AC');\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Helpers/HttpUtility.cs",
    "content": "#pragma warning disable CS1591, CS1574, CS1711, CS1712 //  Disable XML comment related warnings\r\n\r\n//\r\n// System.Web.HttpUtility\r\n//\r\n// Authors:\r\n//   Patrik Torstensson (Patrik.Torstensson@labs2.com)\r\n//   Wictor Wiln (decode/encode functions) (wictor@ibizkit.se)\r\n//   Tim Coleman (tim@timcoleman.com)\r\n//   Gonzalo Paniagua Javier (gonzalo@ximian.com)\r\n//\r\n// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)\r\n//\r\n// Permission is hereby granted, free of charge, to any person obtaining\r\n// a copy of this software and associated documentation files (the\r\n// \"Software\"), to deal in the Software without restriction, including\r\n// without limitation the rights to use, copy, modify, merge, publish,\r\n// distribute, sublicense, and/or sell copies of the Software, and to\r\n// permit persons to whom the Software is furnished to do so, subject to\r\n// the following conditions:\r\n//\r\n// The above copyright notice and this permission notice shall be\r\n// included in all copies or substantial portions of the Software.\r\n//\r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\r\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\r\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\r\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\r\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n//\r\n\r\nnamespace Nancy.Helpers\r\n{\r\n    using Extensions;\r\n    using System;\r\n    using System.Collections;\r\n    using System.Collections.Generic;\r\n    using System.Collections.Specialized;\r\n    using System.IO;\r\n    using System.Text;\r\n\r\n    public sealed class HttpUtility\r\n    {\r\n        sealed class HttpQSCollection : NameValueCollection\r\n        {\r\n            public HttpQSCollection()\r\n                : this(StaticConfiguration.CaseSensitive)\r\n            {\r\n            }\r\n\r\n            public HttpQSCollection(bool caseSensitive)\r\n                : base(caseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase)\r\n            {\r\n            }\r\n\r\n            public override string ToString()\r\n            {\r\n                int count = Count;\r\n                if (count == 0)\r\n                    return \"\";\r\n                StringBuilder sb = new StringBuilder();\r\n                string[] keys = AllKeys;\r\n                for (int i = 0; i < count; i++)\r\n                {\r\n                    sb.AppendFormat(\"{0}={1}&\", keys[i], this[keys[i]]);\r\n                }\r\n                if (sb.Length > 0)\r\n                    sb.Length--;\r\n                return sb.ToString();\r\n            }\r\n        }\r\n\r\n        #region Constructors\r\n\r\n        public HttpUtility()\r\n        {\r\n        }\r\n\r\n        #endregion // Constructors\r\n\r\n        #region Methods\r\n\r\n        public static void HtmlAttributeEncode(string s, TextWriter output)\r\n        {\r\n            if (output == null)\r\n            {\r\n#if NET_4_0\r\n\t\t\t\tthrow new ArgumentNullException (\"output\");\r\n#else\r\n                throw new NullReferenceException(\".NET emulation\");\r\n#endif\r\n            }\r\n#if NET_4_0\r\n\t\t\tHttpEncoder.Current.HtmlAttributeEncode (s, output);\r\n#else\r\n            output.Write(HttpEncoder.HtmlAttributeEncode(s));\r\n#endif\r\n        }\r\n\r\n        public static string HtmlAttributeEncode(string s)\r\n        {\r\n#if NET_4_0\r\n\t\t\tif (s == null)\r\n\t\t\t\treturn null;\r\n\r\n\t\t\tusing (var sw = new StringWriter ()) {\r\n\t\t\t\tHttpEncoder.Current.HtmlAttributeEncode (s, sw);\r\n\t\t\t\treturn sw.ToString ();\r\n\t\t\t}\r\n#else\r\n            return HttpEncoder.HtmlAttributeEncode(s);\r\n#endif\r\n        }\r\n\r\n        public static string UrlDecode(string str)\r\n        {\r\n            return UrlDecode(str, Encoding.UTF8);\r\n        }\r\n\r\n        static char[] GetChars(MemoryStream b, Encoding e)\r\n        {\r\n            var buffer = b.GetBufferSegment();\r\n            return e.GetChars(buffer.Array, buffer.Offset, buffer.Count);\r\n        }\r\n\r\n        static void WriteCharBytes(IList buf, char ch, Encoding e)\r\n        {\r\n            if (ch > 255)\r\n            {\r\n                foreach (byte b in e.GetBytes(new char[] { ch }))\r\n                    buf.Add(b);\r\n            }\r\n            else\r\n                buf.Add((byte)ch);\r\n        }\r\n\r\n        public static string UrlDecode(string s, Encoding e)\r\n        {\r\n            if (null == s)\r\n                return null;\r\n\r\n            if (s.IndexOf('%') == -1 && s.IndexOf('+') == -1)\r\n                return s;\r\n\r\n            if (e == null)\r\n                e = Encoding.UTF8;\r\n\r\n            long len = s.Length;\r\n            var bytes = new List<byte>();\r\n            int xchar;\r\n            char ch;\r\n\r\n            for (int i = 0; i < len; i++)\r\n            {\r\n                ch = s[i];\r\n                if (ch == '%' && i + 2 < len && s[i + 1] != '%')\r\n                {\r\n                    if (s[i + 1] == 'u' && i + 5 < len)\r\n                    {\r\n                        // unicode hex sequence\r\n                        xchar = GetChar(s, i + 2, 4);\r\n                        if (xchar != -1)\r\n                        {\r\n                            WriteCharBytes(bytes, (char)xchar, e);\r\n                            i += 5;\r\n                        }\r\n                        else\r\n                            WriteCharBytes(bytes, '%', e);\r\n                    }\r\n                    else if ((xchar = GetChar(s, i + 1, 2)) != -1)\r\n                    {\r\n                        WriteCharBytes(bytes, (char)xchar, e);\r\n                        i += 2;\r\n                    }\r\n                    else\r\n                    {\r\n                        WriteCharBytes(bytes, '%', e);\r\n                    }\r\n                    continue;\r\n                }\r\n\r\n                if (ch == '+')\r\n                    WriteCharBytes(bytes, ' ', e);\r\n                else\r\n                    WriteCharBytes(bytes, ch, e);\r\n            }\r\n\r\n            byte[] buf = bytes.ToArray();\r\n            bytes = null;\r\n            return e.GetString(buf);\r\n\r\n        }\r\n\r\n        public static string UrlDecode(byte[] bytes, Encoding e)\r\n        {\r\n            if (bytes == null)\r\n                return null;\r\n\r\n            return UrlDecode(bytes, 0, bytes.Length, e);\r\n        }\r\n\r\n        static int GetInt(byte b)\r\n        {\r\n            char c = (char)b;\r\n            if (c >= '0' && c <= '9')\r\n                return c - '0';\r\n\r\n            if (c >= 'a' && c <= 'f')\r\n                return c - 'a' + 10;\r\n\r\n            if (c >= 'A' && c <= 'F')\r\n                return c - 'A' + 10;\r\n\r\n            return -1;\r\n        }\r\n\r\n        static int GetChar(byte[] bytes, int offset, int length)\r\n        {\r\n            int value = 0;\r\n            int end = length + offset;\r\n            for (int i = offset; i < end; i++)\r\n            {\r\n                int current = GetInt(bytes[i]);\r\n                if (current == -1)\r\n                    return -1;\r\n                value = (value << 4) + current;\r\n            }\r\n\r\n            return value;\r\n        }\r\n\r\n        static int GetChar(string str, int offset, int length)\r\n        {\r\n            int val = 0;\r\n            int end = length + offset;\r\n            for (int i = offset; i < end; i++)\r\n            {\r\n                char c = str[i];\r\n                if (c > 127)\r\n                    return -1;\r\n\r\n                int current = GetInt((byte)c);\r\n                if (current == -1)\r\n                    return -1;\r\n                val = (val << 4) + current;\r\n            }\r\n\r\n            return val;\r\n        }\r\n\r\n        public static string UrlDecode(byte[] bytes, int offset, int count, Encoding e)\r\n        {\r\n            if (bytes == null)\r\n                return null;\r\n            if (count == 0)\r\n                return string.Empty;\r\n\r\n            if (offset < 0 || offset > bytes.Length)\r\n                throw new ArgumentOutOfRangeException(\"offset\");\r\n\r\n            if (count < 0 || offset + count > bytes.Length)\r\n                throw new ArgumentOutOfRangeException(\"count\");\r\n\r\n            var output = new StringBuilder();\r\n            var acc = new MemoryStream();\r\n\r\n            int end = count + offset;\r\n            int xchar;\r\n            for (int i = offset; i < end; i++)\r\n            {\r\n                if (bytes[i] == '%' && i + 2 < count && bytes[i + 1] != '%')\r\n                {\r\n                    if (bytes[i + 1] == (byte)'u' && i + 5 < end)\r\n                    {\r\n                        if (acc.Length > 0)\r\n                        {\r\n                            output.Append(GetChars(acc, e));\r\n                            acc.SetLength(0);\r\n                        }\r\n                        xchar = GetChar(bytes, i + 2, 4);\r\n                        if (xchar != -1)\r\n                        {\r\n                            output.Append((char)xchar);\r\n                            i += 5;\r\n                            continue;\r\n                        }\r\n                    }\r\n                    else if ((xchar = GetChar(bytes, i + 1, 2)) != -1)\r\n                    {\r\n                        acc.WriteByte((byte)xchar);\r\n                        i += 2;\r\n                        continue;\r\n                    }\r\n                }\r\n\r\n                if (acc.Length > 0)\r\n                {\r\n                    output.Append(GetChars(acc, e));\r\n                    acc.SetLength(0);\r\n                }\r\n\r\n                if (bytes[i] == '+')\r\n                {\r\n                    output.Append(' ');\r\n                }\r\n                else\r\n                {\r\n                    output.Append((char)bytes[i]);\r\n                }\r\n            }\r\n\r\n            if (acc.Length > 0)\r\n            {\r\n                output.Append(GetChars(acc, e));\r\n            }\r\n\r\n            acc = null;\r\n            return output.ToString();\r\n        }\r\n\r\n        public static byte[] UrlDecodeToBytes(byte[] bytes)\r\n        {\r\n            if (bytes == null)\r\n                return null;\r\n\r\n            return UrlDecodeToBytes(bytes, 0, bytes.Length);\r\n        }\r\n\r\n        public static byte[] UrlDecodeToBytes(string str)\r\n        {\r\n            return UrlDecodeToBytes(str, Encoding.UTF8);\r\n        }\r\n\r\n        public static byte[] UrlDecodeToBytes(string str, Encoding e)\r\n        {\r\n            if (str == null)\r\n                return null;\r\n\r\n            if (e == null)\r\n                throw new ArgumentNullException(\"e\");\r\n\r\n            return UrlDecodeToBytes(e.GetBytes(str));\r\n        }\r\n\r\n        public static byte[] UrlDecodeToBytes(byte[] bytes, int offset, int count)\r\n        {\r\n            if (bytes == null)\r\n                return null;\r\n            if (count == 0)\r\n                return ArrayCache.Empty<byte>();\r\n\r\n            int len = bytes.Length;\r\n            if (offset < 0 || offset >= len)\r\n                throw new ArgumentOutOfRangeException(\"offset\");\r\n\r\n            if (count < 0 || offset > len - count)\r\n                throw new ArgumentOutOfRangeException(\"count\");\r\n\r\n            MemoryStream result = new MemoryStream();\r\n            int end = offset + count;\r\n            for (int i = offset; i < end; i++)\r\n            {\r\n                char c = (char)bytes[i];\r\n                if (c == '+')\r\n                {\r\n                    c = ' ';\r\n                }\r\n                else if (c == '%' && i < end - 2)\r\n                {\r\n                    int xchar = GetChar(bytes, i + 1, 2);\r\n                    if (xchar != -1)\r\n                    {\r\n                        c = (char)xchar;\r\n                        i += 2;\r\n                    }\r\n                }\r\n                result.WriteByte((byte)c);\r\n            }\r\n\r\n            return result.ToArray();\r\n        }\r\n\r\n        public static string UrlEncode(string str)\r\n        {\r\n            return UrlEncode(str, Encoding.UTF8);\r\n        }\r\n\r\n        public static string UrlEncode(string s, Encoding Enc)\r\n        {\r\n            if (s == null)\r\n                return null;\r\n\r\n            if (s == String.Empty)\r\n                return String.Empty;\r\n\r\n            bool needEncode = false;\r\n            int len = s.Length;\r\n            for (int i = 0; i < len; i++)\r\n            {\r\n                char c = s[i];\r\n                if ((c < '0') || (c < 'A' && c > '9') || (c > 'Z' && c < 'a') || (c > 'z'))\r\n                {\r\n                    if (HttpEncoder.NotEncoded(c))\r\n                        continue;\r\n\r\n                    needEncode = true;\r\n                    break;\r\n                }\r\n            }\r\n\r\n            if (!needEncode)\r\n                return s;\r\n\r\n            // avoided GetByteCount call\r\n            byte[] bytes = new byte[Enc.GetMaxByteCount(s.Length)];\r\n            int realLen = Enc.GetBytes(s, 0, s.Length, bytes, 0);\r\n            return Encoding.ASCII.GetString(UrlEncodeToBytes(bytes, 0, realLen));\r\n        }\r\n\r\n        public static string UrlEncode(byte[] bytes)\r\n        {\r\n            if (bytes == null)\r\n                return null;\r\n\r\n            if (bytes.Length == 0)\r\n                return String.Empty;\r\n\r\n            return Encoding.ASCII.GetString(UrlEncodeToBytes(bytes, 0, bytes.Length));\r\n        }\r\n\r\n        public static string UrlEncode(byte[] bytes, int offset, int count)\r\n        {\r\n            if (bytes == null)\r\n                return null;\r\n\r\n            if (bytes.Length == 0)\r\n                return String.Empty;\r\n\r\n            return Encoding.ASCII.GetString(UrlEncodeToBytes(bytes, offset, count));\r\n        }\r\n\r\n        public static byte[] UrlEncodeToBytes(string str)\r\n        {\r\n            return UrlEncodeToBytes(str, Encoding.UTF8);\r\n        }\r\n\r\n        public static byte[] UrlEncodeToBytes(string str, Encoding e)\r\n        {\r\n            if (str == null)\r\n                return null;\r\n\r\n            if (str.Length == 0)\r\n                return ArrayCache.Empty<byte>();\r\n\r\n            byte[] bytes = e.GetBytes(str);\r\n            return UrlEncodeToBytes(bytes, 0, bytes.Length);\r\n        }\r\n\r\n        public static byte[] UrlEncodeToBytes(byte[] bytes)\r\n        {\r\n            if (bytes == null)\r\n                return null;\r\n\r\n            if (bytes.Length == 0)\r\n                return ArrayCache.Empty<byte>();\r\n\r\n            return UrlEncodeToBytes(bytes, 0, bytes.Length);\r\n        }\r\n\r\n        public static byte[] UrlEncodeToBytes(byte[] bytes, int offset, int count)\r\n        {\r\n            if (bytes == null)\r\n                return null;\r\n#if NET_4_0\r\n\t\t\treturn HttpEncoder.Current.UrlEncode (bytes, offset, count);\r\n#else\r\n            return HttpEncoder.UrlEncodeToBytes(bytes, offset, count);\r\n#endif\r\n        }\r\n\r\n        public static string UrlEncodeUnicode(string str)\r\n        {\r\n            if (str == null)\r\n                return null;\r\n\r\n            return Encoding.ASCII.GetString(UrlEncodeUnicodeToBytes(str));\r\n        }\r\n\r\n        public static byte[] UrlEncodeUnicodeToBytes(string str)\r\n        {\r\n            if (str == null)\r\n                return null;\r\n\r\n            if (str.Length == 0)\r\n                return ArrayCache.Empty<byte>();\r\n\r\n            MemoryStream result = new MemoryStream(str.Length);\r\n            foreach (char c in str)\r\n            {\r\n                HttpEncoder.UrlEncodeChar(c, result, true);\r\n            }\r\n            return result.ToArray();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Decodes an HTML-encoded string and returns the decoded string.\r\n        /// </summary>\r\n        /// <param name=\"s\">The HTML string to decode. </param>\r\n        /// <returns>The decoded text.</returns>\r\n        public static string HtmlDecode(string s)\r\n        {\r\n#if NET_4_0\r\n\t\t\tif (s == null)\r\n\t\t\t\treturn null;\r\n\r\n\t\t\tusing (var sw = new StringWriter ()) {\r\n\t\t\t\tHttpEncoder.Current.HtmlDecode (s, sw);\r\n\t\t\t\treturn sw.ToString ();\r\n\t\t\t}\r\n#else\r\n            return HttpEncoder.HtmlDecode(s);\r\n#endif\r\n        }\r\n\r\n        /// <summary>\r\n        /// Decodes an HTML-encoded string and sends the resulting output to a TextWriter output stream.\r\n        /// </summary>\r\n        /// <param name=\"s\">The HTML string to decode</param>\r\n        /// <param name=\"output\">The TextWriter output stream containing the decoded string. </param>\r\n        public static void HtmlDecode(string s, TextWriter output)\r\n        {\r\n            if (output == null)\r\n            {\r\n#if NET_4_0\r\n\t\t\t\tthrow new ArgumentNullException (\"output\");\r\n#else\r\n                throw new NullReferenceException(\".NET emulation\");\r\n#endif\r\n            }\r\n\r\n            if (!string.IsNullOrEmpty(s))\r\n            {\r\n#if NET_4_0\r\n\t\t\t\tHttpEncoder.Current.HtmlDecode (s, output);\r\n#else\r\n                output.Write(HttpEncoder.HtmlDecode(s));\r\n#endif\r\n            }\r\n        }\r\n\r\n        public static string HtmlEncode(string s)\r\n        {\r\n#if NET_4_0\r\n\t\t\tif (s == null)\r\n\t\t\t\treturn null;\r\n\r\n\t\t\tusing (var sw = new StringWriter ()) {\r\n\t\t\t\tHttpEncoder.Current.HtmlEncode (s, sw);\r\n\t\t\t\treturn sw.ToString ();\r\n\t\t\t}\r\n#else\r\n            return HttpEncoder.HtmlEncode(s);\r\n#endif\r\n        }\r\n\r\n        /// <summary>\r\n        /// HTML-encodes a string and sends the resulting output to a TextWriter output stream.\r\n        /// </summary>\r\n        /// <param name=\"s\">The string to encode. </param>\r\n        /// <param name=\"output\">The TextWriter output stream containing the encoded string. </param>\r\n        public static void HtmlEncode(string s, TextWriter output)\r\n        {\r\n            if (output == null)\r\n            {\r\n#if NET_4_0\r\n\t\t\t\tthrow new ArgumentNullException (\"output\");\r\n#else\r\n                throw new NullReferenceException(\".NET emulation\");\r\n#endif\r\n            }\r\n\r\n            if (!string.IsNullOrEmpty(s))\r\n            {\r\n#if NET_4_0\r\n\t\t\t\tHttpEncoder.Current.HtmlEncode (s, output);\r\n#else\r\n                output.Write(HttpEncoder.HtmlEncode(s));\r\n#endif\r\n            }\r\n        }\r\n#if NET_4_0\r\n\t\tpublic static string HtmlEncode (object value)\r\n\t\t{\r\n\t\t\tif (value == null)\r\n\t\t\t\treturn null;\r\n\r\n\t\t\tIHtmlString htmlString = value as IHtmlString;\r\n\t\t\tif (htmlString != null)\r\n\t\t\t\treturn htmlString.ToHtmlString ();\r\n\r\n\t\t\treturn HtmlEncode (value.ToString ());\r\n\t\t}\r\n\r\n\t\tpublic static string JavaScriptStringEncode (string value)\r\n\t\t{\r\n\t\t\treturn JavaScriptStringEncode (value, false);\r\n\t\t}\r\n\r\n\t\tpublic static string JavaScriptStringEncode (string value, bool addDoubleQuotes)\r\n\t\t{\r\n\t\t\tif (string.IsNullOrEmpty (value))\r\n\t\t\t\treturn addDoubleQuotes ? \"\\\"\\\"\" : String.Empty;\r\n\r\n\t\t\tint len = value.Length;\r\n\t\t\tbool needEncode = false;\r\n\t\t\tchar c;\r\n\t\t\tfor (int i = 0; i < len; i++) {\r\n\t\t\t\tc = value [i];\r\n\r\n\t\t\t\tif (c >= 0 && c <= 31 || c == 34 || c == 39 || c == 60 || c == 62 || c == 92) {\r\n\t\t\t\t\tneedEncode = true;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (!needEncode)\r\n\t\t\t\treturn addDoubleQuotes ? \"\\\"\" + value + \"\\\"\" : value;\r\n\r\n\t\t\tvar sb = new StringBuilder ();\r\n\t\t\tif (addDoubleQuotes)\r\n\t\t\t\tsb.Append ('\"');\r\n\r\n\t\t\tfor (int i = 0; i < len; i++) {\r\n\t\t\t\tc = value [i];\r\n\t\t\t\tif (c >= 0 && c <= 7 || c == 11 || c >= 14 && c <= 31 || c == 39 || c == 60 || c == 62)\r\n\t\t\t\t\tsb.AppendFormat (\"\\\\u{0:x4}\", (int)c);\r\n\t\t\t\telse switch ((int)c) {\r\n\t\t\t\t\t\tcase 8:\r\n\t\t\t\t\t\t\tsb.Append (\"\\\\b\");\r\n\t\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\t\tcase 9:\r\n\t\t\t\t\t\t\tsb.Append (\"\\\\t\");\r\n\t\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\t\tcase 10:\r\n\t\t\t\t\t\t\tsb.Append (\"\\\\n\");\r\n\t\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\t\tcase 12:\r\n\t\t\t\t\t\t\tsb.Append (\"\\\\f\");\r\n\t\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\t\tcase 13:\r\n\t\t\t\t\t\t\tsb.Append (\"\\\\r\");\r\n\t\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\t\tcase 34:\r\n\t\t\t\t\t\t\tsb.Append (\"\\\\\\\"\");\r\n\t\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\t\tcase 92:\r\n\t\t\t\t\t\t\tsb.Append (\"\\\\\\\\\");\r\n\t\t\t\t\t\t\tbreak;\r\n\r\n\t\t\t\t\t\tdefault:\r\n\t\t\t\t\t\t\tsb.Append (c);\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (addDoubleQuotes)\r\n\t\t\t\tsb.Append ('\"');\r\n\r\n\t\t\treturn sb.ToString ();\r\n\t\t}\r\n#endif\r\n        public static string UrlPathEncode(string s)\r\n        {\r\n#if NET_4_0\r\n\t\t\treturn HttpEncoder.Current.UrlPathEncode (s);\r\n#else\r\n            return HttpEncoder.UrlPathEncode(s);\r\n#endif\r\n        }\r\n\r\n        public static NameValueCollection ParseQueryString(string query)\r\n        {\r\n            return ParseQueryString(query, Encoding.UTF8);\r\n        }\r\n\r\n        public static NameValueCollection ParseQueryString(string query, bool caseSensitive)\r\n        {\r\n            return ParseQueryString(query, Encoding.UTF8, caseSensitive);\r\n        }\r\n\r\n        public static NameValueCollection ParseQueryString(string query, Encoding encoding)\r\n        {\r\n            return ParseQueryString(query, encoding, StaticConfiguration.CaseSensitive);\r\n        }\r\n\r\n        public static NameValueCollection ParseQueryString(string query, Encoding encoding, bool caseSensitive)\r\n        {\r\n            if (query == null)\r\n                throw new ArgumentNullException(\"query\");\r\n            if (encoding == null)\r\n                throw new ArgumentNullException(\"encoding\");\r\n            if (query.Length == 0 || (query.Length == 1 && query[0] == '?'))\r\n                return new HttpQSCollection(caseSensitive);\r\n            if (query[0] == '?')\r\n                query = query.Substring(1);\r\n\r\n            NameValueCollection result = new HttpQSCollection(caseSensitive);\r\n            ParseQueryString(query, encoding, result);\r\n            return result;\r\n        }\r\n\r\n        internal static void ParseQueryString(string query, Encoding encoding, NameValueCollection result)\r\n        {\r\n            if (query.Length == 0)\r\n                return;\r\n\r\n            var decoded = HtmlDecode(query);\r\n            var segments = decoded.Split(new[] {'&'}, StringSplitOptions.None);\r\n\r\n            foreach (var segment in segments)\r\n            {\r\n                var keyValuePair = ParseQueryStringSegment(segment, encoding);\r\n                if (!Equals(keyValuePair, default(KeyValuePair<string, string>)))\r\n                    result.Add(keyValuePair.Key, keyValuePair.Value);\r\n            }\r\n        }\r\n\r\n        private static KeyValuePair<string, string> ParseQueryStringSegment(string segment, Encoding encoding)\r\n        {\r\n            if (String.IsNullOrWhiteSpace(segment))\r\n                return default(KeyValuePair<string, string>);\r\n\r\n            var indexOfEquals = segment.IndexOf('=');\r\n            if (indexOfEquals == -1)\r\n            {\r\n                var decoded = UrlDecode(segment, encoding);\r\n                return new KeyValuePair<string, string>(decoded, decoded);\r\n            }\r\n\r\n            var key = UrlDecode(segment.Substring(0, indexOfEquals), encoding);\r\n            var length = (segment.Length - indexOfEquals) - 1;\r\n            var value = UrlDecode(segment.Substring(indexOfEquals + 1, length), encoding);\r\n            return new KeyValuePair<string, string>(key, value);\r\n        }\r\n\r\n#endregion // Methods\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Helpers/ProxyNancyReferenceProber.cs",
    "content": "#if !CORE\r\nnamespace Nancy.Helpers\r\n{\r\n    using System;\r\n    using System.Reflection;\r\n    using Nancy.Extensions;\r\n\r\n    /// <summary>\r\n    /// Utility class used to probe assembly references.\r\n    /// </summary>\r\n    /// <remarks>\r\n    /// Because this class inherits from <see cref=\"T:System.MarshalByRefObject\"/> it can be used across different <see cref=\"T:System.AppDomain\"/>.\r\n    /// </remarks>\r\n    internal class ProxyNancyReferenceProber : MarshalByRefObject\r\n    {\r\n        /// <summary>\r\n        /// Determines if the assembly has a reference (dependency) upon another one.\r\n        /// </summary>\r\n        /// <param name=\"assemblyNameForProbing\">The name of the assembly that will be tested.</param>\r\n        /// <param name=\"referenceAssemblyName\">The reference assembly name.</param>\r\n        /// <returns>A boolean value indicating if there is a reference.</returns>\r\n        public bool HasReference(AssemblyName assemblyNameForProbing, AssemblyName referenceAssemblyName)\r\n        {\r\n            var assemblyForInspection = Assembly.ReflectionOnlyLoad(assemblyNameForProbing.Name);\r\n\r\n            return assemblyForInspection.IsReferencing(referenceAssemblyName);\r\n        }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "src/Nancy/Helpers/ReflectionUtils.cs",
    "content": "#region License\r\n// Copyright (c) 2007 James Newton-King\r\n//\r\n// Permission is hereby granted, free of charge, to any person\r\n// obtaining a copy of this software and associated documentation\r\n// files (the \"Software\"), to deal in the Software without\r\n// restriction, including without limitation the rights to use,\r\n// copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n// copies of the Software, and to permit persons to whom the\r\n// Software is furnished to do so, subject to the following\r\n// conditions:\r\n//\r\n// The above copyright notice and this permission notice shall be\r\n// included in all copies or substantial portions of the Software.\r\n//\r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\r\n// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\r\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\n// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\r\n// OTHER DEALINGS IN THE SOFTWARE.\r\n#endregion\r\n\r\nnamespace Nancy.Helpers\r\n{\r\n    using System;\r\n    using System.Collections;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n\r\n    internal static class ReflectionUtils\r\n    {\r\n        public static bool IsInstantiatableType(Type t)\r\n        {\r\n            if (t == null)\r\n                throw new ArgumentNullException(\"t\");\r\n\r\n            if (t.GetTypeInfo().IsAbstract || t.GetTypeInfo().IsInterface || t.IsArray)\r\n                return false;\r\n\r\n            if (t.GetTypeInfo().IsGenericType)\r\n                return false;\r\n\r\n            if (!HasDefaultConstructor(t))\r\n                return false;\r\n\r\n            return true;\r\n        }\r\n\r\n        public static bool HasDefaultConstructor(Type t)\r\n        {\r\n            if (t == null)\r\n            {\r\n                throw new ArgumentNullException(\"t\");\r\n            }\r\n\r\n            var hasDefaultConstructor =\r\n                t.GetTypeInfo().DeclaredConstructors.Any(ctor => !ctor.GetParameters().Any());\r\n\r\n            return hasDefaultConstructor;\r\n        }\r\n\r\n        public static bool IsAssignable(Type to, Type from)\r\n        {\r\n            if (to == null)\r\n            {\r\n                throw new ArgumentNullException(\"to\");\r\n            }\r\n\r\n            if (to.IsAssignableFrom(from))\r\n            {\r\n                return true;\r\n            }\r\n\r\n            if (to.GetTypeInfo().IsGenericType && from.GetTypeInfo().IsGenericTypeDefinition)\r\n            {\r\n                return to.IsAssignableFrom(from.MakeGenericType(to.GetGenericArguments()));\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        public static bool IsSubClass(Type type, Type check)\r\n        {\r\n            if (type == null || check == null)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            if (type == check)\r\n            {\r\n                return true;\r\n            }\r\n\r\n            if (check.GetTypeInfo().IsInterface)\r\n            {\r\n                foreach (Type t in type.GetInterfaces())\r\n                {\r\n                    if (IsSubClass(t, check)) return true;\r\n                }\r\n            }\r\n            if (type.GetTypeInfo().IsGenericType && !type.GetTypeInfo().IsGenericTypeDefinition)\r\n            {\r\n                if (IsSubClass(type.GetGenericTypeDefinition(), check))\r\n                    return true;\r\n            }\r\n            return IsSubClass(type.GetTypeInfo().BaseType, check);\r\n        }\r\n\r\n        static readonly Type GenericListType = typeof(List<>);\r\n\r\n        /// <summary>\r\n        /// Gets the type of the typed list's items.\r\n        /// </summary>\r\n        /// <param name=\"type\">The type.</param>\r\n        /// <returns>The type of the typed list's items.</returns>\r\n        public static Type GetTypedListItemType(Type type)\r\n        {\r\n            if (type == null)\r\n                throw new ArgumentNullException(\"type\");\r\n\r\n            if (type.IsArray)\r\n                return type.GetElementType();\r\n            else if (type.GetTypeInfo().IsGenericType\r\n                         && GenericListType.IsAssignableFrom(type.GetGenericTypeDefinition()))\r\n            {\r\n                return type.GetGenericArguments()[0];\r\n            }\r\n            else\r\n            {\r\n                throw new Exception(\"Bad type\");\r\n            }\r\n        }\r\n\r\n        public static Type GetTypedDictionaryValueType(Type type)\r\n        {\r\n            if (type == null)\r\n            {\r\n                throw new ArgumentNullException(\"type\");\r\n            }\r\n\r\n            var genDictType = GetGenericDictionary(type);\r\n\r\n            if (genDictType != null)\r\n            {\r\n                return genDictType.GetGenericArguments()[1];\r\n            }\r\n            else if (typeof(IDictionary).IsAssignableFrom(type))\r\n            {\r\n                return null;\r\n            }\r\n            else\r\n            {\r\n                throw new Exception(\"Bad type\");\r\n            }\r\n        }\r\n\r\n        static readonly Type GenericDictionaryType = typeof(IDictionary<,>);\r\n\r\n        public static Type GetGenericDictionary(Type type)\r\n        {\r\n            if (type.GetTypeInfo().IsGenericType\r\n                && GenericDictionaryType.IsAssignableFrom(type.GetGenericTypeDefinition()))\r\n            {\r\n                return type;\r\n            }\r\n\r\n            var ifaces = type.GetInterfaces();\r\n            if (ifaces != null)\r\n            {\r\n                for (int i = 0; i < ifaces.Length; i++)\r\n                {\r\n                    Type current = GetGenericDictionary(ifaces[i]);\r\n                    if (current != null)\r\n                        return current;\r\n                }\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        public static Type GetMemberUnderlyingType(MemberInfo member)\r\n        {\r\n            if (member is FieldInfo)\r\n            {\r\n                return ((FieldInfo)member).FieldType;\r\n            }\r\n            else if (member is PropertyInfo)\r\n            {\r\n                return ((PropertyInfo)member).PropertyType;\r\n            }\r\n            else if (member is EventInfo)\r\n            {\r\n                return ((EventInfo)member).EventHandlerType;\r\n            }\r\n            else\r\n            {\r\n                throw new ArgumentException(\"MemberInfo must be if type FieldInfo, PropertyInfo or EventInfo\", \"member\");\r\n            }\r\n        }\r\n\r\n\r\n        /// <summary>\r\n        /// Determines whether the member is an indexed property.\r\n        /// </summary>\r\n        /// <param name=\"member\">The member.</param>\r\n        /// <returns>\r\n        /// \t<c>true</c> if the member is an indexed property; otherwise, <c>false</c>.\r\n        /// </returns>\r\n        public static bool IsIndexedProperty(MemberInfo member)\r\n        {\r\n            if (member == null)\r\n            {\r\n                throw new ArgumentNullException(\"member\");\r\n            }\r\n\r\n            var propertyInfo = member as PropertyInfo;\r\n\r\n            if (propertyInfo != null)\r\n            {\r\n                return IsIndexedProperty(propertyInfo);\r\n            }\r\n            else\r\n            {\r\n                return false;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determines whether the property is an indexed property.\r\n        /// </summary>\r\n        /// <param name=\"property\">The property.</param>\r\n        /// <returns>\r\n        /// \t<c>true</c> if the property is an indexed property; otherwise, <c>false</c>.\r\n        /// </returns>\r\n        public static bool IsIndexedProperty(PropertyInfo property)\r\n        {\r\n            if (property == null)\r\n            {\r\n                throw new ArgumentNullException(\"property\");\r\n            }\r\n\r\n            return (property.GetIndexParameters().Length > 0);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the member's value on the object.\r\n        /// </summary>\r\n        /// <param name=\"member\">The member.</param>\r\n        /// <param name=\"target\">The target object.</param>\r\n        /// <returns>The member's value on the object.</returns>\r\n        public static object GetMemberValue(MemberInfo member, object target)\r\n        {\r\n            if (member is FieldInfo)\r\n            {\r\n                return ((FieldInfo)member).GetValue(target);\r\n            }\r\n            else if (member is PropertyInfo)\r\n            {\r\n                try\r\n                {\r\n                    return ((PropertyInfo)member).GetValue(target, null);\r\n                }\r\n                catch (TargetParameterCountException e)\r\n                {\r\n                    throw new ArgumentException(\"MemberInfo has index parameters\", \"member\", e);\r\n                }\r\n            }\r\n            throw new ArgumentException(\"MemberInfo is not of type FieldInfo or PropertyInfo\", \"member\");\r\n        }\r\n\r\n        /// <summary>\r\n        /// Sets the member's value on the target object.\r\n        /// </summary>\r\n        /// <param name=\"member\">The member.</param>\r\n        /// <param name=\"target\">The target.</param>\r\n        /// <param name=\"value\">The value.</param>\r\n        public static void SetMemberValue(MemberInfo member, object target, object value)\r\n        {\r\n            if (member is FieldInfo)\r\n            {\r\n                ((FieldInfo)member).SetValue(target, value);\r\n                return;\r\n            }\r\n            else if (member is PropertyInfo)\r\n            {\r\n                ((PropertyInfo)member).SetValue(target, value, null);\r\n                return;\r\n            }\r\n            throw new ArgumentException(\"MemberInfo must be of type FieldInfo or PropertyInfo\", \"member\");\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determines whether the specified MemberInfo can be read.\r\n        /// </summary>\r\n        /// <param name=\"member\">The MemberInfo to determine whether can be read.</param>\r\n        /// <returns>\r\n        /// \t<c>true</c> if the specified MemberInfo can be read; otherwise, <c>false</c>.\r\n        /// </returns>\r\n        public static bool CanReadMemberValue(MemberInfo member)\r\n        {\r\n            if (member is FieldInfo)\r\n            {\r\n                return true;\r\n            }\r\n            else if (member is PropertyInfo)\r\n            {\r\n                return ((PropertyInfo)member).CanRead;\r\n            }\r\n            return false;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determines whether the specified MemberInfo can be set.\r\n        /// </summary>\r\n        /// <param name=\"member\">The MemberInfo to determine whether can be set.</param>\r\n        /// <returns>\r\n        /// \t<c>true</c> if the specified MemberInfo can be set; otherwise, <c>false</c>.\r\n        /// </returns>\r\n        public static bool CanSetMemberValue(MemberInfo member)\r\n        {\r\n            if (member is FieldInfo)\r\n            {\r\n                return true;\r\n            }\r\n            else if (member is PropertyInfo)\r\n            {\r\n                return ((PropertyInfo)member).CanWrite;\r\n            }\r\n            return false;\r\n        }\r\n\r\n        public static IEnumerable<MemberInfo> GetFieldsAndProperties(Type type, BindingFlags bindingAttr)\r\n        {\r\n\r\n            MemberInfo[] members = type.GetFields(bindingAttr);\r\n            for (int i = 0; i < members.Length; i++)\r\n            {\r\n                yield return members[i];\r\n            }\r\n            members = type.GetProperties(bindingAttr);\r\n            for (int i = 0; i < members.Length; i++)\r\n            {\r\n                yield return members[i];\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Helpers/TaskHelpers.cs",
    "content": "﻿namespace Nancy.Helpers\r\n{\r\n    using System;\r\n    using System.Threading.Tasks;\r\n\r\n    /// <summary>\r\n    /// Convenience class with helper methods for <see cref=\"Task\"/>.\r\n    /// </summary>\r\n    public static class TaskHelpers\r\n    {\r\n        /// <summary>\r\n        /// The completed task\r\n        /// </summary>\r\n        public static readonly Task CompletedTask = Task.FromResult<object>(null);\r\n\r\n        /// <summary>\r\n        /// Gets the faulted task.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">Type for <see cref=\"TaskCompletionSource{T}\"/></typeparam>\r\n        /// <param name=\"exception\">The exception.</param>\r\n        /// <returns>The faulted <see cref=\"Task{T}\"/></returns>\r\n        public static Task<T> GetFaultedTask<T>(Exception exception)\r\n        {\r\n            var tcs = new TaskCompletionSource<T>();\r\n            tcs.SetException(exception);\r\n            return tcs.Task;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/HttpFile.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using System.IO;\r\n\r\n    /// <summary>\r\n    /// Represents a file that was captured in a HTTP multipart/form-data request\r\n    /// </summary>\r\n    public class HttpFile\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"HttpFile\"/> class,\r\n        /// using the provided <paramref name=\"boundary\"/>.\r\n        /// </summary>\r\n        /// <param name=\"boundary\">The <see cref=\"HttpMultipartBoundary\"/> that contains the file information.</param>\r\n        public HttpFile(HttpMultipartBoundary boundary)\r\n            : this(boundary.ContentType, boundary.Filename, boundary.Value, boundary.Name)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"HttpFile\"/> class,\r\n        /// using the provided values\r\n        /// </summary>\r\n        /// <paramref name=\"contentType\">The content type of the file.</paramref>\r\n        /// <paramref name=\"name\">The name of the file.</paramref>\r\n        /// <paramref name=\"value\">The content of the file.</paramref>\r\n        /// <paramref name=\"key\">The name of the field that uploaded the file.</paramref>\r\n        public HttpFile(string contentType, string name, Stream value, string key)\r\n        {\r\n            this.ContentType = contentType;\r\n            this.Name = name;\r\n            this.Value = value;\r\n            this.Key = key;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the type of the content.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the content type of the file.</value>\r\n        public string ContentType { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the name of the file.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the name of the file.</value>\r\n        public string Name { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the form element name of this file.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the key.</value>\r\n        public string Key { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the value stream.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"Stream\"/> containing the contents of the file.</value>\r\n        /// <remarks>This is a <see cref=\"HttpMultipartSubStream\"/> instance that sits ontop of the request stream.</remarks>\r\n        public Stream Value { get; private set; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/HttpLink.cs",
    "content": "namespace Nancy\n{\n    using System;\n    using System.Collections.Generic;\n    using System.Linq;\n    using System.Text;\n    using Nancy.Responses.Negotiation;\n\n    /// <summary>\n    /// Represents one of possibly many RFC 5988 HTTP Links contained in a <see cref=\"HttpLinkBuilder\"/>.\n    /// </summary>\n    public class HttpLink : IEquatable<HttpLink>\n    {\n        private static readonly HttpLinkParameterComparer ParameterComparer = new HttpLinkParameterComparer();\n\n        private readonly IDictionary<string, object> parameters;\n\n        private readonly Uri targetUri;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpLink\" /> class.\n        /// </summary>\n        /// <param name=\"targetUri\">The target URI of the link.</param>\n        /// <param name=\"relation\">The relation that identifies the semantics of the link.</param>\n        /// <exception cref=\"System.ArgumentNullException\"><paramref name=\"targetUri\" /> or <paramref name=\"relation\" /></exception>\n        public HttpLink(string targetUri, string relation)\n            : this(ParseUri(targetUri), relation, string.Empty, string.Empty)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpLink\" /> class.\n        /// </summary>\n        /// <param name=\"targetUri\">The target URI of the link.</param>\n        /// <param name=\"relation\">The relation that identifies the semantics of the link.</param>\n        /// <param name=\"type\">The optional type parameter is a hint indicating what the media type of the result of dereferencing the link should be. Note that this is only a hint; for example, it does not override the HTTP Content-Type header of a HTTP response obtained by actually following the link.</param>\n        /// <exception cref=\"System.ArgumentNullException\"><paramref name=\"targetUri\" /> or <paramref name=\"relation\" /></exception>\n        public HttpLink(string targetUri, string relation, string type)\n            : this(ParseUri(targetUri), relation, type, string.Empty)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpLink\" /> class.\n        /// </summary>\n        /// <param name=\"targetUri\">The target URI of the link.</param>\n        /// <param name=\"relation\">The relation that identifies the semantics of the link.</param>\n        /// <param name=\"type\">The optional type parameter is a hint indicating what the media type of the result of dereferencing the link should be. Note that this is only a hint; for example, it does not override the HTTP Content-Type header of a HTTP response obtained by actually following the link.</param>\n        /// <param name=\"title\">The optional title parameter is used to label the destination of a link such that it can be used as a human-readable identifier (e.g., a menu entry) in the language indicated by the HTTP Content-Language header (if present).</param>\n        /// <exception cref=\"System.ArgumentNullException\"><paramref name=\"targetUri\" /> or <paramref name=\"relation\" /></exception>\n        public HttpLink(string targetUri, string relation, string type, string title)\n            : this(ParseUri(targetUri), relation, type, title)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpLink\" /> class.\n        /// </summary>\n        /// <param name=\"targetUri\">The target URI of the link.</param>\n        /// <param name=\"relation\">The relation that identifies the semantics of the link.</param>\n        /// <param name=\"type\">The optional type parameter is a hint indicating what the media type of the result of dereferencing the link should be. Note that this is only a hint; for example, it does not override the HTTP Content-Type header of a HTTP response obtained by actually following the link.</param>\n        /// <param name=\"title\">The optional title parameter is used to label the destination of a link such that it can be used as a human-readable identifier (e.g., a menu entry) in the language indicated by the HTTP Content-Language header (if present).</param>\n        /// <exception cref=\"System.ArgumentNullException\"><paramref name=\"targetUri\" /> or <paramref name=\"relation\" /></exception>\n        public HttpLink(Uri targetUri, string relation, string type, string title)\n        {\n            if (targetUri == null)\n            {\n                throw new ArgumentNullException(\"targetUri\");\n            }\n\n            if (relation == null)\n            {\n                throw new ArgumentNullException(\"relation\");\n            }\n\n            this.parameters = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase)\n            {\n                { \"rel\", HttpLinkRelation.Parse(relation) }\n            };\n            this.targetUri = targetUri;\n\n            if (!string.IsNullOrWhiteSpace(type))\n            {\n                this.parameters.Add(\"type\", new MediaRange(type));\n            }\n\n            if (!string.IsNullOrEmpty(title))\n            {\n                this.parameters.Add(\"title\", title);\n            }\n        }\n\n        /// <summary>\n        /// The dictionary of parameters associated with the link.\n        /// </summary>\n        public IDictionary<string, object> Parameters\n        {\n            get { return this.parameters; }\n        }\n\n        /// <summary>\n        /// The relation that identifies the semantics of the link.\n        /// </summary>\n        public HttpLinkRelation Relation\n        {\n            get { return this.GetParameterValue<HttpLinkRelation>(\"rel\"); }\n        }\n\n        /// <summary>\n        /// Gets the target URI.\n        /// </summary>\n        public Uri TargetUri\n        {\n            get { return this.targetUri; }\n        }\n\n        /// <summary>\n        /// The optional title parameter is used to label the destination of a link such that it can be used as a human-readable identifier (e.g., a menu entry) in the language indicated by the HTTP Content-Language header (if present).\n        /// </summary>\n        public string Title\n        {\n            get { return this.GetParameterValue<string>(\"title\"); }\n        }\n\n        /// <summary>\n        /// The optional type parameter is a hint indicating what the media type of the result of dereferencing the link should be. Note that this is only a hint; for example, it does not override the HTTP Content-Type header of a HTTP response obtained by actually following the link.\n        /// </summary>\n        public MediaRange Type\n        {\n            get { return this.GetParameterValue<MediaRange>(\"type\"); }\n        }\n\n        /// <summary>\n        /// Indicates whether the current object is equal to another object of the same type.\n        /// </summary>\n        /// <param name=\"other\">An object to compare with this object.</param>\n        /// <returns>\n        /// true if the current object is equal to the <paramref name=\"other\" /> parameter; otherwise, false.\n        /// </returns>\n        public bool Equals(HttpLink other)\n        {\n            if (ReferenceEquals(null, other))\n            {\n                return false;\n            }\n\n            if (ReferenceEquals(this, other))\n            {\n                return true;\n            }\n\n            if (!Equals(this.targetUri, other.targetUri))\n            {\n                return false;\n            }\n\n            foreach (var parameter in other.Parameters)\n            {\n                object parameterValue;\n                if (!this.parameters.TryGetValue(parameter.Key, out parameterValue))\n                {\n                    return false;\n                }\n\n                if (parameterValue == null || parameter.Value == null)\n                {\n                    continue;\n                }\n\n                if (!parameterValue.Equals(parameter.Value))\n                {\n                    return false;\n                }\n            }\n\n            return true;\n        }\n\n        /// <summary>\n        /// Determines whether the specified <see cref=\"System.Object\" />, is equal to this instance.\n        /// </summary>\n        /// <param name=\"other\">The <see cref=\"System.Object\" /> to compare with this instance.</param>\n        /// <returns>\n        ///   <c>true</c> if the specified <see cref=\"System.Object\" /> is equal to this instance; otherwise, <c>false</c>.\n        /// </returns>\n        public override bool Equals(object other)\n        {\n            return other is HttpLink && this.Equals((HttpLink)other);\n        }\n\n        /// <summary>\n        /// Returns a hash code for this instance.\n        /// </summary>\n        /// <returns>\n        /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.\n        /// </returns>\n        public override int GetHashCode()\n        {\n            unchecked\n            {\n                var p = 0;\n\n                foreach (var parameter in this.parameters)\n                {\n                    p ^= StringComparer.OrdinalIgnoreCase.GetHashCode(parameter.Key);\n                    p ^= parameter.Value != null ? parameter.Value.GetHashCode() : 0;\n                }\n\n                var u = this.targetUri != null\n                    ? StringComparer.OrdinalIgnoreCase.GetHashCode(this.targetUri.ToString())\n                    : 0;\n\n                return (p * 397) ^ u;\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            var linkBuilder = new StringBuilder();\n            linkBuilder.Append('<');\n            linkBuilder.Append(this.TargetUri);\n            linkBuilder.Append('>');\n\n            var parameters = this.parameters\n                .Where(parameter => !string.IsNullOrWhiteSpace(parameter.Key))\n                .OrderBy(parameter => parameter.Key, ParameterComparer);\n\n            foreach (var parameter in parameters)\n            {\n                linkBuilder.Append(\"; \");\n                linkBuilder.Append(parameter.Key);\n\n                if (parameter.Value == null)\n                {\n                    continue;\n                }\n\n                linkBuilder.Append('=');\n                linkBuilder.Append('\"');\n                linkBuilder.Append(parameter.Value);\n                linkBuilder.Append('\"');\n            }\n\n            return linkBuilder.ToString();\n        }\n\n        private T GetParameterValue<T>(string parameterName)\n        {\n            object parameterValue;\n            if (!this.parameters.TryGetValue(parameterName, out parameterValue))\n            {\n                return default(T);\n            }\n\n            return (T)parameterValue;\n        }\n\n        /// <summary>\n        /// Parses the specified <paramref name=\"uri\"/> string into a <see cref=\"TargetUri\"/>.\n        /// </summary>\n        /// <param name=\"uri\">The URI string.</param>\n        /// <returns></returns>\n        /// <exception cref=\"System.ArgumentException\">uri</exception>\n        private static Uri ParseUri(string uri)\n        {\n            Uri parsedUri;\n            // Mono workaround. See http://www.mono-project.com/docs/faq/known-issues/urikind-relativeorabsolute/ for details. @asbjornu\n            var uriKind = uri.StartsWith(\"/\") ? UriKind.Relative : UriKind.RelativeOrAbsolute;\n            if (!Uri.TryCreate(uri, uriKind, out parsedUri))\n            {\n                throw new ArgumentException(string.Format(\"Can't parse '{0}' into an URI.\", uri), \"uri\");\n            }\n\n            return parsedUri;\n        }\n\n        private class HttpLinkParameterComparer : IComparer<string>\n        {\n            public int Compare(string x, string y)\n            {\n                if (ReferenceEquals(x, y))\n                {\n                    return 0;\n                }\n\n                if (ReferenceEquals(x, null))\n                {\n                    return -1;\n                }\n\n                if (x == \"rel\")\n                {\n                    return -1;\n                }\n\n                return string.Compare(x, y, StringComparison.Ordinal);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Nancy/HttpLinkBuilder.cs",
    "content": "namespace Nancy\n{\n    using System;\n    using System.Collections.Generic;\n    using System.Text;\n\n    /// <summary>\n    /// Builds an RFC 5988 Link HTTP header as a <see cref=\"List{T}\" /> of <see cref=\"HttpLink\" /> objects.\n    /// </summary>\n    /// <seealso cref=\"HttpLink\" />\n    public class HttpLinkBuilder : List<HttpLink>\n    {\n        private readonly List<string> additionalLinks;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpLinkBuilder\"/> class.\n        /// </summary>\n        public HttpLinkBuilder()\n        {\n            this.additionalLinks = new List<string>();\n        }\n\n        /// <summary>\n        /// Adds the specified link to the builder.\n        /// </summary>\n        /// <param name=\"link\">The link to add to the builder.</param>\n        public void Add(string link)\n        {\n            if (link == null)\n            {\n                throw new ArgumentNullException(\"link\");\n            }\n\n            this.additionalLinks.Add(link);\n        }\n\n        /// <summary>\n        /// Returns a <see cref=\"System.String\" /> that represents an RFC 5988 Link HTTP header.\n        /// </summary>\n        /// <returns>\n        /// A <see cref=\"System.String\" /> that represents an RFC 5988 Link HTTP header.\n        /// </returns>\n        public override string ToString()\n        {\n            var sb = new StringBuilder();\n\n            foreach (var link in this)\n            {\n                if (sb.Length > 0)\n                {\n                    sb.Append(\", \");\n                }\n\n                sb.Append(link);\n            }\n\n            foreach (var link in this.additionalLinks)\n            {\n                if (sb.Length > 0)\n                {\n                    sb.Append(\", \");\n                }\n\n                sb.Append(link);\n            }\n\n            return sb.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "src/Nancy/HttpLinkRelation.cs",
    "content": "﻿namespace Nancy\n{\n    using System;\n\n    /// <summary>\n    /// The relation that identifies the semantics of a <see cref=\"HttpLink\"/> contained in an RFC 5988 Link HTTP header,\n    /// as built by the <see cref=\"HttpLinkBuilder\"/>.\n    /// </summary>\n    /// <seealso cref=\"System.Uri\" />\n    public class HttpLinkRelation : Uri, IEquatable<HttpLinkRelation>\n    {\n        /// <summary>\n        /// The URI prefix to use for IANA registered link relations.\n        /// </summary>\n        public static readonly Uri IanaLinkRelationPrefix = new Uri(\"http://www.iana.org/assignments/relation/\");\n\n        private readonly Uri prefix;\n\n        private readonly string value;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpLinkRelation\"/> class.\n        /// </summary>\n        /// <param name=\"relation\">The relation.</param>\n        public HttpLinkRelation(string relation)\n            : this(Parse(relation).Prefix, Parse(relation).Value)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpLinkRelation\" /> class.\n        /// </summary>\n        /// <param name=\"prefix\">The prefix.</param>\n        /// <param name=\"value\">The value.</param>\n        public HttpLinkRelation(Uri prefix, string value)\n            : base(prefix + value)\n        {\n            this.prefix = prefix;\n            this.value = value;\n        }\n\n\n        /// <summary>\n        /// Gets the <see cref=\"Uri\"/> prefix for the link relation. Will be set to <see cref=\"IanaLinkRelationPrefix\"/>\n        /// if the <see cref=\"Value\"/> is a relative one.\n        /// </summary>\n        /// <value>\n        /// The <see cref=\"Uri\"/> prefix for the link relation.\n        /// </value>\n        public Uri Prefix\n        {\n            get { return this.prefix; }\n        }\n\n        /// <summary>\n        /// Gets the link relation value.\n        /// </summary>\n        /// <value>\n        /// The link relation value.\n        /// </value>\n        public string Value\n        {\n            get { return this.value; }\n        }\n\n        /// <summary>\n        /// Indicates whether the current object is equal to another object of the same type.\n        /// </summary>\n        /// <param name=\"other\">An object to compare with this object.</param>\n        /// <returns>\n        /// true if the current object is equal to the <paramref name=\"other\" /> parameter; otherwise, false.\n        /// </returns>\n        public bool Equals(HttpLinkRelation other)\n        {\n            if (ReferenceEquals(null, other))\n            {\n                return false;\n            }\n\n            if (ReferenceEquals(this, other))\n            {\n                return true;\n            }\n\n            return StringComparer.OrdinalIgnoreCase.Equals(this.ToString(), other.ToString());\n        }\n\n        /// <summary>\n        /// Determines whether the specified <see cref=\"System.Object\" />, is equal to this instance.\n        /// </summary>\n        /// <param name=\"other\">The <see cref=\"System.Object\" /> to compare with this instance.</param>\n        /// <returns>\n        ///   <c>true</c> if the specified <see cref=\"System.Object\" /> is equal to this instance; otherwise, <c>false</c>.\n        /// </returns>\n        public override bool Equals(object other)\n        {\n            return other is HttpLinkRelation && this.Equals((HttpLinkRelation)other);\n        }\n\n        /// <summary>\n        /// Returns a hash code for this instance.\n        /// </summary>\n        /// <returns>\n        /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.\n        /// </returns>\n        public override int GetHashCode()\n        {\n            unchecked\n            {\n                var p = this.prefix != null\n                    ? this.prefix.GetHashCode()\n                    : 0;\n\n                var v = this.value != null\n                    ? StringComparer.OrdinalIgnoreCase.GetHashCode(this.value)\n                    : 0;\n\n                return (p * 397) ^ v;\n            }\n        }\n\n        /// <summary>\n        /// Parses the specified link <paramref name=\"relation\" /> name into an absolute <see cref=\"Uri\" />.\n        /// Will be prefixed with <see cref=\"IanaLinkRelationPrefix\" /> if the <paramref name=\"relation\" /> is\n        /// a relative value.\n        /// </summary>\n        /// <param name=\"relation\">The link relation name.</param>\n        /// <returns>\n        /// A new instance of <see cref=\"HttpLinkRelation\" /> from the parsed link <paramref name=\"relation\"/> value.\n        /// </returns>\n        /// <exception cref=\"System.ArgumentNullException\"><paramref name=\"relation\"/></exception>\n        /// <exception cref=\"System.ArgumentException\"><paramref name=\"relation\"/></exception>\n        public static HttpLinkRelation Parse(string relation)\n        {\n            if (string.IsNullOrEmpty(relation))\n            {\n                throw new ArgumentNullException(\"relation\");\n            }\n\n            Uri parsedRelation;\n\n            if (TryCreate(relation, UriKind.Absolute, out parsedRelation))\n            {\n                if (parsedRelation.AbsolutePath.Length < 2\n                    || !parsedRelation.AbsolutePath.Contains(\"/\")\n                    || parsedRelation.AbsolutePath.EndsWith(\"/\"))\n                {\n                    throw new FormatException(string.Format(\"The link relation '{0}' is invalid.\", relation));\n                }\n\n                var slashIndex = relation.LastIndexOf('/');\n                var prefix = relation.Substring(0, slashIndex + 1);\n                var value = relation.Substring(slashIndex + 1);\n                var prefixUri = new Uri(prefix);\n\n                return new HttpLinkRelation(prefixUri, value);\n            }\n\n            if (TryCreate(IanaLinkRelationPrefix + relation, UriKind.Absolute, out parsedRelation))\n            {\n                return new HttpLinkRelation(IanaLinkRelationPrefix, relation);\n            }\n\n            throw new FormatException(string.Format(\"The link relation '{0}' is invalid.\", relation));\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 this.prefix == IanaLinkRelationPrefix\n                ? this.Value\n                : base.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "src/Nancy/HttpMultipart.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Text;\r\n\r\n    /// <summary>\r\n    /// Retrieves <see cref=\"HttpMultipartBoundary\"/> instances from a request stream.\r\n    /// </summary>\r\n    public class HttpMultipart\r\n    {\r\n        private const byte LF = (byte)'\\n';\r\n        private readonly byte[] boundaryAsBytes;\r\n        private readonly HttpMultipartBuffer readBuffer;\r\n        private readonly Stream requestStream;\r\n        private readonly byte[] closingBoundaryAsBytes;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"HttpMultipart\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"requestStream\">The request stream to parse.</param>\r\n        /// <param name=\"boundary\">The boundary marker to look for.</param>\r\n        public HttpMultipart(Stream requestStream, string boundary)\r\n        {\r\n            this.requestStream = requestStream;\r\n            this.boundaryAsBytes = GetBoundaryAsBytes(boundary, false);\r\n            this.closingBoundaryAsBytes = GetBoundaryAsBytes(boundary, true);\r\n            this.readBuffer = new HttpMultipartBuffer(this.boundaryAsBytes, this.closingBoundaryAsBytes);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"HttpMultipartBoundary\"/> instances from the request stream.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance, containing the found <see cref=\"HttpMultipartBoundary\"/> instances.</returns>\r\n        public IEnumerable<HttpMultipartBoundary> GetBoundaries()\r\n        {\r\n            return\r\n                (from boundaryStream in this.GetBoundarySubStreams()\r\n                select new HttpMultipartBoundary(boundaryStream)).ToList();\r\n        }\r\n\r\n        private IEnumerable<HttpMultipartSubStream> GetBoundarySubStreams()\r\n        {\r\n            var boundarySubStreams = new List<HttpMultipartSubStream>();\r\n            var boundaryStart = this.GetNextBoundaryPosition();\r\n\r\n            var found = 0;\r\n            while (MultipartIsNotCompleted(boundaryStart) && found < StaticConfiguration.RequestQueryFormMultipartLimit)\r\n            {\r\n                var boundaryEnd = this.GetNextBoundaryPosition();\r\n                boundarySubStreams.Add(new HttpMultipartSubStream(\r\n                    this.requestStream,\r\n                    boundaryStart,\r\n                    this.GetActualEndOfBoundary(boundaryEnd)));\r\n\r\n                boundaryStart = boundaryEnd;\r\n\r\n                found++;\r\n            }\r\n\r\n            return boundarySubStreams;\r\n        }\r\n        private bool MultipartIsNotCompleted(long boundaryPosition)\r\n        {\r\n            return boundaryPosition > -1 && !this.readBuffer.IsClosingBoundary;\r\n        }\r\n\r\n        //we add two because or the \\r\\n before the boundary\r\n        private long GetActualEndOfBoundary(long boundaryEnd)\r\n        {\r\n            if (this.CheckIfFoundEndOfStream())\r\n            {\r\n                return this.requestStream.Position - (this.readBuffer.Length + 2);\r\n            }\r\n            return boundaryEnd - (this.readBuffer.Length + 2);\r\n        }\r\n\r\n        private bool CheckIfFoundEndOfStream()\r\n        {\r\n            return this.requestStream.Position.Equals(this.requestStream.Length);\r\n        }\r\n\r\n        private static byte[] GetBoundaryAsBytes(string boundary, bool closing)\r\n        {\r\n            var boundaryBuilder = new StringBuilder();\r\n\r\n            boundaryBuilder.Append(\"--\");\r\n            boundaryBuilder.Append(boundary);\r\n\r\n            if(closing)\r\n            {\r\n                boundaryBuilder.Append(\"--\");\r\n            }\r\n            else\r\n            {\r\n                boundaryBuilder.Append('\\r');\r\n                boundaryBuilder.Append('\\n');\r\n            }\r\n\r\n            var bytes =\r\n                Encoding.ASCII.GetBytes(boundaryBuilder.ToString());\r\n\r\n            return bytes;\r\n        }\r\n\r\n        private long GetNextBoundaryPosition()\r\n        {\r\n            this.readBuffer.Reset();\r\n            while(true)\r\n            {\r\n                var byteReadFromStream = this.requestStream.ReadByte();\r\n\r\n                if (byteReadFromStream == -1)\r\n                {\r\n                    return -1;\r\n                }\r\n\r\n                this.readBuffer.Insert((byte)byteReadFromStream);\r\n\r\n                if (this.readBuffer.IsFull && (this.readBuffer.IsBoundary || this.readBuffer.IsClosingBoundary))\r\n                {\r\n                    return this.requestStream.Position;\r\n                }\r\n\r\n                if (byteReadFromStream.Equals(LF) || this.readBuffer.IsFull)\r\n                {\r\n                    this.readBuffer.Reset();\r\n                }\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/HttpMultipartBoundary.cs",
    "content": "namespace Nancy\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Text;\r\n    using System.Text.RegularExpressions;\r\n\r\n    /// <summary>\r\n    /// Represents the content boundary of a HTTP multipart/form-data boundary in a stream.\r\n    /// </summary>\r\n    public class HttpMultipartBoundary\r\n    {\r\n        private const byte LF = (byte)'\\n';\r\n        private const byte CR = (byte)'\\r';\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"HttpMultipartBoundary\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"boundaryStream\">The stream that contains the boundary information.</param>\r\n        public HttpMultipartBoundary(HttpMultipartSubStream boundaryStream)\r\n        {\r\n            this.Value = boundaryStream;\r\n            this.ExtractHeaders();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the contents type of the boundary value.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the name of the value if it is available; otherwise <see cref=\"string.Empty\"/>.</value>\r\n        public string ContentType { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets or the filename for the boundary value.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the filename value if it is available; otherwise <see cref=\"string.Empty\"/>.</value>\r\n        /// <remarks>This is the RFC2047 decoded value of the filename attribute of the Content-Disposition header.</remarks>\r\n        public string Filename { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets name of the boundary value.\r\n        /// </summary>\r\n        /// <remarks>This is the RFC2047 decoded value of the name attribute of the Content-Disposition header.</remarks>\r\n        public string Name { get; private set; }\r\n\r\n        /// <summary>\r\n        /// A stream containing the value of the boundary.\r\n        /// </summary>\r\n        /// <remarks>This is the RFC2047 decoded value of the Content-Type header.</remarks>\r\n        public HttpMultipartSubStream Value { get; private set; }\r\n\r\n        private void ExtractHeaders()\r\n        {\r\n            while(true)\r\n            {\r\n                var header = ReadLineFromStream(this.Value);\r\n\r\n                if (string.IsNullOrEmpty(header))\r\n                {\r\n                    break;\r\n                }\r\n\r\n                if (header.StartsWith(\"Content-Disposition\", StringComparison.CurrentCultureIgnoreCase))\r\n                {\r\n                    this.Name = Regex.Match(header, @\"name=\"\"?(?<name>[^\\\"\"]*)\", RegexOptions.IgnoreCase).Groups[\"name\"].Value;\r\n                    this.Filename = Regex.Match(header, @\"filename\\*?=\"\"?(?<filename>[^\\\"\";]*)\", RegexOptions.IgnoreCase).Groups[\"filename\"].Value;\r\n                    if (this.Filename.StartsWith(\"utf-8''\", StringComparison.CurrentCultureIgnoreCase))\r\n                    {\r\n                        this.Filename = Uri.UnescapeDataString(this.Filename.Substring(7));\r\n                    }\r\n                }\r\n\r\n                if (header.StartsWith(\"Content-Type\", StringComparison.OrdinalIgnoreCase))\r\n                {\r\n                    this.ContentType = header.Split(new[] { ' ' }).Last().Trim();\r\n                }\r\n            }\r\n\r\n            this.Value.PositionStartAtCurrentLocation();\r\n        }\r\n\r\n        private static string ReadLineFromStream(Stream stream)\r\n        {\r\n            var readBuffer = new List<byte>();\r\n\r\n            while (true)\r\n            {\r\n                var byteReadFromStream = stream.ReadByte();\r\n\r\n                if (byteReadFromStream == -1)\r\n                {\r\n                    return null;\r\n                }\r\n\r\n                if (byteReadFromStream.Equals(LF))\r\n                {\r\n                    break;\r\n                }\r\n\r\n                readBuffer.Add((byte) byteReadFromStream);\r\n            }\r\n\r\n            return Encoding.UTF8.GetString(readBuffer.ToArray()).Trim((char) CR);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/HttpMultipartBuffer.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using System;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// A buffer that is used to locate a HTTP multipart/form-data boundary in a stream.\r\n    /// </summary>\r\n    public class HttpMultipartBuffer\r\n    {\r\n        private readonly byte[] boundaryAsBytes;\r\n        private readonly byte[] closingBoundaryAsBytes;\r\n        private readonly byte[] buffer;\r\n        private int position;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"HttpMultipartBuffer\"/> class, with\r\n        /// the provided <paramref name=\"boundaryAsBytes\"/> and <paramref name=\"closingBoundaryAsBytes\"/>.\r\n        /// </summary>\r\n        /// <param name=\"boundaryAsBytes\">The boundary as a byte-array.</param>\r\n        /// <param name=\"closingBoundaryAsBytes\">The closing boundary as byte-array</param>\r\n        public HttpMultipartBuffer(byte[] boundaryAsBytes, byte[] closingBoundaryAsBytes)\r\n        {\r\n            this.boundaryAsBytes = boundaryAsBytes;\r\n            this.closingBoundaryAsBytes = closingBoundaryAsBytes;\r\n            this.buffer = new byte[this.boundaryAsBytes.Length];\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether the buffer contains the same values as the boundary.\r\n        /// </summary>\r\n        /// <value><see langword=\"true\"/> if buffer contains the same values as the boundary; otherwise, <see langword=\"false\"/>.</value>\r\n        public bool IsBoundary\r\n        {\r\n            get { return this.buffer.SequenceEqual(this.boundaryAsBytes); }\r\n        }\r\n        /// <summary>\r\n        /// Gets a value indicating whether this instance is closing boundary.\r\n        /// </summary>\r\n        /// <value>\r\n        /// <see langword=\"true\"/> if this instance is closing boundary; otherwise, <see langword=\"false\"/>.\r\n        /// </value>\r\n        public bool IsClosingBoundary\r\n        {\r\n            get { return this.buffer.SequenceEqual(this.closingBoundaryAsBytes); }\r\n        }\r\n        /// <summary>\r\n        /// Gets a value indicating whether this buffer is full.\r\n        /// </summary>\r\n        /// <value><see langword=\"true\"/> if buffer is full; otherwise, <see langword=\"false\"/>.</value>\r\n        public bool IsFull\r\n        {\r\n            get { return this.position.Equals(this.buffer.Length); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the number of bytes that can be stored in the buffer.\r\n        /// </summary>\r\n        /// <value>The number of bytes that can be stored in the buffer.</value>\r\n        public int Length\r\n        {\r\n            get { return this.buffer.Length; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Resets the buffer so that inserts happens from the start again.\r\n        /// </summary>\r\n        /// <remarks>This does not clear any previously written data, just resets the buffer position to the start. Data that is inserted after Reset has been called will overwrite old data.</remarks>\r\n        public void Reset()\r\n        {\r\n            this.position = 0;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Inserts the specified value into the buffer and advances the internal position.\r\n        /// </summary>\r\n        /// <param name=\"value\">The value to insert into the buffer.</param>\r\n        /// <remarks>This will throw an <see cref=\"ArgumentOutOfRangeException\"/> is you attempt to call insert more times then the <see cref=\"Length\"/> of the buffer and <see cref=\"Reset\"/> was not invoked.</remarks>\r\n        public void Insert(byte value)\r\n        {\r\n            this.buffer[this.position++] = value;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/HttpMultipartSubStream.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using System;\r\n    using System.IO;\r\n\r\n    /// <summary>\r\n    /// A decorator stream that sits on top of an existing stream and appears as a unique stream.\r\n    /// </summary>\r\n    public class HttpMultipartSubStream : Stream\r\n    {\r\n        private readonly Stream stream;\r\n        private long start;\r\n        private readonly long end;\r\n        private long position;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"HttpMultipartSubStream\"/> class, with\r\n        /// the provided <paramref name=\"stream\"/>, <paramref name=\"start\"/> and <paramref name=\"end\"/>.\r\n        /// </summary>\r\n        /// <param name=\"stream\">The stream to create the sub-stream ontop of.</param>\r\n        /// <param name=\"start\">The start offset on the parent stream where the sub-stream should begin.</param>\r\n        /// <param name=\"end\">The end offset on the parent stream where the sub-stream should end.</param>\r\n        public HttpMultipartSubStream(Stream stream, long start, long end)\r\n        {\r\n            this.stream = stream;\r\n            this.start = start;\r\n            this.position = start;\r\n            this.end = end;\r\n        }\r\n\r\n        /// <summary>\r\n        /// When overridden in a derived class, gets a value indicating whether the current stream supports reading.\r\n        /// </summary>\r\n        /// <returns><see langword=\"true\"/> if the stream supports reading; otherwise, <see langword=\"false\"/>.</returns>\r\n        public override bool CanRead\r\n        {\r\n            get { return true; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// When overridden in a derived class, gets a value indicating whether the current stream supports seeking.\r\n        /// </summary>\r\n        /// <returns><see langword=\"true\"/> if the stream supports seeking; otherwise, <see langword=\"false\"/>.</returns>\r\n        public override bool CanSeek\r\n        {\r\n            get { return true; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// When overridden in a derived class, gets a value indicating whether the current stream supports writing.\r\n        /// </summary>\r\n        /// <returns><see langword=\"true\"/> if the stream supports writing; otherwise, <see langword=\"false\"/>.</returns>\r\n        public override bool CanWrite\r\n        {\r\n            get { return false; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// When overridden in a derived class, gets the length in bytes of the stream.\r\n        /// </summary>\r\n        /// <returns>A long value representing the length of the stream in bytes.</returns>\r\n        /// <exception cref=\"NotSupportedException\">A class derived from Stream does not support seeking. </exception><exception cref=\"T:System.ObjectDisposedException\">Methods were called after the stream was closed.</exception>\r\n        public override long Length\r\n        {\r\n            get { return (this.end - this.start); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// When overridden in a derived class, gets or sets the position within the current stream.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// The current position within the stream.\r\n        /// </returns>\r\n        /// <exception cref=\"T:System.IO.IOException\">An I/O error occurs. </exception><exception cref=\"T:System.NotSupportedException\">The stream does not support seeking. </exception><exception cref=\"T:System.ObjectDisposedException\">Methods were called after the stream was closed. </exception><filterpriority>1</filterpriority>\r\n        public override long Position\r\n        {\r\n            get { return this.position - this.start; }\r\n            set { this.position = this.Seek(value, SeekOrigin.Begin); }\r\n        }\r\n\r\n        private long CalculateSubStreamRelativePosition(SeekOrigin origin, long offset)\r\n        {\r\n            var subStreamRelativePosition = 0L;\r\n\r\n            switch (origin)\r\n            {\r\n                case SeekOrigin.Begin:\r\n                    subStreamRelativePosition = this.start + offset;\r\n                    break;\r\n\r\n                case SeekOrigin.Current:\r\n                    subStreamRelativePosition = this.position + offset;\r\n                    break;\r\n\r\n                case SeekOrigin.End:\r\n                    subStreamRelativePosition = this.end + offset;\r\n                    break;\r\n            }\r\n            return subStreamRelativePosition;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Sets the position of the stream as the start point.\r\n        /// </summary>\r\n        public void PositionStartAtCurrentLocation()\r\n        {\r\n            this.start = this.stream.Position;\r\n        }\r\n\r\n        /// <summary>\r\n        /// When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device.\r\n        /// </summary>\r\n        /// <remarks>In the <see cref=\"HttpMultipartSubStream\"/> type this method is implemented as no-op.</remarks>\r\n        public override void Flush()\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.\r\n        /// </summary>\r\n        /// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached. </returns>\r\n        /// <param name=\"buffer\">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name=\"offset\"/> and (<paramref name=\"offset\"/> + <paramref name=\"count\"/> - 1) replaced by the bytes read from the current source. </param>\r\n        /// <param name=\"offset\">The zero-based byte offset in <paramref name=\"buffer\"/> at which to begin storing the data read from the current stream.</param>\r\n        /// <param name=\"count\">The maximum number of bytes to be read from the current stream. </param>\r\n        public override int Read(byte[] buffer, int offset, int count)\r\n        {\r\n            if (count > (this.end - this.position))\r\n            {\r\n                count = (int)(this.end - this.position);\r\n            }\r\n\r\n            if (count <= 0)\r\n            {\r\n                return 0;\r\n            }\r\n\r\n            this.stream.Position = this.position;\r\n\r\n            var bytesReadFromStream =\r\n                this.stream.Read(buffer, offset, count);\r\n\r\n            this.RepositionAfterRead(bytesReadFromStream);\r\n\r\n            return bytesReadFromStream;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.\r\n        /// </summary>\r\n        /// <returns>The unsigned byte cast to an Int32, or -1 if at the end of the stream.</returns>\r\n        public override int ReadByte()\r\n        {\r\n            if (this.position >= this.end)\r\n            {\r\n                return -1;\r\n            }\r\n\r\n            this.stream.Position = this.position;\r\n\r\n            var byteReadFromStream = this.stream.ReadByte();\r\n\r\n            this.RepositionAfterRead(1);\r\n\r\n            return byteReadFromStream;\r\n        }\r\n\r\n        private void RepositionAfterRead(int bytesReadFromStream)\r\n        {\r\n            if (bytesReadFromStream == -1)\r\n            {\r\n                this.position = this.end;\r\n            }\r\n            else\r\n            {\r\n                this.position += bytesReadFromStream;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// When overridden in a derived class, sets the position within the current stream.\r\n        /// </summary>\r\n        /// <returns>The new position within the current stream.</returns>\r\n        /// <param name=\"offset\">A byte offset relative to the <paramref name=\"origin\"/> parameter.</param>\r\n        /// <param name=\"origin\">A value of type <see cref=\"SeekOrigin\"/> indicating the reference point used to obtain the new position.</param>\r\n        public override long Seek(long offset, SeekOrigin origin)\r\n        {\r\n            var subStreamRelativePosition =\r\n                this.CalculateSubStreamRelativePosition(origin, offset);\r\n\r\n            this.ThrowExceptionIsPositionIsOutOfBounds(subStreamRelativePosition);\r\n\r\n            this.position = this.stream.Seek(subStreamRelativePosition, SeekOrigin.Begin);\r\n\r\n            return this.position;\r\n        }\r\n\r\n        /// <summary>\r\n        /// When overridden in a derived class, sets the length of the current stream.\r\n        /// </summary>\r\n        /// <param name=\"value\">The desired length of the current stream in bytes.</param>\r\n        /// <remarks>This will always throw a <see cref=\"InvalidOperationException\"/> for the <see cref=\"HttpMultipartSubStream\"/> type.</remarks>\r\n        public override void SetLength(long value)\r\n        {\r\n            throw new InvalidOperationException();\r\n        }\r\n\r\n        /// <summary>\r\n        /// When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.\r\n        /// </summary>\r\n        /// <param name=\"buffer\">An array of bytes. This method copies <paramref name=\"count\"/> bytes from <paramref name=\"buffer\"/> to the current stream. </param>\r\n        /// <param name=\"offset\">The zero-based byte offset in <paramref name=\"buffer\"/> at which to begin copying bytes to the current stream. </param>\r\n        /// <param name=\"count\">The number of bytes to be written to the current stream. </param>\r\n        /// <remarks>This will always throw a <see cref=\"InvalidOperationException\"/> for the <see cref=\"HttpMultipartSubStream\"/> type.</remarks>\r\n        public override void Write(byte[] buffer, int offset, int count)\r\n        {\r\n            throw new InvalidOperationException();\r\n        }\r\n\r\n        private void ThrowExceptionIsPositionIsOutOfBounds(long subStreamRelativePosition)\r\n        {\r\n            if (subStreamRelativePosition < 0 || subStreamRelativePosition > this.end)\r\n                throw new InvalidOperationException();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/HttpStatusCode.cs",
    "content": "namespace Nancy\r\n{\r\n    /// <summary>\r\n    /// HTTP Status Codes\r\n    /// </summary>\r\n    /// <remarks>The values are based on the list found at http://en.wikipedia.org/wiki/List_of_HTTP_status_codes </remarks>\r\n    public enum HttpStatusCode\r\n    {\r\n        /// <summary>\r\n        /// 100 Continue\r\n        /// </summary>\r\n        Continue = 100,\r\n        /// <summary>\r\n        /// 101 SwitchingProtocols\r\n        /// </summary>\r\n        SwitchingProtocols = 101,\r\n        /// <summary>\r\n        /// 102 Processing\r\n        /// </summary>\r\n        Processing = 102,\r\n        /// <summary>\r\n        /// 103 Checkpoint\r\n        /// </summary>\r\n        Checkpoint = 103,\r\n        /// <summary>\r\n        /// 200 OK\r\n        /// </summary>\r\n        OK = 200,\r\n        /// <summary>\r\n        /// 201 Created\r\n        /// </summary>\r\n        Created = 201,\r\n        /// <summary>\r\n        /// 202 Accepted\r\n        /// </summary>\r\n        Accepted = 202,\r\n        /// <summary>\r\n        /// 203 NonAuthoritativeInformation\r\n        /// </summary>\r\n        NonAuthoritativeInformation = 203,\r\n        /// <summary>\r\n        /// 204 NoContent\r\n        /// </summary>\r\n        NoContent = 204,\r\n        /// <summary>\r\n        /// 205 ResetContent\r\n        /// </summary>\r\n        ResetContent = 205,\r\n        /// <summary>\r\n        /// 206 PartialContent\r\n        /// </summary>\r\n        PartialContent = 206,\r\n        /// <summary>\r\n        /// 207 MultipleStatus\r\n        /// </summary>\r\n        MultipleStatus = 207,\r\n        /// <summary>\r\n        /// 226 IMUsed\r\n        /// </summary>\r\n        IMUsed = 226,\r\n        /// <summary>\r\n        /// 300 MultipleChoices\r\n        /// </summary>\r\n        MultipleChoices = 300,\r\n        /// <summary>\r\n        /// 301 MovedPermanently\r\n        /// </summary>\r\n        MovedPermanently = 301,\r\n        /// <summary>\r\n        /// 302 Found\r\n        /// </summary>\r\n        Found = 302,\r\n        /// <summary>\r\n        /// 303 SeeOther\r\n        /// </summary>\r\n        SeeOther = 303,\r\n        /// <summary>\r\n        /// 304 NotModified\r\n        /// </summary>\r\n        NotModified = 304,\r\n        /// <summary>\r\n        /// 305 UseProxy\r\n        /// </summary>\r\n        UseProxy = 305,\r\n        /// <summary>\r\n        /// 306 SwitchProxy\r\n        /// </summary>\r\n        SwitchProxy = 306,\r\n        /// <summary>\r\n        /// 307 TemporaryRedirect\r\n        /// </summary>\r\n        TemporaryRedirect = 307,\r\n        /// <summary>\r\n        /// 308 ResumeIncomplete\r\n        /// </summary>\r\n        ResumeIncomplete = 308,\r\n        /// <summary>\r\n        /// 400 BadRequest\r\n        /// </summary>\r\n        BadRequest = 400,\r\n        /// <summary>\r\n        /// 401 Unauthorized\r\n        /// </summary>\r\n        Unauthorized = 401,\r\n        /// <summary>\r\n        /// 402 PaymentRequired\r\n        /// </summary>\r\n        PaymentRequired = 402,\r\n        /// <summary>\r\n        /// 403 Forbidden\r\n        /// </summary>\r\n        Forbidden = 403,\r\n        /// <summary>\r\n        /// 404 NotFound\r\n        /// </summary>\r\n        NotFound = 404,\r\n        /// <summary>\r\n        /// 405 MethodNotAllowed\r\n        /// </summary>\r\n        MethodNotAllowed = 405,\r\n        /// <summary>\r\n        /// 406 NotAcceptable\r\n        /// </summary>\r\n        NotAcceptable = 406,\r\n        /// <summary>\r\n        /// 407 ProxyAuthenticationRequired\r\n        /// </summary>\r\n        ProxyAuthenticationRequired = 407,\r\n        /// <summary>\r\n        /// 408 RequestTimeout\r\n        /// </summary>\r\n        RequestTimeout = 408,\r\n        /// <summary>\r\n        /// 409 Conflict\r\n        /// </summary>\r\n        Conflict = 409,\r\n        /// <summary>\r\n        /// 410 Gone\r\n        /// </summary>\r\n        Gone = 410,\r\n        /// <summary>\r\n        /// 411 LengthRequired\r\n        /// </summary>\r\n        LengthRequired = 411,\r\n        /// <summary>\r\n        /// 412 PreconditionFailed\r\n        /// </summary>\r\n        PreconditionFailed = 412,\r\n        /// <summary>\r\n        /// 413 RequestEntityTooLarge\r\n        /// </summary>\r\n        RequestEntityTooLarge = 413,\r\n        /// <summary>\r\n        /// 414 RequestUriTooLong\r\n        /// </summary>\r\n        RequestUriTooLong = 414,\r\n        /// <summary>\r\n        /// 415 UnsupportedMediaType\r\n        /// </summary>\r\n        UnsupportedMediaType = 415,\r\n        /// <summary>\r\n        /// 416 RequestedRangeNotSatisfiable\r\n        /// </summary>\r\n        RequestedRangeNotSatisfiable = 416,\r\n        /// <summary>\r\n        /// 417 ExpectationFailed\r\n        /// </summary>\r\n        ExpectationFailed = 417,\r\n        /// <summary>\r\n        /// 418 ImATeapot\r\n        /// </summary>\r\n        ImATeapot = 418,\r\n        /// <summary>\r\n        /// 420 Enhance Your Calm\r\n        /// </summary>\r\n        EnhanceYourCalm = 420,\r\n        /// <summary>\r\n        /// 422 UnprocessableEntity\r\n        /// </summary>\r\n        UnprocessableEntity = 422,\r\n        /// <summary>\r\n        /// 423 Locked\r\n        /// </summary>\r\n        Locked = 423,\r\n        /// <summary>\r\n        /// 424 FailedDependency\r\n        /// </summary>\r\n        FailedDependency = 424,\r\n        /// <summary>\r\n        /// 425 UnorderedCollection\r\n        /// </summary>\r\n        UnorderedCollection = 425,\r\n        /// <summary>\r\n        /// 426 UpgradeRequired\r\n        /// </summary>\r\n        UpgradeRequired = 426,\r\n        /// <summary>\r\n        /// 429 Too Many Requests\r\n        /// </summary>\r\n        TooManyRequests = 429,\r\n        /// <summary>\r\n        /// 444 NoResponse\r\n        /// </summary>\r\n        NoResponse = 444,\r\n        /// <summary>\r\n        /// 449 RetryWith\r\n        /// </summary>\r\n        RetryWith = 449,\r\n        /// <summary>\r\n        /// 450 BlockedByWindowsParentalControls\r\n        /// </summary>\r\n        BlockedByWindowsParentalControls = 450,\r\n        /// <summary>\r\n        /// 451 UnavailableForLegalReasons\r\n        /// </summary>\r\n        UnavailableForLegalReasons = 451,\r\n        /// <summary>\r\n        /// 499 ClientClosedRequest\r\n        /// </summary>\r\n        ClientClosedRequest = 499,\r\n        /// <summary>\r\n        /// 500 InternalServerError\r\n        /// </summary>\r\n        InternalServerError = 500,\r\n        /// <summary>\r\n        /// 501 NotImplemented\r\n        /// </summary>\r\n        NotImplemented = 501,\r\n        /// <summary>\r\n        /// 502 BadGateway\r\n        /// </summary>\r\n        BadGateway = 502,\r\n        /// <summary>\r\n        /// 503 ServiceUnavailable\r\n        /// </summary>\r\n        ServiceUnavailable = 503,\r\n        /// <summary>\r\n        /// 504 GatewayTimeout\r\n        /// </summary>\r\n        GatewayTimeout = 504,\r\n        /// <summary>\r\n        /// 505 HttpVersionNotSupported\r\n        /// </summary>\r\n        HttpVersionNotSupported = 505,\r\n        /// <summary>\r\n        /// 506 VariantAlsoNegotiates\r\n        /// </summary>\r\n        VariantAlsoNegotiates = 506,\r\n        /// <summary>\r\n        /// 507 InsufficientStorage\r\n        /// </summary>\r\n        InsufficientStorage = 507,\r\n        /// <summary>\r\n        /// 509 BandwidthLimitExceeded\r\n        /// </summary>\r\n        BandwidthLimitExceeded = 509,\r\n        /// <summary>\r\n        /// 510 NotExtended\r\n        /// </summary>\r\n        NotExtended = 510\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/IAssemblyCatalog.cs",
    "content": "namespace Nancy\r\n{\r\n    using System.Collections.Generic;\r\n    using System.Reflection;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality of an assembly catalog.\r\n    /// </summary>\r\n    public interface IAssemblyCatalog\r\n    {\r\n        /// <summary>\r\n        /// Gets all <see cref=\"Assembly\"/> instances in the catalog.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IReadOnlyCollection{T}\"/> of <see cref=\"Assembly\"/> instances.</returns>\r\n        IReadOnlyCollection<Assembly> GetAssemblies();\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/IHideObjectMembers.cs",
    "content": "namespace Nancy\r\n{\r\n    using System;\r\n    using System.ComponentModel;\r\n\r\n    /// <summary>\r\n    /// Helper interface used to hide the base <see cref=\"object\"/>  members from the fluent API to make it much cleaner\r\n    /// in Visual Studio intellisense.\r\n    /// </summary>\r\n    [EditorBrowsable(EditorBrowsableState.Never)]\r\n    public interface IHideObjectMembers\r\n    {\r\n        /// <summary>\r\n        /// Hides the <see cref=\"Equals\"/> method.\r\n        /// </summary>\r\n        [EditorBrowsable(EditorBrowsableState.Never)]\r\n        bool Equals(object obj);\r\n\r\n        /// <summary>\r\n        /// Hides the <see cref=\"GetHashCode\"/> method.\r\n        /// </summary>\r\n        [EditorBrowsable(EditorBrowsableState.Never)]\r\n        int GetHashCode();\r\n\r\n        /// <summary>\r\n        /// Hides the <see cref=\"GetType\"/> method.\r\n        /// </summary>\r\n        [EditorBrowsable(EditorBrowsableState.Never)]\r\n        Type GetType();\r\n\r\n        /// <summary>\r\n        /// Hides the <see cref=\"ToString\"/> method.\r\n        /// </summary>\r\n        [EditorBrowsable(EditorBrowsableState.Never)]\r\n        string ToString();\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/INancyContextFactory.cs",
    "content": "namespace Nancy\r\n{\r\n    /// <summary>\r\n    /// Creates NancyContext instances\r\n    /// </summary>\r\n    public interface INancyContextFactory\r\n    {\r\n        /// <summary>\r\n        /// Create a new NancyContext\r\n        /// </summary>\r\n        /// <returns>NancyContext instance</returns>\r\n        NancyContext Create(Request request);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/INancyEngine.cs",
    "content": "namespace Nancy\r\n{\r\n    using System;\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n\r\n    using Nancy.Bootstrapper;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality of an engine that can handle Nancy <see cref=\"Request\"/>s.\r\n    /// </summary>\r\n    public interface INancyEngine : IDisposable\r\n    {\r\n        /// <summary>\r\n        /// Factory for creating an <see cref=\"IPipelines\"/> instance for a incoming request.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IPipelines\"/> instance.</value>\r\n        Func<NancyContext, IPipelines> RequestPipelinesFactory { get; set; }\r\n\r\n        /// <summary>\r\n        /// Handles an incoming <see cref=\"Request\"/> async.\r\n        /// </summary>\r\n        /// <param name=\"request\">An <see cref=\"Request\"/> instance, containing the information about the current request.</param>\r\n        /// <param name=\"preRequest\">Delegate to call before the request is processed</param>\r\n        /// <param name=\"cancellationToken\">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>\r\n        /// <returns>The task object representing the asynchronous operation.</returns>\r\n        Task<NancyContext> HandleRequest(Request request, Func<NancyContext, NancyContext> preRequest, CancellationToken cancellationToken);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/INancyModule.cs",
    "content": "namespace Nancy\r\n{\r\n    using System.Collections.Generic;\r\n    using System.ComponentModel;\r\n\r\n    using Nancy.ModelBinding;\r\n    using Nancy.Responses.Negotiation;\r\n    using Nancy.Routing;\r\n    using Nancy.Validation;\r\n    using Nancy.ViewEngines;\r\n\r\n    /// <summary>\r\n    /// Nancy module base interface\r\n    /// Defines all the properties / behaviour needed by Nancy internally\r\n    /// </summary>\r\n    public interface INancyModule\r\n    {\r\n        /// <summary><para>\r\n        /// The post-request hook\r\n        /// </para><para>\r\n        /// The post-request hook is called after the response is created by the route execution.\r\n        /// It can be used to rewrite the response or add/remove items from the context.\r\n        /// </para></summary>\r\n        AfterPipeline After { get; set; }\r\n\r\n        /// <summary><para>\r\n        /// The pre-request hook\r\n        /// </para><para>\r\n        /// The PreRequest hook is called prior to executing a route. If any item in the\r\n        /// pre-request pipeline returns a response then the route is not executed and the\r\n        /// response is returned.\r\n        /// </para></summary>\r\n        BeforePipeline Before { get; set; }\r\n\r\n        /// <summary><para>\r\n        /// The error hook\r\n        /// </para><para>\r\n        /// The error hook is called if an exception is thrown at any time during executing\r\n        /// the PreRequest hook, a route and the PostRequest hook. It can be used to set\r\n        /// the response and/or finish any ongoing tasks (close database session, etc).\r\n        /// </para></summary>\r\n        ErrorPipeline OnError { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the current Nancy context\r\n        /// </summary><value>A <see cref=\"T:Nancy.NancyContext\" /> instance.</value>\r\n        NancyContext Context { get; set; }\r\n\r\n        /// <summary>\r\n        /// An extension point for adding support for formatting response contents.\r\n        /// </summary><value>This property will always return <see langword=\"null\" /> because it acts as an extension point.</value><remarks>Extension methods to this property should always return <see cref=\"P:Nancy.NancyModuleBase.Response\" /> or one of the types that can implicitly be types into a <see cref=\"P:Nancy.NancyModuleBase.Response\" />.</remarks>\r\n        IResponseFormatter Response { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the model binder locator\r\n        /// </summary>\r\n        IModelBinderLocator ModelBinderLocator { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the model validation result\r\n        /// </summary>\r\n        [EditorBrowsable(EditorBrowsableState.Never)]\r\n        ModelValidationResult ModelValidationResult { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the validator locator.\r\n        /// </summary>\r\n        IModelValidatorLocator ValidatorLocator { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets an <see cref=\"Request\" /> instance that represents the current request.\r\n        /// </summary><value>An <see cref=\"Request\" /> instance.</value>\r\n        Request Request { get; set; }\r\n\r\n        /// <summary>\r\n        /// The extension point for accessing the view engines in Nancy.\r\n        /// </summary><value>An <see cref=\"T:Nancy.ViewEngines.IViewFactory\" /> instance.</value><remarks>This is automatically set by Nancy at runtime.</remarks>\r\n        IViewFactory ViewFactory { get; set; }\r\n\r\n        /// <summary>\r\n        /// Get the root path of the routes in the current module.\r\n        /// </summary><value>A <see cref=\"T:System.String\" /> containing the root path of the module or <see langword=\"null\" /> if no root path should be used.</value><remarks>All routes will be relative to this root path.</remarks>\r\n        string ModulePath { get; }\r\n\r\n        /// <summary>\r\n        /// Gets all declared routes by the module.\r\n        /// </summary><value>A <see cref=\"T:System.Collections.Generic.IEnumerable`1\" /> instance, containing all <see cref=\"T:Nancy.Routing.Route\" /> instances declared by the module.</value>\r\n        IEnumerable<Route> Routes { get; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the dynamic object used to locate text resources.\r\n        /// </summary>\r\n        dynamic Text { get; }\r\n\r\n        /// <summary>\r\n        /// Renders a view from inside a route handler.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"ViewRenderer\"/> instance that is used to determine which view that should be rendered.</value>\r\n        ViewRenderer View { get; }\r\n\r\n        /// <summary>\r\n        /// Used to negotiate the content returned based on Accepts header.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"Negotiator\"/> instance that is used to negotiate the content returned.</value>\r\n        Negotiator Negotiate { get; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/INancyModuleCatalog.cs",
    "content": "namespace Nancy\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Catalog of <see cref=\"INancyModule\"/> instances.\r\n    /// </summary>\r\n    public interface INancyModuleCatalog\r\n    {\r\n        /// <summary>\r\n        /// Get all NancyModule implementation instances - should be per-request lifetime\r\n        /// </summary>\r\n        /// <param name=\"context\">The current context</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance containing <see cref=\"INancyModule\"/> instances.</returns>\r\n        IEnumerable<INancyModule> GetAllModules(NancyContext context);\r\n\r\n        /// <summary>\r\n        /// Retrieves a specific <see cref=\"INancyModule\"/> implementation - should be per-request lifetime\r\n        /// </summary>\r\n        /// <param name=\"moduleType\">Module type</param>\r\n        /// <param name=\"context\">The current context</param>\r\n        /// <returns>The <see cref=\"INancyModule\"/> instance</returns>\r\n        INancyModule GetModule(Type moduleType, NancyContext context);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/IO/RequestStream.cs",
    "content": "﻿namespace Nancy.IO\r\n{\r\n    using System;\r\n    using System.IO;\r\n    using System.Threading.Tasks;\r\n\r\n    using Nancy.Extensions;\r\n\r\n    /// <summary>\r\n    /// A <see cref=\"Stream\"/> decorator that can handle moving the stream out from memory and on to disk when the contents reaches a certain length.\r\n    /// </summary>\r\n    public class RequestStream : Stream\r\n    {\r\n        internal const int BufferSize = 4096;\r\n\r\n        /// <summary>\r\n        /// The default switchover threshold\r\n        /// </summary>\r\n        public static long DEFAULT_SWITCHOVER_THRESHOLD = 81920;\r\n\r\n        private bool disableStreamSwitching;\r\n        private readonly long thresholdLength;\r\n        private bool isSafeToDisposeStream;\r\n        private Stream stream;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"RequestStream\"/> class, with\r\n        /// the provided <paramref name=\"expectedLength\"/>, <paramref name=\"thresholdLength\"/> and <paramref name=\"disableStreamSwitching\"/>.\r\n        /// </summary>\r\n        /// <param name=\"expectedLength\">The expected length of the contents in the stream.</param>\r\n        /// <param name=\"thresholdLength\">The content length that will trigger the stream to be moved out of memory.</param>\r\n        /// <param name=\"disableStreamSwitching\">if set to <see langword=\"true\"/> the stream will never explicitly be moved to disk.</param>\r\n        public RequestStream(long expectedLength, long thresholdLength, bool disableStreamSwitching)\r\n            : this(null, expectedLength, thresholdLength, disableStreamSwitching)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"RequestStream\"/> class, with\r\n        /// the provided <paramref name=\"expectedLength\"/>, <paramref name=\"expectedLength\"/> and <paramref name=\"disableStreamSwitching\"/>.\r\n        /// </summary>\r\n        /// <param name=\"stream\">The <see cref=\"Stream\"/> that should be handled by the request stream</param>\r\n        /// <param name=\"expectedLength\">The expected length of the contents in the stream.</param>\r\n        /// <param name=\"disableStreamSwitching\">if set to <see langword=\"true\"/> the stream will never explicitly be moved to disk.</param>\r\n        public RequestStream(Stream stream, long expectedLength, bool disableStreamSwitching)\r\n            : this(stream, expectedLength, DEFAULT_SWITCHOVER_THRESHOLD, disableStreamSwitching)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"RequestStream\"/> class, with\r\n        /// the provided <paramref name=\"expectedLength\"/> and <paramref name=\"disableStreamSwitching\"/>.\r\n        /// </summary>\r\n        /// <param name=\"expectedLength\">The expected length of the contents in the stream.</param>\r\n        /// <param name=\"disableStreamSwitching\">if set to <see langword=\"true\"/> the stream will never explicitly be moved to disk.</param>\r\n        public RequestStream(long expectedLength, bool disableStreamSwitching)\r\n            : this(null, expectedLength, DEFAULT_SWITCHOVER_THRESHOLD, disableStreamSwitching)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"RequestStream\"/> class, with\r\n        /// the provided <paramref name=\"expectedLength\"/>, <paramref name=\"expectedLength\"/>, <paramref name=\"thresholdLength\"/> and <paramref name=\"disableStreamSwitching\"/>.\r\n        /// </summary>\r\n        /// <param name=\"stream\">The <see cref=\"Stream\"/> that should be handled by the request stream</param>\r\n        /// <param name=\"expectedLength\">The expected length of the contents in the stream.</param>\r\n        /// <param name=\"thresholdLength\">The content length that will trigger the stream to be moved out of memory.</param>\r\n        /// <param name=\"disableStreamSwitching\">if set to <see langword=\"true\"/> the stream will never explicitly be moved to disk.</param>\r\n        public RequestStream(Stream stream, long expectedLength, long thresholdLength, bool disableStreamSwitching)\r\n        {\r\n            this.thresholdLength = thresholdLength;\r\n            this.disableStreamSwitching = disableStreamSwitching;\r\n            this.stream = stream ?? this.CreateDefaultMemoryStream(expectedLength);\r\n\r\n            ThrowExceptionIfCtorParametersWereInvalid(this.stream, expectedLength, this.thresholdLength);\r\n\r\n            if (!this.MoveStreamOutOfMemoryIfExpectedLengthExceedSwitchLength(expectedLength))\r\n            {\r\n                this.MoveStreamOutOfMemoryIfContentsLengthExceedThresholdAndSwitchingIsEnabled();\r\n            }\r\n\r\n            if (!this.stream.CanSeek)\r\n            {\r\n                this.MoveToWritableStream();\r\n            }\r\n\r\n            this.stream.Position = 0;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Finalizes an instance of the <see cref=\"RequestStream\"/> class.\r\n        /// </summary>\r\n        ~RequestStream()\r\n        {\r\n            this.Dispose(false);\r\n        }\r\n\r\n        private void MoveToWritableStream()\r\n        {\r\n            var sourceStream = this.stream;\r\n            this.stream = new MemoryStream(BufferSize);\r\n\r\n            sourceStream.CopyTo(this.stream);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether the current stream supports reading.\r\n        /// </summary>\r\n        /// <returns>Always returns <see langword=\"true\"/>.</returns>\r\n        public override bool CanRead\r\n        {\r\n            get { return true; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether the current stream supports seeking.\r\n        /// </summary>\r\n        /// <returns>Always returns <see langword=\"true\"/>.</returns>\r\n        public override bool CanSeek\r\n        {\r\n            get { return this.stream.CanSeek; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a value that determines whether the current stream can time out.\r\n        /// </summary>\r\n        /// <returns>Always returns <see langword=\"false\"/>.</returns>\r\n        public override bool CanTimeout\r\n        {\r\n            get { return false; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether the current stream supports writing.\r\n        /// </summary>\r\n        /// <returns>Always returns <see langword=\"true\"/>.</returns>\r\n        public override bool CanWrite\r\n        {\r\n            get { return true; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the length in bytes of the stream.\r\n        /// </summary>\r\n        /// <returns>A long value representing the length of the stream in bytes.</returns>\r\n        public override long Length\r\n        {\r\n            get { return this.stream.Length; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether the current stream is stored in memory.\r\n        /// </summary>\r\n        /// <value><see langword=\"true\"/> if the stream is stored in memory; otherwise, <see langword=\"false\"/>.</value>\r\n        /// <remarks>The stream is moved to disk when either the length of the contents or expected content length exceeds the threshold specified in the constructor.</remarks>\r\n        public bool IsInMemory\r\n        {\r\n            get { return !(this.stream.GetType() == typeof(FileStream)); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the position within the current stream.\r\n        /// </summary>\r\n        /// <returns>The current position within the stream.</returns>\r\n        public override long Position\r\n        {\r\n            get { return this.stream.Position; }\r\n            set\r\n            {\r\n                if (value < 0)\r\n                    throw new InvalidOperationException(\"The position of the stream cannot be set to less than zero.\");\r\n\r\n                if (value > this.Length)\r\n                    throw new InvalidOperationException(\"The position of the stream cannot exceed the length of the stream.\");\r\n\r\n                this.stream.Position = value;\r\n            }\r\n        }\r\n\r\n#if !NETSTANDARD1_6\r\n        /// <summary>\r\n        /// Begins an asynchronous read operation.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"T:System.IAsyncResult\"/> that represents the asynchronous read, which could still be pending.</returns>\r\n        /// <param name=\"buffer\">The buffer to read the data into. </param>\r\n        /// <param name=\"offset\">The byte offset in <paramref name=\"buffer\"/> at which to begin writing data read from the stream. </param>\r\n        /// <param name=\"count\">The maximum number of bytes to read. </param>\r\n        /// <param name=\"callback\">An optional asynchronous callback, to be called when the read is complete. </param>\r\n        /// <param name=\"state\">A user-provided object that distinguishes this particular asynchronous read request from other requests. </param>\r\n        public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)\r\n        {\r\n            return this.stream.BeginRead(buffer, offset, count, callback, state);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Begins an asynchronous write operation.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IAsyncResult\"/> that represents the asynchronous write, which could still be pending.</returns>\r\n        /// <param name=\"buffer\">The buffer to write data from. </param>\r\n        /// <param name=\"offset\">The byte offset in <paramref name=\"buffer\"/> from which to begin writing. </param>\r\n        /// <param name=\"count\">The maximum number of bytes to write. </param>\r\n        /// <param name=\"callback\">An optional asynchronous callback, to be called when the write is complete. </param>\r\n        /// <param name=\"state\">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>\r\n        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)\r\n        {\r\n            return this.stream.BeginWrite(buffer, offset, count, callback, state);\r\n        }\r\n#endif\r\n\r\n        /// <summary>\r\n        /// Releases the unmanaged resources used by the <see cref=\"T:System.IO.Stream\" /> and optionally releases the managed resources.\r\n        /// </summary>\r\n        /// <param name=\"disposing\">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>\r\n        protected override void Dispose(bool disposing)\r\n        {\r\n            if (this.isSafeToDisposeStream)\r\n            {\r\n                if (this.stream != null)\r\n                {\r\n                    this.stream.Dispose();\r\n                }\r\n\r\n                var fileStream = this.stream as FileStream;\r\n                if (fileStream != null)\r\n                {\r\n                    DeleteTemporaryFile(fileStream.Name);\r\n                }\r\n            }\r\n\r\n            base.Dispose(disposing);\r\n        }\r\n#if !NETSTANDARD1_6\r\n        /// <summary>\r\n        /// Waits for the pending asynchronous read to complete.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// The number of bytes read from the stream, between zero (0) and the number of bytes you requested. Streams return zero (0) only at the end of the stream, otherwise, they should block until at least one byte is available.\r\n        /// </returns>\r\n        /// <param name=\"asyncResult\">The reference to the pending asynchronous request to finish. </param>\r\n        public override int EndRead(IAsyncResult asyncResult)\r\n        {\r\n            return this.stream.EndRead(asyncResult);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Ends an asynchronous write operation.\r\n        /// </summary>\r\n        /// <param name=\"asyncResult\">A reference to the outstanding asynchronous I/O request. </param>\r\n        public override void EndWrite(IAsyncResult asyncResult)\r\n        {\r\n            this.stream.EndWrite(asyncResult);\r\n\r\n            this.ShiftStreamToFileStreamIfNecessary();\r\n        }\r\n#endif\r\n\r\n        /// <summary>\r\n        /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device.\r\n        /// </summary>\r\n        public override void Flush()\r\n        {\r\n            this.stream.Flush();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a new request stream from a stream.\r\n        /// </summary>\r\n        /// <param name=\"stream\">The stream.</param>\r\n        /// <returns>A request stream instance</returns>\r\n        public static RequestStream FromStream(Stream stream)\r\n        {\r\n            return FromStream(stream, 0, DEFAULT_SWITCHOVER_THRESHOLD, false);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a new request stream from a stream.\r\n        /// </summary>\r\n        /// <param name=\"stream\">The stream.</param>\r\n        /// <param name=\"expectedLength\">The expected length.</param>\r\n        /// <returns>A request stream instance</returns>\r\n        public static RequestStream FromStream(Stream stream, long expectedLength)\r\n        {\r\n            return FromStream(stream, expectedLength, DEFAULT_SWITCHOVER_THRESHOLD, false);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a new request stream from a stream.\r\n        /// </summary>\r\n        /// <param name=\"stream\">The stream.</param>\r\n        /// <param name=\"expectedLength\">The expected length.</param>\r\n        /// <param name=\"thresholdLength\">Length of the threshold.</param>\r\n        /// <returns>A request stream instance</returns>\r\n        public static RequestStream FromStream(Stream stream, long expectedLength, long thresholdLength)\r\n        {\r\n            return FromStream(stream, expectedLength, thresholdLength, false);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a new request stream from a stream.\r\n        /// </summary>\r\n        /// <param name=\"stream\">The stream.</param>\r\n        /// <param name=\"expectedLength\">The expected length.</param>\r\n        /// <param name=\"disableStreamSwitching\">if set to <c>true</c> [disable stream switching].</param>\r\n        /// <returns>A request stream instance</returns>\r\n        public static RequestStream FromStream(Stream stream, long expectedLength, bool disableStreamSwitching)\r\n        {\r\n            return FromStream(stream, expectedLength, DEFAULT_SWITCHOVER_THRESHOLD, disableStreamSwitching);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a new request stream from a stream.\r\n        /// </summary>\r\n        /// <param name=\"stream\">The stream.</param>\r\n        /// <param name=\"expectedLength\">The expected length.</param>\r\n        /// <param name=\"thresholdLength\">Length of the threshold.</param>\r\n        /// <param name=\"disableStreamSwitching\">if set to <c>true</c> [disable stream switching].</param>\r\n        /// <returns>A request stream instance</returns>\r\n        public static RequestStream FromStream(Stream stream, long expectedLength, long thresholdLength, bool disableStreamSwitching)\r\n        {\r\n            return new RequestStream(stream, expectedLength, thresholdLength, disableStreamSwitching);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.\r\n        /// </summary>\r\n        /// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns>\r\n        /// <param name=\"buffer\">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name=\"offset\"/> and (<paramref name=\"offset\"/> + <paramref name=\"count\"/> - 1) replaced by the bytes read from the current source. </param>\r\n        /// <param name=\"offset\">The zero-based byte offset in <paramref name=\"buffer\"/> at which to begin storing the data read from the current stream. </param>\r\n        /// <param name=\"count\">The maximum number of bytes to be read from the current stream. </param>\r\n        public override int Read(byte[] buffer, int offset, int count)\r\n        {\r\n            return this.stream.Read(buffer, offset, count);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.\r\n        /// </summary>\r\n        /// <returns>The unsigned byte cast to an Int32, or -1 if at the end of the stream.</returns>\r\n        public override int ReadByte()\r\n        {\r\n            return this.stream.ReadByte();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Sets the position within the current stream.\r\n        /// </summary>\r\n        /// <returns>The new position within the current stream.</returns>\r\n        /// <param name=\"offset\">A byte offset relative to the <paramref name=\"origin\"/> parameter. </param>\r\n        /// <param name=\"origin\">A value of type <see cref=\"T:System.IO.SeekOrigin\"/> indicating the reference point used to obtain the new position. </param>\r\n        public override long Seek(long offset, SeekOrigin origin)\r\n        {\r\n            return this.stream.Seek(offset, origin);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Sets the length of the current stream.\r\n        /// </summary>\r\n        /// <param name=\"value\">The desired length of the current stream in bytes. </param>\r\n        /// <exception cref=\"NotSupportedException\">The stream does not support having its length set.</exception>\r\n        /// <remarks>This functionality is not supported by the <see cref=\"RequestStream\"/> type and will always throw <see cref=\"NotSupportedException\"/>.</remarks>\r\n        public override void SetLength(long value)\r\n        {\r\n            throw new NotSupportedException();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.\r\n        /// </summary>\r\n        /// <param name=\"buffer\">An array of bytes. This method copies <paramref name=\"count\"/> bytes from <paramref name=\"buffer\"/> to the current stream. </param>\r\n        /// <param name=\"offset\">The zero-based byte offset in <paramref name=\"buffer\"/> at which to begin copying bytes to the current stream. </param>\r\n        /// <param name=\"count\">The number of bytes to be written to the current stream. </param>\r\n        public override void Write(byte[] buffer, int offset, int count)\r\n        {\r\n            this.stream.Write(buffer, offset, count);\r\n\r\n            this.ShiftStreamToFileStreamIfNecessary();\r\n        }\r\n\r\n        private void ShiftStreamToFileStreamIfNecessary()\r\n        {\r\n            if (this.disableStreamSwitching)\r\n            {\r\n                return;\r\n            }\r\n\r\n            if (this.stream.Length >= this.thresholdLength)\r\n            {\r\n                // Close the stream here as closing it every time we call\r\n                // MoveStreamContentsToFileStream causes an (ObjectDisposedException)\r\n                // in NancyWcfGenericService - webRequest.UriTemplateMatch\r\n                var old = this.stream;\r\n                this.MoveStreamContentsToFileStream();\r\n#if NETSTANDARD2_0\r\n                old.Dispose();\r\n#else\r\n                old.Close();\r\n#endif\r\n            }\r\n        }\r\n\r\n        private static FileStream CreateTemporaryFileStream()\r\n        {\r\n            // we could use Path.GetTempFilePath() but this is problematic on Windows and more so on Mono\r\n            // symptoms will show when this method has been called > 65k times\r\n            // see docs: https://msdn.microsoft.com/en-us/library/system.io.path.gettempfilename(v=vs.110).aspx\r\n            // comments on Win32 implementation: https://msdn.microsoft.com/en-us/library/windows/desktop/aa364991(v=vs.85).aspx\r\n            // mono implementation: https://github.com/mono/mono/blob/master/mcs/class/corlib/System.IO/Path.cs#L490\r\n\r\n            var filePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString(\"N\") + \".tmp\");\r\n\r\n            return new FileStream(\r\n                filePath,\r\n                FileMode.Create,\r\n                FileAccess.ReadWrite,\r\n                FileShare.None,\r\n                8192,\r\n                StaticConfiguration.AllowFileStreamUploadAsync);\r\n        }\r\n\r\n        private Stream CreateDefaultMemoryStream(long expectedLength)\r\n        {\r\n            this.isSafeToDisposeStream = true;\r\n\r\n            if (this.disableStreamSwitching || expectedLength < this.thresholdLength)\r\n            {\r\n                return new MemoryStream((int)expectedLength);\r\n            }\r\n\r\n            this.disableStreamSwitching = true;\r\n\r\n            return CreateTemporaryFileStream();\r\n        }\r\n\r\n        private static void DeleteTemporaryFile(string fileName)\r\n        {\r\n            if (string.IsNullOrEmpty(fileName) || !File.Exists(fileName))\r\n            {\r\n                return;\r\n            }\r\n\r\n            try\r\n            {\r\n                File.Delete(fileName);\r\n            }\r\n            catch\r\n            {\r\n            }\r\n        }\r\n\r\n        private void MoveStreamOutOfMemoryIfContentsLengthExceedThresholdAndSwitchingIsEnabled()\r\n        {\r\n            if (!this.stream.CanSeek)\r\n            {\r\n                return;\r\n            }\r\n\r\n            try\r\n            {\r\n                if ((this.stream.Length > this.thresholdLength) && !this.disableStreamSwitching)\r\n                {\r\n                    this.MoveStreamContentsToFileStream();\r\n                }\r\n            }\r\n            catch (NotSupportedException)\r\n            {\r\n            }\r\n        }\r\n\r\n        private bool MoveStreamOutOfMemoryIfExpectedLengthExceedSwitchLength(long expectedLength)\r\n        {\r\n            if ((expectedLength >= this.thresholdLength) && !this.disableStreamSwitching)\r\n            {\r\n                this.MoveStreamContentsToFileStream();\r\n                return true;\r\n            }\r\n            return false;\r\n        }\r\n\r\n        private void MoveStreamContentsToFileStream()\r\n        {\r\n            var targetStream = CreateTemporaryFileStream();\r\n            this.isSafeToDisposeStream = true;\r\n\r\n            if (this.stream.CanSeek && this.stream.Length == 0)\r\n            {\r\n#if NETSTANDARD2_0\r\n                this.stream.Dispose();\r\n#else\r\n                this.stream.Close();\r\n#endif\r\n                this.stream = targetStream;\r\n                return;\r\n            }\r\n\r\n            // Seek to 0 if we can, although if we can't seek, and we've already written (if the size is unknown) then\r\n            // we are screwed anyway, and some streams that don't support seek also don't let you read the position so\r\n            // there's no real way to check :-/\r\n            if (this.stream.CanSeek)\r\n            {\r\n                this.stream.Position = 0;\r\n            }\r\n            this.stream.CopyTo(targetStream, 8196);\r\n            if (this.stream.CanWrite)\r\n            {\r\n                this.stream.Flush();\r\n            }\r\n\r\n            this.stream = targetStream;\r\n\r\n            this.disableStreamSwitching = true;\r\n        }\r\n\r\n        private static void ThrowExceptionIfCtorParametersWereInvalid(Stream stream, long expectedLength, long thresholdLength)\r\n        {\r\n            if (!stream.CanRead)\r\n            {\r\n                throw new InvalidOperationException(\"The stream must support reading.\");\r\n            }\r\n\r\n            if (expectedLength < 0)\r\n            {\r\n                throw new ArgumentOutOfRangeException(\"expectedLength\", expectedLength, \"The value of the expectedLength parameter cannot be less than zero.\");\r\n            }\r\n\r\n            if (thresholdLength < 0)\r\n            {\r\n                throw new ArgumentOutOfRangeException(\"thresholdLength\", thresholdLength, \"The value of the threshHoldLength parameter cannot be less than zero.\");\r\n            }\r\n        }\r\n\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/IO/UnclosableStreamWrapper.cs",
    "content": "﻿namespace Nancy.IO\r\n{\r\n    using System;\r\n    using System.IO;\r\n\r\n    /// <summary>\r\n    /// To close the unclosable stream..\r\n    /// To fight the unbeatable foe..\r\n    /// To bear with unbearable sorrow..\r\n    /// To run where the brave dare not go..\r\n    /// </summary>\r\n    public class UnclosableStreamWrapper : Stream, IDisposable\r\n    {\r\n        /// <summary>\r\n        /// The wrapped stream\r\n        /// </summary>\r\n        private readonly Stream baseStream;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"UnclosableStreamWrapper\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"baseStream\">The base stream to wrap.</param>\r\n        public UnclosableStreamWrapper(Stream baseStream)\r\n        {\r\n            if (baseStream == null)\r\n            {\r\n                throw new ArgumentNullException(\"baseStream\");\r\n            }\r\n\r\n            this.baseStream = baseStream;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the base stream that the wrapper is wrapping\r\n        /// </summary>\r\n        public Stream BaseStream\r\n        {\r\n            get\r\n            {\r\n                return this.baseStream;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// When overridden in a derived class, gets a value indicating whether the current stream supports reading.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// true if the stream supports reading; otherwise, false.\r\n        /// </returns>\r\n        /// <filterpriority>1</filterpriority>\r\n        public override bool CanRead\r\n        {\r\n            get\r\n            {\r\n                return this.baseStream.CanRead;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// When overridden in a derived class, gets a value indicating whether the current stream supports seeking.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// true if the stream supports seeking; otherwise, false.\r\n        /// </returns>\r\n        /// <filterpriority>1</filterpriority>\r\n        public override bool CanSeek\r\n        {\r\n            get\r\n            {\r\n                return this.baseStream.CanSeek;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// When overridden in a derived class, gets a value indicating whether the current stream supports writing.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// true if the stream supports writing; otherwise, false.\r\n        /// </returns>\r\n        /// <filterpriority>1</filterpriority>\r\n        public override bool CanWrite\r\n        {\r\n            get\r\n            {\r\n                return this.baseStream.CanWrite;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// When overridden in a derived class, gets the length in bytes of the stream.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// A long value representing the length of the stream in bytes.\r\n        /// </returns>\r\n        /// <exception cref=\"T:System.NotSupportedException\">A class derived from Stream does not support seeking. </exception><exception cref=\"T:System.ObjectDisposedException\">Methods were called after the stream was closed. </exception><filterpriority>1</filterpriority>\r\n        public override long Length\r\n        {\r\n            get\r\n            {\r\n                return this.baseStream.Length;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// When overridden in a derived class, gets or sets the position within the current stream.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// The current position within the stream.\r\n        /// </returns>\r\n        /// <exception cref=\"T:System.IO.IOException\">An I/O error occurs. </exception><exception cref=\"T:System.NotSupportedException\">The stream does not support seeking. </exception><exception cref=\"T:System.ObjectDisposedException\">Methods were called after the stream was closed. </exception><filterpriority>1</filterpriority>\r\n        public override long Position\r\n        {\r\n            get\r\n            {\r\n                return this.baseStream.Position;\r\n            }\r\n\r\n            set\r\n            {\r\n                this.baseStream.Position = value;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a value that determines whether the current stream can time out.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// A value that determines whether the current stream can time out.\r\n        /// </returns>\r\n        /// <filterpriority>2</filterpriority>\r\n        public override bool CanTimeout\r\n        {\r\n            get\r\n            {\r\n                return this.baseStream.CanTimeout;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets a value, in milliseconds, that determines how long the stream will attempt to read before timing out. \r\n        /// </summary>\r\n        /// <returns>\r\n        /// A value, in milliseconds, that determines how long the stream will attempt to read before timing out.\r\n        /// </returns>\r\n        /// <exception cref=\"T:System.InvalidOperationException\">The <see cref=\"P:System.IO.Stream.ReadTimeout\"/> method always throws an <see cref=\"T:System.InvalidOperationException\"/>. </exception><filterpriority>2</filterpriority>\r\n        public override int ReadTimeout\r\n        {\r\n            get\r\n            {\r\n                return this.baseStream.ReadTimeout;\r\n            }\r\n\r\n            set\r\n            {\r\n                this.baseStream.ReadTimeout = value;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets a value, in milliseconds, that determines how long the stream will attempt to write before timing out. \r\n        /// </summary>\r\n        /// <returns>\r\n        /// A value, in milliseconds, that determines how long the stream will attempt to write before timing out.\r\n        /// </returns>\r\n        /// <exception cref=\"T:System.InvalidOperationException\">The <see cref=\"P:System.IO.Stream.WriteTimeout\"/> method always throws an <see cref=\"T:System.InvalidOperationException\"/>. </exception><filterpriority>2</filterpriority>\r\n        public override int WriteTimeout\r\n        {\r\n            get\r\n            {\r\n                return this.baseStream.WriteTimeout;\r\n            }\r\n\r\n            set\r\n            {\r\n                this.baseStream.WriteTimeout = value;\r\n            }\r\n        }\r\n#if !NETSTANDARD1_6\r\n        /// <summary>\r\n        /// Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.\r\n        /// </summary>\r\n        /// <filterpriority>1</filterpriority>\r\n        public override void Close()\r\n        {\r\n        }\r\n#endif\r\n\r\n        /// <summary>\r\n        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.\r\n        /// </summary>\r\n        /// <filterpriority>2</filterpriority>\r\n        public new void Dispose()\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device.\r\n        /// </summary>\r\n        /// <exception cref=\"T:System.IO.IOException\">An I/O error occurs. </exception><filterpriority>2</filterpriority>\r\n        public override void Flush()\r\n        {\r\n            this.baseStream.Flush();\r\n        }\r\n\r\n        /// <summary>\r\n        /// When overridden in a derived class, sets the position within the current stream.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// The new position within the current stream.\r\n        /// </returns>\r\n        /// <param name=\"offset\">A byte offset relative to the <paramref name=\"origin\"/> parameter. </param><param name=\"origin\">A value of type <see cref=\"T:System.IO.SeekOrigin\"/> indicating the reference point used to obtain the new position. </param><exception cref=\"T:System.IO.IOException\">An I/O error occurs. </exception><exception cref=\"T:System.NotSupportedException\">The stream does not support seeking, such as if the stream is constructed from a pipe or console output. </exception><exception cref=\"T:System.ObjectDisposedException\">Methods were called after the stream was closed. </exception><filterpriority>1</filterpriority>\r\n        public override long Seek(long offset, SeekOrigin origin)\r\n        {\r\n            return this.baseStream.Seek(offset, origin);\r\n        }\r\n\r\n        /// <summary>\r\n        /// When overridden in a derived class, sets the length of the current stream.\r\n        /// </summary>\r\n        /// <param name=\"value\">The desired length of the current stream in bytes. </param><exception cref=\"T:System.IO.IOException\">An I/O error occurs. </exception><exception cref=\"T:System.NotSupportedException\">The stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output. </exception><exception cref=\"T:System.ObjectDisposedException\">Methods were called after the stream was closed. </exception><filterpriority>2</filterpriority>\r\n        public override void SetLength(long value)\r\n        {\r\n            this.baseStream.SetLength(value);\r\n        }\r\n\r\n        /// <summary>\r\n        /// When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.\r\n        /// </returns>\r\n        /// <param name=\"buffer\">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name=\"offset\"/> and (<paramref name=\"offset\"/> + <paramref name=\"count\"/> - 1) replaced by the bytes read from the current source. </param><param name=\"offset\">The zero-based byte offset in <paramref name=\"buffer\"/> at which to begin storing the data read from the current stream. </param><param name=\"count\">The maximum number of bytes to be read from the current stream. </param><exception cref=\"T:System.ArgumentException\">The sum of <paramref name=\"offset\"/> and <paramref name=\"count\"/> is larger than the buffer length. </exception><exception cref=\"T:System.ArgumentNullException\"><paramref name=\"buffer\"/> is null. </exception><exception cref=\"T:System.ArgumentOutOfRangeException\"><paramref name=\"offset\"/> or <paramref name=\"count\"/> is negative. </exception><exception cref=\"T:System.IO.IOException\">An I/O error occurs. </exception><exception cref=\"T:System.NotSupportedException\">The stream does not support reading. </exception><exception cref=\"T:System.ObjectDisposedException\">Methods were called after the stream was closed. </exception><filterpriority>1</filterpriority>\r\n        public override int Read(byte[] buffer, int offset, int count)\r\n        {\r\n            return this.baseStream.Read(buffer, offset, count);\r\n        }\r\n\r\n        /// <summary>\r\n        /// When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.\r\n        /// </summary>\r\n        /// <param name=\"buffer\">An array of bytes. This method copies <paramref name=\"count\"/> bytes from <paramref name=\"buffer\"/> to the current stream. </param><param name=\"offset\">The zero-based byte offset in <paramref name=\"buffer\"/> at which to begin copying bytes to the current stream. </param><param name=\"count\">The number of bytes to be written to the current stream. </param><exception cref=\"T:System.ArgumentException\">The sum of <paramref name=\"offset\"/> and <paramref name=\"count\"/> is greater than the buffer length. </exception><exception cref=\"T:System.ArgumentNullException\"><paramref name=\"buffer\"/> is null. </exception><exception cref=\"T:System.ArgumentOutOfRangeException\"><paramref name=\"offset\"/> or <paramref name=\"count\"/> is negative. </exception><exception cref=\"T:System.IO.IOException\">An I/O error occurs. </exception><exception cref=\"T:System.NotSupportedException\">The stream does not support writing. </exception><exception cref=\"T:System.ObjectDisposedException\">Methods were called after the stream was closed. </exception><filterpriority>1</filterpriority>\r\n        public override void Write(byte[] buffer, int offset, int count)\r\n        {\r\n            this.baseStream.Write(buffer, offset, count);\r\n        }\r\n\r\n#if !NETSTANDARD1_6\r\n        /// <summary>\r\n        /// Begins an asynchronous read operation.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// An <see cref=\"T:System.IAsyncResult\"/> that represents the asynchronous read, which could still be pending.\r\n        /// </returns>\r\n        /// <param name=\"buffer\">The buffer to read the data into. </param><param name=\"offset\">The byte offset in <paramref name=\"buffer\"/> at which to begin writing data read from the stream. </param><param name=\"count\">The maximum number of bytes to read. </param><param name=\"callback\">An optional asynchronous callback, to be called when the read is complete. </param><param name=\"state\">A user-provided object that distinguishes this particular asynchronous read request from other requests. </param><exception cref=\"T:System.IO.IOException\">Attempted an asynchronous read past the end of the stream, or a disk error occurs. </exception><exception cref=\"T:System.ArgumentException\">One or more of the arguments is invalid. </exception><exception cref=\"T:System.ObjectDisposedException\">Methods were called after the stream was closed. </exception><exception cref=\"T:System.NotSupportedException\">The current Stream implementation does not support the read operation. </exception><filterpriority>2</filterpriority>\r\n        public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)\r\n        {\r\n            return this.baseStream.BeginRead(buffer, offset, count, callback, state);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Begins an asynchronous write operation.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// An IAsyncResult that represents the asynchronous write, which could still be pending.\r\n        /// </returns>\r\n        /// <param name=\"buffer\">The buffer to write data from. </param><param name=\"offset\">The byte offset in <paramref name=\"buffer\"/> from which to begin writing. </param><param name=\"count\">The maximum number of bytes to write. </param><param name=\"callback\">An optional asynchronous callback, to be called when the write is complete. </param><param name=\"state\">A user-provided object that distinguishes this particular asynchronous write request from other requests. </param><exception cref=\"T:System.IO.IOException\">Attempted an asynchronous write past the end of the stream, or a disk error occurs. </exception><exception cref=\"T:System.ArgumentException\">One or more of the arguments is invalid. </exception><exception cref=\"T:System.ObjectDisposedException\">Methods were called after the stream was closed. </exception><exception cref=\"T:System.NotSupportedException\">The current Stream implementation does not support the write operation. </exception><filterpriority>2</filterpriority>\r\n        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)\r\n        {\r\n            return this.baseStream.BeginWrite(buffer, offset, count, callback, state);\r\n        }\r\n\r\n\r\n        /// <summary>\r\n        /// Waits for the pending asynchronous read to complete.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// The number of bytes read from the stream, between zero (0) and the number of bytes you requested. Streams return zero (0) only at the end of the stream, otherwise, they should block until at least one byte is available.\r\n        /// </returns>\r\n        /// <param name=\"asyncResult\">The reference to the pending asynchronous request to finish. </param><exception cref=\"T:System.ArgumentNullException\"><paramref name=\"asyncResult\"/> is null. </exception><exception cref=\"T:System.ArgumentException\"><paramref name=\"asyncResult\"/> did not originate from a <see cref=\"M:System.IO.Stream.BeginRead(System.Byte[],System.Int32,System.Int32,System.AsyncCallback,System.Object)\"/> method on the current stream. </exception><exception cref=\"T:System.IO.IOException\">The stream is closed or an internal error has occurred.</exception><filterpriority>2</filterpriority>\r\n        public override int EndRead(IAsyncResult asyncResult)\r\n        {\r\n            return this.baseStream.EndRead(asyncResult);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Ends an asynchronous write operation.\r\n        /// </summary>\r\n        /// <param name=\"asyncResult\">A reference to the outstanding asynchronous I/O request. </param><exception cref=\"T:System.ArgumentNullException\"><paramref name=\"asyncResult\"/> is null. </exception><exception cref=\"T:System.ArgumentException\"><paramref name=\"asyncResult\"/> did not originate from a <see cref=\"M:System.IO.Stream.BeginWrite(System.Byte[],System.Int32,System.Int32,System.AsyncCallback,System.Object)\"/> method on the current stream. </exception><exception cref=\"T:System.IO.IOException\">The stream is closed or an internal error has occurred.</exception><filterpriority>2</filterpriority>\r\n        public override void EndWrite(IAsyncResult asyncResult)\r\n        {\r\n            this.baseStream.EndWrite(asyncResult);\r\n        }\r\n#endif\r\n        /// <summary>\r\n        /// Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// The unsigned byte cast to an Int32, or -1 if at the end of the stream.\r\n        /// </returns>\r\n        /// <exception cref=\"T:System.NotSupportedException\">The stream does not support reading. </exception><exception cref=\"T:System.ObjectDisposedException\">Methods were called after the stream was closed. </exception><filterpriority>2</filterpriority>\r\n        public override int ReadByte()\r\n        {\r\n            return this.baseStream.ReadByte();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Writes a byte to the current position in the stream and advances the position within the stream by one byte.\r\n        /// </summary>\r\n        /// <param name=\"value\">The byte to write to the stream. </param><exception cref=\"T:System.IO.IOException\">An I/O error occurs. </exception><exception cref=\"T:System.NotSupportedException\">The stream does not support writing, or the stream is already closed. </exception><exception cref=\"T:System.ObjectDisposedException\">Methods were called after the stream was closed. </exception><filterpriority>2</filterpriority>\r\n        public override void WriteByte(byte value)\r\n        {\r\n            this.baseStream.WriteByte(value);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Releases the unmanaged resources used by the <see cref=\"T:System.IO.Stream\"/> and optionally releases the managed resources.\r\n        /// </summary>\r\n        /// <param name=\"disposing\">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>\r\n        protected override void Dispose(bool disposing)\r\n        {\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/IObjectSerializer.cs",
    "content": "namespace Nancy\r\n{\r\n    /// <summary>\r\n    /// De/Serialisation for cookie objects\r\n    /// </summary>\r\n    public interface IObjectSerializer\r\n    {\r\n        /// <summary>\r\n        /// Serialize an object\r\n        /// </summary>\r\n        /// <param name=\"sourceObject\">Source object</param>\r\n        /// <returns>Serialised object string</returns>\r\n        string Serialize(object sourceObject);\r\n\r\n        /// <summary>\r\n        /// Deserialize an object string\r\n        /// </summary>\r\n        /// <param name=\"sourceString\">Source object string</param>\r\n        /// <returns>Deserialized object</returns>\r\n        object Deserialize(string sourceString);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/IObjectSerializerSelector.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    /// <summary>\r\n    /// Allows setting of the serializer for session object storage\r\n    /// </summary>\r\n    public interface IObjectSerializerSelector : IHideObjectMembers\r\n    {\r\n        /// <summary>\r\n        /// Using the specified serializer\r\n        /// </summary>\r\n        /// <param name=\"newSerializer\">Serializer to use</param>\r\n        void WithSerializer(IObjectSerializer newSerializer);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/IResourceAssemblyProvider.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using System.Collections.Generic;\r\n    using System.Reflection;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality for retrieving which assemblies that should be used by Nancy.\r\n    /// </summary>\r\n    public interface IResourceAssemblyProvider\r\n    {\r\n        /// <summary>\r\n        /// Gets a list of assemblies that should be scanned.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"Assembly\"/> instances.</returns>\r\n        IEnumerable<Assembly> GetAssembliesToScan();\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/IResponseFormatter.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using Nancy.Configuration;\r\n\r\n    /// <summary>\r\n    /// An extension point for adding support for formatting response contents. No members should be added to this interface without good reason.\r\n    /// </summary>\r\n    /// <remarks>Extension methods to this interface should always return <see cref=\"Response\"/> or one of the types that can implicitly be types into a <see cref=\"Response\"/>.</remarks>\r\n    public interface IResponseFormatter : IHideObjectMembers\r\n    {\r\n        /// <summary>\r\n        /// Gets all <see cref=\"ISerializerFactory\"/> factory.\r\n        /// </summary>\r\n        ISerializerFactory SerializerFactory { get; }\r\n\r\n        /// <summary>\r\n        /// Gets the context for which the response is being formatted.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"NancyContext\"/> instance.</value>\r\n        NancyContext Context { get; }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"INancyEnvironment\"/>.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"INancyEnvironment\"/> instance.</value>\r\n        INancyEnvironment Environment { get; }\r\n\r\n        /// <summary>\r\n        /// Gets the root path of the application.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the root path.</value>\r\n        string RootPath { get; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/IResponseFormatterFactory.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    /// <summary>\r\n    /// Defines the functionality of a <see cref=\"IResponseFormatter\"/> factory.\r\n    /// </summary>\r\n    public interface IResponseFormatterFactory\r\n    {\r\n        /// <summary>\r\n        /// Creates a new <see cref=\"IResponseFormatter\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> instance that should be used by the response formatter.</param>\r\n        /// <returns>An <see cref=\"IResponseFormatter\"/> instance.</returns>\r\n        IResponseFormatter Create(NancyContext context);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/IRootPathProvider.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    /// <summary>\r\n    /// Defines the functionality to retrieve the root folder path of the current Nancy application.\r\n    /// </summary>\r\n    public interface IRootPathProvider : IHideObjectMembers\r\n    {\r\n        /// <summary>\r\n        /// Returns the root folder path of the current Nancy application.\r\n        /// </summary>\r\n        /// <returns>A <see cref=\"string\"/> containing the path of the root folder.</returns>\r\n        string GetRootPath();\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/IRuntimeEnvironmentInformation.cs",
    "content": "namespace Nancy\r\n{\r\n    /// <summary>\r\n    /// Defines functionality for getting information about the runtime execution environment.\r\n    /// </summary>\r\n    public interface IRuntimeEnvironmentInformation\r\n    {\r\n        /// <summary>\r\n        /// Gets a value indicating if the application is running in debug mode.\r\n        /// </summary>\r\n        /// <returns><see langword=\"true\"/> if the application is running in debug mode, otherwise <see langword=\"false\"/>.</returns>\r\n        bool IsDebug { get; }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/ISerializer.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using Nancy.Responses.Negotiation;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality for providing serialization support.\r\n    /// </summary>\r\n    public interface ISerializer\r\n    {\r\n        /// <summary>\r\n        /// Whether the serializer can serialize the content type\r\n        /// </summary>\r\n        /// <param name=\"mediaRange\">Content type to serialise</param>\r\n        /// <returns>True if supported, false otherwise</returns>\r\n        bool CanSerialize(MediaRange mediaRange);\r\n\r\n        /// <summary>\r\n        /// Gets the list of extensions that the serializer can handle.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> of extensions if any are available, otherwise an empty enumerable.</value>\r\n        IEnumerable<string> Extensions { get; }\r\n\r\n        /// <summary>\r\n        /// Serialize the given model with the given contentType\r\n        /// </summary>\r\n        /// <param name=\"mediaRange\">Content type to serialize into</param>\r\n        /// <param name=\"model\">Model to serialize</param>\r\n        /// <param name=\"outputStream\">Output stream to serialize to</param>\r\n        /// <returns>Serialised object</returns>\r\n        void Serialize<TModel>(MediaRange mediaRange, TModel model, Stream outputStream);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ISerializerFactory.cs",
    "content": "namespace Nancy\r\n{\r\n    using Nancy.Responses.Negotiation;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality of an <see cref=\"ISerializer\"/> factory.\r\n    /// </summary>\r\n    public interface ISerializerFactory\r\n    {\r\n        /// <summary>\r\n        /// Gets the <see cref=\"ISerializer\"/> implementation that can serialize the provided <paramref name=\"mediaRange\"/>.\r\n        /// </summary>\r\n        /// <param name=\"mediaRange\">The <see cref=\"MediaRange\"/> to get a serializer for.</param>\r\n        /// <returns>An <see cref=\"ISerializer\"/> instance, or <see langword=\"null\" /> if not match was found.</returns>\r\n        ISerializer GetSerializer(MediaRange mediaRange);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/IStaticContentProvider.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    /// <summary>\r\n    /// Provides static content delivery\r\n    /// </summary>\r\n    public interface IStaticContentProvider\r\n    {\r\n        /// <summary>\r\n        /// Gets the static content response, if possible.\r\n        /// </summary>\r\n        /// <param name=\"context\">Current context</param>\r\n        /// <returns>Response if serving content, null otherwise</returns>\r\n        Response GetContent(NancyContext context);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/IStatusCodeHandler.cs",
    "content": "namespace Nancy.ErrorHandling\r\n{\r\n    /// <summary>\r\n    /// Provides informative responses for particular HTTP status codes\r\n    /// </summary>\r\n    public interface IStatusCodeHandler\r\n    {\r\n        /// <summary>\r\n        /// Check if the error handler can handle errors of the provided status code.\r\n        /// </summary>\r\n        /// <param name=\"statusCode\">Status code</param>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> instance of the current request.</param>\r\n        /// <returns>True if handled, false otherwise</returns>\r\n        bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context);\r\n\r\n        /// <summary>\r\n        /// Handle the error code\r\n        /// </summary>\r\n        /// <param name=\"statusCode\">Status code</param>\r\n        /// <param name=\"context\">Current context</param>\r\n        void Handle(HttpStatusCode statusCode, NancyContext context);\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/ITypeCatalog.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality of a type catalog.\r\n    /// </summary>\r\n    public interface ITypeCatalog\r\n    {\r\n        /// <summary>\r\n        /// Gets all types that are assignable to the provided <paramref name=\"type\"/>.\r\n        /// </summary>\r\n        /// <param name=\"type\">The <see cref=\"Type\"/> that returned types should be assignable to.</param>\r\n        /// <param name=\"strategy\">A <see cref=\"TypeResolveStrategy\"/> that should be used when retrieving types.</param>\r\n        /// <returns>An <see cref=\"IReadOnlyCollection{T}\"/> of <see cref=\"Type\"/> instances.</returns>\r\n        IReadOnlyCollection<Type> GetTypesAssignableTo(Type type, TypeResolveStrategy strategy);\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/IncludeInNancyAssemblyScanningAttribute.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Add this attribute to an assembly to make sure\r\n    /// it is included in Nancy's assembly scanning.\r\n    /// </summary>\r\n    /// <example>\r\n    /// Apply the attribute, typically in AssemblyInfo.(cs|fs|vb), as follows:\r\n    /// <code>[assembly: IncludeInNancyAssemblyScanning]</code>\r\n    /// </example>\r\n    [AttributeUsage(AttributeTargets.Assembly)]\r\n    public sealed class IncludeInNancyAssemblyScanningAttribute : Attribute\r\n    {\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Json/Converters/TimeSpanConverter.cs",
    "content": "namespace Nancy.Json.Converters\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Converts a dictionary with time info into a time span instance or vice versa.\r\n    /// </summary>\r\n    /// <seealso cref=\"Nancy.Json.JavaScriptConverter\" />\r\n    public class TimeSpanConverter : JavaScriptConverter\r\n    {\r\n        /// <summary>\r\n        /// Gets the supported types.\r\n        /// </summary>\r\n        /// <value>The collection of supported types.</value>\r\n        public override IEnumerable<Type> SupportedTypes\r\n        {\r\n            get\r\n            {\r\n                return new[] { typeof(TimeSpan) };\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Deserializes the specified dictionary into a timespan instance.\r\n        /// </summary>\r\n        /// <param name=\"dictionary\">The dictionary.</param>\r\n        /// <param name=\"type\">The type.</param>\r\n        /// <param name=\"serializer\">The serializer.</param>\r\n        /// <returns>A <see cref=\"TimeSpan\"/> instance as <see cref=\"object\"/></returns>\r\n        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)\r\n        {\r\n            return new TimeSpan(\r\n                this.GetValue(dictionary, \"Days\"),\r\n                this.GetValue(dictionary, \"Hours\"),\r\n                this.GetValue(dictionary, \"Minutes\"),\r\n                this.GetValue(dictionary, \"Seconds\"),\r\n                this.GetValue(dictionary, \"Milliseconds\"));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Serializes the specified object.\r\n        /// </summary>\r\n        /// <param name=\"obj\">The object.</param>\r\n        /// <param name=\"serializer\">The serializer.</param>\r\n        /// <returns>A <see cref=\"Dictionary{TKey,TValue}\"/> representing a <see cref=\"TimeSpan\"/> object</returns>\r\n        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)\r\n        {\r\n            var timeSpan = (TimeSpan)obj;\r\n\r\n            var result = new Dictionary<string, object>\r\n                             {\r\n                                 { \"Days\", timeSpan.Days },\r\n                                 { \"Hours\", timeSpan.Hours },\r\n                                 { \"Minutes\", timeSpan.Minutes },\r\n                                 { \"Seconds\", timeSpan.Seconds },\r\n                                 { \"Milliseconds\", timeSpan.Milliseconds }\r\n                             };\r\n\r\n            return result;\r\n        }\r\n\r\n        private int GetValue(IDictionary<string, object> dictionary, string key)\r\n        {\r\n            const int DefaultValue = 0;\r\n\r\n            object value;\r\n            if (!dictionary.TryGetValue(key, out value))\r\n            {\r\n                return DefaultValue;\r\n            }\r\n\r\n            if (value is int)\r\n            {\r\n                return (int)value;\r\n            }\r\n\r\n            if (value is long)\r\n            {\r\n                return Convert.ToInt32((long)value);\r\n            }\r\n\r\n            var valueString = value as string;\r\n            if (valueString == null)\r\n            {\r\n                return DefaultValue;\r\n            }\r\n\r\n            int returnValue;\r\n            return !int.TryParse(valueString, out returnValue) ? DefaultValue : returnValue;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Json/Converters/TupleConverter.cs",
    "content": "﻿namespace Nancy.Json.Converters\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n\r\n    /// <summary>\r\n    /// Converts a dictionary into a list of tuples.\r\n    /// </summary>\r\n    /// <seealso cref=\"Nancy.Json.JavaScriptConverter\" />\r\n    public class TupleConverter : JavaScriptConverter\r\n    {\r\n        /// <summary>\r\n        /// Gets the supported tuple types.\r\n        /// </summary>\r\n        /// <value>The supported types.</value>\r\n        public override IEnumerable<Type> SupportedTypes\r\n        {\r\n            get\r\n            {\r\n                yield return typeof(Tuple<>);\r\n                yield return typeof(Tuple<,>);\r\n                yield return typeof(Tuple<,,>);\r\n                yield return typeof(Tuple<,,,>);\r\n                yield return typeof(Tuple<,,,,>);\r\n                yield return typeof(Tuple<,,,,,>);\r\n                yield return typeof(Tuple<,,,,,,>);\r\n                yield return typeof(Tuple<,,,,,,,>);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Deserializes the specified dictionary into a list of tuples.\r\n        /// </summary>\r\n        /// <param name=\"dictionary\">The dictionary.</param>\r\n        /// <param name=\"type\">The type.</param>\r\n        /// <param name=\"serializer\">The serializer.</param>\r\n        /// <returns>A list of <see cref=\"Tuple{T1, T2}\"/> representing the <paramref name=\"dictionary\"/></returns>\r\n        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)\r\n        {\r\n            var ctor = type.GetConstructors().First();\r\n            object instance = ctor.Invoke(dictionary.Values.ToArray());\r\n            return instance;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Serializes the specified object.\r\n        /// </summary>\r\n        /// <param name=\"obj\">The object.</param>\r\n        /// <param name=\"serializer\">The serializer.</param>\r\n        /// <exception cref=\"System.NotImplementedException\"></exception>\r\n        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)\r\n        {\r\n            throw new NotImplementedException();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Json/DefaultJsonConfigurationProvider.cs",
    "content": "namespace Nancy.Json\r\n{\r\n    using Nancy.Configuration;\r\n\r\n    /// <summary>\r\n    /// Provides the default configuration for <see cref=\"JsonConfiguration\"/>.\r\n    /// </summary>\r\n    public class DefaultJsonConfigurationProvider : NancyDefaultConfigurationProvider<JsonConfiguration>\r\n    {\r\n        /// <summary>\r\n        /// Gets the default configuration instance to register in the <see cref=\"INancyEnvironment\"/>.\r\n        /// </summary>\r\n        /// <returns>The configuration instance</returns>\r\n        /// <remarks>Will return <see cref=\"JsonConfiguration.Default\"/></remarks>\r\n        public override JsonConfiguration GetDefaultConfiguration()\r\n        {\r\n            return JsonConfiguration.Default;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Json/JavaScriptConverter.cs",
    "content": "﻿//\r\n// JavaScriptConverter.cs\r\n//\r\n// Author:\r\n//   Igor Zelmanovich <igorz@mainsoft.com>\r\n//\r\n// (C) 2007 Mainsoft, Inc.  http://www.mainsoft.com\r\n//\r\n//\r\n// Permission is hereby granted, free of charge, to any person obtaining\r\n// a copy of this software and associated documentation files (the\r\n// \"Software\"), to deal in the Software without restriction, including\r\n// without limitation the rights to use, copy, modify, merge, publish,\r\n// distribute, sublicense, and/or sell copies of the Software, and to\r\n// permit persons to whom the Software is furnished to do so, subject to\r\n// the following conditions:\r\n// \r\n// The above copyright notice and this permission notice shall be\r\n// included in all copies or substantial portions of the Software.\r\n// \r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\r\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\r\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\r\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\r\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n//\r\nnamespace Nancy.Json\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Abstracr base class for javascript converter operations.\r\n    /// </summary>\r\n    public abstract class JavaScriptConverter\r\n\t{\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"JavaScriptConverter\"/> class.\r\n        /// </summary>\r\n        protected JavaScriptConverter () { }\r\n\r\n        /// <summary>\r\n        /// Gets the supported types.\r\n        /// </summary>\r\n        /// <value>The supported types.</value>\r\n        public abstract IEnumerable<Type> SupportedTypes { get; }\r\n\r\n        /// <summary>\r\n        /// Deserializes the specified dictionary.\r\n        /// </summary>\r\n        /// <param name=\"dictionary\">The dictionary.</param>\r\n        /// <param name=\"type\">The type.</param>\r\n        /// <returns>The deserialized <paramref name=\"dictionary\"/></returns>\r\n        public virtual object Deserialize(IDictionary<string, object> dictionary, Type type)\r\n        {\r\n            return Deserialize(dictionary, type, null);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Deserializes the specified dictionary.\r\n        /// </summary>\r\n        /// <param name=\"dictionary\">The dictionary.</param>\r\n        /// <param name=\"type\">The type.</param>\r\n        /// <param name=\"serializer\">The serializer.</param>\r\n        /// <returns>An <see cref=\"object\"/> representing <paramref name=\"dictionary\"/></returns>\r\n        public abstract object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer);\r\n\r\n        /// <summary>\r\n        /// Serializes the specified object.\r\n        /// </summary>\r\n        /// <param name=\"obj\">The object.</param>\r\n        /// <returns>A <see cref=\"Dictionary{TKey,TValue}\"/> instance</returns>\r\n        public IDictionary<string, object> Serialize(object obj)\r\n        {\r\n            return Serialize(obj, null);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Serializes the specified object.\r\n        /// </summary>\r\n        /// <param name=\"obj\">The object.</param>\r\n        /// <param name=\"serializer\">The serializer.</param>\r\n        /// <returns>A <see cref=\"Dictionary{TKey,TValue}\"/> instance</returns>\r\n        public abstract IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer);\r\n\t}\r\n}"
  },
  {
    "path": "src/Nancy/Json/JavaScriptPrimitiveConverter.cs",
    "content": "﻿namespace Nancy.Json\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    ///  Operations for converting javascript primitives.\r\n    /// </summary>\r\n    public abstract class JavaScriptPrimitiveConverter\r\n    {\r\n        /// <summary>\r\n        /// Gets the supported types.\r\n        /// </summary>\r\n        /// <value>The supported types.</value>\r\n        public abstract IEnumerable<Type> SupportedTypes { get; }\r\n\r\n        /// <summary>\r\n        /// Deserializes the specified primitive value.\r\n        /// </summary>\r\n        /// <param name=\"primitiveValue\">The primitive value.</param>\r\n        /// <param name=\"type\">The type.</param>\r\n        /// <returns>The deserialized <paramref name=\"primitiveValue\"/></returns>\r\n        public virtual object Deserialize(object primitiveValue, Type type)\r\n        {\r\n            return Deserialize(primitiveValue, type, null);    \r\n        }\r\n\r\n        /// <summary>\r\n        /// Deserializes the specified primitive value.\r\n        /// </summary>\r\n        /// <param name=\"primitiveValue\">The primitive value.</param>\r\n        /// <param name=\"type\">The type.</param>\r\n        /// <param name=\"serializer\">The serializer.</param>\r\n        /// <returns>The deserialized <paramref name=\"primitiveValue\"/></returns>\r\n        public abstract object Deserialize(object primitiveValue, Type type, JavaScriptSerializer serializer);\r\n\r\n        /// <summary>\r\n        /// Serializes the specified object.\r\n        /// </summary>\r\n        /// <param name=\"obj\">The object.</param>\r\n        /// <returns>The serialized <see cref=\"object\"/></returns>\r\n        public virtual object Serialize(object obj)\r\n        {\r\n            return Serialize(obj, null);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Serializes the specified object.\r\n        /// </summary>\r\n        /// <param name=\"obj\">The object.</param>\r\n        /// <param name=\"serializer\">The serializer.</param>\r\n        /// <returns>The serialized <see cref=\"object\"/></returns>\r\n        public abstract object Serialize(object obj, JavaScriptSerializer serializer);\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Json/JavaScriptSerializer.cs",
    "content": "﻿//\r\n// JavaScriptSerializer.cs\r\n//\r\n// Author:\r\n//   Konstantin Triger <kostat@mainsoft.com>\r\n//\r\n// (C) 2007 Mainsoft, Inc.  http://www.mainsoft.com\r\n//\r\n//\r\n// Permission is hereby granted, free of charge, to any person obtaining\r\n// a copy of this software and associated documentation files (the\r\n// \"Software\"), to deal in the Software without restriction, including\r\n// without limitation the rights to use, copy, modify, merge, publish,\r\n// distribute, sublicense, and/or sell copies of the Software, and to\r\n// permit persons to whom the Software is furnished to do so, subject to\r\n// the following conditions:\r\n//\r\n// The above copyright notice and this permission notice shall be\r\n// included in all copies or substantial portions of the Software.\r\n//\r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\r\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\r\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\r\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\r\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n//\r\n\r\nnamespace Nancy.Json\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using Nancy.Json.Simple;\r\n    using Nancy.Extensions;\r\n    /// <summary>\r\n    /// JavaScriptSerializer responsible for serializing objects\r\n    /// </summary>\r\n    public class JavaScriptSerializer\r\n    {\r\n        private readonly JsonConfiguration jsonConfiguration;\r\n\r\n        private readonly GlobalizationConfiguration globalizationConfiguration;\r\n\r\n        private readonly NancySerializationStrategy serializerStrategy;\r\n\r\n        /// <summary>\r\n        /// Creates an instance of <see cref=\"JavaScriptSerializer\"/>\r\n        /// </summary>\r\n        public JavaScriptSerializer() : this(JsonConfiguration.Default, GlobalizationConfiguration.Default)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates an instance of <see cref=\"JavaScriptSerializer\"/>\r\n        /// </summary>\r\n        /// <param name=\"jsonConfiguration\">A <see cref=\"JsonConfiguration\"/> object to configure the serializer</param>\r\n        /// <param name=\"globalizationConfiguration\">A <see cref=\"GlobalizationConfiguration\"/> object to configure the serializer</param>\r\n        public JavaScriptSerializer(JsonConfiguration jsonConfiguration, GlobalizationConfiguration globalizationConfiguration)\r\n        {\r\n            this.jsonConfiguration = jsonConfiguration;\r\n            this.globalizationConfiguration = globalizationConfiguration;\r\n            this.serializerStrategy = new NancySerializationStrategy(jsonConfiguration.RetainCasing, jsonConfiguration.SerializeEnumToString);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates an instance of <see cref=\"JavaScriptSerializer\"/>\r\n        /// </summary>\r\n        /// <param name=\"jsonConfiguration\">A <see cref=\"JsonConfiguration\"/> object to configure the serializer</param>\r\n        /// <param name=\"registerConverters\">A boolean to determine whether to register custom converters</param>\r\n        /// <param name=\"globalizationConfiguration\">A <see cref=\"GlobalizationConfiguration\"/> object to configure the serializer</param>\r\n        public JavaScriptSerializer(JsonConfiguration jsonConfiguration, bool registerConverters, GlobalizationConfiguration globalizationConfiguration) : this(jsonConfiguration, globalizationConfiguration)\r\n        {\r\n            this.jsonConfiguration = jsonConfiguration;\r\n            this.globalizationConfiguration = globalizationConfiguration;\r\n            if (registerConverters)\r\n            {\r\n                this.RegisterConverters(jsonConfiguration.Converters, jsonConfiguration.PrimitiveConverters);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Deserialize JSON\r\n        /// </summary>\r\n        /// <param name=\"input\">JSON representation</param>\r\n        /// <typeparam name=\"T\">The <see cref=\"Type\"/> to deserialize into</typeparam>\r\n        /// <returns>An instance of type <typeparamref name=\"T\"/> representing <paramref name=\"input\"/> as an object</returns>\r\n        public T Deserialize<T>(string input)\r\n        {\r\n            return SimpleJson.DeserializeObject<T>(input, this.serializerStrategy, this.globalizationConfiguration.DateTimeStyles);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Deserialize JSON\r\n        /// </summary>\r\n        /// <param name=\"input\">JSON representation</param>\r\n        /// <returns>An object representing <paramref name=\"input\"/></returns>\r\n        public object DeserializeObject(string input)\r\n        {\r\n            return SimpleJson.DeserializeObject(input, null, this.serializerStrategy, this.globalizationConfiguration.DateTimeStyles);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Register custom JSON converters\r\n        /// </summary>\r\n        /// <param name=\"converters\">An array of <see cref=\"JavaScriptConverter\"/> to register</param>\r\n        /// <exception cref=\"ArgumentNullException\"><paramref name=\"converters\"/> is null</exception>\r\n        public void RegisterConverters(IEnumerable<JavaScriptConverter> converters)\r\n        {\r\n            if (converters == null)\r\n            {\r\n                throw new ArgumentNullException(\"converters\");\r\n            }\r\n\r\n            this.serializerStrategy.RegisterConverters(converters);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Register custom JSON converters\r\n        /// </summary>\r\n        /// <param name=\"primitiveConverters\">An array of <see cref=\"JavaScriptPrimitiveConverter\"/></param>\r\n        /// <exception cref=\"ArgumentNullException\"><paramref name=\"primitiveConverters\"/> is null</exception>\r\n        public void RegisterConverters(IEnumerable<JavaScriptPrimitiveConverter> primitiveConverters)\r\n        {\r\n            if (primitiveConverters == null)\r\n            {\r\n                throw new ArgumentNullException(\"primitiveConverters\");\r\n            }\r\n\r\n            this.serializerStrategy.RegisterConverters(primitiveConverters);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Register custom JSON converters\r\n        /// </summary>\r\n        /// <param name=\"converters\">An array of <see cref=\"JavaScriptConverter\"/> to register</param>\r\n        /// <param name=\"primitiveConverters\">An array of <see cref=\"JavaScriptPrimitiveConverter\"/></param>\r\n        public void RegisterConverters(IEnumerable<JavaScriptConverter> converters,\r\n            IEnumerable<JavaScriptPrimitiveConverter> primitiveConverters)\r\n        {\r\n            if (converters != null)\r\n            {\r\n                this.RegisterConverters(converters);\r\n            }\r\n\r\n            if (primitiveConverters != null)\r\n            {\r\n                this.RegisterConverters(primitiveConverters);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Serialize an object to JSON\r\n        /// </summary>\r\n        /// <param name=\"obj\">The object to serialize</param>\r\n        /// <returns>A JSON string representation of <paramref name=\"obj\"/></returns>\r\n        public string Serialize(object obj)\r\n        {\r\n            return SimpleJson.SerializeObject(obj, this.serializerStrategy, this.jsonConfiguration.ExcludeNullValues);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Serialize an object to JSON and write result to <paramref name=\"output\"/>\r\n        /// </summary>\r\n        /// <param name=\"obj\">The object to serialize</param>\r\n        /// <param name=\"output\">An instance of <see cref=\"TextWriter\" /> to write the serialized <paramref name=\"obj\"/></param>\r\n        public void Serialize(object obj, TextWriter output)\r\n        {\r\n            output.Write(this.Serialize(obj));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Json/Json.cs",
    "content": "//\r\n// Json.cs\r\n//\r\n// Author:\r\n//   Marek Habersack <mhabersack@novell.com>\r\n//\r\n// (C) 2008 Novell, Inc.  http://novell.com/\r\n//\r\n//\r\n// Permission is hereby granted, free of charge, to any person obtaining\r\n// a copy of this software and associated documentation files (the\r\n// \"Software\"), to deal in the Software without restriction, including\r\n// without limitation the rights to use, copy, modify, merge, publish,\r\n// distribute, sublicense, and/or sell copies of the Software, and to\r\n// permit persons to whom the Software is furnished to do so, subject to\r\n// the following conditions:\r\n//\r\n// The above copyright notice and this permission notice shall be\r\n// included in all copies or substantial portions of the Software.\r\n//\r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\r\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\r\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\r\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\r\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n//\r\nnamespace Nancy.Json\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// JSON Helper Class.\r\n    /// </summary>\r\n    public static class Json\r\n    {\r\n        private const StringComparison ComparisonType = StringComparison.OrdinalIgnoreCase;\r\n\r\n        /// <summary>\r\n        /// Attempts to detect if the content type is JSON.\r\n        /// Supports:\r\n        ///   application/json\r\n        ///   text/json\r\n        ///   [something]+json\r\n        /// Matches are case insensitive to try and be as \"accepting\" as possible.\r\n        /// </summary>\r\n        /// <param name=\"contentType\">Request content type</param>\r\n        /// <returns>True if content type is JSON, false otherwise</returns>\r\n        public static bool IsJsonContentType(string contentType)\r\n        {\r\n            if (string.IsNullOrEmpty(contentType))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            var index = contentType.IndexOf(';');\r\n\r\n            if (index >= 0)\r\n            {\r\n                contentType = contentType.Substring(0, index);\r\n            }\r\n\r\n            contentType = contentType.Trim();\r\n\r\n            return contentType.StartsWith(\"application/json\", ComparisonType)\r\n                || contentType.Equals(\"text/json\", ComparisonType)\r\n                || contentType.EndsWith(\"+json\", ComparisonType);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Json/JsonConfiguration.cs",
    "content": "namespace Nancy.Json\r\n{\r\n    using System.Collections.Generic;\r\n    using System.Text;\r\n    using Nancy.Json.Converters;\r\n\r\n    /// <summary>\r\n    /// Configuration for JSON serialization.\r\n    /// </summary>\r\n    public class JsonConfiguration\r\n    {\r\n        /// <summary>\r\n        /// A default instance of the <see cref=\"JsonConfiguration\"/> class.\r\n        /// </summary>\r\n        public static readonly JsonConfiguration Default = new JsonConfiguration\r\n        {\r\n            Converters = new List<JavaScriptConverter> { new TimeSpanConverter(), new TupleConverter() },\r\n            DefaultEncoding = Encoding.UTF8,\r\n            PrimitiveConverters = new List<JavaScriptPrimitiveConverter>(),\r\n            RetainCasing = false,\r\n            SerializeEnumToString = false,\r\n            ExcludeNullValues = false\r\n        };\r\n\r\n        private JsonConfiguration()\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"JsonConfiguration\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"defaultEncoding\">The default <see cref=\"Encoding\"/> that should be used by the serializer.</param>\r\n        /// <param name=\"converters\">List of <see cref=\"JavaScriptConverter\"/> instances.</param>\r\n        /// <param name=\"primitiveConverters\">List of <see cref=\"JavaScriptPrimitiveConverter\"/> instances.</param>\r\n        /// <param name=\"retainCasing\"><see langword=\"true\"/> if the name casing should be retained during serialization, otherwise <see langword=\"false\"/>.</param>\r\n        /// <param name=\"serializeEnumToString\"><see langword=\"true\"/> if enums should be represented as string otherwise <see langword=\"false\"/>.</param>\r\n        /// <param name=\"excludeNullValues\"><see langword=\"true\" /> if the serializer should exclude null values for properties on objects otherwise <see langword=\"false\" />.</param>\r\n        public JsonConfiguration(Encoding defaultEncoding, IList<JavaScriptConverter> converters, IList<JavaScriptPrimitiveConverter> primitiveConverters, bool? retainCasing, bool? serializeEnumToString, bool? excludeNullValues)\r\n        {\r\n            this.DefaultEncoding = defaultEncoding ?? Default.DefaultEncoding;\r\n            this.Converters = converters ?? Default.Converters;\r\n            this.PrimitiveConverters = primitiveConverters ?? Default.PrimitiveConverters;\r\n            this.RetainCasing = retainCasing ?? Default.RetainCasing;\r\n            this.SerializeEnumToString = serializeEnumToString ?? Default.SerializeEnumToString;\r\n            this.ExcludeNullValues = excludeNullValues ?? Default.ExcludeNullValues;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the default <see cref=\"Encoding\"/> for JSON responses.\r\n        /// </summary>\r\n        /// <remarks>The default is <see langword=\"Encoding.UTF8\" />.</remarks>\r\n        public Encoding DefaultEncoding { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the type converters that should be used.\r\n        /// </summary>\r\n        /// <remarks>The default is <see cref=\"TimeSpanConverter\"/> and <see cref=\"TupleConverter\"/>.</remarks>\r\n        public IList<JavaScriptConverter> Converters { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the converters used for primitive types.\r\n        /// </summary>\r\n        /// <remarks>The default are no converters.</remarks>\r\n        public IList<JavaScriptPrimitiveConverter> PrimitiveConverters { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets if C# casing should be retained or if camel-casing should be enforeced.\r\n        /// </summary>\r\n        /// <remarks>The default is <see langword=\"false\"/>.</remarks>\r\n        public bool RetainCasing { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Get or sets whether enums should be treated as string\r\n        /// </summary>\r\n        public bool SerializeEnumToString{ get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets if the serializer should return null values for properties on objects\r\n        /// </summary>\r\n        public bool ExcludeNullValues { get; set; }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Json/JsonConfigurationExtensions.cs",
    "content": "namespace Nancy.Json\r\n{\r\n    using System.Collections.Generic;\r\n    using System.Text;\r\n    using Nancy.Configuration;\r\n\r\n    /// <summary>\r\n    /// Contains <see cref=\"JsonConfiguration\"/> configuration extensions for <see cref=\"INancyEnvironment\"/>.\r\n    /// </summary>\r\n    public static class JsonConfigurationExtensions\r\n    {\r\n        /// <summary>\r\n        /// Configures JSON serialization.\r\n        /// </summary>\r\n        /// <param name=\"environment\"><see cref=\"INancyEnvironment\"/> that should be configured.</param>\r\n        /// <param name=\"defaultEncoding\">The <see cref=\"Encoding\"/> that should be as a default.</param>\r\n        /// <param name=\"converters\">List of <see cref=\"JavaScriptConverter\"/> that should be used.</param>\r\n        /// <param name=\"primitiveConverters\">List of <see cref=\"JavaScriptPrimitiveConverter\"/> that should be used.</param>\r\n        /// <param name=\"retainCasing\"><see langword=\"true\" /> if C# casing should be retained, otherwise <see langword=\"false\" /> to use camel-casing.</param>\r\n        /// <param name=\"serializeEnumToString\"><see langword=\"true\"/> if enums should be represented as string otherwise <see langword=\"false\"/>.</param>\r\n        /// <param name=\"excludeNullValues\"><see langword=\"true\" /> if the serializer should exclude null values for properties on objects otherwise <see langword=\"false\" />.</param>\r\n        public static void Json(this INancyEnvironment environment, Encoding defaultEncoding = null, IList<JavaScriptConverter> converters = null, IList<JavaScriptPrimitiveConverter> primitiveConverters = null, bool? retainCasing = null, bool? serializeEnumToString = null, bool? excludeNullValues = false)\r\n        {\r\n            environment.AddValue(new JsonConfiguration(\r\n                defaultEncoding ?? JsonConfiguration.Default.DefaultEncoding,\r\n                converters ?? JsonConfiguration.Default.Converters,\r\n                primitiveConverters ?? JsonConfiguration.Default.PrimitiveConverters,\r\n                retainCasing ?? JsonConfiguration.Default.RetainCasing,\r\n                serializeEnumToString ?? JsonConfiguration.Default.SerializeEnumToString,\r\n                excludeNullValues ?? JsonConfiguration.Default.ExcludeNullValues));\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Json/ScriptIgnoreAttribute.cs",
    "content": "﻿//\r\n// ScriptIgnoreAttribute.cs\r\n//\r\n// Author:\r\n//   Igor Zelmanovich <igorz@mainsoft.com>\r\n//\r\n// (C) 2007 Mainsoft, Inc.  http://www.mainsoft.com\r\n//\r\n//\r\n// Permission is hereby granted, free of charge, to any person obtaining\r\n// a copy of this software and associated documentation files (the\r\n// \"Software\"), to deal in the Software without restriction, including\r\n// without limitation the rights to use, copy, modify, merge, publish,\r\n// distribute, sublicense, and/or sell copies of the Software, and to\r\n// permit persons to whom the Software is furnished to do so, subject to\r\n// the following conditions:\r\n// \r\n// The above copyright notice and this permission notice shall be\r\n// included in all copies or substantial portions of the Software.\r\n// \r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\r\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\r\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\r\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\r\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n//\r\nnamespace Nancy.Json\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Property attribute for ignoring scripts.\r\n    /// </summary>\r\n    /// <seealso cref=\"System.Attribute\" />\r\n    [AttributeUsage (AttributeTargets.Property | AttributeTargets.Field)]\r\n    public sealed class ScriptIgnoreAttribute : Attribute\r\n\t{\r\n\t}\r\n}"
  },
  {
    "path": "src/Nancy/Json/Simple/NancySerializationStrategy.cs",
    "content": "﻿namespace Nancy.Json.Simple\r\n{\r\n    using System;\r\n    using System.Collections.Concurrent;\r\n    using System.Collections.Generic;\r\n    using System.Globalization;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using Nancy.Extensions;\r\n\r\n    /// <summary>\r\n    /// Nancy serialization stategy for SimpleJson\r\n    /// </summary>\r\n    public class NancySerializationStrategy : PocoJsonSerializerStrategy\r\n    {\r\n        private readonly bool retainCasing;\r\n        private readonly bool serializeEnumToString;\r\n        private readonly List<JavaScriptConverter> converters = new List<JavaScriptConverter>();\r\n        private readonly List<JavaScriptPrimitiveConverter> primitiveConverters = new List<JavaScriptPrimitiveConverter>();\r\n        private readonly ConcurrentDictionary<Type, JavaScriptConverter> converterCache = new ConcurrentDictionary<Type, JavaScriptConverter>();\r\n        private readonly ConcurrentDictionary<Type, JavaScriptPrimitiveConverter> primitiveConverterCache = new ConcurrentDictionary<Type, JavaScriptPrimitiveConverter>();\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancySerializationStrategy\"/> class.\r\n        /// </summary>\r\n        /// <remarks>C# casing of objects will be defaulted to camelCase and enums treated as integers</remarks>\r\n        public NancySerializationStrategy() : this(false, false)\r\n        {\r\n\r\n        }\r\n\r\n        /// <summary>\r\n        ///  Initializes a new instance of the <see cref=\"NancySerializationStrategy\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"retainCasing\">Retain C# casing of objects when serialized</param>\r\n        /// <param name=\"serializeEnumToString\">Should enums be represented as string</param>\r\n        public NancySerializationStrategy(bool retainCasing, bool serializeEnumToString)\r\n        {\r\n            this.retainCasing = retainCasing;\r\n            this.serializeEnumToString = serializeEnumToString;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Register custom <see cref=\"JavaScriptConverter\"/> converters\r\n        /// </summary>\r\n        /// <param name=\"javaScriptConverters\">An array of <see cref=\"JavaScriptConverter\"/></param>\r\n        public void RegisterConverters(IEnumerable<JavaScriptConverter> javaScriptConverters)\r\n        {\r\n            this.converters.AddRange(javaScriptConverters);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Register custom <see cref=\"JavaScriptPrimitiveConverter\"/>\r\n        /// </summary>\r\n        /// <param name=\"javaScriptPrimitiveConverters\">An array of <see cref=\"JavaScriptPrimitiveConverter\"/></param>\r\n        public void RegisterConverters(IEnumerable<JavaScriptPrimitiveConverter> javaScriptPrimitiveConverters)\r\n        {\r\n            this.primitiveConverters.AddRange(javaScriptPrimitiveConverters);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Formats a property name to a JSON field name\r\n        /// </summary>\r\n        /// <param name=\"clrPropertyName\">The property name to format</param>\r\n        /// <returns>camelCase <paramref name=\"clrPropertyName\"/> if retainCasing is false, otherwise <paramref name=\"clrPropertyName\"/></returns>\r\n        protected override string MapClrMemberNameToJsonFieldName(string clrPropertyName)\r\n        {\r\n            return this.retainCasing\r\n                ? base.MapClrMemberNameToJsonFieldName(clrPropertyName)\r\n                : clrPropertyName.ToCamelCase();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Deserialize an object\r\n        /// </summary>\r\n        /// <param name=\"value\">The object to deserialize</param>\r\n        /// <param name=\"type\">The type of object to deserialize</param>\r\n        /// <param name=\"dateTimeStyles\">The <see cref=\"DateTimeStyles\"/> ton convert <see cref=\"DateTime\"/> objects</param>\r\n        /// <returns>A instance of <paramref name=\"type\" /> deserialized from <paramref name=\"value\"/></returns>\r\n        public override object DeserializeObject(object value, Type type, DateTimeStyles dateTimeStyles)\r\n        {\r\n            var typeInfo = type.GetTypeInfo();\r\n            if (typeInfo.IsEnum || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type).GetTypeInfo().IsEnum))\r\n            {\r\n                var typeToParse = ReflectionUtils.IsNullableType(type)\r\n                    ? Nullable.GetUnderlyingType(type)\r\n                    : type;\r\n\r\n                return value == null\r\n                    ? null\r\n                    : Enum.Parse(typeToParse, value.ToString(), true);\r\n            }\r\n\r\n            var primitiveConverter = this.FindPrimitiveConverter(type);\r\n            if (primitiveConverter != null)\r\n            {\r\n                return primitiveConverter.Deserialize(value, type);\r\n            }\r\n\r\n            var valueDictionary = value as IDictionary<string, object>;\r\n            if (valueDictionary == null)\r\n            {\r\n                return base.DeserializeObject(value, type, dateTimeStyles);\r\n            }\r\n\r\n            var javascriptConverter = this.FindJavaScriptConverter(type);\r\n            if (javascriptConverter != null)\r\n            {\r\n                return javascriptConverter.Deserialize(valueDictionary, type);\r\n            }\r\n\r\n            if (!typeInfo.IsGenericType)\r\n            {\r\n                return base.DeserializeObject(value, type, dateTimeStyles);\r\n            }\r\n\r\n            var genericType = typeInfo.GetGenericTypeDefinition();\r\n            var genericTypeConverter = this.FindJavaScriptConverter(genericType);\r\n\r\n            if (genericTypeConverter == null)\r\n            {\r\n                return base.DeserializeObject(value, type, dateTimeStyles);\r\n            }\r\n\r\n            var values = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);\r\n            var genericArguments = type.GetGenericArguments();\r\n\r\n            for (var i = 0; i < genericArguments.Length; i++)\r\n            {\r\n                var deserializedObject = this.DeserializeObject(valueDictionary.Values.ElementAt(i),\r\n                    genericArguments[i], dateTimeStyles);\r\n\r\n                values.Add(valueDictionary.Keys.ElementAt(i), deserializedObject);\r\n            }\r\n\r\n            return genericTypeConverter.Deserialize(values, type);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Serializes an <see cref=\"Enum\"/>.\r\n        /// </summary>\r\n        /// <param name=\"p\">The enum value to serialize.</param>\r\n        /// <returns>The serialized value.</returns>\r\n        protected override object SerializeEnum(Enum p)\r\n        {\r\n            if (this.serializeEnumToString)\r\n            {\r\n                return p.ToString();\r\n            }\r\n            return base.SerializeEnum(p);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Serialize an object\r\n        /// </summary>\r\n        /// <param name=\"input\">The object to serialize</param>\r\n        /// <param name=\"output\">The serialized object</param>\r\n        /// <returns>true if <paramref name=\"input\"/> was converted successfully; otherwise, false</returns>\r\n        protected override bool TrySerializeKnownTypes(object input, out object output)\r\n        {\r\n            var dynamicValue = input as DynamicDictionaryValue;\r\n            if (!ReferenceEquals(dynamicValue, null) && dynamicValue.HasValue)\r\n            {\r\n                output = dynamicValue.Value;\r\n                return true;\r\n            }\r\n\r\n            var inputType = input.GetType();\r\n\r\n            if (this.TrySerializeJavaScriptConverter(input, out output, inputType))\r\n            {\r\n                return true;\r\n            }\r\n\r\n            if (this.TrySerializePrimitiveConverter(input, ref output, inputType))\r\n            {\r\n                return true;\r\n            }\r\n\r\n            var type = input as Type;\r\n\r\n            if (type != null)\r\n            {\r\n                output = type.GetTypeInfo().FullName;\r\n                return true;\r\n            }\r\n\r\n            if (input is DateTime)\r\n            {\r\n                return this.SerializeDateTime((DateTime)input, out output);\r\n            }\r\n\r\n            if (input is DateTimeOffset)\r\n            {\r\n                var dto = (DateTimeOffset)input;\r\n                output = dto.ToString(\"o\", CultureInfo.InvariantCulture);\r\n                return true;\r\n            }\r\n\r\n            return base.TrySerializeKnownTypes(input, out output);\r\n        }\r\n\r\n        private bool SerializeDateTime(DateTime input, out object output)\r\n        {\r\n            var dateTime = input;\r\n            if (dateTime.Kind == DateTimeKind.Unspecified)\r\n            {\r\n                dateTime = new DateTime(dateTime.Ticks, DateTimeKind.Local);\r\n            }\r\n\r\n            output = dateTime.ToString(\"o\", CultureInfo.InvariantCulture);\r\n\r\n            return true;\r\n        }\r\n\r\n        private bool TrySerializePrimitiveConverter(object input, ref object output, Type inputType)\r\n        {\r\n            var primitiveConverter = this.FindPrimitiveConverter(inputType);\r\n            if (primitiveConverter == null)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            output = primitiveConverter.Serialize(input);\r\n            return true;\r\n        }\r\n\r\n        private JavaScriptPrimitiveConverter FindPrimitiveConverter(Type inputType)\r\n        {\r\n            return this.primitiveConverterCache.GetOrAdd(inputType, typeToConvert => this.primitiveConverters.FirstOrDefault(converter => converter.SupportedTypes.Any(supportedType => supportedType.IsAssignableFrom(typeToConvert))));\r\n        }\r\n\r\n        private bool TrySerializeJavaScriptConverter(object input, out object output, Type inputType)\r\n        {\r\n            output = null;\r\n            var converter = this.FindJavaScriptConverter(inputType);\r\n            if (converter == null)\r\n            {\r\n                return false;\r\n            }\r\n            var result = converter.Serialize(input);\r\n            output = result.ToDictionary(kvp => this.MapClrMemberNameToJsonFieldName(kvp.Key), kvp => kvp.Value);\r\n            return true;\r\n        }\r\n\r\n        private JavaScriptConverter FindJavaScriptConverter(Type inputType)\r\n        {\r\n            return this.converterCache.GetOrAdd(inputType, typeToConvert => this.converters.FirstOrDefault(converter => converter.SupportedTypes.Any(supportedType => supportedType.IsAssignableFrom(typeToConvert))));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Json/Simple/SimpleJson.cs",
    "content": "#pragma warning disable CS1591, CS1574, CS1711, CS1712 //  Disable XML comment related warnings\r\n\r\n//-----------------------------------------------------------------------\r\n// <copyright file=\"SimpleJson.cs\" company=\"The Outercurve Foundation\">\r\n//    Copyright (c) 2011, The Outercurve Foundation.\r\n//\r\n//    Licensed under the MIT License (the \"License\");\r\n//    you may not use this file except in compliance with the License.\r\n//    You may obtain a copy of the License at\r\n//      http://www.opensource.org/licenses/mit-license.php\r\n//\r\n//    Unless required by applicable law or agreed to in writing, software\r\n//    distributed under the License is distributed on an \"AS IS\" BASIS,\r\n//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n//    See the License for the specific language governing permissions and\r\n//    limitations under the License.\r\n// </copyright>\r\n// <author>Nathan Totten (ntotten.com), Jim Zimmerman (jimzimmerman.com) and Prabir Shrestha (prabir.me)</author>\r\n// <website>https://github.com/facebook-csharp-sdk/simple-json</website>\r\n//-----------------------------------------------------------------------\r\n\r\n// VERSION: 0.38.0\r\n\r\n// NOTE: uncomment the following line to make SimpleJson class internal.\r\n//#define SIMPLE_JSON_INTERNAL\r\n\r\n// NOTE: uncomment the following line to make JsonArray and JsonObject class internal.\r\n//#define SIMPLE_JSON_OBJARRAYINTERNAL\r\n\r\n// NOTE: uncomment the following line to enable dynamic support.\r\n#define SIMPLE_JSON_DYNAMIC\r\n\r\n// NOTE: uncomment the following line to enable DataContract support.\r\n//#define SIMPLE_JSON_DATACONTRACT\r\n\r\n// NOTE: uncomment the following line to enable IReadOnlyCollection<T> and IReadOnlyList<T> support.\r\n//#define SIMPLE_JSON_READONLY_COLLECTIONS\r\n\r\n// NOTE: uncomment the following line to disable linq expressions/compiled lambda (better performance) instead of method.invoke().\r\n// define if you are using .net framework <= 3.0 or < WP7.5\r\n//#define SIMPLE_JSON_NO_LINQ_EXPRESSION\r\n\r\n// NOTE: uncomment the following line if you are compiling under Window Metro style application/library.\r\n// usually already defined in properties\r\n//#define NETFX_CORE;\r\n\r\n// If you are targetting WinStore, WP8 and NET4.5+ PCL make sure to #define SIMPLE_JSON_TYPEINFO;\r\n#define SIMPLE_JSON_TYPEINFO\r\n\r\n// original json parsing code from http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html\r\n\r\n#if NETFX_CORE\r\n#define SIMPLE_JSON_TYPEINFO\r\n#endif\r\nnamespace Nancy.Json.Simple\r\n{\r\n    using System;\r\n    using System.CodeDom.Compiler;\r\n    using System.Collections;\r\n    using System.Collections.Generic;\r\n    using System.ComponentModel;\r\n    using System.Diagnostics.CodeAnalysis;\r\n    using System.Dynamic;\r\n    using System.Globalization;\r\n    using System.Linq;\r\n    using System.Linq.Expressions;\r\n    using System.Reflection;\r\n    using System.Runtime.Serialization;\r\n    using System.Text;\r\n\r\n    // ReSharper disable LoopCanBeConvertedToQuery\r\n    // ReSharper disable RedundantExplicitArrayCreation\r\n    // ReSharper disable SuggestUseVarKeywordEvident\r\n    /// <summary>\r\n    /// Represents the json array.\r\n    /// </summary>\r\n    [GeneratedCode(\"simple-json\", \"1.0.0\")]\r\n    [EditorBrowsable(EditorBrowsableState.Never)]\r\n    [SuppressMessage(\"Microsoft.Naming\", \"CA1710:IdentifiersShouldHaveCorrectSuffix\")]\r\n#if SIMPLE_JSON_OBJARRAYINTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n        class JsonArray : List<object>\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"JsonArray\"/> class.\r\n        /// </summary>\r\n        public JsonArray() { }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"JsonArray\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"capacity\">The capacity of the json array.</param>\r\n        public JsonArray(int capacity) : base(capacity) { }\r\n\r\n        /// <summary>\r\n        /// The json representation of the array.\r\n        /// </summary>\r\n        /// <returns>The json representation of the array.</returns>\r\n        public override string ToString()\r\n        {\r\n            return SimpleJson.SerializeObject(this) ?? string.Empty;\r\n        }\r\n    }\r\n\r\n    /// <summary>\r\n    /// Represents the json object.\r\n    /// </summary>\r\n    [GeneratedCode(\"simple-json\", \"1.0.0\")]\r\n    [EditorBrowsable(EditorBrowsableState.Never)]\r\n    [SuppressMessage(\"Microsoft.Naming\", \"CA1710:IdentifiersShouldHaveCorrectSuffix\")]\r\n#if SIMPLE_JSON_OBJARRAYINTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n        class JsonObject :\r\n#if SIMPLE_JSON_DYNAMIC\r\n            DynamicObject,\r\n#endif\r\n            IDictionary<string, object>\r\n    {\r\n        /// <summary>\r\n        /// The internal member dictionary.\r\n        /// </summary>\r\n        private readonly Dictionary<string, object> _members;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of <see cref=\"JsonObject\"/>.\r\n        /// </summary>\r\n        public JsonObject() : this(StringComparer.OrdinalIgnoreCase) { }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of <see cref=\"JsonObject\"/>.\r\n        /// </summary>\r\n        /// <param name=\"comparer\">The <see cref=\"T:System.Collections.Generic.IEqualityComparer`1\"/> implementation to use when comparing keys, or null to use the default <see cref=\"T:System.Collections.Generic.EqualityComparer`1\"/> for the type of the key.</param>\r\n        public JsonObject(IEqualityComparer<string> comparer)\r\n        {\r\n            this._members = new Dictionary<string, object>(comparer);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"System.Object\"/> at the specified index.\r\n        /// </summary>\r\n        /// <value></value>\r\n        public object this[int index]\r\n        {\r\n            get { return GetAtIndex(this._members, index); }\r\n        }\r\n\r\n        internal static object GetAtIndex(IDictionary<string, object> obj, int index)\r\n        {\r\n            if (obj == null)\r\n                throw new ArgumentNullException(\"obj\");\r\n            if (index >= obj.Count)\r\n                throw new ArgumentOutOfRangeException(\"index\");\r\n            int i = 0;\r\n            foreach (KeyValuePair<string, object> o in obj)\r\n                if (i++ == index) return o.Value;\r\n            return null;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds the specified key.\r\n        /// </summary>\r\n        /// <param name=\"key\">The key.</param>\r\n        /// <param name=\"value\">The value.</param>\r\n        public void Add(string key, object value)\r\n        {\r\n            this._members.Add(key, value);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determines whether the specified key contains key.\r\n        /// </summary>\r\n        /// <param name=\"key\">The key.</param>\r\n        /// <returns>\r\n        ///     <c>true</c> if the specified key contains key; otherwise, <c>false</c>.\r\n        /// </returns>\r\n        public bool ContainsKey(string key)\r\n        {\r\n            return this._members.ContainsKey(key);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the keys.\r\n        /// </summary>\r\n        /// <value>The keys.</value>\r\n        public ICollection<string> Keys\r\n        {\r\n            get { return this._members.Keys; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Removes the specified key.\r\n        /// </summary>\r\n        /// <param name=\"key\">The key.</param>\r\n        /// <returns></returns>\r\n        public bool Remove(string key)\r\n        {\r\n            return this._members.Remove(key);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tries the get value.\r\n        /// </summary>\r\n        /// <param name=\"key\">The key.</param>\r\n        /// <param name=\"value\">The value.</param>\r\n        /// <returns></returns>\r\n        public bool TryGetValue(string key, out object value)\r\n        {\r\n            return this._members.TryGetValue(key, out value);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the values.\r\n        /// </summary>\r\n        /// <value>The values.</value>\r\n        public ICollection<object> Values\r\n        {\r\n            get { return this._members.Values; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the <see cref=\"System.Object\"/> with the specified key.\r\n        /// </summary>\r\n        /// <value></value>\r\n        public object this[string key]\r\n        {\r\n            get { return this._members[key]; }\r\n            set { this._members[key] = value; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds the specified item.\r\n        /// </summary>\r\n        /// <param name=\"item\">The item.</param>\r\n        public void Add(KeyValuePair<string, object> item)\r\n        {\r\n            this._members.Add(item.Key, item.Value);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Clears this instance.\r\n        /// </summary>\r\n        public void Clear()\r\n        {\r\n            this._members.Clear();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determines whether [contains] [the specified item].\r\n        /// </summary>\r\n        /// <param name=\"item\">The item.</param>\r\n        /// <returns>\r\n        /// \t<c>true</c> if [contains] [the specified item]; otherwise, <c>false</c>.\r\n        /// </returns>\r\n        public bool Contains(KeyValuePair<string, object> item)\r\n        {\r\n            object value;\r\n            return this._members.TryGetValue(item.Key, out value) && value == item.Value;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Copies to.\r\n        /// </summary>\r\n        /// <param name=\"array\">The array.</param>\r\n        /// <param name=\"arrayIndex\">Index of the array.</param>\r\n        public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)\r\n        {\r\n            if (array == null) throw new ArgumentNullException(\"array\");\r\n            int num = this.Count;\r\n            foreach (KeyValuePair<string, object> kvp in this)\r\n            {\r\n                array[arrayIndex++] = kvp;\r\n                if (--num <= 0)\r\n                    return;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the count.\r\n        /// </summary>\r\n        /// <value>The count.</value>\r\n        public int Count\r\n        {\r\n            get { return this._members.Count; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether this instance is read only.\r\n        /// </summary>\r\n        /// <value>\r\n        /// \t<c>true</c> if this instance is read only; otherwise, <c>false</c>.\r\n        /// </value>\r\n        public bool IsReadOnly\r\n        {\r\n            get { return false; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Removes the specified item.\r\n        /// </summary>\r\n        /// <param name=\"item\">The item.</param>\r\n        /// <returns></returns>\r\n        public bool Remove(KeyValuePair<string, object> item)\r\n        {\r\n            return this._members.Remove(item.Key);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the enumerator.\r\n        /// </summary>\r\n        /// <returns></returns>\r\n        public IEnumerator<KeyValuePair<string, object>> GetEnumerator()\r\n        {\r\n            return this._members.GetEnumerator();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an enumerator that iterates through a collection.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// An <see cref=\"T:System.Collections.IEnumerator\"/> object that can be used to iterate through the collection.\r\n        /// </returns>\r\n        IEnumerator IEnumerable.GetEnumerator()\r\n        {\r\n            return this._members.GetEnumerator();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns a json <see cref=\"T:System.String\"/> that represents the current <see cref=\"T:System.Object\"/>.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// A json <see cref=\"T:System.String\"/> that represents the current <see cref=\"T:System.Object\"/>.\r\n        /// </returns>\r\n        public override string ToString()\r\n        {\r\n            return SimpleJson.SerializeObject(this);\r\n        }\r\n\r\n#if SIMPLE_JSON_DYNAMIC\r\n        /// <summary>\r\n        /// Provides implementation for type conversion operations. Classes derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class can override this method to specify dynamic behavior for operations that convert an object from one type to another.\r\n        /// </summary>\r\n        /// <param name=\"binder\">Provides information about the conversion operation. The binder.Type property provides the type to which the object must be converted. For example, for the statement (String)sampleObject in C# (CType(sampleObject, Type) in Visual Basic), where sampleObject is an instance of the class derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class, binder.Type returns the <see cref=\"T:System.String\"/> type. The binder.Explicit property provides information about the kind of conversion that occurs. It returns true for explicit conversion and false for implicit conversion.</param>\r\n        /// <param name=\"result\">The result of the type conversion operation.</param>\r\n        /// <returns>\r\n        /// Alwasy returns true.\r\n        /// </returns>\r\n        public override bool TryConvert(ConvertBinder binder, out object result)\r\n        {\r\n            // <pex>\r\n            if (binder == null)\r\n                throw new ArgumentNullException(\"binder\");\r\n            // </pex>\r\n            Type targetType = binder.Type;\r\n\r\n            if ((targetType == typeof(IEnumerable)) ||\r\n                (targetType == typeof(IEnumerable<KeyValuePair<string, object>>)) ||\r\n                (targetType == typeof(IDictionary<string, object>)) ||\r\n                (targetType == typeof(IDictionary)))\r\n            {\r\n                result = this;\r\n                return true;\r\n            }\r\n\r\n            return base.TryConvert(binder, out result);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Provides the implementation for operations that delete an object member. This method is not intended for use in C# or Visual Basic.\r\n        /// </summary>\r\n        /// <param name=\"binder\">Provides information about the deletion.</param>\r\n        /// <returns>\r\n        /// Alwasy returns true.\r\n        /// </returns>\r\n        public override bool TryDeleteMember(DeleteMemberBinder binder)\r\n        {\r\n            // <pex>\r\n            if (binder == null)\r\n                throw new ArgumentNullException(\"binder\");\r\n            // </pex>\r\n            return this._members.Remove(binder.Name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Provides the implementation for operations that get a value by index. Classes derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class can override this method to specify dynamic behavior for indexing operations.\r\n        /// </summary>\r\n        /// <param name=\"binder\">Provides information about the operation.</param>\r\n        /// <param name=\"indexes\">The indexes that are used in the operation. For example, for the sampleObject[3] operation in C# (sampleObject(3) in Visual Basic), where sampleObject is derived from the DynamicObject class, <paramref name=\"indexes\"/> is equal to 3.</param>\r\n        /// <param name=\"result\">The result of the index operation.</param>\r\n        /// <returns>\r\n        /// Alwasy returns true.\r\n        /// </returns>\r\n        public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)\r\n        {\r\n            if (indexes == null) throw new ArgumentNullException(\"indexes\");\r\n            if (indexes.Length == 1)\r\n            {\r\n                result = ((IDictionary<string, object>)this)[(string)indexes[0]];\r\n                return true;\r\n            }\r\n            result = null;\r\n            return true;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Provides the implementation for operations that get member values. Classes derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class can override this method to specify dynamic behavior for operations such as getting a value for a property.\r\n        /// </summary>\r\n        /// <param name=\"binder\">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member on which the dynamic operation is performed. For example, for the Console.WriteLine(sampleObject.SampleProperty) statement, where sampleObject is an instance of the class derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class, binder.Name returns \"SampleProperty\". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param>\r\n        /// <param name=\"result\">The result of the get operation. For example, if the method is called for a property, you can assign the property value to <paramref name=\"result\"/>.</param>\r\n        /// <returns>\r\n        /// Alwasy returns true.\r\n        /// </returns>\r\n        public override bool TryGetMember(GetMemberBinder binder, out object result)\r\n        {\r\n            object value;\r\n            if (this._members.TryGetValue(binder.Name, out value))\r\n            {\r\n                result = value;\r\n                return true;\r\n            }\r\n            result = null;\r\n            return true;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Provides the implementation for operations that set a value by index. Classes derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class can override this method to specify dynamic behavior for operations that access objects by a specified index.\r\n        /// </summary>\r\n        /// <param name=\"binder\">Provides information about the operation.</param>\r\n        /// <param name=\"indexes\">The indexes that are used in the operation. For example, for the sampleObject[3] = 10 operation in C# (sampleObject(3) = 10 in Visual Basic), where sampleObject is derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class, <paramref name=\"indexes\"/> is equal to 3.</param>\r\n        /// <param name=\"value\">The value to set to the object that has the specified index. For example, for the sampleObject[3] = 10 operation in C# (sampleObject(3) = 10 in Visual Basic), where sampleObject is derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class, <paramref name=\"value\"/> is equal to 10.</param>\r\n        /// <returns>\r\n        /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.\r\n        /// </returns>\r\n        public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)\r\n        {\r\n            if (indexes == null) throw new ArgumentNullException(\"indexes\");\r\n            if (indexes.Length == 1)\r\n            {\r\n                ((IDictionary<string, object>)this)[(string)indexes[0]] = value;\r\n                return true;\r\n            }\r\n            return base.TrySetIndex(binder, indexes, value);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Provides the implementation for operations that set member values. Classes derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class can override this method to specify dynamic behavior for operations such as setting a value for a property.\r\n        /// </summary>\r\n        /// <param name=\"binder\">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member to which the value is being assigned. For example, for the statement sampleObject.SampleProperty = \"Test\", where sampleObject is an instance of the class derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class, binder.Name returns \"SampleProperty\". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param>\r\n        /// <param name=\"value\">The value to set to the member. For example, for sampleObject.SampleProperty = \"Test\", where sampleObject is an instance of the class derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class, the <paramref name=\"value\"/> is \"Test\".</param>\r\n        /// <returns>\r\n        /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.)\r\n        /// </returns>\r\n        public override bool TrySetMember(SetMemberBinder binder, object value)\r\n        {\r\n            // <pex>\r\n            if (binder == null)\r\n                throw new ArgumentNullException(\"binder\");\r\n            // </pex>\r\n            this._members[binder.Name] = value;\r\n            return true;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns the enumeration of all dynamic member names.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// A sequence that contains dynamic member names.\r\n        /// </returns>\r\n        public override IEnumerable<string> GetDynamicMemberNames()\r\n        {\r\n            foreach (var key in this.Keys)\r\n                yield return key;\r\n        }\r\n#endif\r\n    }\r\n\r\n    /// <summary>\r\n    /// This class encodes and decodes JSON strings.\r\n    /// Spec. details, see http://www.json.org/\r\n    ///\r\n    /// JSON uses Arrays and Objects. These correspond here to the datatypes JsonArray(IList&lt;object>) and JsonObject(IDictionary&lt;string,object>).\r\n    /// All numbers are parsed to doubles.\r\n    /// </summary>\r\n    [GeneratedCode(\"simple-json\", \"1.0.0\")]\r\n#if SIMPLE_JSON_INTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n        static class SimpleJson\r\n    {\r\n        private const int TOKEN_NONE = 0;\r\n        private const int TOKEN_CURLY_OPEN = 1;\r\n        private const int TOKEN_CURLY_CLOSE = 2;\r\n        private const int TOKEN_SQUARED_OPEN = 3;\r\n        private const int TOKEN_SQUARED_CLOSE = 4;\r\n        private const int TOKEN_COLON = 5;\r\n        private const int TOKEN_COMMA = 6;\r\n        private const int TOKEN_STRING = 7;\r\n        private const int TOKEN_NUMBER = 8;\r\n        private const int TOKEN_TRUE = 9;\r\n        private const int TOKEN_FALSE = 10;\r\n        private const int TOKEN_NULL = 11;\r\n        private const int BUILDER_CAPACITY = 2000;\r\n\r\n        private static readonly char[] EscapeTable;\r\n        private static readonly char[] EscapeCharacters = new char[] { '\"', '\\\\', '\\b', '\\f', '\\n', '\\r', '\\t' };\r\n        private static readonly string EscapeCharactersString = new string(EscapeCharacters);\r\n\r\n        static SimpleJson()\r\n        {\r\n            EscapeTable = new char[93];\r\n            EscapeTable['\"']  = '\"';\r\n            EscapeTable['\\\\'] = '\\\\';\r\n            EscapeTable['\\b'] = 'b';\r\n            EscapeTable['\\f'] = 'f';\r\n            EscapeTable['\\n'] = 'n';\r\n            EscapeTable['\\r'] = 'r';\r\n            EscapeTable['\\t'] = 't';\r\n        }\r\n\r\n        /// <summary>\r\n        /// Parses the string json into a value\r\n        /// </summary>\r\n        /// <param name=\"json\">A JSON string.</param>\r\n        /// <returns>An IList&lt;object>, a IDictionary&lt;string,object>, a double, a string, null, true, or false</returns>\r\n        public static object DeserializeObject(string json)\r\n        {\r\n            if (string.IsNullOrWhiteSpace(json))\r\n            {\r\n                return null;\r\n            }\r\n\r\n            object obj;\r\n            if (TryDeserializeObject(json, out obj))\r\n                return obj;\r\n            throw new SerializationException(\"Invalid JSON string\");\r\n        }\r\n\r\n        /// <summary>\r\n        /// Try parsing the json string into a value.\r\n        /// </summary>\r\n        /// <param name=\"json\">\r\n        /// A JSON string.\r\n        /// </param>\r\n        /// <param name=\"obj\">\r\n        /// The object.\r\n        /// </param>\r\n        /// <returns>\r\n        /// Returns true if successfull otherwise false.\r\n        /// </returns>\r\n        [SuppressMessage(\"Microsoft.Design\", \"CA1007:UseGenericsWhereAppropriate\", Justification=\"Need to support .NET 2\")]\r\n        public static bool TryDeserializeObject(string json, out object obj)\r\n        {\r\n            bool success = true;\r\n            if (json != null)\r\n            {\r\n                char[] charArray = json.ToCharArray();\r\n                int index = 0;\r\n                obj = ParseValue(charArray, ref index, ref success);\r\n            }\r\n            else\r\n                obj = null;\r\n\r\n            return success;\r\n        }\r\n\r\n        public static object DeserializeObject(string json, Type type, IJsonSerializerStrategy jsonSerializerStrategy, DateTimeStyles dateTimeStyles)\r\n        {\r\n            object jsonObject = DeserializeObject(json);\r\n            return type == null || jsonObject != null && ReflectionUtils.IsAssignableFrom(jsonObject.GetType(), type)\r\n                ? jsonObject\r\n                : (jsonSerializerStrategy ?? CurrentJsonSerializerStrategy).DeserializeObject(jsonObject, type, dateTimeStyles);\r\n        }\r\n\r\n        public static object DeserializeObject(string json, Type type, DateTimeStyles dateTimeStyles)\r\n        {\r\n            return DeserializeObject(json, type, null, dateTimeStyles);\r\n        }\r\n\r\n        public static T DeserializeObject<T>(string json, IJsonSerializerStrategy jsonSerializerStrategy, DateTimeStyles dateTimeStyles)\r\n        {\r\n            return (T)DeserializeObject(json, typeof(T), jsonSerializerStrategy, dateTimeStyles);\r\n        }\r\n\r\n        public static T DeserializeObject<T>(string json)\r\n        {\r\n            return (T)DeserializeObject(json, typeof(T), null, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Converts a IDictionary&lt;string,object> / IList&lt;object> object into a JSON string\r\n        /// </summary>\r\n        /// <param name=\"json\">A IDictionary&lt;string,object> / IList&lt;object></param>\r\n        /// <param name=\"jsonSerializerStrategy\">Serializer strategy to use</param>\r\n        /// <param name=\"excludeNullValues\"><see langword=\"true\" /> if the serializer should exclude null values for properties on objects otherwise <see langword=\"false\" /></param>\r\n        /// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>\r\n        public static string SerializeObject(object json, IJsonSerializerStrategy jsonSerializerStrategy, bool excludeNullValues)\r\n        {\r\n            StringBuilder builder = new StringBuilder(BUILDER_CAPACITY);\r\n            bool success = SerializeValue(jsonSerializerStrategy, json, builder, excludeNullValues);\r\n            return (success ? builder.ToString() : null);\r\n        }\r\n\r\n        public static string SerializeObject(object json)\r\n        {\r\n            return SerializeObject(json, CurrentJsonSerializerStrategy, false);\r\n        }\r\n\r\n        public static string EscapeToJavascriptString(string jsonString)\r\n        {\r\n            if (string.IsNullOrEmpty(jsonString))\r\n                return jsonString;\r\n\r\n            StringBuilder sb = new StringBuilder();\r\n            char c;\r\n\r\n            for (int i = 0; i < jsonString.Length; )\r\n            {\r\n                c = jsonString[i++];\r\n\r\n                if (c == '\\\\')\r\n                {\r\n                    int remainingLength = jsonString.Length - i;\r\n                    if (remainingLength >= 2)\r\n                    {\r\n                        char lookahead = jsonString[i];\r\n                        if (lookahead == '\\\\')\r\n                        {\r\n                            sb.Append('\\\\');\r\n                            ++i;\r\n                        }\r\n                        else if (lookahead == '\"')\r\n                        {\r\n                            sb.Append(\"\\\"\");\r\n                            ++i;\r\n                        }\r\n                        else if (lookahead == 't')\r\n                        {\r\n                            sb.Append('\\t');\r\n                            ++i;\r\n                        }\r\n                        else if (lookahead == 'b')\r\n                        {\r\n                            sb.Append('\\b');\r\n                            ++i;\r\n                        }\r\n                        else if (lookahead == 'n')\r\n                        {\r\n                            sb.Append('\\n');\r\n                            ++i;\r\n                        }\r\n                        else if (lookahead == 'r')\r\n                        {\r\n                            sb.Append('\\r');\r\n                            ++i;\r\n                        }\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    sb.Append(c);\r\n                }\r\n            }\r\n            return sb.ToString();\r\n        }\r\n\r\n        static IDictionary<string, object> ParseObject(char[] json, ref int index, ref bool success)\r\n        {\r\n            IDictionary<string, object> table = new JsonObject();\r\n            int token;\r\n\r\n            // {\r\n            NextToken(json, ref index);\r\n\r\n            bool done = false;\r\n            while (!done)\r\n            {\r\n                token = LookAhead(json, index);\r\n                if (token == TOKEN_NONE)\r\n                {\r\n                    success = false;\r\n                    return null;\r\n                }\r\n                else if (token == TOKEN_COMMA)\r\n                    NextToken(json, ref index);\r\n                else if (token == TOKEN_CURLY_CLOSE)\r\n                {\r\n                    NextToken(json, ref index);\r\n                    return table;\r\n                }\r\n                else\r\n                {\r\n                    // name\r\n                    string name = ParseString(json, ref index, ref success);\r\n                    if (!success)\r\n                    {\r\n                        success = false;\r\n                        return null;\r\n                    }\r\n                    // :\r\n                    token = NextToken(json, ref index);\r\n                    if (token != TOKEN_COLON)\r\n                    {\r\n                        success = false;\r\n                        return null;\r\n                    }\r\n                    // value\r\n                    object value = ParseValue(json, ref index, ref success);\r\n                    if (!success)\r\n                    {\r\n                        success = false;\r\n                        return null;\r\n                    }\r\n                    table[name] = value;\r\n                }\r\n            }\r\n            return table;\r\n        }\r\n\r\n        static JsonArray ParseArray(char[] json, ref int index, ref bool success)\r\n        {\r\n            JsonArray array = new JsonArray();\r\n\r\n            // [\r\n            NextToken(json, ref index);\r\n\r\n            bool done = false;\r\n            while (!done)\r\n            {\r\n                int token = LookAhead(json, index);\r\n                if (token == TOKEN_NONE)\r\n                {\r\n                    success = false;\r\n                    return null;\r\n                }\r\n                else if (token == TOKEN_COMMA)\r\n                    NextToken(json, ref index);\r\n                else if (token == TOKEN_SQUARED_CLOSE)\r\n                {\r\n                    NextToken(json, ref index);\r\n                    break;\r\n                }\r\n                else\r\n                {\r\n                    object value = ParseValue(json, ref index, ref success);\r\n                    if (!success)\r\n                        return null;\r\n                    array.Add(value);\r\n                }\r\n            }\r\n            return array;\r\n        }\r\n\r\n        static object ParseValue(char[] json, ref int index, ref bool success)\r\n        {\r\n            switch (LookAhead(json, index))\r\n            {\r\n                case TOKEN_STRING:\r\n                    return ParseString(json, ref index, ref success);\r\n                case TOKEN_NUMBER:\r\n                    return ParseNumber(json, ref index, ref success);\r\n                case TOKEN_CURLY_OPEN:\r\n                    return ParseObject(json, ref index, ref success);\r\n                case TOKEN_SQUARED_OPEN:\r\n                    return ParseArray(json, ref index, ref success);\r\n                case TOKEN_TRUE:\r\n                    NextToken(json, ref index);\r\n                    return true;\r\n                case TOKEN_FALSE:\r\n                    NextToken(json, ref index);\r\n                    return false;\r\n                case TOKEN_NULL:\r\n                    NextToken(json, ref index);\r\n                    return null;\r\n                case TOKEN_NONE:\r\n                    break;\r\n            }\r\n            success = false;\r\n            return null;\r\n        }\r\n\r\n        static string ParseString(char[] json, ref int index, ref bool success)\r\n        {\r\n            StringBuilder s = new StringBuilder(BUILDER_CAPACITY);\r\n            char c;\r\n\r\n            EatWhitespace(json, ref index);\r\n\r\n            // \"\r\n            c = json[index++];\r\n            bool complete = false;\r\n            while (!complete)\r\n            {\r\n                if (index == json.Length)\r\n                    break;\r\n\r\n                c = json[index++];\r\n                if (c == '\"')\r\n                {\r\n                    complete = true;\r\n                    break;\r\n                }\r\n                else if (c == '\\\\')\r\n                {\r\n                    if (index == json.Length)\r\n                        break;\r\n                    c = json[index++];\r\n                    if (c == '\"')\r\n                        s.Append('\"');\r\n                    else if (c == '\\\\')\r\n                        s.Append('\\\\');\r\n                    else if (c == '/')\r\n                        s.Append('/');\r\n                    else if (c == 'b')\r\n                        s.Append('\\b');\r\n                    else if (c == 'f')\r\n                        s.Append('\\f');\r\n                    else if (c == 'n')\r\n                        s.Append('\\n');\r\n                    else if (c == 'r')\r\n                        s.Append('\\r');\r\n                    else if (c == 't')\r\n                        s.Append('\\t');\r\n                    else if (c == 'u')\r\n                    {\r\n                        int remainingLength = json.Length - index;\r\n                        if (remainingLength >= 4)\r\n                        {\r\n                            // parse the 32 bit hex into an integer codepoint\r\n                            uint codePoint;\r\n                            if (!(success = UInt32.TryParse(new string(json, index, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out codePoint)))\r\n                                return \"\";\r\n\r\n                            // convert the integer codepoint to a unicode char and add to string\r\n                            if (0xD800 <= codePoint && codePoint <= 0xDBFF)  // if high surrogate\r\n                            {\r\n                                index += 4; // skip 4 chars\r\n                                remainingLength = json.Length - index;\r\n                                if (remainingLength >= 6)\r\n                                {\r\n                                    uint lowCodePoint;\r\n                                    if (new string(json, index, 2) == \"\\\\u\" && UInt32.TryParse(new string(json, index + 2, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out lowCodePoint))\r\n                                    {\r\n                                        if (0xDC00 <= lowCodePoint && lowCodePoint <= 0xDFFF)    // if low surrogate\r\n                                        {\r\n                                            s.Append((char)codePoint);\r\n                                            s.Append((char)lowCodePoint);\r\n                                            index += 6; // skip 6 chars\r\n                                            continue;\r\n                                        }\r\n                                    }\r\n                                }\r\n                                success = false;    // invalid surrogate pair\r\n                                return \"\";\r\n                            }\r\n                            s.Append(ConvertFromUtf32((int)codePoint));\r\n                            // skip 4 chars\r\n                            index += 4;\r\n                        }\r\n                        else\r\n                            break;\r\n                    }\r\n                }\r\n                else\r\n                    s.Append(c);\r\n            }\r\n            if (!complete)\r\n            {\r\n                success = false;\r\n                return null;\r\n            }\r\n            return s.ToString();\r\n        }\r\n\r\n        private static string ConvertFromUtf32(int utf32)\r\n        {\r\n            // http://www.java2s.com/Open-Source/CSharp/2.6.4-mono-.net-core/System/System/Char.cs.htm\r\n            if (utf32 < 0 || utf32 > 0x10FFFF)\r\n                throw new ArgumentOutOfRangeException(\"utf32\", \"The argument must be from 0 to 0x10FFFF.\");\r\n            if (0xD800 <= utf32 && utf32 <= 0xDFFF)\r\n                throw new ArgumentOutOfRangeException(\"utf32\", \"The argument must not be in surrogate pair range.\");\r\n            if (utf32 < 0x10000)\r\n                return new string((char)utf32, 1);\r\n            utf32 -= 0x10000;\r\n            return new string(new char[] { (char)((utf32 >> 10) + 0xD800), (char)(utf32 % 0x0400 + 0xDC00) });\r\n        }\r\n\r\n        static object ParseNumber(char[] json, ref int index, ref bool success)\r\n        {\r\n            EatWhitespace(json, ref index);\r\n            int lastIndex = GetLastIndexOfNumber(json, index);\r\n            int charLength = (lastIndex - index) + 1;\r\n            object returnNumber;\r\n            string str = new string(json, index, charLength);\r\n            if (str.IndexOf(\".\", StringComparison.OrdinalIgnoreCase) != -1 || str.IndexOf(\"e\", StringComparison.OrdinalIgnoreCase) != -1)\r\n            {\r\n                double number;\r\n                success = double.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number);\r\n                returnNumber = number;\r\n            }\r\n            else\r\n            {\r\n                long number;\r\n                success = long.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number);\r\n                returnNumber = number;\r\n            }\r\n            index = lastIndex + 1;\r\n            return returnNumber;\r\n        }\r\n\r\n        static int GetLastIndexOfNumber(char[] json, int index)\r\n        {\r\n            int lastIndex;\r\n            for (lastIndex = index; lastIndex < json.Length; lastIndex++)\r\n                if (\"0123456789+-.eE\".IndexOf(json[lastIndex]) == -1) break;\r\n            return lastIndex - 1;\r\n        }\r\n\r\n        static void EatWhitespace(char[] json, ref int index)\r\n        {\r\n            for (; index < json.Length; index++)\r\n                if (\" \\t\\n\\r\\b\\f\".IndexOf(json[index]) == -1) break;\r\n        }\r\n\r\n        static int LookAhead(char[] json, int index)\r\n        {\r\n            int saveIndex = index;\r\n            return NextToken(json, ref saveIndex);\r\n        }\r\n\r\n        [SuppressMessage(\"Microsoft.Maintainability\", \"CA1502:AvoidExcessiveComplexity\")]\r\n        static int NextToken(char[] json, ref int index)\r\n        {\r\n            EatWhitespace(json, ref index);\r\n            if (index == json.Length)\r\n                return TOKEN_NONE;\r\n            char c = json[index];\r\n            index++;\r\n            switch (c)\r\n            {\r\n                case '{':\r\n                    return TOKEN_CURLY_OPEN;\r\n                case '}':\r\n                    return TOKEN_CURLY_CLOSE;\r\n                case '[':\r\n                    return TOKEN_SQUARED_OPEN;\r\n                case ']':\r\n                    return TOKEN_SQUARED_CLOSE;\r\n                case ',':\r\n                    return TOKEN_COMMA;\r\n                case '\"':\r\n                    return TOKEN_STRING;\r\n                case '0':\r\n                case '1':\r\n                case '2':\r\n                case '3':\r\n                case '4':\r\n                case '5':\r\n                case '6':\r\n                case '7':\r\n                case '8':\r\n                case '9':\r\n                case '-':\r\n                    return TOKEN_NUMBER;\r\n                case ':':\r\n                    return TOKEN_COLON;\r\n            }\r\n            index--;\r\n            int remainingLength = json.Length - index;\r\n            // false\r\n            if (remainingLength >= 5)\r\n            {\r\n                if (json[index] == 'f' && json[index + 1] == 'a' && json[index + 2] == 'l' && json[index + 3] == 's' && json[index + 4] == 'e')\r\n                {\r\n                    index += 5;\r\n                    return TOKEN_FALSE;\r\n                }\r\n            }\r\n            // true\r\n            if (remainingLength >= 4)\r\n            {\r\n                if (json[index] == 't' && json[index + 1] == 'r' && json[index + 2] == 'u' && json[index + 3] == 'e')\r\n                {\r\n                    index += 4;\r\n                    return TOKEN_TRUE;\r\n                }\r\n            }\r\n            // null\r\n            if (remainingLength >= 4)\r\n            {\r\n                if (json[index] == 'n' && json[index + 1] == 'u' && json[index + 2] == 'l' && json[index + 3] == 'l')\r\n                {\r\n                    index += 4;\r\n                    return TOKEN_NULL;\r\n                }\r\n            }\r\n            return TOKEN_NONE;\r\n        }\r\n\r\n        static bool SerializeValue(IJsonSerializerStrategy jsonSerializerStrategy, object value, StringBuilder builder, bool excludeNullValues)\r\n        {\r\n            bool success = true;\r\n\r\n            string stringValue = value as string;\r\n            if (stringValue != null)\r\n                success = SerializeString(stringValue, builder);\r\n            else\r\n            {\r\n                IDictionary<string, object> dict = value as IDictionary<string, object>;\r\n                if (dict != null)\r\n                {\r\n                    success = SerializeObject(jsonSerializerStrategy, dict.Keys, dict.Values, builder, excludeNullValues);\r\n                }\r\n                else\r\n                {\r\n                    IDictionary<string, string> stringDictionary = value as IDictionary<string, string>;\r\n                    if (stringDictionary != null)\r\n                    {\r\n                        success = SerializeObject(jsonSerializerStrategy, stringDictionary.Keys, stringDictionary.Values, builder, excludeNullValues);\r\n                    }\r\n                    else\r\n                    {\r\n                        IEnumerable enumerableValue = value as IEnumerable;\r\n                        if (enumerableValue != null)\r\n                            success = SerializeArray(jsonSerializerStrategy, enumerableValue, builder, excludeNullValues);\r\n                        else if (IsNumeric(value))\r\n                            success = SerializeNumber(value, builder);\r\n                        else if (value is bool)\r\n                            builder.Append((bool)value ? \"true\" : \"false\");\r\n                        else if (value == null)\r\n                            builder.Append(\"null\");\r\n                        else\r\n                        {\r\n                            object serializedObject;\r\n                            success = jsonSerializerStrategy.TrySerializeNonPrimitiveObject(value, out serializedObject);\r\n                            if (success)\r\n                                SerializeValue(jsonSerializerStrategy, serializedObject, builder, excludeNullValues);\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n            return success;\r\n        }\r\n\r\n        static bool SerializeObject(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable keys, IEnumerable values, StringBuilder builder, bool excludeNullValues)\r\n        {\r\n            builder.Append(\"{\");\r\n            IEnumerator ke = keys.GetEnumerator();\r\n            IEnumerator ve = values.GetEnumerator();\r\n            bool first = true;\r\n            while (ke.MoveNext() && ve.MoveNext())\r\n            {\r\n                object key = ke.Current;\r\n                object value = ve.Current;\r\n\r\n                if (value == null && excludeNullValues)\r\n                {\r\n                    continue;\r\n                }\r\n\r\n                if (!first)\r\n                    builder.Append(\",\");\r\n                string stringKey = key as string;\r\n                if (stringKey != null)\r\n                    SerializeString(jsonSerializerStrategy.MapDictionaryKeyToFieldName(stringKey), builder);\r\n                else\r\n                    if (!SerializeValue(jsonSerializerStrategy, value, builder, excludeNullValues)) return false;\r\n                builder.Append(\":\");\r\n                if (!SerializeValue(jsonSerializerStrategy, value, builder, excludeNullValues))\r\n                    return false;\r\n                first = false;\r\n            }\r\n            builder.Append(\"}\");\r\n            return true;\r\n        }\r\n\r\n        static bool SerializeArray(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable anArray, StringBuilder builder, bool excludeNullValues)\r\n        {\r\n            builder.Append(\"[\");\r\n            bool first = true;\r\n            foreach (object value in anArray)\r\n            {\r\n                if (!first)\r\n                    builder.Append(\",\");\r\n                if (!SerializeValue(jsonSerializerStrategy, value, builder, excludeNullValues))\r\n                    return false;\r\n                first = false;\r\n            }\r\n            builder.Append(\"]\");\r\n            return true;\r\n        }\r\n\r\n        static bool SerializeString(string aString, StringBuilder builder)\r\n        {\r\n            // Happy path if there's nothing to be escaped. IndexOfAny is highly optimized (and unmanaged)\r\n            if (aString.IndexOfAny(EscapeCharacters) == -1)\r\n            {\r\n                builder.Append('\"');\r\n                builder.Append(aString);\r\n                builder.Append('\"');\r\n\r\n                return true;\r\n            }\r\n\r\n            builder.Append('\"');\r\n            int safeCharacterCount = 0;\r\n            char[] charArray = aString.ToCharArray();\r\n\r\n            for (int i = 0; i < charArray.Length; i++)\r\n            {\r\n                char c = charArray[i];\r\n\r\n                // Non ascii characters are fine, buffer them up and send them to the builder\r\n                // in larger chunks if possible. The escape table is a 1:1 translation table\r\n                // with \\0 [default(char)] denoting a safe character.\r\n                if (c >= EscapeTable.Length || EscapeTable[c] == default(char))\r\n                {\r\n                    safeCharacterCount++;\r\n                }\r\n                else\r\n                {\r\n                    if (safeCharacterCount > 0)\r\n                    {\r\n                        builder.Append(charArray, i - safeCharacterCount, safeCharacterCount);\r\n                        safeCharacterCount = 0;\r\n                    }\r\n\r\n                    builder.Append('\\\\');\r\n                    builder.Append(EscapeTable[c]);\r\n                }\r\n            }\r\n\r\n            if (safeCharacterCount > 0)\r\n            {\r\n                builder.Append(charArray, charArray.Length - safeCharacterCount, safeCharacterCount);\r\n            }\r\n\r\n            builder.Append('\"');\r\n            return true;\r\n        }\r\n\r\n        static bool SerializeNumber(object number, StringBuilder builder)\r\n        {\r\n            if (number is long)\r\n                builder.Append(((long)number).ToString(CultureInfo.InvariantCulture));\r\n            else if (number is ulong)\r\n                builder.Append(((ulong)number).ToString(CultureInfo.InvariantCulture));\r\n            else if (number is int)\r\n                builder.Append(((int)number).ToString(CultureInfo.InvariantCulture));\r\n            else if (number is uint)\r\n                builder.Append(((uint)number).ToString(CultureInfo.InvariantCulture));\r\n            else if (number is decimal)\r\n                builder.Append(((decimal)number).ToString(CultureInfo.InvariantCulture));\r\n            else if (number is float)\r\n                builder.Append(((float)number).ToString(CultureInfo.InvariantCulture));\r\n            else\r\n                builder.Append(Convert.ToDouble(number, CultureInfo.InvariantCulture).ToString(\"r\", CultureInfo.InvariantCulture));\r\n            return true;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determines if a given object is numeric in any way\r\n        /// (can be integer, double, null, etc).\r\n        /// </summary>\r\n        static bool IsNumeric(object value)\r\n        {\r\n            if (value is sbyte) return true;\r\n            if (value is byte) return true;\r\n            if (value is short) return true;\r\n            if (value is ushort) return true;\r\n            if (value is int) return true;\r\n            if (value is uint) return true;\r\n            if (value is long) return true;\r\n            if (value is ulong) return true;\r\n            if (value is float) return true;\r\n            if (value is double) return true;\r\n            if (value is decimal) return true;\r\n            return false;\r\n        }\r\n\r\n        private static IJsonSerializerStrategy _currentJsonSerializerStrategy;\r\n        public static IJsonSerializerStrategy CurrentJsonSerializerStrategy\r\n        {\r\n            get\r\n            {\r\n                return _currentJsonSerializerStrategy ??\r\n                    (_currentJsonSerializerStrategy =\r\n#if SIMPLE_JSON_DATACONTRACT\r\n DataContractJsonSerializerStrategy\r\n#else\r\n                        PocoJsonSerializerStrategy\r\n#endif\r\n                        );\r\n            }\r\n            set\r\n            {\r\n                _currentJsonSerializerStrategy = value;\r\n            }\r\n        }\r\n\r\n        private static PocoJsonSerializerStrategy _pocoJsonSerializerStrategy;\r\n        [EditorBrowsable(EditorBrowsableState.Advanced)]\r\n        public static PocoJsonSerializerStrategy PocoJsonSerializerStrategy\r\n        {\r\n            get\r\n            {\r\n                return _pocoJsonSerializerStrategy ?? (_pocoJsonSerializerStrategy = new PocoJsonSerializerStrategy());\r\n            }\r\n        }\r\n\r\n#if SIMPLE_JSON_DATACONTRACT\r\n\r\n        private static DataContractJsonSerializerStrategy _dataContractJsonSerializerStrategy;\r\n        [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Advanced)]\r\n        public static DataContractJsonSerializerStrategy DataContractJsonSerializerStrategy\r\n        {\r\n            get\r\n            {\r\n                return _dataContractJsonSerializerStrategy ?? (_dataContractJsonSerializerStrategy = new DataContractJsonSerializerStrategy());\r\n            }\r\n        }\r\n\r\n#endif\r\n    }\r\n\r\n    [GeneratedCode(\"simple-json\", \"1.0.0\")]\r\n#if SIMPLE_JSON_INTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n        interface IJsonSerializerStrategy\r\n    {\r\n        [SuppressMessage(\"Microsoft.Design\", \"CA1007:UseGenericsWhereAppropriate\", Justification=\"Need to support .NET 2\")]\r\n        bool TrySerializeNonPrimitiveObject(object input, out object output);\r\n        object DeserializeObject(object value, Type type, DateTimeStyles dateTimeStyles);\r\n\r\n        string MapDictionaryKeyToFieldName(string stringKey);\r\n    }\r\n\r\n#if SIMPLE_JSON_INTERNAL\r\n    internal\r\n#else\r\n\r\n    public\r\n#endif\r\n        class NamedConstructorArgs\r\n    {\r\n        public Type Type { get; private set; }\r\n\r\n        public string[] ParameterNames { get; private set; }\r\n\r\n        public NamedConstructorArgs(Type type, string[] parameterNames)\r\n        {\r\n            this.Type = type;\r\n            this.ParameterNames = parameterNames;\r\n        }\r\n    }\r\n\r\n    [GeneratedCode(\"simple-json\", \"1.0.0\")]\r\n#if SIMPLE_JSON_INTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n        class PocoJsonSerializerStrategy : IJsonSerializerStrategy\r\n    {\r\n        internal static IDictionary<Type, ReflectionUtils.ConstructorDelegate> DefaultConstructorCache;\r\n        internal static IDictionary<NamedConstructorArgs, ReflectionUtils.ConstructorDelegate> TypedConstructorCache;\r\n\r\n        internal static IDictionary<Type, IDictionary<string, ReflectionUtils.GetDelegate>> GetCache;\r\n        internal static IDictionary<Type, IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>> SetCache;\r\n        internal static IDictionary<NamedConstructorArgs, IDictionary<string, Type>> ParameterTypeCache;\r\n\r\n        internal static readonly Type[] EmptyTypes = ArrayCache.Empty<Type>();\r\n        internal static readonly Type[] ArrayConstructorParameterTypes = new Type[] { typeof(int) };\r\n        protected static string FullDateTimeWithOffset = @\"yyyy-MM-dd\\THH:mm:ss.fffffffzzz\";\r\n        protected static string FullDateTimeUtc = @\"yyyy-MM-dd\\THH:mm:ss.fffffff\\Z\";\r\n\r\n        private static readonly string[] Iso8601Format = new string[]\r\n        {\r\n            FullDateTimeWithOffset,\r\n            @\"yyyy-MM-dd\\THH:mm:ss.FFFFFFFK\",\r\n            FullDateTimeUtc,\r\n            @\"yyyy-MM-dd\\THH:mm:ss\\Z\",\r\n            @\"yyyy-MM-dd\\THH:mm:ssK\"\r\n        };\r\n\r\n\r\n        static PocoJsonSerializerStrategy()\r\n        {\r\n            DefaultConstructorCache = new ReflectionUtils.ThreadSafeDictionary<Type, ReflectionUtils.ConstructorDelegate>(ContructorDelegateFactory);\r\n            TypedConstructorCache = new ReflectionUtils.ThreadSafeDictionary<NamedConstructorArgs, ReflectionUtils.ConstructorDelegate>(ContructorDelegateFactory);\r\n            GetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<string, ReflectionUtils.GetDelegate>>(GetterValueFactory);\r\n            SetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>>(SetterValueFactory);\r\n            ParameterTypeCache = new ReflectionUtils.ThreadSafeDictionary<NamedConstructorArgs, IDictionary<string, Type>>(ParameterTypeFactory);\r\n        }\r\n\r\n        public string MapDictionaryKeyToFieldName(string stringKey)\r\n        {\r\n            return this.MapClrMemberNameToJsonFieldName(stringKey);\r\n        }\r\n\r\n        protected virtual string MapClrMemberNameToJsonFieldName(string clrPropertyName)\r\n        {\r\n            return clrPropertyName;\r\n        }\r\n\r\n        internal static ReflectionUtils.ConstructorDelegate ContructorDelegateFactory(Type key)\r\n        {\r\n            return ReflectionUtils.GetConstructor(key, key.IsArray ? ArrayConstructorParameterTypes : EmptyTypes);\r\n        }\r\n\r\n        internal static ReflectionUtils.ConstructorDelegate ContructorDelegateFactory(NamedConstructorArgs constructorArgs)\r\n        {\r\n            return ReflectionUtils.GetNamedConstructor(constructorArgs.Type, constructorArgs.ParameterNames);\r\n        }\r\n\r\n        internal static IDictionary<string, ReflectionUtils.GetDelegate> GetterValueFactory(Type type)\r\n        {\r\n            IDictionary<string, ReflectionUtils.GetDelegate> result = new Dictionary<string, ReflectionUtils.GetDelegate>();\r\n            foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type))\r\n            {\r\n                if (propertyInfo.CanRead && !Nancy.Helpers.ReflectionUtils.IsIndexedProperty(propertyInfo))\r\n                {\r\n                    MethodInfo getMethod = ReflectionUtils.GetGetterMethodInfo(propertyInfo);\r\n                    if (getMethod.IsStatic || !getMethod.IsPublic)\r\n                        continue;\r\n                    result[propertyInfo.Name] = ReflectionUtils.GetGetMethod(propertyInfo);\r\n                }\r\n            }\r\n            foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type))\r\n            {\r\n                if (fieldInfo.IsStatic || !fieldInfo.IsPublic)\r\n                    continue;\r\n                result[fieldInfo.Name] = ReflectionUtils.GetGetMethod(fieldInfo);\r\n            }\r\n            return result;\r\n        }\r\n\r\n        internal static IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> SetterValueFactory(Type type)\r\n        {\r\n            IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> result = new Dictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>();\r\n            foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type))\r\n            {\r\n                if (propertyInfo.CanWrite && !Nancy.Helpers.ReflectionUtils.IsIndexedProperty(propertyInfo))\r\n                {\r\n                    MethodInfo setMethod = ReflectionUtils.GetSetterMethodInfo(propertyInfo);\r\n                    if (setMethod.IsStatic || !setMethod.IsPublic)\r\n                        continue;\r\n                    result[propertyInfo.Name] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(\r\n                        propertyInfo.PropertyType, ReflectionUtils.GetSetMethod(propertyInfo));\r\n                }\r\n            }\r\n\r\n            foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type))\r\n            {\r\n                if (fieldInfo.IsInitOnly || fieldInfo.IsStatic || !fieldInfo.IsPublic)\r\n                    continue;\r\n                result[fieldInfo.Name] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(fieldInfo.FieldType, ReflectionUtils.GetSetMethod(fieldInfo));\r\n            }\r\n\r\n            return result;\r\n        }\r\n\r\n\r\n        internal static IDictionary<string, Type> ParameterTypeFactory(NamedConstructorArgs constructor)\r\n        {\r\n            IDictionary<string, Type> result = new Dictionary<string, Type>();\r\n            foreach (ParameterInfo paramterInfo in ReflectionUtils\r\n                .GetNamedConstructorInfo(constructor.Type, constructor.ParameterNames)\r\n                .GetParameters())\r\n            {\r\n                result[paramterInfo.Name] = paramterInfo.ParameterType;\r\n            }\r\n\r\n            return result;\r\n        }\r\n\r\n        public virtual bool TrySerializeNonPrimitiveObject(object input, out object output)\r\n        {\r\n            return this.TrySerializeKnownTypes(input, out output) || this.TrySerializeUnknownTypes(input, out output);\r\n        }\r\n\r\n        [SuppressMessage(\"Microsoft.Maintainability\", \"CA1502:AvoidExcessiveComplexity\")]\r\n        public virtual object DeserializeObject(object value, Type type, DateTimeStyles dateTimeStyles)\r\n        {\r\n            if (type == null) throw new ArgumentNullException(\"type\");\r\n            string str = value as string;\r\n\r\n            if (type == typeof (Guid) && string.IsNullOrEmpty(str))\r\n                return default(Guid);\r\n\r\n            if (value == null)\r\n                return null;\r\n\r\n            object obj = null;\r\n\r\n            if (str != null)\r\n            {\r\n                if (str.Length != 0) // We know it can't be null now.\r\n                {\r\n                    if (type == typeof(DateTime) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(DateTime)))\r\n                        return DateTime.ParseExact(str, Iso8601Format, CultureInfo.InvariantCulture, dateTimeStyles);\r\n                    if (type == typeof(DateTimeOffset) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(DateTimeOffset)))\r\n                        return DateTimeOffset.ParseExact(str, Iso8601Format, CultureInfo.InvariantCulture, dateTimeStyles);\r\n                    if (type == typeof(Guid) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid)))\r\n                        return new Guid(str);\r\n                    if (type == typeof(Uri))\r\n                    {\r\n                        bool isValid =  Uri.IsWellFormedUriString(str, UriKind.RelativeOrAbsolute);\r\n\r\n                        Uri result;\r\n                        if (isValid && Uri.TryCreate(str, UriKind.RelativeOrAbsolute, out result))\r\n                            return result;\r\n\r\n                        return null;\r\n                    }\r\n\r\n                    if (type == typeof(string))\r\n                        return str;\r\n\r\n                // allows assigning \"123\" to int?\r\n                if (ReflectionUtils.IsNullableType(type))\r\n                {\r\n                    return ReflectionUtils.ToNullableType(str, type);\r\n                }\r\n\r\n                    return Convert.ChangeType(str, type, CultureInfo.InvariantCulture);\r\n                }\r\n                else\r\n                {\r\n                    if (type == typeof(Guid))\r\n                        obj = default(Guid);\r\n                    else if (ReflectionUtils.IsNullableType(type))\r\n                        obj = null;\r\n                    else\r\n                        obj = str;\r\n                }\r\n                // Empty string case\r\n                if (!ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid))\r\n                    return str;\r\n            }\r\n            else if (value is bool)\r\n                return value;\r\n\r\n            bool valueIsLong = value is long;\r\n            bool valueIsDouble = value is double;\r\n            if ((valueIsLong && type == typeof(long)) || (valueIsDouble && type == typeof(double)))\r\n                return value;\r\n            if ((valueIsDouble && type != typeof(double)) || (valueIsLong && type != typeof(long)))\r\n            {\r\n                obj = type == typeof(int) || type == typeof(uint) || type == typeof(long) || type == typeof(ulong) || type == typeof(double) || type == typeof(float) || type == typeof(bool) || type == typeof(decimal) || type == typeof(byte) || type == typeof(short) || type == (typeof(ushort))\r\n                    ? Convert.ChangeType(value, type, CultureInfo.InvariantCulture)\r\n                    : value;\r\n            }\r\n            else\r\n            {\r\n                IDictionary<string, object> objects = value as IDictionary<string, object>;\r\n                if (objects != null)\r\n                {\r\n                    IDictionary<string, object> jsonObject = objects;\r\n\r\n                    if (ReflectionUtils.IsTypeDictionary(type))\r\n                    {\r\n                        // if dictionary then\r\n                        Type[] types = ReflectionUtils.GetGenericTypeArguments(type);\r\n                        Type keyType = types[0];\r\n                        Type valueType = types[1];\r\n\r\n                        Type genericType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType);\r\n\r\n                        IDictionary dict = (IDictionary)DefaultConstructorCache[genericType]();\r\n\r\n                        foreach (KeyValuePair<string, object> kvp in jsonObject)\r\n                            dict.Add(kvp.Key, this.DeserializeObject(kvp.Value, valueType, dateTimeStyles));\r\n\r\n                        obj = dict;\r\n                    }\r\n                    else\r\n                    {\r\n                        if (type == typeof(object))\r\n                        {\r\n                            obj = value;\r\n                        }\r\n                        else\r\n                        {\r\n                            var constructor = DefaultConstructorCache[type];\r\n\r\n                            if (constructor != null)\r\n                            {\r\n                                obj = constructor();\r\n                                foreach (KeyValuePair<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> setter in\r\n                                    SetCache[type])\r\n                                {\r\n                                    object jsonValue;\r\n                                    if (jsonObject.TryGetValue(setter.Key, out jsonValue))\r\n                                    {\r\n                                        jsonValue = this.DeserializeObject(jsonValue, setter.Value.Key, dateTimeStyles);\r\n                                        setter.Value.Value(obj, jsonValue);\r\n                                    }\r\n                                }\r\n                            }\r\n                            else\r\n                            {\r\n                                var args = new NamedConstructorArgs(type, jsonObject.Keys.ToArray());\r\n                                constructor = TypedConstructorCache[args];\r\n\r\n                                if (constructor == null)\r\n                                {\r\n                                    throw new ValidConstructorNotFoundException(type);\r\n                                }\r\n\r\n                                var arguments = new object[jsonObject.Count];\r\n\r\n                                var index = 0;\r\n                                foreach (KeyValuePair<string, Type> parameterType in ParameterTypeCache[args])\r\n                                {\r\n                                    object jsonValue;\r\n                                    if (jsonObject.TryGetValue(parameterType.Key, out jsonValue))\r\n                                    {\r\n                                        jsonValue = this.DeserializeObject(jsonValue, parameterType.Value, dateTimeStyles);\r\n                                        arguments[index] = jsonValue;\r\n                                        index++;\r\n                                    }\r\n                                }\r\n\r\n                                obj = constructor(arguments);\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    IList<object> valueAsList = value as IList<object>;\r\n                    if (valueAsList != null)\r\n                    {\r\n                        IList<object> jsonObject = valueAsList;\r\n                        IList list = null;\r\n\r\n                        if (type.IsArray)\r\n                        {\r\n                            list = (IList)DefaultConstructorCache[type](jsonObject.Count);\r\n                            int i = 0;\r\n                            foreach (object o in jsonObject)\r\n                                list[i++] = this.DeserializeObject(o, type.GetElementType(), dateTimeStyles);\r\n                        }\r\n                        else if (ReflectionUtils.IsTypeGenericeCollectionInterface(type) || ReflectionUtils.IsAssignableFrom(typeof(IList), type))\r\n                        {\r\n                            Type innerType = ReflectionUtils.GetGenericListElementType(type);\r\n                            list = (IList)(DefaultConstructorCache[type] ?? DefaultConstructorCache[typeof(List<>).MakeGenericType(innerType)])(jsonObject.Count);\r\n                            foreach (object o in jsonObject)\r\n                                list.Add(this.DeserializeObject(o, innerType, dateTimeStyles));\r\n                        }\r\n                        obj = list;\r\n                    }\r\n                }\r\n                return obj;\r\n            }\r\n            if (ReflectionUtils.IsNullableType(type))\r\n                return ReflectionUtils.ToNullableType(obj, type);\r\n            return obj;\r\n        }\r\n\r\n        protected virtual object SerializeEnum(Enum p)\r\n        {\r\n            return Convert.ToDouble(p, CultureInfo.InvariantCulture);\r\n        }\r\n\r\n        [SuppressMessage(\"Microsoft.Design\", \"CA1007:UseGenericsWhereAppropriate\", Justification=\"Need to support .NET 2\")]\r\n        protected virtual bool TrySerializeKnownTypes(object input, out object output)\r\n        {\r\n            bool returnValue = true;\r\n            if (input is DateTime)\r\n                output = ((DateTime)input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture);\r\n            else if (input is DateTimeOffset)\r\n                output = ((DateTimeOffset)input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture);\r\n            else if (input is Guid)\r\n                output = ((Guid)input).ToString(\"D\");\r\n            else if (input is Uri)\r\n                output = input.ToString();\r\n            else\r\n            {\r\n                Enum inputEnum = input as Enum;\r\n                if (inputEnum != null)\r\n                    output = this.SerializeEnum(inputEnum);\r\n                else\r\n                {\r\n                    returnValue = false;\r\n                    output = null;\r\n                }\r\n            }\r\n            return returnValue;\r\n        }\r\n        [SuppressMessage(\"Microsoft.Design\", \"CA1007:UseGenericsWhereAppropriate\", Justification=\"Need to support .NET 2\")]\r\n        protected virtual bool TrySerializeUnknownTypes(object input, out object output)\r\n        {\r\n            if (input == null) throw new ArgumentNullException(\"input\");\r\n            output = null;\r\n            Type type = input.GetType();\r\n            if (type.FullName == null)\r\n                return false;\r\n            IDictionary<string, object> obj = new JsonObject();\r\n            IDictionary<string, ReflectionUtils.GetDelegate> getters = GetCache[type];\r\n            foreach (KeyValuePair<string, ReflectionUtils.GetDelegate> getter in getters)\r\n            {\r\n                if (getter.Value != null)\r\n                    obj.Add(this.MapClrMemberNameToJsonFieldName(getter.Key), getter.Value(input));\r\n            }\r\n            output = obj;\r\n            return true;\r\n        }\r\n    }\r\n\r\n#if SIMPLE_JSON_DATACONTRACT\r\n    [GeneratedCode(\"simple-json\", \"1.0.0\")]\r\n#if SIMPLE_JSON_INTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n class DataContractJsonSerializerStrategy : PocoJsonSerializerStrategy\r\n    {\r\n        public DataContractJsonSerializerStrategy()\r\n        {\r\n            GetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<string, ReflectionUtils.GetDelegate>>(GetterValueFactory);\r\n            SetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>>(SetterValueFactory);\r\n        }\r\n\r\n        internal override IDictionary<string, ReflectionUtils.GetDelegate> GetterValueFactory(Type type)\r\n        {\r\n            bool hasDataContract = ReflectionUtils.GetAttribute(type, typeof(DataContractAttribute)) != null;\r\n            if (!hasDataContract)\r\n                return base.GetterValueFactory(type);\r\n            string jsonKey;\r\n            IDictionary<string, ReflectionUtils.GetDelegate> result = new Dictionary<string, ReflectionUtils.GetDelegate>();\r\n            foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type))\r\n            {\r\n                if (propertyInfo.CanRead)\r\n                {\r\n                    MethodInfo getMethod = ReflectionUtils.GetGetterMethodInfo(propertyInfo);\r\n                    if (!getMethod.IsStatic && CanAdd(propertyInfo, out jsonKey))\r\n                        result[jsonKey] = ReflectionUtils.GetGetMethod(propertyInfo);\r\n                }\r\n            }\r\n            foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type))\r\n            {\r\n                if (!fieldInfo.IsStatic && CanAdd(fieldInfo, out jsonKey))\r\n                    result[jsonKey] = ReflectionUtils.GetGetMethod(fieldInfo);\r\n            }\r\n            return result;\r\n        }\r\n\r\n        internal override IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> SetterValueFactory(Type type)\r\n        {\r\n            bool hasDataContract = ReflectionUtils.GetAttribute(type, typeof(DataContractAttribute)) != null;\r\n            if (!hasDataContract)\r\n                return base.SetterValueFactory(type);\r\n            string jsonKey;\r\n            IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> result = new Dictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>();\r\n            foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type))\r\n            {\r\n                if (propertyInfo.CanWrite)\r\n                {\r\n                    MethodInfo setMethod = ReflectionUtils.GetSetterMethodInfo(propertyInfo);\r\n                    if (!setMethod.IsStatic && CanAdd(propertyInfo, out jsonKey))\r\n                        result[jsonKey] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(propertyInfo.PropertyType, ReflectionUtils.GetSetMethod(propertyInfo));\r\n                }\r\n            }\r\n            foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type))\r\n            {\r\n                if (!fieldInfo.IsInitOnly && !fieldInfo.IsStatic && CanAdd(fieldInfo, out jsonKey))\r\n                    result[jsonKey] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(fieldInfo.FieldType, ReflectionUtils.GetSetMethod(fieldInfo));\r\n            }\r\n            // todo implement sorting for DATACONTRACT.\r\n            return result;\r\n        }\r\n\r\n        private static bool CanAdd(MemberInfo info, out string jsonKey)\r\n        {\r\n            jsonKey = null;\r\n            if (ReflectionUtils.GetAttribute(info, typeof(IgnoreDataMemberAttribute)) != null)\r\n                return false;\r\n            DataMemberAttribute dataMemberAttribute = (DataMemberAttribute)ReflectionUtils.GetAttribute(info, typeof(DataMemberAttribute));\r\n            if (dataMemberAttribute == null)\r\n                return false;\r\n            jsonKey = string.IsNullOrEmpty(dataMemberAttribute.Name) ? info.Name : dataMemberAttribute.Name;\r\n            return true;\r\n        }\r\n    }\r\n\r\n#endif\r\n\r\n    internal class ValidConstructorNotFoundException : Exception\r\n    {\r\n        public ValidConstructorNotFoundException(Type type) : base(string.Format(\"No valid constructor could be found for {0}\", type.FullName))\r\n        {\r\n        }\r\n    }\r\n\r\n    // This class is meant to be copied into other libraries. So we want to exclude it from Code Analysis rules\r\n    // that might be in place in the target project.\r\n    [GeneratedCode(\"reflection-utils\", \"1.0.0\")]\r\n#if SIMPLE_JSON_REFLECTION_UTILS_PUBLIC\r\n        public\r\n#else\r\n    internal\r\n#endif\r\n        class ReflectionUtils\r\n    {\r\n        private static readonly object[] EmptyObjects = new object[] { };\r\n\r\n        public delegate object GetDelegate(object source);\r\n        public delegate void SetDelegate(object source, object value);\r\n        public delegate object ConstructorDelegate(params object[] args);\r\n\r\n        public delegate TValue ThreadSafeDictionaryValueFactory<TKey, TValue>(TKey key);\r\n\r\n#if SIMPLE_JSON_TYPEINFO\r\n            public static TypeInfo GetTypeInfo(Type type)\r\n            {\r\n                return type.GetTypeInfo();\r\n            }\r\n#else\r\n        public static Type GetTypeInfo(Type type)\r\n        {\r\n            return type;\r\n        }\r\n#endif\r\n\r\n        public static Attribute GetAttribute(MemberInfo info, Type type)\r\n        {\r\n#if SIMPLE_JSON_TYPEINFO\r\n                if (info == null || type == null || !info.IsDefined(type))\r\n                    return null;\r\n                return info.GetCustomAttribute(type);\r\n#else\r\n            if (info == null || type == null || !Attribute.IsDefined(info, type))\r\n                return null;\r\n            return Attribute.GetCustomAttribute(info, type);\r\n#endif\r\n        }\r\n\r\n        public static Type GetGenericListElementType(Type type)\r\n        {\r\n            IEnumerable<Type> interfaces;\r\n#if SIMPLE_JSON_TYPEINFO\r\n                interfaces = type.GetTypeInfo().ImplementedInterfaces;\r\n#else\r\n            interfaces = type.GetInterfaces();\r\n#endif\r\n            foreach (Type implementedInterface in interfaces)\r\n            {\r\n                if (IsTypeGeneric(implementedInterface) &&\r\n                    implementedInterface.GetGenericTypeDefinition() == typeof (IList<>))\r\n                {\r\n                    return GetGenericTypeArguments(implementedInterface)[0];\r\n                }\r\n            }\r\n            return GetGenericTypeArguments(type)[0];\r\n        }\r\n\r\n        public static Attribute GetAttribute(Type objectType, Type attributeType)\r\n        {\r\n\r\n#if SIMPLE_JSON_TYPEINFO\r\n                if (objectType == null || attributeType == null || !objectType.GetTypeInfo().IsDefined(attributeType))\r\n                    return null;\r\n                return objectType.GetTypeInfo().GetCustomAttribute(attributeType);\r\n#else\r\n            if (objectType == null || attributeType == null || !Attribute.IsDefined(objectType, attributeType))\r\n                return null;\r\n            return Attribute.GetCustomAttribute(objectType, attributeType);\r\n#endif\r\n        }\r\n\r\n        public static Type[] GetGenericTypeArguments(Type type)\r\n        {\r\n#if SIMPLE_JSON_TYPEINFO\r\n                return type.GetTypeInfo().GenericTypeArguments;\r\n#else\r\n            return type.GetGenericArguments();\r\n#endif\r\n        }\r\n\r\n        public static bool IsTypeGeneric(Type type)\r\n        {\r\n            return GetTypeInfo(type).IsGenericType;\r\n        }\r\n\r\n        public static bool IsTypeGenericeCollectionInterface(Type type)\r\n        {\r\n            if (!IsTypeGeneric(type))\r\n                return false;\r\n\r\n            Type genericDefinition = type.GetGenericTypeDefinition();\r\n\r\n            return (genericDefinition == typeof(IList<>)\r\n                || genericDefinition == typeof(ICollection<>)\r\n                || genericDefinition == typeof(IEnumerable<>)\r\n#if SIMPLE_JSON_READONLY_COLLECTIONS\r\n                    || genericDefinition == typeof(IReadOnlyCollection<>)\r\n                    || genericDefinition == typeof(IReadOnlyList<>)\r\n#endif\r\n                );\r\n        }\r\n\r\n        public static bool IsAssignableFrom(Type type1, Type type2)\r\n        {\r\n            return GetTypeInfo(type1).IsAssignableFrom(GetTypeInfo(type2));\r\n        }\r\n\r\n        public static bool IsTypeDictionary(Type type)\r\n        {\r\n#if SIMPLE_JSON_TYPEINFO\r\n                if (typeof(IDictionary<,>).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()))\r\n                    return true;\r\n#else\r\n            if (typeof(System.Collections.IDictionary).IsAssignableFrom(type))\r\n                return true;\r\n#endif\r\n            if (!GetTypeInfo(type).IsGenericType)\r\n                return false;\r\n\r\n            Type genericDefinition = type.GetGenericTypeDefinition();\r\n            return genericDefinition == typeof(IDictionary<,>);\r\n        }\r\n\r\n        public static bool IsNullableType(Type type)\r\n        {\r\n            return GetTypeInfo(type).IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);\r\n        }\r\n\r\n        public static object ToNullableType(object obj, Type nullableType)\r\n        {\r\n            return obj == null ? null : Convert.ChangeType(obj, Nullable.GetUnderlyingType(nullableType), CultureInfo.InvariantCulture);\r\n        }\r\n\r\n        public static bool IsValueType(Type type)\r\n        {\r\n            return GetTypeInfo(type).IsValueType;\r\n        }\r\n\r\n        public static IEnumerable<ConstructorInfo> GetConstructors(Type type)\r\n        {\r\n#if SIMPLE_JSON_TYPEINFO\r\n                return type.GetTypeInfo().DeclaredConstructors;\r\n#else\r\n            return type.GetConstructors();\r\n#endif\r\n        }\r\n\r\n        public static ConstructorInfo GetConstructorInfo(Type type, params Type[] argsType)\r\n        {\r\n             IEnumerable<ConstructorInfo> constructorInfos = GetConstructors(type);\r\n             int i;\r\n             bool matches;\r\n             foreach (ConstructorInfo constructorInfo in constructorInfos)\r\n             {\r\n                 ParameterInfo[] parameters = constructorInfo.GetParameters();\r\n                 if (argsType.Length != parameters.Length)\r\n                     continue;\r\n\r\n                 i = 0;\r\n                 matches = true;\r\n                 foreach (ParameterInfo parameterInfo in constructorInfo.GetParameters())\r\n                 {\r\n                     if (parameterInfo.ParameterType != argsType[i])\r\n                     {\r\n                         matches = false;\r\n                         break;\r\n                     }\r\n                 }\r\n\r\n                 if (matches)\r\n                     return constructorInfo;\r\n             }\r\n\r\n             return null;\r\n        }\r\n\r\n        public static ConstructorInfo GetNamedConstructorInfo(Type type, params string[] parameterNames)\r\n        {\r\n            IEnumerable<ConstructorInfo> constructorInfos = GetConstructors(type);\r\n            foreach (ConstructorInfo constructorInfo in constructorInfos)\r\n            {\r\n                ParameterInfo[] parameters = constructorInfo.GetParameters();\r\n                if (parameterNames.Length != parameters.Length)\r\n                    continue;\r\n\r\n                var i = 0;\r\n                var matches = true;\r\n                foreach (ParameterInfo parameterInfo in constructorInfo.GetParameters())\r\n                {\r\n                    if (!string.Equals(parameterInfo.Name, parameterNames[i], StringComparison.OrdinalIgnoreCase))\r\n                    {\r\n                        matches = false;\r\n                        break;\r\n                    }\r\n                    i++;\r\n                }\r\n\r\n                if (matches)\r\n                    return constructorInfo;\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        public static IEnumerable<PropertyInfo> GetProperties(Type type)\r\n        {\r\n#if SIMPLE_JSON_TYPEINFO\r\n                return type.GetRuntimeProperties();\r\n#else\r\n            return type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);\r\n#endif\r\n        }\r\n\r\n        public static IEnumerable<FieldInfo> GetFields(Type type)\r\n        {\r\n#if SIMPLE_JSON_TYPEINFO\r\n                return type.GetRuntimeFields();\r\n#else\r\n            return type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);\r\n#endif\r\n        }\r\n\r\n        public static MethodInfo GetGetterMethodInfo(PropertyInfo propertyInfo)\r\n        {\r\n#if SIMPLE_JSON_TYPEINFO\r\n                return propertyInfo.GetMethod;\r\n#else\r\n            return propertyInfo.GetGetMethod(true);\r\n#endif\r\n        }\r\n\r\n        public static MethodInfo GetSetterMethodInfo(PropertyInfo propertyInfo)\r\n        {\r\n#if SIMPLE_JSON_TYPEINFO\r\n                return propertyInfo.SetMethod;\r\n#else\r\n            return propertyInfo.GetSetMethod(true);\r\n#endif\r\n        }\r\n\r\n        public static ConstructorDelegate GetConstructor(ConstructorInfo constructorInfo)\r\n        {\r\n#if SIMPLE_JSON_NO_LINQ_EXPRESSION\r\n                return GetConstructorByReflection(constructorInfo);\r\n#else\r\n            return GetConstructorByExpression(constructorInfo);\r\n#endif\r\n        }\r\n\r\n        public static ConstructorDelegate GetConstructor(Type type, params Type[] argsType)\r\n                 {\r\n         #if SIMPLE_JSON_NO_LINQ_EXPRESSION\r\n                         return GetConstructorByReflection(type, argsType);\r\n         #else\r\n                     return GetConstructorByExpression(type, argsType);\r\n         #endif\r\n                 }\r\n\r\n        public static ConstructorDelegate GetNamedConstructor(Type type, params string[] parameterNames)\r\n        {\r\n#if SIMPLE_JSON_NO_LINQ_EXPRESSION\r\n                         return GetNamedConstructorByReflection(type, parameterNames);\r\n         #else\r\n            return GetNamedConstructorByExpression(type, parameterNames);\r\n#endif\r\n        }\r\n\r\n        public static ConstructorDelegate GetConstructorByReflection(ConstructorInfo constructorInfo)\r\n        {\r\n            return delegate(object[] args) { return constructorInfo.Invoke(args); };\r\n        }\r\n\r\n        public static ConstructorDelegate GetConstructorByReflection(Type type, params Type[] argsType)\r\n        {\r\n            ConstructorInfo constructorInfo = GetConstructorInfo(type, argsType);\r\n            return constructorInfo == null ? null : GetConstructorByReflection(constructorInfo);\r\n        }\r\n\r\n        public static ConstructorDelegate GetNamedConstructorByReflection(Type type, params string[] parameterNames)\r\n        {\r\n            ConstructorInfo constructorInfo = GetNamedConstructorInfo(type, parameterNames);\r\n            return constructorInfo == null ? null : GetConstructorByReflection(constructorInfo);\r\n        }\r\n\r\n#if !SIMPLE_JSON_NO_LINQ_EXPRESSION\r\n\r\n        public static ConstructorDelegate GetConstructorByExpression(ConstructorInfo constructorInfo)\r\n        {\r\n            ParameterInfo[] paramsInfo = constructorInfo.GetParameters();\r\n            ParameterExpression param = Expression.Parameter(typeof(object[]), \"args\");\r\n            Expression[] argsExp = new Expression[paramsInfo.Length];\r\n            for (int i = 0; i < paramsInfo.Length; i++)\r\n            {\r\n                Expression index = Expression.Constant(i);\r\n                Type paramType = paramsInfo[i].ParameterType;\r\n                Expression paramAccessorExp = Expression.ArrayIndex(param, index);\r\n                Expression paramCastExp = Expression.Convert(paramAccessorExp, paramType);\r\n                argsExp[i] = paramCastExp;\r\n            }\r\n            NewExpression newExp = Expression.New(constructorInfo, argsExp);\r\n            Expression<Func<object[], object>> lambda = Expression.Lambda<Func<object[], object>>(newExp, param);\r\n            Func<object[], object> compiledLambda = lambda.Compile();\r\n            return delegate(object[] args) { return compiledLambda(args); };\r\n        }\r\n\r\n        public static ConstructorDelegate GetConstructorByExpression(Type type, params Type[] argsType)\r\n        {\r\n            ConstructorInfo constructorInfo = GetConstructorInfo(type, argsType);\r\n            return constructorInfo == null ? null : GetConstructorByExpression(constructorInfo);\r\n        }\r\n\r\n        public static ConstructorDelegate GetNamedConstructorByExpression(Type type, params string[] parameterNames)\r\n        {\r\n            ConstructorInfo constructorInfo = GetNamedConstructorInfo(type, parameterNames);\r\n            return constructorInfo == null ? null : GetConstructorByExpression(constructorInfo);\r\n        }\r\n\r\n#endif\r\n\r\n        public static GetDelegate GetGetMethod(PropertyInfo propertyInfo)\r\n        {\r\n#if SIMPLE_JSON_NO_LINQ_EXPRESSION\r\n                return GetGetMethodByReflection(propertyInfo);\r\n#else\r\n            return GetGetMethodByExpression(propertyInfo);\r\n#endif\r\n        }\r\n\r\n        public static GetDelegate GetGetMethod(FieldInfo fieldInfo)\r\n        {\r\n#if SIMPLE_JSON_NO_LINQ_EXPRESSION\r\n                return GetGetMethodByReflection(fieldInfo);\r\n#else\r\n            return GetGetMethodByExpression(fieldInfo);\r\n#endif\r\n        }\r\n\r\n        public static GetDelegate GetGetMethodByReflection(PropertyInfo propertyInfo)\r\n        {\r\n            MethodInfo methodInfo = GetGetterMethodInfo(propertyInfo);\r\n            return delegate(object source) { return methodInfo.Invoke(source, EmptyObjects); };\r\n        }\r\n\r\n        public static GetDelegate GetGetMethodByReflection(FieldInfo fieldInfo)\r\n        {\r\n            return delegate(object source) { return fieldInfo.GetValue(source); };\r\n        }\r\n\r\n#if !SIMPLE_JSON_NO_LINQ_EXPRESSION\r\n\r\n        public static GetDelegate GetGetMethodByExpression(PropertyInfo propertyInfo)\r\n        {\r\n            MethodInfo getMethodInfo = GetGetterMethodInfo(propertyInfo);\r\n            ParameterExpression instance = Expression.Parameter(typeof(object), \"instance\");\r\n            UnaryExpression instanceCast = (!IsValueType(propertyInfo.DeclaringType)) ? Expression.TypeAs(instance, propertyInfo.DeclaringType) : Expression.Convert(instance, propertyInfo.DeclaringType);\r\n            Func<object, object> compiled = Expression.Lambda<Func<object, object>>(Expression.TypeAs(Expression.Call(instanceCast, getMethodInfo), typeof(object)), instance).Compile();\r\n            return delegate(object source) { return compiled(source); };\r\n        }\r\n\r\n        public static GetDelegate GetGetMethodByExpression(FieldInfo fieldInfo)\r\n        {\r\n            ParameterExpression instance = Expression.Parameter(typeof(object), \"instance\");\r\n            MemberExpression member = Expression.Field(Expression.Convert(instance, fieldInfo.DeclaringType), fieldInfo);\r\n            GetDelegate compiled = Expression.Lambda<GetDelegate>(Expression.Convert(member, typeof(object)), instance).Compile();\r\n            return delegate(object source) { return compiled(source); };\r\n        }\r\n\r\n#endif\r\n\r\n        public static SetDelegate GetSetMethod(PropertyInfo propertyInfo)\r\n        {\r\n#if SIMPLE_JSON_NO_LINQ_EXPRESSION\r\n                return GetSetMethodByReflection(propertyInfo);\r\n#else\r\n            return GetSetMethodByExpression(propertyInfo);\r\n#endif\r\n        }\r\n\r\n        public static SetDelegate GetSetMethod(FieldInfo fieldInfo)\r\n        {\r\n#if SIMPLE_JSON_NO_LINQ_EXPRESSION\r\n                return GetSetMethodByReflection(fieldInfo);\r\n#else\r\n            return GetSetMethodByExpression(fieldInfo);\r\n#endif\r\n        }\r\n\r\n        public static SetDelegate GetSetMethodByReflection(PropertyInfo propertyInfo)\r\n        {\r\n            MethodInfo methodInfo = GetSetterMethodInfo(propertyInfo);\r\n            return delegate(object source, object value) { methodInfo.Invoke(source, new object[] { value }); };\r\n        }\r\n\r\n        public static SetDelegate GetSetMethodByReflection(FieldInfo fieldInfo)\r\n        {\r\n            return delegate(object source, object value) { fieldInfo.SetValue(source, value); };\r\n        }\r\n\r\n#if !SIMPLE_JSON_NO_LINQ_EXPRESSION\r\n\r\n        public static SetDelegate GetSetMethodByExpression(PropertyInfo propertyInfo)\r\n        {\r\n            MethodInfo setMethodInfo = GetSetterMethodInfo(propertyInfo);\r\n            ParameterExpression instance = Expression.Parameter(typeof(object), \"instance\");\r\n            ParameterExpression value = Expression.Parameter(typeof(object), \"value\");\r\n            UnaryExpression instanceCast = (!IsValueType(propertyInfo.DeclaringType)) ? Expression.TypeAs(instance, propertyInfo.DeclaringType) : Expression.Convert(instance, propertyInfo.DeclaringType);\r\n            UnaryExpression valueCast = (!IsValueType(propertyInfo.PropertyType)) ? Expression.TypeAs(value, propertyInfo.PropertyType) : Expression.Convert(value, propertyInfo.PropertyType);\r\n            Action<object, object> compiled = Expression.Lambda<Action<object, object>>(Expression.Call(instanceCast, setMethodInfo, valueCast), new ParameterExpression[] { instance, value }).Compile();\r\n            return delegate(object source, object val) { compiled(source, val); };\r\n        }\r\n\r\n        public static SetDelegate GetSetMethodByExpression(FieldInfo fieldInfo)\r\n        {\r\n            ParameterExpression instance = Expression.Parameter(typeof(object), \"instance\");\r\n            ParameterExpression value = Expression.Parameter(typeof(object), \"value\");\r\n            Action<object, object> compiled = Expression.Lambda<Action<object, object>>(\r\n                Assign(Expression.Field(Expression.Convert(instance, fieldInfo.DeclaringType), fieldInfo), Expression.Convert(value, fieldInfo.FieldType)), instance, value).Compile();\r\n            return delegate(object source, object val) { compiled(source, val); };\r\n        }\r\n\r\n        public static BinaryExpression Assign(Expression left, Expression right)\r\n        {\r\n#if SIMPLE_JSON_TYPEINFO\r\n                return Expression.Assign(left, right);\r\n#else\r\n            MethodInfo assign = typeof(Assigner<>).MakeGenericType(left.Type).GetMethod(\"Assign\");\r\n            BinaryExpression assignExpr = Expression.Add(left, right, assign);\r\n            return assignExpr;\r\n#endif\r\n        }\r\n\r\n        private static class Assigner<T>\r\n        {\r\n            public static T Assign(ref T left, T right)\r\n            {\r\n                return (left = right);\r\n            }\r\n        }\r\n\r\n#endif\r\n\r\n        public sealed class ThreadSafeDictionary<TKey, TValue> : IDictionary<TKey, TValue>\r\n        {\r\n            private readonly object _lock = new object();\r\n            private readonly ThreadSafeDictionaryValueFactory<TKey, TValue> _valueFactory;\r\n            private Dictionary<TKey, TValue> _dictionary;\r\n\r\n            public ThreadSafeDictionary(ThreadSafeDictionaryValueFactory<TKey, TValue> valueFactory)\r\n            {\r\n                this._valueFactory = valueFactory;\r\n            }\r\n\r\n            private TValue Get(TKey key)\r\n            {\r\n                if (this._dictionary == null)\r\n                    return this.AddValue(key);\r\n                TValue value;\r\n                if (!this._dictionary.TryGetValue(key, out value))\r\n                    return this.AddValue(key);\r\n                return value;\r\n            }\r\n\r\n            private TValue AddValue(TKey key)\r\n            {\r\n                TValue value = this._valueFactory(key);\r\n                lock (this._lock)\r\n                {\r\n                    if (this._dictionary == null)\r\n                    {\r\n                        this._dictionary = new Dictionary<TKey, TValue>();\r\n                        this._dictionary[key] = value;\r\n                    }\r\n                    else\r\n                    {\r\n                        TValue val;\r\n                        if (this._dictionary.TryGetValue(key, out val))\r\n                            return val;\r\n                        Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>(this._dictionary);\r\n                        dict[key] = value;\r\n                        this._dictionary = dict;\r\n                    }\r\n                }\r\n                return value;\r\n            }\r\n\r\n            public void Add(TKey key, TValue value)\r\n            {\r\n                throw new NotImplementedException();\r\n            }\r\n\r\n            public bool ContainsKey(TKey key)\r\n            {\r\n                return this._dictionary.ContainsKey(key);\r\n            }\r\n\r\n            public ICollection<TKey> Keys\r\n            {\r\n                get { return this._dictionary.Keys; }\r\n            }\r\n\r\n            public bool Remove(TKey key)\r\n            {\r\n                throw new NotImplementedException();\r\n            }\r\n\r\n            public bool TryGetValue(TKey key, out TValue value)\r\n            {\r\n                value = this[key];\r\n                return true;\r\n            }\r\n\r\n            public ICollection<TValue> Values\r\n            {\r\n                get { return this._dictionary.Values; }\r\n            }\r\n\r\n            public TValue this[TKey key]\r\n            {\r\n                get { return this.Get(key); }\r\n                set { throw new NotImplementedException(); }\r\n            }\r\n\r\n            public void Add(KeyValuePair<TKey, TValue> item)\r\n            {\r\n                throw new NotImplementedException();\r\n            }\r\n\r\n            public void Clear()\r\n            {\r\n                throw new NotImplementedException();\r\n            }\r\n\r\n            public bool Contains(KeyValuePair<TKey, TValue> item)\r\n            {\r\n                throw new NotImplementedException();\r\n            }\r\n\r\n            public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)\r\n            {\r\n                throw new NotImplementedException();\r\n            }\r\n\r\n            public int Count\r\n            {\r\n                get { return this._dictionary.Count; }\r\n            }\r\n\r\n            public bool IsReadOnly\r\n            {\r\n                get { throw new NotImplementedException(); }\r\n            }\r\n\r\n            public bool Remove(KeyValuePair<TKey, TValue> item)\r\n            {\r\n                throw new NotImplementedException();\r\n            }\r\n\r\n            public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()\r\n            {\r\n                return this._dictionary.GetEnumerator();\r\n            }\r\n\r\n            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\r\n            {\r\n                return this._dictionary.GetEnumerator();\r\n            }\r\n        }\r\n\r\n    }\r\n\r\n    // ReSharper restore LoopCanBeConvertedToQuery\r\n    // ReSharper restore RedundantExplicitArrayCreation\r\n    // ReSharper restore SuggestUseVarKeywordEvident\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Json/SimpleJson.cs",
    "content": "//-----------------------------------------------------------------------\r\n// <copyright file=\"SimpleJson.cs\" company=\"The Outercurve Foundation\">\r\n//    Copyright (c) 2011, The Outercurve Foundation.\r\n//\r\n//    Licensed under the MIT License (the \"License\");\r\n//    you may not use this file except in compliance with the License.\r\n//    You may obtain a copy of the License at\r\n//      http://www.opensource.org/licenses/mit-license.php\r\n//\r\n//    Unless required by applicable law or agreed to in writing, software\r\n//    distributed under the License is distributed on an \"AS IS\" BASIS,\r\n//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n//    See the License for the specific language governing permissions and\r\n//    limitations under the License.\r\n// </copyright>\r\n// <author>Nathan Totten (ntotten.com), Jim Zimmerman (jimzimmerman.com) and Prabir Shrestha (prabir.me)</author>\r\n// <website>https://github.com/facebook-csharp-sdk/simple-json</website>\r\n//-----------------------------------------------------------------------\r\n\r\n// VERSION: 0.38.0\r\n\r\n// NOTE: uncomment the following line to make SimpleJson class internal.\r\n#define SIMPLE_JSON_INTERNAL\r\n\r\n// NOTE: uncomment the following line to make JsonArray and JsonObject class internal.\r\n#define SIMPLE_JSON_OBJARRAYINTERNAL\r\n\r\n// NOTE: uncomment the following line to enable dynamic support.\r\n#define SIMPLE_JSON_DYNAMIC\r\n\r\n// NOTE: uncomment the following line to enable DataContract support.\r\n//#define SIMPLE_JSON_DATACONTRACT\r\n\r\n// NOTE: uncomment the following line to enable IReadOnlyCollection<T> and IReadOnlyList<T> support.\r\n//#define SIMPLE_JSON_READONLY_COLLECTIONS\r\n\r\n// NOTE: uncomment the following line to disable linq expressions/compiled lambda (better performance) instead of method.invoke().\r\n// define if you are using .net framework <= 3.0 or < WP7.5\r\n//#define SIMPLE_JSON_NO_LINQ_EXPRESSION\r\n\r\n// NOTE: uncomment the following line if you are compiling under Window Metro style application/library.\r\n// usually already defined in properties\r\n//#define NETFX_CORE;\r\n\r\n// If you are targetting WinStore, WP8 and NET4.5+ PCL make sure to #define SIMPLE_JSON_TYPEINFO;\r\n\r\n// original json parsing code from http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html\r\n\r\n#if NETFX_CORE || NETSTANDARD1_6\r\n#define SIMPLE_JSON_TYPEINFO\r\n#endif\r\n\r\nusing System;\r\nusing System.CodeDom.Compiler;\r\nusing System.Collections;\r\nusing System.Collections.Generic;\r\n#if !SIMPLE_JSON_NO_LINQ_EXPRESSION\r\nusing System.Linq.Expressions;\r\n#endif\r\nusing System.ComponentModel;\r\nusing System.Diagnostics.CodeAnalysis;\r\n#if SIMPLE_JSON_DYNAMIC\r\nusing System.Dynamic;\r\n#endif\r\nusing System.Globalization;\r\nusing System.Reflection;\r\nusing System.Runtime.Serialization;\r\nusing System.Text;\r\nusing Nancy.Reflection;\r\n\r\n// ReSharper disable LoopCanBeConvertedToQuery\r\n// ReSharper disable RedundantExplicitArrayCreation\r\n// ReSharper disable SuggestUseVarKeywordEvident\r\nnamespace Nancy\r\n{\r\n    /// <summary>\r\n    /// Represents the json array.\r\n    /// </summary>\r\n    [GeneratedCode(\"simple-json\", \"1.0.0\")]\r\n    [EditorBrowsable(EditorBrowsableState.Never)]\r\n    [SuppressMessage(\"Microsoft.Naming\", \"CA1710:IdentifiersShouldHaveCorrectSuffix\")]\r\n#if SIMPLE_JSON_OBJARRAYINTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n class JsonArray : List<object>\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"JsonArray\"/> class. \r\n        /// </summary>\r\n        public JsonArray() { }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"JsonArray\"/> class. \r\n        /// </summary>\r\n        /// <param name=\"capacity\">The capacity of the json array.</param>\r\n        public JsonArray(int capacity) : base(capacity) { }\r\n\r\n        /// <summary>\r\n        /// The json representation of the array.\r\n        /// </summary>\r\n        /// <returns>The json representation of the array.</returns>\r\n        public override string ToString()\r\n        {\r\n            return SimpleJson.SerializeObject(this) ?? string.Empty;\r\n        }\r\n    }\r\n\r\n    /// <summary>\r\n    /// Represents the json object.\r\n    /// </summary>\r\n    [GeneratedCode(\"simple-json\", \"1.0.0\")]\r\n    [EditorBrowsable(EditorBrowsableState.Never)]\r\n    [SuppressMessage(\"Microsoft.Naming\", \"CA1710:IdentifiersShouldHaveCorrectSuffix\")]\r\n#if SIMPLE_JSON_OBJARRAYINTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n class JsonObject :\r\n#if SIMPLE_JSON_DYNAMIC\r\n DynamicObject,\r\n#endif\r\n IDictionary<string, object>\r\n    {\r\n        /// <summary>\r\n        /// The internal member dictionary.\r\n        /// </summary>\r\n        private readonly Dictionary<string, object> _members;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of <see cref=\"JsonObject\"/>.\r\n        /// </summary>\r\n        public JsonObject()\r\n        {\r\n            _members = new Dictionary<string, object>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of <see cref=\"JsonObject\"/>.\r\n        /// </summary>\r\n        /// <param name=\"comparer\">The <see cref=\"T:System.Collections.Generic.IEqualityComparer`1\"/> implementation to use when comparing keys, or null to use the default <see cref=\"T:System.Collections.Generic.EqualityComparer`1\"/> for the type of the key.</param>\r\n        public JsonObject(IEqualityComparer<string> comparer)\r\n        {\r\n            _members = new Dictionary<string, object>(comparer);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"System.Object\"/> at the specified index.\r\n        /// </summary>\r\n        /// <value></value>\r\n        public object this[int index]\r\n        {\r\n            get { return GetAtIndex(_members, index); }\r\n        }\r\n\r\n        internal static object GetAtIndex(IDictionary<string, object> obj, int index)\r\n        {\r\n            if (obj == null)\r\n                throw new ArgumentNullException(\"obj\");\r\n            if (index >= obj.Count)\r\n                throw new ArgumentOutOfRangeException(\"index\");\r\n            int i = 0;\r\n            foreach (KeyValuePair<string, object> o in obj)\r\n                if (i++ == index) return o.Value;\r\n            return null;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds the specified key.\r\n        /// </summary>\r\n        /// <param name=\"key\">The key.</param>\r\n        /// <param name=\"value\">The value.</param>\r\n        public void Add(string key, object value)\r\n        {\r\n            _members.Add(key, value);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determines whether the specified key contains key.\r\n        /// </summary>\r\n        /// <param name=\"key\">The key.</param>\r\n        /// <returns>\r\n        ///     <c>true</c> if the specified key contains key; otherwise, <c>false</c>.\r\n        /// </returns>\r\n        public bool ContainsKey(string key)\r\n        {\r\n            return _members.ContainsKey(key);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the keys.\r\n        /// </summary>\r\n        /// <value>The keys.</value>\r\n        public ICollection<string> Keys\r\n        {\r\n            get { return _members.Keys; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Removes the specified key.\r\n        /// </summary>\r\n        /// <param name=\"key\">The key.</param>\r\n        /// <returns></returns>\r\n        public bool Remove(string key)\r\n        {\r\n            return _members.Remove(key);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tries the get value.\r\n        /// </summary>\r\n        /// <param name=\"key\">The key.</param>\r\n        /// <param name=\"value\">The value.</param>\r\n        /// <returns></returns>\r\n        public bool TryGetValue(string key, out object value)\r\n        {\r\n            return _members.TryGetValue(key, out value);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the values.\r\n        /// </summary>\r\n        /// <value>The values.</value>\r\n        public ICollection<object> Values\r\n        {\r\n            get { return _members.Values; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the <see cref=\"System.Object\"/> with the specified key.\r\n        /// </summary>\r\n        /// <value></value>\r\n        public object this[string key]\r\n        {\r\n            get { return _members[key]; }\r\n            set { _members[key] = value; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds the specified item.\r\n        /// </summary>\r\n        /// <param name=\"item\">The item.</param>\r\n        public void Add(KeyValuePair<string, object> item)\r\n        {\r\n            _members.Add(item.Key, item.Value);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Clears this instance.\r\n        /// </summary>\r\n        public void Clear()\r\n        {\r\n            _members.Clear();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determines whether [contains] [the specified item].\r\n        /// </summary>\r\n        /// <param name=\"item\">The item.</param>\r\n        /// <returns>\r\n        /// \t<c>true</c> if [contains] [the specified item]; otherwise, <c>false</c>.\r\n        /// </returns>\r\n        public bool Contains(KeyValuePair<string, object> item)\r\n        {\r\n            object value;\r\n            return _members.TryGetValue(item.Key, out value) && value == item.Value;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Copies to.\r\n        /// </summary>\r\n        /// <param name=\"array\">The array.</param>\r\n        /// <param name=\"arrayIndex\">Index of the array.</param>\r\n        public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)\r\n        {\r\n            if (array == null) throw new ArgumentNullException(\"array\");\r\n            int num = Count;\r\n            foreach (KeyValuePair<string, object> kvp in this)\r\n            {\r\n                array[arrayIndex++] = kvp;\r\n                if (--num <= 0)\r\n                    return;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the count.\r\n        /// </summary>\r\n        /// <value>The count.</value>\r\n        public int Count\r\n        {\r\n            get { return _members.Count; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether this instance is read only.\r\n        /// </summary>\r\n        /// <value>\r\n        /// \t<c>true</c> if this instance is read only; otherwise, <c>false</c>.\r\n        /// </value>\r\n        public bool IsReadOnly\r\n        {\r\n            get { return false; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Removes the specified item.\r\n        /// </summary>\r\n        /// <param name=\"item\">The item.</param>\r\n        /// <returns></returns>\r\n        public bool Remove(KeyValuePair<string, object> item)\r\n        {\r\n            return _members.Remove(item.Key);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the enumerator.\r\n        /// </summary>\r\n        /// <returns></returns>\r\n        public IEnumerator<KeyValuePair<string, object>> GetEnumerator()\r\n        {\r\n            return _members.GetEnumerator();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an enumerator that iterates through a collection.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// An <see cref=\"T:System.Collections.IEnumerator\"/> object that can be used to iterate through the collection.\r\n        /// </returns>\r\n        IEnumerator IEnumerable.GetEnumerator()\r\n        {\r\n            return _members.GetEnumerator();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns a json <see cref=\"T:System.String\"/> that represents the current <see cref=\"T:System.Object\"/>.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// A json <see cref=\"T:System.String\"/> that represents the current <see cref=\"T:System.Object\"/>.\r\n        /// </returns>\r\n        public override string ToString()\r\n        {\r\n            return SimpleJson.SerializeObject(this);\r\n        }\r\n\r\n#if SIMPLE_JSON_DYNAMIC\r\n        /// <summary>\r\n        /// Provides implementation for type conversion operations. Classes derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class can override this method to specify dynamic behavior for operations that convert an object from one type to another.\r\n        /// </summary>\r\n        /// <param name=\"binder\">Provides information about the conversion operation. The binder.Type property provides the type to which the object must be converted. For example, for the statement (String)sampleObject in C# (CType(sampleObject, Type) in Visual Basic), where sampleObject is an instance of the class derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class, binder.Type returns the <see cref=\"T:System.String\"/> type. The binder.Explicit property provides information about the kind of conversion that occurs. It returns true for explicit conversion and false for implicit conversion.</param>\r\n        /// <param name=\"result\">The result of the type conversion operation.</param>\r\n        /// <returns>\r\n        /// Alwasy returns true.\r\n        /// </returns>\r\n        public override bool TryConvert(ConvertBinder binder, out object result)\r\n        {\r\n            // <pex>\r\n            if (binder == null)\r\n                throw new ArgumentNullException(\"binder\");\r\n            // </pex>\r\n            Type targetType = binder.Type;\r\n\r\n            if ((targetType == typeof(IEnumerable)) ||\r\n                (targetType == typeof(IEnumerable<KeyValuePair<string, object>>)) ||\r\n                (targetType == typeof(IDictionary<string, object>)) ||\r\n                (targetType == typeof(IDictionary)))\r\n            {\r\n                result = this;\r\n                return true;\r\n            }\r\n\r\n            return base.TryConvert(binder, out result);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Provides the implementation for operations that delete an object member. This method is not intended for use in C# or Visual Basic.\r\n        /// </summary>\r\n        /// <param name=\"binder\">Provides information about the deletion.</param>\r\n        /// <returns>\r\n        /// Alwasy returns true.\r\n        /// </returns>\r\n        public override bool TryDeleteMember(DeleteMemberBinder binder)\r\n        {\r\n            // <pex>\r\n            if (binder == null)\r\n                throw new ArgumentNullException(\"binder\");\r\n            // </pex>\r\n            return _members.Remove(binder.Name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Provides the implementation for operations that get a value by index. Classes derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class can override this method to specify dynamic behavior for indexing operations.\r\n        /// </summary>\r\n        /// <param name=\"binder\">Provides information about the operation.</param>\r\n        /// <param name=\"indexes\">The indexes that are used in the operation. For example, for the sampleObject[3] operation in C# (sampleObject(3) in Visual Basic), where sampleObject is derived from the DynamicObject class, <paramref name=\"indexes\"/> is equal to 3.</param>\r\n        /// <param name=\"result\">The result of the index operation.</param>\r\n        /// <returns>\r\n        /// Alwasy returns true.\r\n        /// </returns>\r\n        public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)\r\n        {\r\n            if (indexes == null) throw new ArgumentNullException(\"indexes\");\r\n            if (indexes.Length == 1)\r\n            {\r\n                result = ((IDictionary<string, object>)this)[(string)indexes[0]];\r\n                return true;\r\n            }\r\n            result = null;\r\n            return true;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Provides the implementation for operations that get member values. Classes derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class can override this method to specify dynamic behavior for operations such as getting a value for a property.\r\n        /// </summary>\r\n        /// <param name=\"binder\">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member on which the dynamic operation is performed. For example, for the Console.WriteLine(sampleObject.SampleProperty) statement, where sampleObject is an instance of the class derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class, binder.Name returns \"SampleProperty\". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param>\r\n        /// <param name=\"result\">The result of the get operation. For example, if the method is called for a property, you can assign the property value to <paramref name=\"result\"/>.</param>\r\n        /// <returns>\r\n        /// Alwasy returns true.\r\n        /// </returns>\r\n        public override bool TryGetMember(GetMemberBinder binder, out object result)\r\n        {\r\n            object value;\r\n            if (_members.TryGetValue(binder.Name, out value))\r\n            {\r\n                result = value;\r\n                return true;\r\n            }\r\n            result = null;\r\n            return true;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Provides the implementation for operations that set a value by index. Classes derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class can override this method to specify dynamic behavior for operations that access objects by a specified index.\r\n        /// </summary>\r\n        /// <param name=\"binder\">Provides information about the operation.</param>\r\n        /// <param name=\"indexes\">The indexes that are used in the operation. For example, for the sampleObject[3] = 10 operation in C# (sampleObject(3) = 10 in Visual Basic), where sampleObject is derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class, <paramref name=\"indexes\"/> is equal to 3.</param>\r\n        /// <param name=\"value\">The value to set to the object that has the specified index. For example, for the sampleObject[3] = 10 operation in C# (sampleObject(3) = 10 in Visual Basic), where sampleObject is derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class, <paramref name=\"value\"/> is equal to 10.</param>\r\n        /// <returns>\r\n        /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.\r\n        /// </returns>\r\n        public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)\r\n        {\r\n            if (indexes == null) throw new ArgumentNullException(\"indexes\");\r\n            if (indexes.Length == 1)\r\n            {\r\n                ((IDictionary<string, object>)this)[(string)indexes[0]] = value;\r\n                return true;\r\n            }\r\n            return base.TrySetIndex(binder, indexes, value);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Provides the implementation for operations that set member values. Classes derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class can override this method to specify dynamic behavior for operations such as setting a value for a property.\r\n        /// </summary>\r\n        /// <param name=\"binder\">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member to which the value is being assigned. For example, for the statement sampleObject.SampleProperty = \"Test\", where sampleObject is an instance of the class derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class, binder.Name returns \"SampleProperty\". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param>\r\n        /// <param name=\"value\">The value to set to the member. For example, for sampleObject.SampleProperty = \"Test\", where sampleObject is an instance of the class derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class, the <paramref name=\"value\"/> is \"Test\".</param>\r\n        /// <returns>\r\n        /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.)\r\n        /// </returns>\r\n        public override bool TrySetMember(SetMemberBinder binder, object value)\r\n        {\r\n            // <pex>\r\n            if (binder == null)\r\n                throw new ArgumentNullException(\"binder\");\r\n            // </pex>\r\n            _members[binder.Name] = value;\r\n            return true;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns the enumeration of all dynamic member names.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// A sequence that contains dynamic member names.\r\n        /// </returns>\r\n        public override IEnumerable<string> GetDynamicMemberNames()\r\n        {\r\n            foreach (var key in Keys)\r\n                yield return key;\r\n        }\r\n#endif\r\n    }\r\n}\r\n\r\nnamespace Nancy\r\n{\r\n    /// <summary>\r\n    /// This class encodes and decodes JSON strings.\r\n    /// Spec. details, see http://www.json.org/\r\n    /// \r\n    /// JSON uses Arrays and Objects. These correspond here to the datatypes JsonArray(IList&lt;object>) and JsonObject(IDictionary&lt;string,object>).\r\n    /// All numbers are parsed to doubles.\r\n    /// </summary>\r\n    [GeneratedCode(\"simple-json\", \"1.0.0\")]\r\n#if SIMPLE_JSON_INTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n static class SimpleJson\r\n    {\r\n        private const int TOKEN_NONE = 0;\r\n        private const int TOKEN_CURLY_OPEN = 1;\r\n        private const int TOKEN_CURLY_CLOSE = 2;\r\n        private const int TOKEN_SQUARED_OPEN = 3;\r\n        private const int TOKEN_SQUARED_CLOSE = 4;\r\n        private const int TOKEN_COLON = 5;\r\n        private const int TOKEN_COMMA = 6;\r\n        private const int TOKEN_STRING = 7;\r\n        private const int TOKEN_NUMBER = 8;\r\n        private const int TOKEN_TRUE = 9;\r\n        private const int TOKEN_FALSE = 10;\r\n        private const int TOKEN_NULL = 11;\r\n        private const int BUILDER_CAPACITY = 2000;\r\n\r\n        private static readonly char[] EscapeTable;\r\n        private static readonly char[] EscapeCharacters = new char[] { '\"', '\\\\', '\\b', '\\f', '\\n', '\\r', '\\t' };\r\n        private static readonly string EscapeCharactersString = new string(EscapeCharacters);\r\n\r\n        static SimpleJson()\r\n        {\r\n            EscapeTable = new char[93];\r\n            EscapeTable['\"']  = '\"';\r\n            EscapeTable['\\\\'] = '\\\\';\r\n            EscapeTable['\\b'] = 'b';\r\n            EscapeTable['\\f'] = 'f';\r\n            EscapeTable['\\n'] = 'n';\r\n            EscapeTable['\\r'] = 'r';\r\n            EscapeTable['\\t'] = 't';\r\n        }\r\n\r\n        /// <summary>\r\n        /// Parses the string json into a value\r\n        /// </summary>\r\n        /// <param name=\"json\">A JSON string.</param>\r\n        /// <returns>An IList&lt;object>, a IDictionary&lt;string,object>, a double, a string, null, true, or false</returns>\r\n        public static object DeserializeObject(string json)\r\n        {\r\n            object obj;\r\n            if (TryDeserializeObject(json, out obj))\r\n                return obj;\r\n            throw new SerializationException(\"Invalid JSON string\");\r\n        }\r\n\r\n        /// <summary>\r\n        /// Try parsing the json string into a value.\r\n        /// </summary>\r\n        /// <param name=\"json\">\r\n        /// A JSON string.\r\n        /// </param>\r\n        /// <param name=\"obj\">\r\n        /// The object.\r\n        /// </param>\r\n        /// <returns>\r\n        /// Returns true if successfull otherwise false.\r\n        /// </returns>\r\n        [SuppressMessage(\"Microsoft.Design\", \"CA1007:UseGenericsWhereAppropriate\", Justification=\"Need to support .NET 2\")]\r\n        public static bool TryDeserializeObject(string json, out object obj)\r\n        {\r\n            bool success = true;\r\n            if (json != null)\r\n            {\r\n                char[] charArray = json.ToCharArray();\r\n                int index = 0;\r\n                obj = ParseValue(charArray, ref index, ref success);\r\n            }\r\n            else\r\n                obj = null;\r\n\r\n            return success;\r\n        }\r\n\r\n        public static object DeserializeObject(string json, Type type, IJsonSerializerStrategy jsonSerializerStrategy)\r\n        {\r\n            object jsonObject = DeserializeObject(json);\r\n            return type == null || jsonObject != null && ReflectionUtils.IsAssignableFrom(jsonObject.GetType(), type)\r\n                       ? jsonObject\r\n                       : (jsonSerializerStrategy ?? CurrentJsonSerializerStrategy).DeserializeObject(jsonObject, type);\r\n        }\r\n\r\n        public static object DeserializeObject(string json, Type type)\r\n        {\r\n            return DeserializeObject(json, type, null);\r\n        }\r\n\r\n        public static T DeserializeObject<T>(string json, IJsonSerializerStrategy jsonSerializerStrategy)\r\n        {\r\n            return (T)DeserializeObject(json, typeof(T), jsonSerializerStrategy);\r\n        }\r\n\r\n        public static T DeserializeObject<T>(string json)\r\n        {\r\n            return (T)DeserializeObject(json, typeof(T), null);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Converts a IDictionary&lt;string,object> / IList&lt;object> object into a JSON string\r\n        /// </summary>\r\n        /// <param name=\"json\">A IDictionary&lt;string,object> / IList&lt;object></param>\r\n        /// <param name=\"jsonSerializerStrategy\">Serializer strategy to use</param>\r\n        /// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>\r\n        public static string SerializeObject(object json, IJsonSerializerStrategy jsonSerializerStrategy)\r\n        {\r\n            StringBuilder builder = new StringBuilder(BUILDER_CAPACITY);\r\n            bool success = SerializeValue(jsonSerializerStrategy, json, builder);\r\n            return (success ? builder.ToString() : null);\r\n        }\r\n\r\n        public static string SerializeObject(object json)\r\n        {\r\n            return SerializeObject(json, CurrentJsonSerializerStrategy);\r\n        }\r\n\r\n        public static string EscapeToJavascriptString(string jsonString)\r\n        {\r\n            if (string.IsNullOrEmpty(jsonString))\r\n                return jsonString;\r\n\r\n            StringBuilder sb = new StringBuilder();\r\n            char c;\r\n\r\n            for (int i = 0; i < jsonString.Length; )\r\n            {\r\n                c = jsonString[i++];\r\n\r\n                if (c == '\\\\')\r\n                {\r\n                    int remainingLength = jsonString.Length - i;\r\n                    if (remainingLength >= 2)\r\n                    {\r\n                        char lookahead = jsonString[i];\r\n                        if (lookahead == '\\\\')\r\n                        {\r\n                            sb.Append('\\\\');\r\n                            ++i;\r\n                        }\r\n                        else if (lookahead == '\"')\r\n                        {\r\n                            sb.Append(\"\\\"\");\r\n                            ++i;\r\n                        }\r\n                        else if (lookahead == 't')\r\n                        {\r\n                            sb.Append('\\t');\r\n                            ++i;\r\n                        }\r\n                        else if (lookahead == 'b')\r\n                        {\r\n                            sb.Append('\\b');\r\n                            ++i;\r\n                        }\r\n                        else if (lookahead == 'n')\r\n                        {\r\n                            sb.Append('\\n');\r\n                            ++i;\r\n                        }\r\n                        else if (lookahead == 'r')\r\n                        {\r\n                            sb.Append('\\r');\r\n                            ++i;\r\n                        }\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    sb.Append(c);\r\n                }\r\n            }\r\n            return sb.ToString();\r\n        }\r\n\r\n        static IDictionary<string, object> ParseObject(char[] json, ref int index, ref bool success)\r\n        {\r\n            IDictionary<string, object> table = new JsonObject();\r\n            int token;\r\n\r\n            // {\r\n            NextToken(json, ref index);\r\n\r\n            bool done = false;\r\n            while (!done)\r\n            {\r\n                token = LookAhead(json, index);\r\n                if (token == TOKEN_NONE)\r\n                {\r\n                    success = false;\r\n                    return null;\r\n                }\r\n                else if (token == TOKEN_COMMA)\r\n                    NextToken(json, ref index);\r\n                else if (token == TOKEN_CURLY_CLOSE)\r\n                {\r\n                    NextToken(json, ref index);\r\n                    return table;\r\n                }\r\n                else\r\n                {\r\n                    // name\r\n                    string name = ParseString(json, ref index, ref success);\r\n                    if (!success)\r\n                    {\r\n                        success = false;\r\n                        return null;\r\n                    }\r\n                    // :\r\n                    token = NextToken(json, ref index);\r\n                    if (token != TOKEN_COLON)\r\n                    {\r\n                        success = false;\r\n                        return null;\r\n                    }\r\n                    // value\r\n                    object value = ParseValue(json, ref index, ref success);\r\n                    if (!success)\r\n                    {\r\n                        success = false;\r\n                        return null;\r\n                    }\r\n                    table[name] = value;\r\n                }\r\n            }\r\n            return table;\r\n        }\r\n\r\n        static JsonArray ParseArray(char[] json, ref int index, ref bool success)\r\n        {\r\n            JsonArray array = new JsonArray();\r\n\r\n            // [\r\n            NextToken(json, ref index);\r\n\r\n            bool done = false;\r\n            while (!done)\r\n            {\r\n                int token = LookAhead(json, index);\r\n                if (token == TOKEN_NONE)\r\n                {\r\n                    success = false;\r\n                    return null;\r\n                }\r\n                else if (token == TOKEN_COMMA)\r\n                    NextToken(json, ref index);\r\n                else if (token == TOKEN_SQUARED_CLOSE)\r\n                {\r\n                    NextToken(json, ref index);\r\n                    break;\r\n                }\r\n                else\r\n                {\r\n                    object value = ParseValue(json, ref index, ref success);\r\n                    if (!success)\r\n                        return null;\r\n                    array.Add(value);\r\n                }\r\n            }\r\n            return array;\r\n        }\r\n\r\n        static object ParseValue(char[] json, ref int index, ref bool success)\r\n        {\r\n            switch (LookAhead(json, index))\r\n            {\r\n                case TOKEN_STRING:\r\n                    return ParseString(json, ref index, ref success);\r\n                case TOKEN_NUMBER:\r\n                    return ParseNumber(json, ref index, ref success);\r\n                case TOKEN_CURLY_OPEN:\r\n                    return ParseObject(json, ref index, ref success);\r\n                case TOKEN_SQUARED_OPEN:\r\n                    return ParseArray(json, ref index, ref success);\r\n                case TOKEN_TRUE:\r\n                    NextToken(json, ref index);\r\n                    return true;\r\n                case TOKEN_FALSE:\r\n                    NextToken(json, ref index);\r\n                    return false;\r\n                case TOKEN_NULL:\r\n                    NextToken(json, ref index);\r\n                    return null;\r\n                case TOKEN_NONE:\r\n                    break;\r\n            }\r\n            success = false;\r\n            return null;\r\n        }\r\n\r\n        static string ParseString(char[] json, ref int index, ref bool success)\r\n        {\r\n            StringBuilder s = new StringBuilder(BUILDER_CAPACITY);\r\n            char c;\r\n\r\n            EatWhitespace(json, ref index);\r\n\r\n            // \"\r\n            c = json[index++];\r\n            bool complete = false;\r\n            while (!complete)\r\n            {\r\n                if (index == json.Length)\r\n                    break;\r\n\r\n                c = json[index++];\r\n                if (c == '\"')\r\n                {\r\n                    complete = true;\r\n                    break;\r\n                }\r\n                else if (c == '\\\\')\r\n                {\r\n                    if (index == json.Length)\r\n                        break;\r\n                    c = json[index++];\r\n                    if (c == '\"')\r\n                        s.Append('\"');\r\n                    else if (c == '\\\\')\r\n                        s.Append('\\\\');\r\n                    else if (c == '/')\r\n                        s.Append('/');\r\n                    else if (c == 'b')\r\n                        s.Append('\\b');\r\n                    else if (c == 'f')\r\n                        s.Append('\\f');\r\n                    else if (c == 'n')\r\n                        s.Append('\\n');\r\n                    else if (c == 'r')\r\n                        s.Append('\\r');\r\n                    else if (c == 't')\r\n                        s.Append('\\t');\r\n                    else if (c == 'u')\r\n                    {\r\n                        int remainingLength = json.Length - index;\r\n                        if (remainingLength >= 4)\r\n                        {\r\n                            // parse the 32 bit hex into an integer codepoint\r\n                            uint codePoint;\r\n                            if (!(success = UInt32.TryParse(new string(json, index, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out codePoint)))\r\n                                return \"\";\r\n\r\n                            // convert the integer codepoint to a unicode char and add to string\r\n                            if (0xD800 <= codePoint && codePoint <= 0xDBFF)  // if high surrogate\r\n                            {\r\n                                index += 4; // skip 4 chars\r\n                                remainingLength = json.Length - index;\r\n                                if (remainingLength >= 6)\r\n                                {\r\n                                    uint lowCodePoint;\r\n                                    if (new string(json, index, 2) == \"\\\\u\" && UInt32.TryParse(new string(json, index + 2, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out lowCodePoint))\r\n                                    {\r\n                                        if (0xDC00 <= lowCodePoint && lowCodePoint <= 0xDFFF)    // if low surrogate\r\n                                        {\r\n                                            s.Append((char)codePoint);\r\n                                            s.Append((char)lowCodePoint);\r\n                                            index += 6; // skip 6 chars\r\n                                            continue;\r\n                                        }\r\n                                    }\r\n                                }\r\n                                success = false;    // invalid surrogate pair\r\n                                return \"\";\r\n                            }\r\n                            s.Append(ConvertFromUtf32((int)codePoint));\r\n                            // skip 4 chars\r\n                            index += 4;\r\n                        }\r\n                        else\r\n                            break;\r\n                    }\r\n                }\r\n                else\r\n                    s.Append(c);\r\n            }\r\n            if (!complete)\r\n            {\r\n                success = false;\r\n                return null;\r\n            }\r\n            return s.ToString();\r\n        }\r\n\r\n        private static string ConvertFromUtf32(int utf32)\r\n        {\r\n            // http://www.java2s.com/Open-Source/CSharp/2.6.4-mono-.net-core/System/System/Char.cs.htm\r\n            if (utf32 < 0 || utf32 > 0x10FFFF)\r\n                throw new ArgumentOutOfRangeException(\"utf32\", \"The argument must be from 0 to 0x10FFFF.\");\r\n            if (0xD800 <= utf32 && utf32 <= 0xDFFF)\r\n                throw new ArgumentOutOfRangeException(\"utf32\", \"The argument must not be in surrogate pair range.\");\r\n            if (utf32 < 0x10000)\r\n                return new string((char)utf32, 1);\r\n            utf32 -= 0x10000;\r\n            return new string(new char[] { (char)((utf32 >> 10) + 0xD800), (char)(utf32 % 0x0400 + 0xDC00) });\r\n        }\r\n\r\n        static object ParseNumber(char[] json, ref int index, ref bool success)\r\n        {\r\n            EatWhitespace(json, ref index);\r\n            int lastIndex = GetLastIndexOfNumber(json, index);\r\n            int charLength = (lastIndex - index) + 1;\r\n            object returnNumber;\r\n            string str = new string(json, index, charLength);\r\n            if (str.IndexOf(\".\", StringComparison.OrdinalIgnoreCase) != -1 || str.IndexOf(\"e\", StringComparison.OrdinalIgnoreCase) != -1)\r\n            {\r\n                double number;\r\n                success = double.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number);\r\n                returnNumber = number;\r\n            }\r\n            else\r\n            {\r\n                long number;\r\n                success = long.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number);\r\n                returnNumber = number;\r\n            }\r\n            index = lastIndex + 1;\r\n            return returnNumber;\r\n        }\r\n\r\n        static int GetLastIndexOfNumber(char[] json, int index)\r\n        {\r\n            int lastIndex;\r\n            for (lastIndex = index; lastIndex < json.Length; lastIndex++)\r\n                if (\"0123456789+-.eE\".IndexOf(json[lastIndex]) == -1) break;\r\n            return lastIndex - 1;\r\n        }\r\n\r\n        static void EatWhitespace(char[] json, ref int index)\r\n        {\r\n            for (; index < json.Length; index++)\r\n                if (\" \\t\\n\\r\\b\\f\".IndexOf(json[index]) == -1) break;\r\n        }\r\n\r\n        static int LookAhead(char[] json, int index)\r\n        {\r\n            int saveIndex = index;\r\n            return NextToken(json, ref saveIndex);\r\n        }\r\n\r\n        [SuppressMessage(\"Microsoft.Maintainability\", \"CA1502:AvoidExcessiveComplexity\")]\r\n        static int NextToken(char[] json, ref int index)\r\n        {\r\n            EatWhitespace(json, ref index);\r\n            if (index == json.Length)\r\n                return TOKEN_NONE;\r\n            char c = json[index];\r\n            index++;\r\n            switch (c)\r\n            {\r\n                case '{':\r\n                    return TOKEN_CURLY_OPEN;\r\n                case '}':\r\n                    return TOKEN_CURLY_CLOSE;\r\n                case '[':\r\n                    return TOKEN_SQUARED_OPEN;\r\n                case ']':\r\n                    return TOKEN_SQUARED_CLOSE;\r\n                case ',':\r\n                    return TOKEN_COMMA;\r\n                case '\"':\r\n                    return TOKEN_STRING;\r\n                case '0':\r\n                case '1':\r\n                case '2':\r\n                case '3':\r\n                case '4':\r\n                case '5':\r\n                case '6':\r\n                case '7':\r\n                case '8':\r\n                case '9':\r\n                case '-':\r\n                    return TOKEN_NUMBER;\r\n                case ':':\r\n                    return TOKEN_COLON;\r\n            }\r\n            index--;\r\n            int remainingLength = json.Length - index;\r\n            // false\r\n            if (remainingLength >= 5)\r\n            {\r\n                if (json[index] == 'f' && json[index + 1] == 'a' && json[index + 2] == 'l' && json[index + 3] == 's' && json[index + 4] == 'e')\r\n                {\r\n                    index += 5;\r\n                    return TOKEN_FALSE;\r\n                }\r\n            }\r\n            // true\r\n            if (remainingLength >= 4)\r\n            {\r\n                if (json[index] == 't' && json[index + 1] == 'r' && json[index + 2] == 'u' && json[index + 3] == 'e')\r\n                {\r\n                    index += 4;\r\n                    return TOKEN_TRUE;\r\n                }\r\n            }\r\n            // null\r\n            if (remainingLength >= 4)\r\n            {\r\n                if (json[index] == 'n' && json[index + 1] == 'u' && json[index + 2] == 'l' && json[index + 3] == 'l')\r\n                {\r\n                    index += 4;\r\n                    return TOKEN_NULL;\r\n                }\r\n            }\r\n            return TOKEN_NONE;\r\n        }\r\n\r\n        static bool SerializeValue(IJsonSerializerStrategy jsonSerializerStrategy, object value, StringBuilder builder)\r\n        {\r\n            bool success = true;\r\n            string stringValue = value as string;\r\n            if (stringValue != null)\r\n                success = SerializeString(stringValue, builder);\r\n            else\r\n            {\r\n                IDictionary<string, object> dict = value as IDictionary<string, object>;\r\n                if (dict != null)\r\n                {\r\n                    success = SerializeObject(jsonSerializerStrategy, dict.Keys, dict.Values, builder);\r\n                }\r\n                else\r\n                {\r\n                    IDictionary<string, string> stringDictionary = value as IDictionary<string, string>;\r\n                    if (stringDictionary != null)\r\n                    {\r\n                        success = SerializeObject(jsonSerializerStrategy, stringDictionary.Keys, stringDictionary.Values, builder);\r\n                    }\r\n                    else\r\n                    {\r\n                        IEnumerable enumerableValue = value as IEnumerable;\r\n                        if (enumerableValue != null)\r\n                            success = SerializeArray(jsonSerializerStrategy, enumerableValue, builder);\r\n                        else if (IsNumeric(value))\r\n                            success = SerializeNumber(value, builder);\r\n                        else if (value is bool)\r\n                            builder.Append((bool)value ? \"true\" : \"false\");\r\n                        else if (value == null)\r\n                            builder.Append(\"null\");\r\n                        else\r\n                        {\r\n                            object serializedObject;\r\n                            success = jsonSerializerStrategy.TrySerializeNonPrimitiveObject(value, out serializedObject);\r\n                            if (success)\r\n                                SerializeValue(jsonSerializerStrategy, serializedObject, builder);\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n            return success;\r\n        }\r\n\r\n        static bool SerializeObject(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable keys, IEnumerable values, StringBuilder builder)\r\n        {\r\n            builder.Append(\"{\");\r\n            IEnumerator ke = keys.GetEnumerator();\r\n            IEnumerator ve = values.GetEnumerator();\r\n            bool first = true;\r\n            while (ke.MoveNext() && ve.MoveNext())\r\n            {\r\n                object key = ke.Current;\r\n                object value = ve.Current;\r\n                if (!first)\r\n                    builder.Append(\",\");\r\n                string stringKey = key as string;\r\n                if (stringKey != null)\r\n                    SerializeString(stringKey, builder);\r\n                else\r\n                    if (!SerializeValue(jsonSerializerStrategy, value, builder)) return false;\r\n                builder.Append(\":\");\r\n                if (!SerializeValue(jsonSerializerStrategy, value, builder))\r\n                    return false;\r\n                first = false;\r\n            }\r\n            builder.Append(\"}\");\r\n            return true;\r\n        }\r\n\r\n        static bool SerializeArray(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable anArray, StringBuilder builder)\r\n        {\r\n            builder.Append(\"[\");\r\n            bool first = true;\r\n            foreach (object value in anArray)\r\n            {\r\n                if (!first)\r\n                    builder.Append(\",\");\r\n                if (!SerializeValue(jsonSerializerStrategy, value, builder))\r\n                    return false;\r\n                first = false;\r\n            }\r\n            builder.Append(\"]\");\r\n            return true;\r\n        }\r\n\r\n        static bool SerializeString(string aString, StringBuilder builder)\r\n        {\r\n            // Happy path if there's nothing to be escaped. IndexOfAny is highly optimized (and unmanaged)\r\n            if (aString.IndexOfAny(EscapeCharacters) == -1)\r\n            {\r\n                builder.Append('\"');\r\n                builder.Append(aString);\r\n                builder.Append('\"');\r\n\r\n                return true;\r\n            }\r\n\r\n            builder.Append('\"');\r\n            int safeCharacterCount = 0;\r\n            char[] charArray = aString.ToCharArray();\r\n\r\n            for (int i = 0; i < charArray.Length; i++)\r\n            {\r\n                char c = charArray[i];\r\n\r\n                // Non ascii characters are fine, buffer them up and send them to the builder\r\n                // in larger chunks if possible. The escape table is a 1:1 translation table\r\n                // with \\0 [default(char)] denoting a safe character.\r\n                if (c >= EscapeTable.Length || EscapeTable[c] == default(char))\r\n                {\r\n                    safeCharacterCount++;\r\n                }\r\n                else\r\n                {\r\n                    if (safeCharacterCount > 0)\r\n                    {\r\n                        builder.Append(charArray, i - safeCharacterCount, safeCharacterCount);\r\n                        safeCharacterCount = 0;\r\n                    }\r\n\r\n                    builder.Append('\\\\');\r\n                    builder.Append(EscapeTable[c]);\r\n                }\r\n            }\r\n\r\n            if (safeCharacterCount > 0)\r\n            {\r\n                builder.Append(charArray, charArray.Length - safeCharacterCount, safeCharacterCount);\r\n            }\r\n\r\n            builder.Append('\"');\r\n            return true;\r\n        }\r\n\r\n        static bool SerializeNumber(object number, StringBuilder builder)\r\n        {\r\n            if (number is long)\r\n                builder.Append(((long)number).ToString(CultureInfo.InvariantCulture));\r\n            else if (number is ulong)\r\n                builder.Append(((ulong)number).ToString(CultureInfo.InvariantCulture));\r\n            else if (number is int)\r\n                builder.Append(((int)number).ToString(CultureInfo.InvariantCulture));\r\n            else if (number is uint)\r\n                builder.Append(((uint)number).ToString(CultureInfo.InvariantCulture));\r\n            else if (number is decimal)\r\n                builder.Append(((decimal)number).ToString(CultureInfo.InvariantCulture));\r\n            else if (number is float)\r\n                builder.Append(((float)number).ToString(CultureInfo.InvariantCulture));\r\n            else\r\n                builder.Append(Convert.ToDouble(number, CultureInfo.InvariantCulture).ToString(\"r\", CultureInfo.InvariantCulture));\r\n            return true;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determines if a given object is numeric in any way\r\n        /// (can be integer, double, null, etc).\r\n        /// </summary>\r\n        static bool IsNumeric(object value)\r\n        {\r\n            if (value is sbyte) return true;\r\n            if (value is byte) return true;\r\n            if (value is short) return true;\r\n            if (value is ushort) return true;\r\n            if (value is int) return true;\r\n            if (value is uint) return true;\r\n            if (value is long) return true;\r\n            if (value is ulong) return true;\r\n            if (value is float) return true;\r\n            if (value is double) return true;\r\n            if (value is decimal) return true;\r\n            return false;\r\n        }\r\n\r\n        private static IJsonSerializerStrategy _currentJsonSerializerStrategy;\r\n        public static IJsonSerializerStrategy CurrentJsonSerializerStrategy\r\n        {\r\n            get\r\n            {\r\n                return _currentJsonSerializerStrategy ??\r\n                    (_currentJsonSerializerStrategy =\r\n#if SIMPLE_JSON_DATACONTRACT\r\n DataContractJsonSerializerStrategy\r\n#else\r\n PocoJsonSerializerStrategy\r\n#endif\r\n);\r\n            }\r\n            set\r\n            {\r\n                _currentJsonSerializerStrategy = value;\r\n            }\r\n        }\r\n\r\n        private static PocoJsonSerializerStrategy _pocoJsonSerializerStrategy;\r\n        [EditorBrowsable(EditorBrowsableState.Advanced)]\r\n        public static PocoJsonSerializerStrategy PocoJsonSerializerStrategy\r\n        {\r\n            get\r\n            {\r\n                return _pocoJsonSerializerStrategy ?? (_pocoJsonSerializerStrategy = new PocoJsonSerializerStrategy());\r\n            }\r\n        }\r\n\r\n#if SIMPLE_JSON_DATACONTRACT\r\n\r\n        private static DataContractJsonSerializerStrategy _dataContractJsonSerializerStrategy;\r\n        [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Advanced)]\r\n        public static DataContractJsonSerializerStrategy DataContractJsonSerializerStrategy\r\n        {\r\n            get\r\n            {\r\n                return _dataContractJsonSerializerStrategy ?? (_dataContractJsonSerializerStrategy = new DataContractJsonSerializerStrategy());\r\n            }\r\n        }\r\n\r\n#endif\r\n    }\r\n    \r\n    [GeneratedCode(\"simple-json\", \"1.0.0\")]\r\n#if SIMPLE_JSON_INTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n interface IJsonSerializerStrategy\r\n    {\r\n        [SuppressMessage(\"Microsoft.Design\", \"CA1007:UseGenericsWhereAppropriate\", Justification=\"Need to support .NET 2\")]\r\n        bool TrySerializeNonPrimitiveObject(object input, out object output);\r\n        object DeserializeObject(object value, Type type);\r\n    }\r\n\r\n    [GeneratedCode(\"simple-json\", \"1.0.0\")]\r\n#if SIMPLE_JSON_INTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n class PocoJsonSerializerStrategy : IJsonSerializerStrategy\r\n    {\r\n        internal IDictionary<Type, ReflectionUtils.ConstructorDelegate> ConstructorCache;\r\n        internal IDictionary<Type, IDictionary<string, ReflectionUtils.GetDelegate>> GetCache;\r\n        internal IDictionary<Type, IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>> SetCache;\r\n\r\n        internal static readonly Type[] EmptyTypes = new Type[0];\r\n        internal static readonly Type[] ArrayConstructorParameterTypes = new Type[] { typeof(int) };\r\n\r\n        private static readonly string[] Iso8601Format = new string[]\r\n                                                             {\r\n                                                                 @\"yyyy-MM-dd\\THH:mm:ss.FFFFFFF\\Z\",\r\n                                                                 @\"yyyy-MM-dd\\THH:mm:ss\\Z\",\r\n                                                                 @\"yyyy-MM-dd\\THH:mm:ssK\"\r\n                                                             };\r\n\r\n        public PocoJsonSerializerStrategy()\r\n        {\r\n            ConstructorCache = new ReflectionUtils.ThreadSafeDictionary<Type, ReflectionUtils.ConstructorDelegate>(ContructorDelegateFactory);\r\n            GetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<string, ReflectionUtils.GetDelegate>>(GetterValueFactory);\r\n            SetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>>(SetterValueFactory);\r\n        }\r\n\r\n        protected virtual string MapClrMemberNameToJsonFieldName(string clrPropertyName)\r\n        {\r\n            return clrPropertyName;\r\n        }\r\n\r\n        internal virtual ReflectionUtils.ConstructorDelegate ContructorDelegateFactory(Type key)\r\n        {\r\n            return ReflectionUtils.GetContructor(key, key.IsArray ? ArrayConstructorParameterTypes : EmptyTypes);\r\n        }\r\n\r\n        internal virtual IDictionary<string, ReflectionUtils.GetDelegate> GetterValueFactory(Type type)\r\n        {\r\n            IDictionary<string, ReflectionUtils.GetDelegate> result = new Dictionary<string, ReflectionUtils.GetDelegate>();\r\n            foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type))\r\n            {\r\n                if (propertyInfo.CanRead)\r\n                {\r\n                    MethodInfo getMethod = ReflectionUtils.GetGetterMethodInfo(propertyInfo);\r\n                    if (getMethod.IsStatic || !getMethod.IsPublic)\r\n                        continue;\r\n                    result[MapClrMemberNameToJsonFieldName(propertyInfo.Name)] = ReflectionUtils.GetGetMethod(propertyInfo);\r\n                }\r\n            }\r\n            foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type))\r\n            {\r\n                if (fieldInfo.IsStatic || !fieldInfo.IsPublic)\r\n                    continue;\r\n                result[MapClrMemberNameToJsonFieldName(fieldInfo.Name)] = ReflectionUtils.GetGetMethod(fieldInfo);\r\n            }\r\n            return result;\r\n        }\r\n\r\n        internal virtual IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> SetterValueFactory(Type type)\r\n        {\r\n            IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> result = new Dictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>();\r\n            foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type))\r\n            {\r\n                if (propertyInfo.CanWrite)\r\n                {\r\n                    MethodInfo setMethod = ReflectionUtils.GetSetterMethodInfo(propertyInfo);\r\n                    if (setMethod.IsStatic || !setMethod.IsPublic)\r\n                        continue;\r\n                    result[MapClrMemberNameToJsonFieldName(propertyInfo.Name)] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(propertyInfo.PropertyType, ReflectionUtils.GetSetMethod(propertyInfo));\r\n                }\r\n            }\r\n            foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type))\r\n            {\r\n                if (fieldInfo.IsInitOnly || fieldInfo.IsStatic || !fieldInfo.IsPublic)\r\n                    continue;\r\n                result[MapClrMemberNameToJsonFieldName(fieldInfo.Name)] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(fieldInfo.FieldType, ReflectionUtils.GetSetMethod(fieldInfo));\r\n            }\r\n            return result;\r\n        }\r\n\r\n        public virtual bool TrySerializeNonPrimitiveObject(object input, out object output)\r\n        {\r\n            return TrySerializeKnownTypes(input, out output) || TrySerializeUnknownTypes(input, out output);\r\n        }\r\n\r\n        [SuppressMessage(\"Microsoft.Maintainability\", \"CA1502:AvoidExcessiveComplexity\")]\r\n        public virtual object DeserializeObject(object value, Type type)\r\n        {\r\n            if (type == null) throw new ArgumentNullException(\"type\");\r\n            string str = value as string;\r\n\r\n            if (type == typeof (Guid) && string.IsNullOrEmpty(str))\r\n                return default(Guid);\r\n\r\n            if (value == null)\r\n                return null;\r\n            \r\n            object obj = null;\r\n\r\n            if (str != null)\r\n            {\r\n                if (str.Length != 0) // We know it can't be null now.\r\n                {\r\n                    if (type == typeof(DateTime) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(DateTime)))\r\n                        return DateTime.ParseExact(str, Iso8601Format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);\r\n                    if (type == typeof(DateTimeOffset) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(DateTimeOffset)))\r\n                        return DateTimeOffset.ParseExact(str, Iso8601Format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);\r\n                    if (type == typeof(Guid) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid)))\r\n                        return new Guid(str);\r\n                    if (type == typeof(Uri))\r\n                    {\r\n                        bool isValid =  Uri.IsWellFormedUriString(str, UriKind.RelativeOrAbsolute);\r\n\r\n                        Uri result;\r\n                        if (isValid && Uri.TryCreate(str, UriKind.RelativeOrAbsolute, out result))\r\n                            return result;\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn null;\r\n                    }\r\n                  \r\n\t\t\t\t\t\t\t\t\tif (type == typeof(string))  \r\n\t\t\t\t\t\t\t\t\t\treturn str;\r\n\r\n\t\t\t\t\t\t\t\t\treturn Convert.ChangeType(str, type, CultureInfo.InvariantCulture);\r\n                }\r\n                else\r\n                {\r\n                    if (type == typeof(Guid))\r\n                        obj = default(Guid);\r\n                    else if (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid))\r\n                        obj = null;\r\n                    else\r\n                        obj = str;\r\n                }\r\n                // Empty string case\r\n                if (!ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid))\r\n                    return str;\r\n            }\r\n            else if (value is bool)\r\n                return value;\r\n            \r\n            bool valueIsLong = value is long;\r\n            bool valueIsDouble = value is double;\r\n            if ((valueIsLong && type == typeof(long)) || (valueIsDouble && type == typeof(double)))\r\n                return value;\r\n            if ((valueIsDouble && type != typeof(double)) || (valueIsLong && type != typeof(long)))\r\n            {\r\n                obj = type == typeof(int) || type == typeof(long) || type == typeof(double) || type == typeof(float) || type == typeof(bool) || type == typeof(decimal) || type == typeof(byte) || type == typeof(short)\r\n                            ? Convert.ChangeType(value, type, CultureInfo.InvariantCulture)\r\n                            : value;\r\n            }\r\n            else\r\n            {\r\n                IDictionary<string, object> objects = value as IDictionary<string, object>;\r\n                if (objects != null)\r\n                {\r\n                    IDictionary<string, object> jsonObject = objects;\r\n\r\n                    if (ReflectionUtils.IsTypeDictionary(type))\r\n                    {\r\n                        // if dictionary then\r\n                        Type[] types = ReflectionUtils.GetGenericTypeArguments(type);\r\n                        Type keyType = types[0];\r\n                        Type valueType = types[1];\r\n\r\n                        Type genericType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType);\r\n\r\n                        IDictionary dict = (IDictionary)ConstructorCache[genericType]();\r\n\r\n                        foreach (KeyValuePair<string, object> kvp in jsonObject)\r\n                            dict.Add(kvp.Key, DeserializeObject(kvp.Value, valueType));\r\n\r\n                        obj = dict;\r\n                    }\r\n                    else\r\n                    {\r\n                        if (type == typeof(object))\r\n                            obj = value;\r\n                        else\r\n                        {\r\n                            obj = ConstructorCache[type]();\r\n                            foreach (KeyValuePair<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> setter in SetCache[type])\r\n                            {\r\n                                object jsonValue;\r\n                                if (jsonObject.TryGetValue(setter.Key, out jsonValue))\r\n                                {\r\n                                    jsonValue = DeserializeObject(jsonValue, setter.Value.Key);\r\n                                    setter.Value.Value(obj, jsonValue);\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    IList<object> valueAsList = value as IList<object>;\r\n                    if (valueAsList != null)\r\n                    {\r\n                        IList<object> jsonObject = valueAsList;\r\n                        IList list = null;\r\n\r\n                        if (type.IsArray)\r\n                        {\r\n                            list = (IList)ConstructorCache[type](jsonObject.Count);\r\n                            int i = 0;\r\n                            foreach (object o in jsonObject)\r\n                                list[i++] = DeserializeObject(o, type.GetElementType());\r\n                        }\r\n                        else if (ReflectionUtils.IsTypeGenericeCollectionInterface(type) || ReflectionUtils.IsAssignableFrom(typeof(IList), type))\r\n                        {\r\n                            Type innerType = ReflectionUtils.GetGenericListElementType(type);\r\n                            list = (IList)(ConstructorCache[type] ?? ConstructorCache[typeof(List<>).MakeGenericType(innerType)])(jsonObject.Count);\r\n                            foreach (object o in jsonObject)\r\n                                list.Add(DeserializeObject(o, innerType));\r\n                        }\r\n                        obj = list;\r\n                    }\r\n                }\r\n                return obj;\r\n            }\r\n            if (ReflectionUtils.IsNullableType(type))\r\n                return ReflectionUtils.ToNullableType(obj, type);\r\n            return obj;\r\n        }\r\n\r\n        protected virtual object SerializeEnum(Enum p)\r\n        {\r\n            return Convert.ToDouble(p, CultureInfo.InvariantCulture);\r\n        }\r\n\r\n        [SuppressMessage(\"Microsoft.Design\", \"CA1007:UseGenericsWhereAppropriate\", Justification=\"Need to support .NET 2\")]\r\n        protected virtual bool TrySerializeKnownTypes(object input, out object output)\r\n        {\r\n            bool returnValue = true;\r\n            if (input is DateTime)\r\n                output = ((DateTime)input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture);\r\n            else if (input is DateTimeOffset)\r\n                output = ((DateTimeOffset)input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture);\r\n            else if (input is Guid)\r\n                output = ((Guid)input).ToString(\"D\");\r\n            else if (input is Uri)\r\n                output = input.ToString();\r\n            else\r\n            {\r\n                Enum inputEnum = input as Enum;\r\n                if (inputEnum != null)\r\n                    output = SerializeEnum(inputEnum);\r\n                else\r\n                {\r\n                    returnValue = false;\r\n                    output = null;\r\n                }\r\n            }\r\n            return returnValue;\r\n        }\r\n        [SuppressMessage(\"Microsoft.Design\", \"CA1007:UseGenericsWhereAppropriate\", Justification=\"Need to support .NET 2\")]\r\n        protected virtual bool TrySerializeUnknownTypes(object input, out object output)\r\n        {\r\n            if (input == null) throw new ArgumentNullException(\"input\");\r\n            output = null;\r\n            Type type = input.GetType();\r\n            if (type.FullName == null)\r\n                return false;\r\n            IDictionary<string, object> obj = new JsonObject();\r\n            IDictionary<string, ReflectionUtils.GetDelegate> getters = GetCache[type];\r\n            foreach (KeyValuePair<string, ReflectionUtils.GetDelegate> getter in getters)\r\n            {\r\n                if (getter.Value != null)\r\n                    obj.Add(MapClrMemberNameToJsonFieldName(getter.Key), getter.Value(input));\r\n            }\r\n            output = obj;\r\n            return true;\r\n        }\r\n    }\r\n\r\n#if SIMPLE_JSON_DATACONTRACT\r\n    [GeneratedCode(\"simple-json\", \"1.0.0\")]\r\n#if SIMPLE_JSON_INTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n class DataContractJsonSerializerStrategy : PocoJsonSerializerStrategy\r\n    {\r\n        public DataContractJsonSerializerStrategy()\r\n        {\r\n            GetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<string, ReflectionUtils.GetDelegate>>(GetterValueFactory);\r\n            SetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>>(SetterValueFactory);\r\n        }\r\n\r\n        internal override IDictionary<string, ReflectionUtils.GetDelegate> GetterValueFactory(Type type)\r\n        {\r\n            bool hasDataContract = ReflectionUtils.GetAttribute(type, typeof(DataContractAttribute)) != null;\r\n            if (!hasDataContract)\r\n                return base.GetterValueFactory(type);\r\n            string jsonKey;\r\n            IDictionary<string, ReflectionUtils.GetDelegate> result = new Dictionary<string, ReflectionUtils.GetDelegate>();\r\n            foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type))\r\n            {\r\n                if (propertyInfo.CanRead)\r\n                {\r\n                    MethodInfo getMethod = ReflectionUtils.GetGetterMethodInfo(propertyInfo);\r\n                    if (!getMethod.IsStatic && CanAdd(propertyInfo, out jsonKey))\r\n                        result[jsonKey] = ReflectionUtils.GetGetMethod(propertyInfo);\r\n                }\r\n            }\r\n            foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type))\r\n            {\r\n                if (!fieldInfo.IsStatic && CanAdd(fieldInfo, out jsonKey))\r\n                    result[jsonKey] = ReflectionUtils.GetGetMethod(fieldInfo);\r\n            }\r\n            return result;\r\n        }\r\n\r\n        internal override IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> SetterValueFactory(Type type)\r\n        {\r\n            bool hasDataContract = ReflectionUtils.GetAttribute(type, typeof(DataContractAttribute)) != null;\r\n            if (!hasDataContract)\r\n                return base.SetterValueFactory(type);\r\n            string jsonKey;\r\n            IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> result = new Dictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>();\r\n            foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type))\r\n            {\r\n                if (propertyInfo.CanWrite)\r\n                {\r\n                    MethodInfo setMethod = ReflectionUtils.GetSetterMethodInfo(propertyInfo);\r\n                    if (!setMethod.IsStatic && CanAdd(propertyInfo, out jsonKey))\r\n                        result[jsonKey] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(propertyInfo.PropertyType, ReflectionUtils.GetSetMethod(propertyInfo));\r\n                }\r\n            }\r\n            foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type))\r\n            {\r\n                if (!fieldInfo.IsInitOnly && !fieldInfo.IsStatic && CanAdd(fieldInfo, out jsonKey))\r\n                    result[jsonKey] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(fieldInfo.FieldType, ReflectionUtils.GetSetMethod(fieldInfo));\r\n            }\r\n            // todo implement sorting for DATACONTRACT.\r\n            return result;\r\n        }\r\n\r\n        private static bool CanAdd(MemberInfo info, out string jsonKey)\r\n        {\r\n            jsonKey = null;\r\n            if (ReflectionUtils.GetAttribute(info, typeof(IgnoreDataMemberAttribute)) != null)\r\n                return false;\r\n            DataMemberAttribute dataMemberAttribute = (DataMemberAttribute)ReflectionUtils.GetAttribute(info, typeof(DataMemberAttribute));\r\n            if (dataMemberAttribute == null)\r\n                return false;\r\n            jsonKey = string.IsNullOrEmpty(dataMemberAttribute.Name) ? info.Name : dataMemberAttribute.Name;\r\n            return true;\r\n        }\r\n    }\r\n\r\n#endif\r\n\r\n    namespace Reflection\r\n    {\r\n        // This class is meant to be copied into other libraries. So we want to exclude it from Code Analysis rules\r\n \t    // that might be in place in the target project.\r\n        [GeneratedCode(\"reflection-utils\", \"1.0.0\")]\r\n#if SIMPLE_JSON_REFLECTION_UTILS_PUBLIC\r\n        public\r\n#else\r\n        internal\r\n#endif\r\n class ReflectionUtils\r\n        {\r\n            private static readonly object[] EmptyObjects = new object[] { };\r\n\r\n            public delegate object GetDelegate(object source);\r\n            public delegate void SetDelegate(object source, object value);\r\n            public delegate object ConstructorDelegate(params object[] args);\r\n\r\n            public delegate TValue ThreadSafeDictionaryValueFactory<TKey, TValue>(TKey key);\r\n\r\n#if SIMPLE_JSON_TYPEINFO\r\n            public static TypeInfo GetTypeInfo(Type type)\r\n            {\r\n                return type.GetTypeInfo();\r\n            }\r\n#else\r\n            public static Type GetTypeInfo(Type type)\r\n            {\r\n                return type;\r\n            }\r\n#endif\r\n\r\n            public static Attribute GetAttribute(MemberInfo info, Type type)\r\n            {\r\n#if SIMPLE_JSON_TYPEINFO\r\n                if (info == null || type == null || !info.IsDefined(type))\r\n                    return null;\r\n                return info.GetCustomAttribute(type);\r\n#else\r\n                if (info == null || type == null || !Attribute.IsDefined(info, type))\r\n                    return null;\r\n                return Attribute.GetCustomAttribute(info, type);\r\n#endif\r\n            }\r\n\r\n            public static Type GetGenericListElementType(Type type)\r\n            {\r\n                IEnumerable<Type> interfaces;\r\n#if SIMPLE_JSON_TYPEINFO\r\n                interfaces = type.GetTypeInfo().ImplementedInterfaces;\r\n#else\r\n                interfaces = type.GetInterfaces();\r\n#endif\r\n                foreach (Type implementedInterface in interfaces)\r\n                {\r\n                    if (IsTypeGeneric(implementedInterface) &&\r\n                        implementedInterface.GetGenericTypeDefinition() == typeof (IList<>))\r\n                    {\r\n                        return GetGenericTypeArguments(implementedInterface)[0];\r\n                    }\r\n                }\r\n                return GetGenericTypeArguments(type)[0];\r\n            }\r\n\r\n            public static Attribute GetAttribute(Type objectType, Type attributeType)\r\n            {\r\n\r\n#if SIMPLE_JSON_TYPEINFO\r\n                if (objectType == null || attributeType == null || !objectType.GetTypeInfo().IsDefined(attributeType))\r\n                    return null;\r\n                return objectType.GetTypeInfo().GetCustomAttribute(attributeType);\r\n#else\r\n                if (objectType == null || attributeType == null || !Attribute.IsDefined(objectType, attributeType))\r\n                    return null;\r\n                return Attribute.GetCustomAttribute(objectType, attributeType);\r\n#endif\r\n            }\r\n\r\n            public static Type[] GetGenericTypeArguments(Type type)\r\n            {\r\n#if SIMPLE_JSON_TYPEINFO\r\n                return type.GetTypeInfo().GenericTypeArguments;\r\n#else\r\n                return type.GetGenericArguments();\r\n#endif\r\n            }\r\n\r\n            public static bool IsTypeGeneric(Type type)\r\n            {\r\n                return GetTypeInfo(type).IsGenericType;\r\n            }\r\n\r\n            public static bool IsTypeGenericeCollectionInterface(Type type)\r\n            {\r\n                if (!IsTypeGeneric(type))\r\n                    return false;\r\n\r\n                Type genericDefinition = type.GetGenericTypeDefinition();\r\n\r\n                return (genericDefinition == typeof(IList<>)\r\n                    || genericDefinition == typeof(ICollection<>)\r\n                    || genericDefinition == typeof(IEnumerable<>)\r\n#if SIMPLE_JSON_READONLY_COLLECTIONS\r\n                    || genericDefinition == typeof(IReadOnlyCollection<>)\r\n                    || genericDefinition == typeof(IReadOnlyList<>)\r\n#endif\r\n                    );\r\n            }\r\n\r\n            public static bool IsAssignableFrom(Type type1, Type type2)\r\n            {\r\n                return GetTypeInfo(type1).IsAssignableFrom(GetTypeInfo(type2));\r\n            }\r\n\r\n            public static bool IsTypeDictionary(Type type)\r\n            {\r\n#if SIMPLE_JSON_TYPEINFO\r\n                if (typeof(IDictionary<,>).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()))\r\n                    return true;\r\n#else\r\n                if (typeof(System.Collections.IDictionary).IsAssignableFrom(type))\r\n                    return true;\r\n#endif\r\n                if (!GetTypeInfo(type).IsGenericType)\r\n                    return false;\r\n\r\n                Type genericDefinition = type.GetGenericTypeDefinition();\r\n                return genericDefinition == typeof(IDictionary<,>);\r\n            }\r\n\r\n            public static bool IsNullableType(Type type)\r\n            {\r\n                return GetTypeInfo(type).IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);\r\n            }\r\n\r\n            public static object ToNullableType(object obj, Type nullableType)\r\n            {\r\n                return obj == null ? null : Convert.ChangeType(obj, Nullable.GetUnderlyingType(nullableType), CultureInfo.InvariantCulture);\r\n            }\r\n\r\n            public static bool IsValueType(Type type)\r\n            {\r\n                return GetTypeInfo(type).IsValueType;\r\n            }\r\n\r\n            public static IEnumerable<ConstructorInfo> GetConstructors(Type type)\r\n            {\r\n#if SIMPLE_JSON_TYPEINFO\r\n                return type.GetTypeInfo().DeclaredConstructors;\r\n#else\r\n                return type.GetConstructors();\r\n#endif\r\n            }\r\n\r\n            public static ConstructorInfo GetConstructorInfo(Type type, params Type[] argsType)\r\n            {\r\n                IEnumerable<ConstructorInfo> constructorInfos = GetConstructors(type);\r\n                int i;\r\n                bool matches;\r\n                foreach (ConstructorInfo constructorInfo in constructorInfos)\r\n                {\r\n                    ParameterInfo[] parameters = constructorInfo.GetParameters();\r\n                    if (argsType.Length != parameters.Length)\r\n                        continue;\r\n\r\n                    i = 0;\r\n                    matches = true;\r\n                    foreach (ParameterInfo parameterInfo in constructorInfo.GetParameters())\r\n                    {\r\n                        if (parameterInfo.ParameterType != argsType[i])\r\n                        {\r\n                            matches = false;\r\n                            break;\r\n                        }\r\n                    }\r\n\r\n                    if (matches)\r\n                        return constructorInfo;\r\n                }\r\n\r\n                return null;\r\n            }\r\n\r\n            public static IEnumerable<PropertyInfo> GetProperties(Type type)\r\n            {\r\n#if SIMPLE_JSON_TYPEINFO\r\n                return type.GetRuntimeProperties();\r\n#else\r\n                return type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);\r\n#endif\r\n            }\r\n\r\n            public static IEnumerable<FieldInfo> GetFields(Type type)\r\n            {\r\n#if SIMPLE_JSON_TYPEINFO\r\n                return type.GetRuntimeFields();\r\n#else\r\n                return type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);\r\n#endif\r\n            }\r\n\r\n            public static MethodInfo GetGetterMethodInfo(PropertyInfo propertyInfo)\r\n            {\r\n#if SIMPLE_JSON_TYPEINFO\r\n                return propertyInfo.GetMethod;\r\n#else\r\n                return propertyInfo.GetGetMethod(true);\r\n#endif\r\n            }\r\n\r\n            public static MethodInfo GetSetterMethodInfo(PropertyInfo propertyInfo)\r\n            {\r\n#if SIMPLE_JSON_TYPEINFO\r\n                return propertyInfo.SetMethod;\r\n#else\r\n                return propertyInfo.GetSetMethod(true);\r\n#endif\r\n            }\r\n\r\n            public static ConstructorDelegate GetContructor(ConstructorInfo constructorInfo)\r\n            {\r\n#if SIMPLE_JSON_NO_LINQ_EXPRESSION\r\n                return GetConstructorByReflection(constructorInfo);\r\n#else\r\n                return GetConstructorByExpression(constructorInfo);\r\n#endif\r\n            }\r\n\r\n            public static ConstructorDelegate GetContructor(Type type, params Type[] argsType)\r\n            {\r\n#if SIMPLE_JSON_NO_LINQ_EXPRESSION\r\n                return GetConstructorByReflection(type, argsType);\r\n#else\r\n                return GetConstructorByExpression(type, argsType);\r\n#endif\r\n            }\r\n\r\n            public static ConstructorDelegate GetConstructorByReflection(ConstructorInfo constructorInfo)\r\n            {\r\n                return delegate(object[] args) { return constructorInfo.Invoke(args); };\r\n            }\r\n\r\n            public static ConstructorDelegate GetConstructorByReflection(Type type, params Type[] argsType)\r\n            {\r\n                ConstructorInfo constructorInfo = GetConstructorInfo(type, argsType);\r\n                return constructorInfo == null ? null : GetConstructorByReflection(constructorInfo);\r\n            }\r\n\r\n#if !SIMPLE_JSON_NO_LINQ_EXPRESSION\r\n\r\n            public static ConstructorDelegate GetConstructorByExpression(ConstructorInfo constructorInfo)\r\n            {\r\n                ParameterInfo[] paramsInfo = constructorInfo.GetParameters();\r\n                ParameterExpression param = Expression.Parameter(typeof(object[]), \"args\");\r\n                Expression[] argsExp = new Expression[paramsInfo.Length];\r\n                for (int i = 0; i < paramsInfo.Length; i++)\r\n                {\r\n                    Expression index = Expression.Constant(i);\r\n                    Type paramType = paramsInfo[i].ParameterType;\r\n                    Expression paramAccessorExp = Expression.ArrayIndex(param, index);\r\n                    Expression paramCastExp = Expression.Convert(paramAccessorExp, paramType);\r\n                    argsExp[i] = paramCastExp;\r\n                }\r\n                NewExpression newExp = Expression.New(constructorInfo, argsExp);\r\n                Expression<Func<object[], object>> lambda = Expression.Lambda<Func<object[], object>>(newExp, param);\r\n                Func<object[], object> compiledLambda = lambda.Compile();\r\n                return delegate(object[] args) { return compiledLambda(args); };\r\n            }\r\n\r\n            public static ConstructorDelegate GetConstructorByExpression(Type type, params Type[] argsType)\r\n            {\r\n                ConstructorInfo constructorInfo = GetConstructorInfo(type, argsType);\r\n                return constructorInfo == null ? null : GetConstructorByExpression(constructorInfo);\r\n            }\r\n\r\n#endif\r\n\r\n            public static GetDelegate GetGetMethod(PropertyInfo propertyInfo)\r\n            {\r\n#if SIMPLE_JSON_NO_LINQ_EXPRESSION\r\n                return GetGetMethodByReflection(propertyInfo);\r\n#else\r\n                return GetGetMethodByExpression(propertyInfo);\r\n#endif\r\n            }\r\n\r\n            public static GetDelegate GetGetMethod(FieldInfo fieldInfo)\r\n            {\r\n#if SIMPLE_JSON_NO_LINQ_EXPRESSION\r\n                return GetGetMethodByReflection(fieldInfo);\r\n#else\r\n                return GetGetMethodByExpression(fieldInfo);\r\n#endif\r\n            }\r\n\r\n            public static GetDelegate GetGetMethodByReflection(PropertyInfo propertyInfo)\r\n            {\r\n                MethodInfo methodInfo = GetGetterMethodInfo(propertyInfo);\r\n                return delegate(object source) { return methodInfo.Invoke(source, EmptyObjects); };\r\n            }\r\n\r\n            public static GetDelegate GetGetMethodByReflection(FieldInfo fieldInfo)\r\n            {\r\n                return delegate(object source) { return fieldInfo.GetValue(source); };\r\n            }\r\n\r\n#if !SIMPLE_JSON_NO_LINQ_EXPRESSION\r\n\r\n            public static GetDelegate GetGetMethodByExpression(PropertyInfo propertyInfo)\r\n            {\r\n                MethodInfo getMethodInfo = GetGetterMethodInfo(propertyInfo);\r\n                ParameterExpression instance = Expression.Parameter(typeof(object), \"instance\");\r\n                UnaryExpression instanceCast = (!IsValueType(propertyInfo.DeclaringType)) ? Expression.TypeAs(instance, propertyInfo.DeclaringType) : Expression.Convert(instance, propertyInfo.DeclaringType);\r\n                Func<object, object> compiled = Expression.Lambda<Func<object, object>>(Expression.TypeAs(Expression.Call(instanceCast, getMethodInfo), typeof(object)), instance).Compile();\r\n                return delegate(object source) { return compiled(source); };\r\n            }\r\n\r\n            public static GetDelegate GetGetMethodByExpression(FieldInfo fieldInfo)\r\n            {\r\n                ParameterExpression instance = Expression.Parameter(typeof(object), \"instance\");\r\n                MemberExpression member = Expression.Field(Expression.Convert(instance, fieldInfo.DeclaringType), fieldInfo);\r\n                GetDelegate compiled = Expression.Lambda<GetDelegate>(Expression.Convert(member, typeof(object)), instance).Compile();\r\n                return delegate(object source) { return compiled(source); };\r\n            }\r\n\r\n#endif\r\n\r\n            public static SetDelegate GetSetMethod(PropertyInfo propertyInfo)\r\n            {\r\n#if SIMPLE_JSON_NO_LINQ_EXPRESSION\r\n                return GetSetMethodByReflection(propertyInfo);\r\n#else\r\n                return GetSetMethodByExpression(propertyInfo);\r\n#endif\r\n            }\r\n\r\n            public static SetDelegate GetSetMethod(FieldInfo fieldInfo)\r\n            {\r\n#if SIMPLE_JSON_NO_LINQ_EXPRESSION\r\n                return GetSetMethodByReflection(fieldInfo);\r\n#else\r\n                return GetSetMethodByExpression(fieldInfo);\r\n#endif\r\n            }\r\n\r\n            public static SetDelegate GetSetMethodByReflection(PropertyInfo propertyInfo)\r\n            {\r\n                MethodInfo methodInfo = GetSetterMethodInfo(propertyInfo);\r\n                return delegate(object source, object value) { methodInfo.Invoke(source, new object[] { value }); };\r\n            }\r\n\r\n            public static SetDelegate GetSetMethodByReflection(FieldInfo fieldInfo)\r\n            {\r\n                return delegate(object source, object value) { fieldInfo.SetValue(source, value); };\r\n            }\r\n\r\n#if !SIMPLE_JSON_NO_LINQ_EXPRESSION\r\n\r\n            public static SetDelegate GetSetMethodByExpression(PropertyInfo propertyInfo)\r\n            {\r\n                MethodInfo setMethodInfo = GetSetterMethodInfo(propertyInfo);\r\n                ParameterExpression instance = Expression.Parameter(typeof(object), \"instance\");\r\n                ParameterExpression value = Expression.Parameter(typeof(object), \"value\");\r\n                UnaryExpression instanceCast = (!IsValueType(propertyInfo.DeclaringType)) ? Expression.TypeAs(instance, propertyInfo.DeclaringType) : Expression.Convert(instance, propertyInfo.DeclaringType);\r\n                UnaryExpression valueCast = (!IsValueType(propertyInfo.PropertyType)) ? Expression.TypeAs(value, propertyInfo.PropertyType) : Expression.Convert(value, propertyInfo.PropertyType);\r\n                Action<object, object> compiled = Expression.Lambda<Action<object, object>>(Expression.Call(instanceCast, setMethodInfo, valueCast), new ParameterExpression[] { instance, value }).Compile();\r\n                return delegate(object source, object val) { compiled(source, val); };\r\n            }\r\n\r\n            public static SetDelegate GetSetMethodByExpression(FieldInfo fieldInfo)\r\n            {\r\n                ParameterExpression instance = Expression.Parameter(typeof(object), \"instance\");\r\n                ParameterExpression value = Expression.Parameter(typeof(object), \"value\");\r\n                Action<object, object> compiled = Expression.Lambda<Action<object, object>>(\r\n                    Assign(Expression.Field(Expression.Convert(instance, fieldInfo.DeclaringType), fieldInfo), Expression.Convert(value, fieldInfo.FieldType)), instance, value).Compile();\r\n                return delegate(object source, object val) { compiled(source, val); };\r\n            }\r\n\r\n            public static BinaryExpression Assign(Expression left, Expression right)\r\n            {\r\n#if SIMPLE_JSON_TYPEINFO\r\n                return Expression.Assign(left, right);\r\n#else\r\n                MethodInfo assign = typeof(Assigner<>).MakeGenericType(left.Type).GetMethod(\"Assign\");\r\n                BinaryExpression assignExpr = Expression.Add(left, right, assign);\r\n                return assignExpr;\r\n#endif\r\n            }\r\n\r\n            private static class Assigner<T>\r\n            {\r\n                public static T Assign(ref T left, T right)\r\n                {\r\n                    return (left = right);\r\n                }\r\n            }\r\n\r\n#endif\r\n\r\n            public sealed class ThreadSafeDictionary<TKey, TValue> : IDictionary<TKey, TValue>\r\n            {\r\n                private readonly object _lock = new object();\r\n                private readonly ThreadSafeDictionaryValueFactory<TKey, TValue> _valueFactory;\r\n                private Dictionary<TKey, TValue> _dictionary;\r\n\r\n                public ThreadSafeDictionary(ThreadSafeDictionaryValueFactory<TKey, TValue> valueFactory)\r\n                {\r\n                    _valueFactory = valueFactory;\r\n                }\r\n\r\n                private TValue Get(TKey key)\r\n                {\r\n                    if (_dictionary == null)\r\n                        return AddValue(key);\r\n                    TValue value;\r\n                    if (!_dictionary.TryGetValue(key, out value))\r\n                        return AddValue(key);\r\n                    return value;\r\n                }\r\n\r\n                private TValue AddValue(TKey key)\r\n                {\r\n                    TValue value = _valueFactory(key);\r\n                    lock (_lock)\r\n                    {\r\n                        if (_dictionary == null)\r\n                        {\r\n                            _dictionary = new Dictionary<TKey, TValue>();\r\n                            _dictionary[key] = value;\r\n                        }\r\n                        else\r\n                        {\r\n                            TValue val;\r\n                            if (_dictionary.TryGetValue(key, out val))\r\n                                return val;\r\n                            Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>(_dictionary);\r\n                            dict[key] = value;\r\n                            _dictionary = dict;\r\n                        }\r\n                    }\r\n                    return value;\r\n                }\r\n\r\n                public void Add(TKey key, TValue value)\r\n                {\r\n                    throw new NotImplementedException();\r\n                }\r\n\r\n                public bool ContainsKey(TKey key)\r\n                {\r\n                    return _dictionary.ContainsKey(key);\r\n                }\r\n\r\n                public ICollection<TKey> Keys\r\n                {\r\n                    get { return _dictionary.Keys; }\r\n                }\r\n\r\n                public bool Remove(TKey key)\r\n                {\r\n                    throw new NotImplementedException();\r\n                }\r\n\r\n                public bool TryGetValue(TKey key, out TValue value)\r\n                {\r\n                    value = this[key];\r\n                    return true;\r\n                }\r\n\r\n                public ICollection<TValue> Values\r\n                {\r\n                    get { return _dictionary.Values; }\r\n                }\r\n\r\n                public TValue this[TKey key]\r\n                {\r\n                    get { return Get(key); }\r\n                    set { throw new NotImplementedException(); }\r\n                }\r\n\r\n                public void Add(KeyValuePair<TKey, TValue> item)\r\n                {\r\n                    throw new NotImplementedException();\r\n                }\r\n\r\n                public void Clear()\r\n                {\r\n                    throw new NotImplementedException();\r\n                }\r\n\r\n                public bool Contains(KeyValuePair<TKey, TValue> item)\r\n                {\r\n                    throw new NotImplementedException();\r\n                }\r\n\r\n                public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)\r\n                {\r\n                    throw new NotImplementedException();\r\n                }\r\n\r\n                public int Count\r\n                {\r\n                    get { return _dictionary.Count; }\r\n                }\r\n\r\n                public bool IsReadOnly\r\n                {\r\n                    get { throw new NotImplementedException(); }\r\n                }\r\n\r\n                public bool Remove(KeyValuePair<TKey, TValue> item)\r\n                {\r\n                    throw new NotImplementedException();\r\n                }\r\n\r\n                public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()\r\n                {\r\n                    return _dictionary.GetEnumerator();\r\n                }\r\n\r\n                System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\r\n                {\r\n                    return _dictionary.GetEnumerator();\r\n                }\r\n            }\r\n\r\n        }\r\n    }\r\n}\r\n// ReSharper restore LoopCanBeConvertedToQuery\r\n// ReSharper restore RedundantExplicitArrayCreation\r\n// ReSharper restore SuggestUseVarKeywordEvident\r\n"
  },
  {
    "path": "src/Nancy/Jsonp.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using System;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Text;\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Configuration;\r\n    using Nancy.Json;\r\n\r\n    /// <summary>\r\n    /// Handles JSONP requests.\r\n    /// </summary>\r\n    public static class Jsonp\r\n    {\r\n        private static readonly PipelineItem<Action<NancyContext>> JsonpItem;\r\n        private static Encoding encoding;\r\n\r\n        static Jsonp()\r\n        {\r\n            JsonpItem = new PipelineItem<Action<NancyContext>>(\"JSONP\", PrepareJsonp);\r\n        }\r\n\r\n        private static string Encoding\r\n        {\r\n            get { return string.Concat(\"; charset=\", encoding.WebName); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Enable JSONP support in the application\r\n        /// </summary>\r\n        /// <param name=\"pipelines\">Application Pipeline to Hook into</param>\r\n        /// <param name=\"environment\">An <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        public static void Enable(IPipelines pipelines, INancyEnvironment environment)\r\n        {\r\n            var jsonpEnabled = pipelines.AfterRequest.PipelineItems.Any(ctx => ctx.Name == \"JSONP\");\r\n\r\n            if (!jsonpEnabled)\r\n            {\r\n                encoding = environment.GetValue<JsonConfiguration>().DefaultEncoding;\r\n                pipelines.AfterRequest.AddItemToEndOfPipeline(JsonpItem);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Disable JSONP support in the application\r\n        /// </summary>\r\n        /// <param name=\"pipelines\">Application Pipeline to Hook into</param>\r\n        public static void Disable(IPipelines pipelines)\r\n        {\r\n            pipelines.AfterRequest.RemoveByName(\"JSONP\");\r\n        }\r\n\r\n        /// <summary>\r\n        /// Transmogrify original response and apply JSONP Padding\r\n        /// </summary>\r\n        /// <param name=\"context\">Current Nancy Context</param>\r\n        private static void PrepareJsonp(NancyContext context)\r\n        {\r\n            var isJson = Json.Json.IsJsonContentType(context.Response.ContentType);\r\n            bool hasCallback = context.Request.Query[\"callback\"].HasValue;\r\n\r\n            if (!isJson || !hasCallback)\r\n            {\r\n                return;\r\n            }\r\n\r\n            // grab original contents for running later\r\n            var original = context.Response.Contents;\r\n            string callback = context.Request.Query[\"callback\"].Value;\r\n\r\n            // set content type to application/javascript so browsers can handle it by default\r\n            // http://stackoverflow.com/questions/111302/best-content-type-to-serve-jsonp\r\n            context.Response.ContentType = string.Concat(\"application/javascript\", Encoding);\r\n\r\n            context.Response.Contents = stream =>\r\n            {\r\n                // disposing of stream is handled elsewhere\r\n                var writer = new StreamWriter(stream)\r\n                {\r\n                    AutoFlush = true\r\n                };\r\n\r\n                writer.Write(\"{0}(\", callback);\r\n                original(stream);\r\n                writer.Write(\");\");\r\n            };\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/JsonpApplicationStartup.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Configuration;\r\n\r\n    /// <summary>\r\n    /// Enables JSONP support at application startup.\r\n    /// </summary>\r\n    public class JsonpApplicationStartup : IApplicationStartup\r\n    {\r\n        private readonly INancyEnvironment environment;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"JsonpApplicationStartup\"/> class,\r\n        /// with the provided <see cref=\"INancyEnvironment\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"environment\">An <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        public JsonpApplicationStartup(INancyEnvironment environment)\r\n        {\r\n            this.environment = environment;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Perform any initialisation tasks\r\n        /// </summary>\r\n        /// <param name=\"pipelines\">Application pipelines</param>\r\n        public void Initialize(IPipelines pipelines)\r\n        {\r\n            Jsonp.Enable(pipelines, this.environment);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Localization/ITextResource.cs",
    "content": "namespace Nancy.Localization\r\n{\r\n    /// <summary>\r\n    /// Used to return string values\r\n    /// </summary>\r\n    public interface ITextResource\r\n    {\r\n        /// <summary>\r\n        /// Gets a translation based on the provided key.\r\n        /// </summary>\r\n        /// <param name=\"key\">The key to look up the translation for.</param>\r\n        /// <param name=\"context\">The current <see cref=\"NancyContext\"/> instance.</param>\r\n        string this[string key, NancyContext context] { get; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Localization/ResourceBasedTextResource.cs",
    "content": "namespace Nancy.Localization\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Resources;\r\n\r\n    /// <summary>\r\n    /// Resource based implementation of <see cref=\"ITextResource\"/>\r\n    /// </summary>\r\n    public class ResourceBasedTextResource  : ITextResource\r\n    {\r\n        private readonly IResourceAssemblyProvider resourceAssemblyProvider;\r\n        private readonly IDictionary<string, ResourceManager> resourceManagers;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of <see cref=\"ResourceBasedTextResource\"/> to read strings from *.resx files\r\n        /// </summary>\r\n        /// <param name=\"resourceAssemblyProvider\">The <see cref=\"IResourceAssemblyProvider\"/> that should be used when scanning.</param>\r\n        public ResourceBasedTextResource(IResourceAssemblyProvider resourceAssemblyProvider)\r\n        {\r\n            this.resourceAssemblyProvider = resourceAssemblyProvider;\r\n\r\n            var resources =\r\n                from assembly in this.resourceAssemblyProvider.GetAssembliesToScan()\r\n                from resourceName in assembly.GetManifestResourceNames()\r\n                where resourceName.EndsWith(\".resources\")\r\n                let name = Path.GetFileNameWithoutExtension(resourceName)\r\n                let baseName = resourceName.Replace(\".resources\", string.Empty)\r\n                select new\r\n                    {\r\n                        Name = name,\r\n                        Manager = new ResourceManager(baseName, assembly)\r\n                    };\r\n\r\n            this.resourceManagers = new Dictionary<string, ResourceManager>(StringComparer.OrdinalIgnoreCase);\r\n\r\n            foreach (var x in resources)\r\n            {\r\n                if (!this.resourceManagers.ContainsKey(x.Name))\r\n                {\r\n                    this.resourceManagers[x.Name] = x.Manager;\r\n                }\r\n                else\r\n                {\r\n                    throw new ArgumentException(string.Format(\"Key '{0}' already exists;\",x.Name));\r\n                }\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Used to return a string value from *.resx files\r\n        /// </summary>\r\n        /// <param name=\"key\">The key to look for in the resource file</param>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> used to determine the culture for returning culture specific values.</param>\r\n        /// <returns>Returns a string value from culture specific or default file or null if key does not exist as determined by <see cref=\"ResourceManager\"/>.</returns>\r\n        public string this[string key, NancyContext context]\r\n        {\r\n            get\r\n            {\r\n                var components =\r\n                    GetKeyComponents(key);\r\n\r\n                var candidates =\r\n                    this.resourceManagers.Where(\r\n                        x => x.Key.EndsWith(\".\" + components.Item1, StringComparison.OrdinalIgnoreCase)).ToArray();\r\n\r\n                if (candidates.Count() > 1)\r\n                {\r\n                    throw new InvalidOperationException(\"More than one text resources match the \" + components.Item1 + \" key. Try providing a more specific key.\");\r\n                }\r\n\r\n                var manager = candidates.Any() ?\r\n                    candidates.First().Value :\r\n                    null;\r\n\r\n                return (manager == null) ? null : manager.GetString(components.Item2, context.Culture);\r\n            }\r\n        }\r\n\r\n        private static Tuple<string, string> GetKeyComponents(string key)\r\n        {\r\n            var index =\r\n                key.LastIndexOf(\".\", StringComparison.Ordinal);\r\n\r\n            if (index == -1)\r\n            {\r\n                throw new InvalidOperationException(\"The text key needs to be specified in the format resourcename.resourcekey, where resourcename should at least be the name of the resource file and at most the fully qualified path.\");\r\n            }\r\n\r\n            return new Tuple<string, string>(\r\n                key.Substring(0, index),\r\n                key.Substring(index + 1));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Localization/TextResourceFinder.cs",
    "content": "﻿namespace Nancy.Localization\r\n{\r\n    using System;\r\n    using System.Dynamic;\r\n\r\n    /// <summary>\r\n    /// Returns text from an implemented ITextResource\r\n    /// </summary>\r\n    public class TextResourceFinder : DynamicObject\r\n    {\r\n        private readonly ITextResource textResource;\r\n        private readonly NancyContext context;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"TextResourceFinder\"/> class, with\r\n        /// the provided <paramref name=\"textResource\"/> and <paramref name=\"context\"/>.\r\n        /// </summary>\r\n        /// <param name=\"textResource\">The <see cref=\"ITextResource\"/> that should be used by the TextResourceFinder</param>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> that should be used by the TextResourceFinder</param>\r\n        public TextResourceFinder(ITextResource textResource, NancyContext context)\r\n        {\r\n            this.textResource = textResource;\r\n            this.context = context;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"ITextResource\"/> that is being used to locate texts.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"ITextResource\"/> instance.</value>\r\n        public ITextResource Resource\r\n        {\r\n            get { return this.textResource; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Finds text resource\r\n        /// </summary>\r\n        /// <param name=\"binder\">GetMemberBinder with dynamic text key</param>\r\n        /// <param name=\"result\">Text item</param>\r\n        /// <returns>Returns a value or a non existing value from the <see cref=\"ITextResource\"/> implementation</returns>\r\n        public override bool TryGetMember(GetMemberBinder binder, out object result)\r\n        {\r\n            result =\r\n                new DynamicMemberChainer(binder.Name, this.context, this.textResource);\r\n\r\n            return true;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a translation based on the provided key.\r\n        /// </summary>\r\n        /// <param name=\"key\">The key to look up the translation for.</param>\r\n        public string this[string key]\r\n        {\r\n            get\r\n            {\r\n                return this.textResource[key, this.context];\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Provides implementation for type conversion operations. Classes derived from the <see cref=\"T:System.Dynamic.DynamicObject\" /> class can override this method to specify dynamic behavior for operations that convert an object from one type to another.\r\n        /// </summary>\r\n        public class DynamicMemberChainer : DynamicObject\r\n        {\r\n            private string memberName;\r\n            private readonly NancyContext context;\r\n            private readonly ITextResource textResource;\r\n\r\n            /// <summary>\r\n            /// Initializes a new instance of the <see cref=\"DynamicMemberChainer\"/> class.\r\n            /// </summary>\r\n            /// <param name=\"memberName\">Name of the member.</param>\r\n            /// <param name=\"context\">The nancy context instance.</param>\r\n            /// <param name=\"resource\">The text resource instance.</param>\r\n            public DynamicMemberChainer(string memberName, NancyContext context, ITextResource resource)\r\n            {\r\n                this.memberName = memberName;\r\n                this.context = context;\r\n                this.textResource = resource;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Gets the member name concatenated to binder name.\r\n            /// </summary>\r\n            /// <param name=\"binder\">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member on which the dynamic operation is performed. For example, for the Console.WriteLine(sampleObject.SampleProperty) statement, where sampleObject is an instance of the class derived from the <see cref=\"T:System.Dynamic.DynamicObject\" /> class, binder.Name returns \"SampleProperty\". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param>\r\n            /// <param name=\"result\">The result of the get operation. For example, if the method is called for a property, you can assign the property value to <paramref name=\"result\" />.</param>\r\n            /// <returns>\r\n            /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a run-time exception is thrown.)\r\n            /// </returns>\r\n            public override bool TryGetMember(GetMemberBinder binder, out object result)\r\n            {\r\n                this.memberName =\r\n                    string.Concat(this.memberName, \".\", binder.Name);\r\n\r\n                result = this;\r\n\r\n                return true;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Attempts to convert provided member name and context to the text resource representation.\r\n            /// </summary>\r\n            /// <param name=\"binder\">Provides information about the conversion operation. The binder.Type property provides the type to which the object must be converted. For example, for the statement (String)sampleObject in C# (CType(sampleObject, Type) in Visual Basic), where sampleObject is an instance of the class derived from the <see cref=\"T:System.Dynamic.DynamicObject\" /> class, binder.Type returns the <see cref=\"T:System.String\" /> type. The binder.Explicit property provides information about the kind of conversion that occurs. It returns true for explicit conversion and false for implicit conversion.</param>\r\n            /// <param name=\"result\">The result of the type conversion operation.</param>\r\n            /// <returns>\r\n            /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.)\r\n            /// </returns>\r\n            /// <exception cref=\"System.InvalidOperationException\">Cannot cast dynamic member access to anything else than a string.</exception>\r\n            public override bool TryConvert(ConvertBinder binder, out object result)\r\n            {\r\n                if (binder.ReturnType == typeof(string))\r\n                {\r\n                    result = this.textResource[this.memberName, this.context];\r\n                    return true;\r\n                }\r\n\r\n                throw new InvalidOperationException(\"Cannot cast dynamic member access to anything else than a string.\");\r\n            }\r\n\r\n            /// <summary>\r\n            /// Returns a <see cref=\"System.String\" /> that represents this instance.\r\n            /// </summary>\r\n            /// <returns>\r\n            /// A <see cref=\"System.String\" /> that represents this instance.\r\n            /// </returns>\r\n            public override string ToString()\r\n            {\r\n                return this.textResource[this.memberName, this.context];\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/MimeTypes.cs",
    "content": "﻿//\r\n// Nancy.MimeTypes\r\n//\r\n// Authors:\r\n//\tGonzalo Paniagua Javier (gonzalo@ximian.com)\r\n//\r\n// (C) 2002 Ximian, Inc (http://www.ximian.com)\r\n// (C) 2003-2009 Novell, Inc (http://novell.com)\r\n\r\n//\r\n// Permission is hereby granted, free of charge, to any person obtaining\r\n// a copy of this software and associated documentation files (the\r\n// \"Software\"), to deal in the Software without restriction, including\r\n// without limitation the rights to use, copy, modify, merge, publish,\r\n// distribute, sublicense, and/or sell copies of the Software, and to\r\n// permit persons to whom the Software is furnished to do so, subject to\r\n// the following conditions:\r\n// \r\n// The above copyright notice and this permission notice shall be\r\n// included in all copies or substantial portions of the Software.\r\n// \r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\r\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\r\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\r\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\r\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n//\r\n\r\nnamespace Nancy\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Holds the MIME types\r\n    /// </summary>\r\n    public sealed class MimeTypes\r\n    {\r\n        static Dictionary <string, string> mimeTypes;\r\n\r\n        static MimeTypes ()\r\n        {\r\n            mimeTypes = new Dictionary <string, string> (StringComparer.OrdinalIgnoreCase);\r\n            mimeTypes.Add (\"323\", \"text/h323\");\r\n            mimeTypes.Add (\"3dmf\", \"x-world/x-3dmf\");\r\n            mimeTypes.Add (\"3dm\", \"x-world/x-3dmf\");\r\n            mimeTypes.Add (\"7z\", \"application/x-7z-compressed\");\r\n            mimeTypes.Add (\"aab\", \"application/x-authorware-bin\");\r\n            mimeTypes.Add (\"aam\", \"application/x-authorware-map\");\r\n            mimeTypes.Add (\"aas\", \"application/x-authorware-seg\");\r\n            mimeTypes.Add (\"abc\", \"text/vnd.abc\");\r\n            mimeTypes.Add (\"acgi\", \"text/html\");\r\n            mimeTypes.Add (\"acx\", \"application/internet-property-stream\");\r\n            mimeTypes.Add (\"afl\", \"video/animaflex\");\r\n            mimeTypes.Add (\"ai\", \"application/postscript\");\r\n            mimeTypes.Add (\"aif\", \"audio/aiff\");\r\n            mimeTypes.Add (\"aifc\", \"audio/aiff\");\r\n            mimeTypes.Add (\"aiff\", \"audio/aiff\");\r\n            mimeTypes.Add (\"aim\", \"application/x-aim\");\r\n            mimeTypes.Add (\"aip\", \"text/x-audiosoft-intra\");\r\n            mimeTypes.Add (\"ani\", \"application/x-navi-animation\");\r\n            mimeTypes.Add (\"aos\", \"application/x-nokia-9000-communicator-add-on-software\");\r\n            mimeTypes.Add (\"application\", \"application/x-ms-application\");\r\n            mimeTypes.Add (\"aps\", \"application/mime\");\r\n            mimeTypes.Add (\"art\", \"image/x-jg\");\r\n            mimeTypes.Add (\"asf\", \"video/x-ms-asf\");\r\n            mimeTypes.Add (\"asm\", \"text/x-asm\");\r\n            mimeTypes.Add (\"asp\", \"text/asp\");\r\n            mimeTypes.Add (\"asr\", \"video/x-ms-asf\");\r\n            mimeTypes.Add (\"asx\", \"application/x-mplayer2\");\r\n            mimeTypes.Add (\"atom\", \"application/atom.xml\");\r\n            mimeTypes.Add (\"atomcat\", \"application/atomcat+xml\");\r\n            mimeTypes.Add (\"atomsvc\", \"application/atomsvc+xml\");\r\n            mimeTypes.Add (\"au\", \"audio/x-au\");\r\n            mimeTypes.Add (\"avi\", \"video/avi\");\r\n            mimeTypes.Add (\"avs\", \"video/avs-video\");\r\n            mimeTypes.Add (\"axs\", \"application/olescript\");\r\n            mimeTypes.Add (\"bas\", \"text/plain\");\r\n            mimeTypes.Add (\"bcpio\", \"application/x-bcpio\");\r\n            mimeTypes.Add (\"bin\", \"application/octet-stream\");\r\n            mimeTypes.Add (\"bm\", \"image/bmp\");\r\n            mimeTypes.Add (\"bmp\", \"image/bmp\");\r\n            mimeTypes.Add (\"boo\", \"application/book\");\r\n            mimeTypes.Add (\"book\", \"application/book\");\r\n            mimeTypes.Add (\"boz\", \"application/x-bzip2\");\r\n            mimeTypes.Add (\"bsh\", \"application/x-bsh\");\r\n            mimeTypes.Add (\"bz2\", \"application/x-bzip2\");\r\n            mimeTypes.Add (\"bz\", \"application/x-bzip\");\r\n            mimeTypes.Add (\"cat\", \"application/vnd.ms-pki.seccat\");\r\n            mimeTypes.Add (\"ccad\", \"application/clariscad\");\r\n            mimeTypes.Add (\"cco\", \"application/x-cocoa\");\r\n            mimeTypes.Add (\"cc\", \"text/plain\");\r\n            mimeTypes.Add (\"cdf\", \"application/cdf\");\r\n            mimeTypes.Add (\"cer\", \"application/pkix-cert\");\r\n            mimeTypes.Add (\"cha\", \"application/x-chat\");\r\n            mimeTypes.Add (\"chat\", \"application/x-chat\");\r\n            mimeTypes.Add (\"class\", \"application/java\");\r\n            mimeTypes.Add (\"clp\", \"application/x-msclip\");\r\n            mimeTypes.Add (\"cmx\", \"image/x-cmx\");\r\n            mimeTypes.Add (\"cod\", \"image/cis-cod\");\r\n            mimeTypes.Add (\"conf\", \"text/plain\");\r\n            mimeTypes.Add (\"cpio\", \"application/x-cpio\");\r\n            mimeTypes.Add (\"cpp\", \"text/plain\");\r\n            mimeTypes.Add (\"cpt\", \"application/x-cpt\");\r\n            mimeTypes.Add (\"crd\", \"application/x-mscardfile\");\r\n            mimeTypes.Add (\"crl\", \"application/pkix-crl\");\r\n            mimeTypes.Add (\"crt\", \"application/pkix-cert\");\r\n            mimeTypes.Add (\"csh\", \"application/x-csh\");\r\n            mimeTypes.Add (\"css\", \"text/css\");\r\n            mimeTypes.Add (\"c\", \"text/plain\");\r\n            mimeTypes.Add (\"c++\", \"text/plain\");\r\n            mimeTypes.Add (\"cs\", \"text/plain\");\r\n            mimeTypes.Add (\"cxx\", \"text/plain\");\r\n            mimeTypes.Add (\"dcr\", \"application/x-director\");\r\n            mimeTypes.Add (\"deepv\", \"application/x-deepv\");\r\n            mimeTypes.Add (\"def\", \"text/plain\");\r\n            mimeTypes.Add (\"deploy\", \"application/octet-stream\");\r\n            mimeTypes.Add (\"der\", \"application/x-x509-ca-cert\");\r\n            mimeTypes.Add (\"dib\", \"image/bmp\");\r\n            mimeTypes.Add (\"dif\", \"video/x-dv\");\r\n            mimeTypes.Add (\"dir\", \"application/x-director\");\r\n            mimeTypes.Add (\"disco\", \"application/xml\");\r\n            mimeTypes.Add (\"dll\", \"application/x-msdownload\");\r\n            mimeTypes.Add (\"dl\", \"video/dl\");\r\n            mimeTypes.Add (\"doc\", \"application/msword\");\r\n            mimeTypes.Add (\"dot\", \"application/msword\");\r\n            mimeTypes.Add (\"dp\", \"application/commonground\");\r\n            mimeTypes.Add (\"drw\", \"application/drafting\");\r\n            mimeTypes.Add (\"dvi\", \"application/x-dvi\");\r\n            mimeTypes.Add (\"dv\", \"video/x-dv\");\r\n            mimeTypes.Add (\"dwf\", \"drawing/x-dwf (old)\");\r\n            mimeTypes.Add (\"dwg\", \"application/acad\");\r\n            mimeTypes.Add (\"dxf\", \"application/dxf\");\r\n            mimeTypes.Add (\"dxr\", \"application/x-director\");\r\n            mimeTypes.Add (\"elc\", \"application/x-elc\");\r\n            mimeTypes.Add (\"el\", \"text/x-script.elisp\");\r\n            mimeTypes.Add (\"eml\", \"message/rfc822\");\r\n            mimeTypes.Add (\"eot\", \"application/vnd.bw-fontobject\");\r\n            mimeTypes.Add (\"eps\", \"application/postscript\");\r\n            mimeTypes.Add (\"es\", \"application/x-esrehber\");\r\n            mimeTypes.Add (\"etx\", \"text/x-setext\");\r\n            mimeTypes.Add (\"evy\", \"application/envoy\");\r\n            mimeTypes.Add (\"exe\", \"application/octet-stream\");\r\n            mimeTypes.Add (\"f77\", \"text/plain\");\r\n            mimeTypes.Add (\"f90\", \"text/plain\");\r\n            mimeTypes.Add (\"fdf\", \"application/vnd.fdf\");\r\n            mimeTypes.Add (\"fif\", \"image/fif\");\r\n            mimeTypes.Add (\"fli\", \"video/fli\");\r\n            mimeTypes.Add (\"flo\", \"image/florian\");\r\n            mimeTypes.Add (\"flr\", \"x-world/x-vrml\");\r\n            mimeTypes.Add (\"flx\", \"text/vnd.fmi.flexstor\");\r\n            mimeTypes.Add (\"fmf\", \"video/x-atomic3d-feature\");\r\n            mimeTypes.Add (\"for\", \"text/plain\");\r\n            mimeTypes.Add (\"fpx\", \"image/vnd.fpx\");\r\n            mimeTypes.Add (\"frl\", \"application/freeloader\");\r\n            mimeTypes.Add (\"f\", \"text/plain\");\r\n            mimeTypes.Add (\"funk\", \"audio/make\");\r\n            mimeTypes.Add (\"g3\", \"image/g3fax\");\r\n            mimeTypes.Add (\"gadget\", \"application/x-windows-gadget\");\r\n            mimeTypes.Add (\"gif\", \"image/gif\");\r\n            mimeTypes.Add (\"gl\", \"video/gl\");\r\n            mimeTypes.Add (\"gsd\", \"audio/x-gsm\");\r\n            mimeTypes.Add (\"gsm\", \"audio/x-gsm\");\r\n            mimeTypes.Add (\"gsp\", \"application/x-gsp\");\r\n            mimeTypes.Add (\"gss\", \"application/x-gss\");\r\n            mimeTypes.Add (\"gtar\", \"application/x-gtar\");\r\n            mimeTypes.Add (\"g\", \"text/plain\");\r\n            mimeTypes.Add (\"gz\", \"application/x-gzip\");\r\n            mimeTypes.Add (\"gzip\", \"application/x-gzip\");\r\n            mimeTypes.Add (\"hdf\", \"application/x-hdf\");\r\n            mimeTypes.Add (\"help\", \"application/x-helpfile\");\r\n            mimeTypes.Add (\"hgl\", \"application/vnd.hp-HPGL\");\r\n            mimeTypes.Add (\"hh\", \"text/plain\");\r\n            mimeTypes.Add (\"hlb\", \"text/x-script\");\r\n            mimeTypes.Add (\"hlp\", \"application/x-helpfile\");\r\n            mimeTypes.Add (\"hpg\", \"application/vnd.hp-HPGL\");\r\n            mimeTypes.Add (\"hpgl\", \"application/vnd.hp-HPGL\");\r\n            mimeTypes.Add (\"hqx\", \"application/binhex\");\r\n            mimeTypes.Add (\"hta\", \"application/hta\");\r\n            mimeTypes.Add (\"htc\", \"text/x-component\");\r\n            mimeTypes.Add (\"h\", \"text/plain\");\r\n            mimeTypes.Add (\"htmls\", \"text/html\");\r\n            mimeTypes.Add (\"html\", \"text/html\");\r\n            mimeTypes.Add (\"htm\", \"text/html\");\r\n            mimeTypes.Add (\"htt\", \"text/webviewhtml\");\r\n            mimeTypes.Add (\"htx\", \"text/html\");\r\n            mimeTypes.Add (\"ice\", \"x-conference/x-cooltalk\");\r\n            mimeTypes.Add (\"ico\", \"image/x-icon\");\r\n            mimeTypes.Add (\"idc\", \"text/plain\");\r\n            mimeTypes.Add (\"ief\", \"image/ief\");\r\n            mimeTypes.Add (\"iefs\", \"image/ief\");\r\n            mimeTypes.Add (\"iges\", \"application/iges\");\r\n            mimeTypes.Add (\"igs\", \"application/iges\");\r\n            mimeTypes.Add (\"iii\", \"application/x-iphone\");\r\n            mimeTypes.Add (\"ima\", \"application/x-ima\");\r\n            mimeTypes.Add (\"imap\", \"application/x-httpd-imap\");\r\n            mimeTypes.Add (\"inf\", \"application/inf\");\r\n            mimeTypes.Add (\"ins\", \"application/x-internett-signup\");\r\n            mimeTypes.Add (\"ip\", \"application/x-ip2\");\r\n            mimeTypes.Add (\"isp\", \"application/x-internet-signup\");\r\n            mimeTypes.Add (\"isu\", \"video/x-isvideo\");\r\n            mimeTypes.Add (\"it\", \"audio/it\");\r\n            mimeTypes.Add (\"iv\", \"application/x-inventor\");\r\n            mimeTypes.Add (\"ivf\", \"video/x-ivf\");\r\n            mimeTypes.Add (\"ivr\", \"i-world/i-vrml\");\r\n            mimeTypes.Add (\"ivy\", \"application/x-livescreen\");\r\n            mimeTypes.Add (\"jam\", \"audio/x-jam\");\r\n            mimeTypes.Add (\"java\", \"text/plain\");\r\n            mimeTypes.Add (\"jav\", \"text/plain\");\r\n            mimeTypes.Add (\"jcm\", \"application/x-java-commerce\");\r\n            mimeTypes.Add (\"jfif\", \"image/jpeg\");\r\n            mimeTypes.Add (\"jfif-tbnl\", \"image/jpeg\");\r\n            mimeTypes.Add (\"jpeg\", \"image/jpeg\");\r\n            mimeTypes.Add (\"jpe\", \"image/jpeg\");\r\n            mimeTypes.Add (\"jpg\", \"image/jpeg\");\r\n            mimeTypes.Add (\"jps\", \"image/x-jps\");\r\n            mimeTypes.Add (\"js\", \"application/javascript\");\r\n            mimeTypes.Add (\"json\", \"application/json\");\r\n            mimeTypes.Add (\"jut\", \"image/jutvision\");\r\n            mimeTypes.Add (\"kar\", \"audio/midi\");\r\n            mimeTypes.Add (\"ksh\", \"text/x-script.ksh\");\r\n            mimeTypes.Add (\"la\", \"audio/nspaudio\");\r\n            mimeTypes.Add (\"lam\", \"audio/x-liveaudio\");\r\n            mimeTypes.Add (\"latex\", \"application/x-latex\");\r\n            mimeTypes.Add (\"less\", \"text/css\");\r\n            mimeTypes.Add (\"list\", \"text/plain\");\r\n            mimeTypes.Add (\"lma\", \"audio/nspaudio\");\r\n            mimeTypes.Add (\"log\", \"text/plain\");\r\n            mimeTypes.Add (\"lsp\", \"application/x-lisp\");\r\n            mimeTypes.Add (\"lst\", \"text/plain\");\r\n            mimeTypes.Add (\"lsx\", \"text/x-la-asf\");\r\n            mimeTypes.Add (\"ltx\", \"application/x-latex\");\r\n            mimeTypes.Add (\"m13\", \"application/x-msmediaview\");\r\n            mimeTypes.Add (\"m14\", \"application/x-msmediaview\");\r\n            mimeTypes.Add (\"m1v\", \"video/mpeg\");\r\n            mimeTypes.Add (\"m2a\", \"audio/mpeg\");\r\n            mimeTypes.Add (\"m2v\", \"video/mpeg\");\r\n            mimeTypes.Add (\"m3u\", \"audio/x-mpequrl\");\r\n            mimeTypes.Add (\"m4u\", \"video/x-mpegurl\");\r\n            mimeTypes.Add (\"m4v\", \"video/mp4\");\r\n            mimeTypes.Add (\"m4a\", \"audio/mp4\");\r\n            mimeTypes.Add (\"m4r\", \"audio/mp4\");\r\n            mimeTypes.Add (\"m4b\", \"audio/mp4\");\r\n            mimeTypes.Add (\"m4p\", \"audio/mp4\");\r\n            mimeTypes.Add (\"man\", \"application/x-troff-man\");\r\n            mimeTypes.Add (\"manifest\", \"application/x-ms-manifest\");\r\n            mimeTypes.Add (\"map\", \"application/x-navimap\");\r\n            mimeTypes.Add (\"mar\", \"text/plain\");\r\n            mimeTypes.Add (\"mbd\", \"application/mbedlet\");\r\n            mimeTypes.Add (\"mc$\", \"application/x-magic-cap-package-1.0\");\r\n            mimeTypes.Add (\"mcd\", \"application/mcad\");\r\n            mimeTypes.Add (\"mcf\", \"image/vasa\");\r\n            mimeTypes.Add (\"mcp\", \"application/netmc\");\r\n            mimeTypes.Add (\"mdb\", \"application/x-msaccess\");\r\n            mimeTypes.Add (\"me\", \"application/x-troff-me\");\r\n            mimeTypes.Add (\"mht\", \"message/rfc822\");\r\n            mimeTypes.Add (\"mhtml\", \"message/rfc822\");\r\n            mimeTypes.Add (\"mid\", \"audio/midi\");\r\n            mimeTypes.Add (\"midi\", \"audio/midi\");\r\n            mimeTypes.Add (\"mif\", \"application/x-mif\");\r\n            mimeTypes.Add (\"mime\", \"message/rfc822\");\r\n            mimeTypes.Add (\"mjf\", \"audio/x-vnd.AudioExplosion.MjuiceMediaFile\");\r\n            mimeTypes.Add (\"mjpg\", \"video/x-motion-jpeg\");\r\n            mimeTypes.Add (\"mm\", \"application/base64\");\r\n            mimeTypes.Add (\"mme\", \"application/base64\");\r\n            mimeTypes.Add (\"mny\", \"application/x-msmoney\");\r\n            mimeTypes.Add (\"mod\", \"audio/mod\");\r\n            mimeTypes.Add (\"moov\", \"video/quicktime\");\r\n            mimeTypes.Add (\"movie\", \"video/x-sgi-movie\");\r\n            mimeTypes.Add (\"mov\", \"video/quicktime\");\r\n            mimeTypes.Add (\"mp2\", \"video/mpeg\");\r\n            mimeTypes.Add (\"mp3\", \"audio/mpeg\");\r\n            mimeTypes.Add (\"mp4\", \"video/mp4\");\r\n            mimeTypes.Add (\"mp4v\", \"video/mp4\");\r\n            mimeTypes.Add (\"mpa\", \"audio/mpeg\");\r\n            mimeTypes.Add (\"mpc\", \"application/x-project\");\r\n            mimeTypes.Add (\"mpeg\", \"video/mpeg\");\r\n            mimeTypes.Add (\"mpe\", \"video/mpeg\");\r\n            mimeTypes.Add (\"mpga\", \"audio/mpeg\");\r\n            mimeTypes.Add (\"mpg\", \"video/mpeg\");\r\n            mimeTypes.Add (\"mpg4\", \"video/mp4\");\r\n            mimeTypes.Add (\"mpp\", \"application/vnd.ms-project\");\r\n            mimeTypes.Add (\"mpt\", \"application/x-project\");\r\n            mimeTypes.Add (\"mpv2\", \"video/mpeg\");\r\n            mimeTypes.Add (\"mpv\", \"application/x-project\");\r\n            mimeTypes.Add (\"mpx\", \"application/x-project\");\r\n            mimeTypes.Add (\"mrc\", \"application/marc\");\r\n            mimeTypes.Add (\"ms\", \"application/x-troff-ms\");\r\n            mimeTypes.Add (\"m\", \"text/plain\");\r\n            mimeTypes.Add (\"mvb\", \"application/x-msmediaview\");\r\n            mimeTypes.Add (\"mv\", \"video/x-sgi-movie\");\r\n            mimeTypes.Add (\"my\", \"audio/make\");\r\n            mimeTypes.Add (\"mzz\", \"application/x-vnd.AudioExplosion.mzz\");\r\n            mimeTypes.Add (\"nap\", \"image/naplps\");\r\n            mimeTypes.Add (\"naplps\", \"image/naplps\");\r\n            mimeTypes.Add (\"nc\", \"application/x-netcdf\");\r\n            mimeTypes.Add (\"ncm\", \"application/vnd.nokia.configuration-message\");\r\n            mimeTypes.Add (\"niff\", \"image/x-niff\");\r\n            mimeTypes.Add (\"nif\", \"image/x-niff\");\r\n            mimeTypes.Add (\"nix\", \"application/x-mix-transfer\");\r\n            mimeTypes.Add (\"nsc\", \"application/x-conference\");\r\n            mimeTypes.Add (\"nvd\", \"application/x-navidoc\");\r\n            mimeTypes.Add (\"nws\", \"message/rfc822\");\r\n            mimeTypes.Add (\"oda\", \"application/oda\");\r\n            mimeTypes.Add (\"ods\", \"application/oleobject\");\r\n            mimeTypes.Add (\"oga\", \"audio/ogg\");\r\n            mimeTypes.Add (\"ogg\", \"audio/ogg\");\r\n            mimeTypes.Add (\"ogv\", \"video/ogg\");\r\n            mimeTypes.Add (\"omc\", \"application/x-omc\");\r\n            mimeTypes.Add (\"omcd\", \"application/x-omcdatamaker\");\r\n            mimeTypes.Add (\"omcr\", \"application/x-omcregerator\");\r\n            mimeTypes.Add (\"otf\", \"application/x-font-otf\");\r\n            mimeTypes.Add (\"p10\", \"application/pkcs10\");\r\n            mimeTypes.Add (\"p12\", \"application/pkcs-12\");\r\n            mimeTypes.Add (\"p7a\", \"application/x-pkcs7-signature\");\r\n            mimeTypes.Add (\"p7b\", \"application/x-pkcs7-certificates\");\r\n            mimeTypes.Add (\"p7c\", \"application/pkcs7-mime\");\r\n            mimeTypes.Add (\"p7m\", \"application/pkcs7-mime\");\r\n            mimeTypes.Add (\"p7r\", \"application/x-pkcs7-certreqresp\");\r\n            mimeTypes.Add (\"p7s\", \"application/pkcs7-signature\");\r\n            mimeTypes.Add (\"part\", \"application/pro_eng\");\r\n            mimeTypes.Add (\"pas\", \"text/pascal\");\r\n            mimeTypes.Add (\"pbm\", \"image/x-portable-bitmap\");\r\n            mimeTypes.Add (\"pcl\", \"application/x-pcl\");\r\n            mimeTypes.Add (\"pct\", \"image/x-pict\");\r\n            mimeTypes.Add (\"pcx\", \"image/x-pcx\");\r\n            mimeTypes.Add (\"pdb\", \"chemical/x-pdb\");\r\n            mimeTypes.Add (\"pdf\", \"application/pdf\");\r\n            mimeTypes.Add (\"pfunk\", \"audio/make\");\r\n            mimeTypes.Add (\"pfx\", \"application/x-pkcs12\");\r\n            mimeTypes.Add (\"pgm\", \"image/x-portable-graymap\");\r\n            mimeTypes.Add (\"pic\", \"image/pict\");\r\n            mimeTypes.Add (\"pict\", \"image/pict\");\r\n            mimeTypes.Add (\"pkg\", \"application/x-newton-compatible-pkg\");\r\n            mimeTypes.Add (\"pko\", \"application/vnd.ms-pki.pko\");\r\n            mimeTypes.Add (\"pl\", \"text/plain\");\r\n            mimeTypes.Add (\"plx\", \"application/x-PiXCLscript\");\r\n            mimeTypes.Add (\"pm4\", \"application/x-pagemaker\");\r\n            mimeTypes.Add (\"pm5\", \"application/x-pagemaker\");\r\n            mimeTypes.Add (\"pma\", \"application/x-perfmon\");\r\n            mimeTypes.Add (\"pmc\", \"application/x-perfmon\");\r\n            mimeTypes.Add (\"pm\", \"image/x-xpixmap\");\r\n            mimeTypes.Add (\"pml\", \"application/x-perfmon\");\r\n            mimeTypes.Add (\"pmr\", \"application/x-perfmon\");\r\n            mimeTypes.Add (\"pmw\", \"application/x-perfmon\");\r\n            mimeTypes.Add (\"png\", \"image/png\");\r\n            mimeTypes.Add (\"pnm\", \"application/x-portable-anymap\");\r\n            mimeTypes.Add (\"pot\", \"application/mspowerpoint\");\r\n            mimeTypes.Add (\"pov\", \"model/x-pov\");\r\n            mimeTypes.Add (\"ppa\", \"application/vnd.ms-powerpoint\");\r\n            mimeTypes.Add (\"ppm\", \"image/x-portable-pixmap\");\r\n            mimeTypes.Add (\"pps\", \"application/mspowerpoint\");\r\n            mimeTypes.Add (\"ppt\", \"application/mspowerpoint\");\r\n            mimeTypes.Add (\"ppz\", \"application/mspowerpoint\");\r\n            mimeTypes.Add (\"pre\", \"application/x-freelance\");\r\n            mimeTypes.Add (\"prf\", \"application/pics-rules\");\r\n            mimeTypes.Add (\"prt\", \"application/pro_eng\");\r\n            mimeTypes.Add (\"ps\", \"application/postscript\");\r\n            mimeTypes.Add (\"p\", \"text/x-pascal\");\r\n            mimeTypes.Add (\"pub\", \"application/x-mspublisher\");\r\n            mimeTypes.Add (\"pvu\", \"paleovu/x-pv\");\r\n            mimeTypes.Add (\"pwz\", \"application/vnd.ms-powerpoint\");\r\n            mimeTypes.Add (\"pyc\", \"applicaiton/x-bytecode.python\");\r\n            mimeTypes.Add (\"py\", \"text/x-script.phyton\");\r\n            mimeTypes.Add (\"qcp\", \"audio/vnd.qcelp\");\r\n            mimeTypes.Add (\"qd3d\", \"x-world/x-3dmf\");\r\n            mimeTypes.Add (\"qd3\", \"x-world/x-3dmf\");\r\n            mimeTypes.Add (\"qif\", \"image/x-quicktime\");\r\n            mimeTypes.Add (\"qtc\", \"video/x-qtc\");\r\n            mimeTypes.Add (\"qtif\", \"image/x-quicktime\");\r\n            mimeTypes.Add (\"qti\", \"image/x-quicktime\");\r\n            mimeTypes.Add (\"qt\", \"video/quicktime\");\r\n            mimeTypes.Add (\"ra\", \"audio/x-pn-realaudio\");\r\n            mimeTypes.Add (\"ram\", \"audio/x-pn-realaudio\");\r\n            mimeTypes.Add (\"ras\", \"application/x-cmu-raster\");\r\n            mimeTypes.Add (\"rast\", \"image/cmu-raster\");\r\n            mimeTypes.Add (\"rexx\", \"text/x-script.rexx\");\r\n            mimeTypes.Add (\"rf\", \"image/vnd.rn-realflash\");\r\n            mimeTypes.Add (\"rgb\", \"image/x-rgb\");\r\n            mimeTypes.Add (\"rm\", \"application/vnd.rn-realmedia\");\r\n            mimeTypes.Add (\"rmi\", \"audio/mid\");\r\n            mimeTypes.Add (\"rmm\", \"audio/x-pn-realaudio\");\r\n            mimeTypes.Add (\"rmp\", \"audio/x-pn-realaudio\");\r\n            mimeTypes.Add (\"rng\", \"application/ringing-tones\");\r\n            mimeTypes.Add (\"rnx\", \"application/vnd.rn-realplayer\");\r\n            mimeTypes.Add (\"roff\", \"application/x-troff\");\r\n            mimeTypes.Add (\"rp\", \"image/vnd.rn-realpix\");\r\n            mimeTypes.Add (\"rpm\", \"audio/x-pn-realaudio-plugin\");\r\n            mimeTypes.Add (\"rss\", \"application/xml\");\r\n            mimeTypes.Add (\"rtf\", \"text/richtext\");\r\n            mimeTypes.Add (\"rt\", \"text/richtext\");\r\n            mimeTypes.Add (\"rtx\", \"text/richtext\");\r\n            mimeTypes.Add (\"rv\", \"video/vnd.rn-realvideo\");\r\n            mimeTypes.Add (\"s3m\", \"audio/s3m\");\r\n            mimeTypes.Add (\"sbk\", \"application/x-tbook\");\r\n            mimeTypes.Add (\"scd\", \"application/x-msschedule\");\r\n            mimeTypes.Add (\"scm\", \"application/x-lotusscreencam\");\r\n            mimeTypes.Add (\"sct\", \"text/scriptlet\");\r\n            mimeTypes.Add (\"sdml\", \"text/plain\");\r\n            mimeTypes.Add (\"sdp\", \"application/sdp\");\r\n            mimeTypes.Add (\"sdr\", \"application/sounder\");\r\n            mimeTypes.Add (\"sea\", \"application/sea\");\r\n            mimeTypes.Add (\"set\", \"application/set\");\r\n            mimeTypes.Add (\"setpay\", \"application/set-payment-initiation\");\r\n            mimeTypes.Add (\"setreg\", \"application/set-registration-initiation\");\r\n            mimeTypes.Add (\"sgml\", \"text/sgml\");\r\n            mimeTypes.Add (\"sgm\", \"text/sgml\");\r\n            mimeTypes.Add (\"shar\", \"application/x-bsh\");\r\n            mimeTypes.Add (\"sh\", \"text/x-script.sh\");\r\n            mimeTypes.Add (\"shtml\", \"text/html\");\r\n            mimeTypes.Add (\"sid\", \"audio/x-psid\");\r\n            mimeTypes.Add (\"sit\", \"application/x-sit\");\r\n            mimeTypes.Add (\"skd\", \"application/x-koan\");\r\n            mimeTypes.Add (\"skm\", \"application/x-koan\");\r\n            mimeTypes.Add (\"skp\", \"application/x-koan\");\r\n            mimeTypes.Add (\"skt\", \"application/x-koan\");\r\n            mimeTypes.Add (\"sl\", \"application/x-seelogo\");\r\n            mimeTypes.Add (\"smi\", \"application/smil\");\r\n            mimeTypes.Add (\"smil\", \"application/smil\");\r\n            mimeTypes.Add (\"snd\", \"audio/basic\");\r\n            mimeTypes.Add (\"sol\", \"application/solids\");\r\n            mimeTypes.Add (\"spc\", \"application/x-pkcs7-certificates\");\r\n            mimeTypes.Add (\"spl\", \"application/futuresplash\");\r\n            mimeTypes.Add (\"spr\", \"application/x-sprite\");\r\n            mimeTypes.Add (\"sprite\", \"application/x-sprite\");\r\n            mimeTypes.Add (\"spx\", \"audio/ogg\");\r\n            mimeTypes.Add (\"src\", \"application/x-wais-source\");\r\n            mimeTypes.Add (\"ssi\", \"text/x-server-parsed-html\");\r\n            mimeTypes.Add (\"ssm\", \"application/streamingmedia\");\r\n            mimeTypes.Add (\"sst\", \"application/vnd.ms-pki.certstore\");\r\n            mimeTypes.Add (\"step\", \"application/step\");\r\n            mimeTypes.Add (\"s\", \"text/x-asm\");\r\n            mimeTypes.Add (\"stl\", \"application/sla\");\r\n            mimeTypes.Add (\"stm\", \"text/html\");\r\n            mimeTypes.Add (\"stp\", \"application/step\");\r\n            mimeTypes.Add (\"sv4cpio\", \"application/x-sv4cpio\");\r\n            mimeTypes.Add (\"sv4crc\", \"application/x-sv4crc\");\r\n            mimeTypes.Add (\"svf\", \"image/x-dwg\");\r\n            mimeTypes.Add (\"svg\", \"image/svg+xml\");\r\n            mimeTypes.Add (\"svgz\", \"image/svg+xml\");\r\n            mimeTypes.Add (\"svr\", \"application/x-world\");\r\n            mimeTypes.Add (\"swf\", \"application/x-shockwave-flash\");\r\n            mimeTypes.Add (\"talk\", \"text/x-speech\");\r\n            mimeTypes.Add (\"t\", \"application/x-troff\");\r\n            mimeTypes.Add (\"tar\", \"application/x-tar\");\r\n            mimeTypes.Add (\"tbk\", \"application/toolbook\");\r\n            mimeTypes.Add (\"tcl\", \"text/x-script.tcl\");\r\n            mimeTypes.Add (\"tcsh\", \"text/x-script.tcsh\");\r\n            mimeTypes.Add (\"tex\", \"application/x-tex\");\r\n            mimeTypes.Add (\"texi\", \"application/x-texinfo\");\r\n            mimeTypes.Add (\"texinfo\", \"application/x-texinfo\");\r\n            mimeTypes.Add (\"text\", \"text/plain\");\r\n            mimeTypes.Add (\"tgz\", \"application/x-compressed\");\r\n            mimeTypes.Add (\"tiff\", \"image/tiff\");\r\n            mimeTypes.Add (\"tif\", \"image/tiff\");\r\n            mimeTypes.Add (\"torrent\", \"application/x-bittorrent\");\r\n            mimeTypes.Add (\"tr\", \"application/x-troff\");\r\n            mimeTypes.Add (\"trm\", \"application/x-msterminal\");\r\n            mimeTypes.Add (\"tsi\", \"audio/tsp-audio\");\r\n            mimeTypes.Add (\"tsp\", \"audio/tsplayer\");\r\n            mimeTypes.Add (\"tsv\", \"text/tab-separated-values\");\r\n            mimeTypes.Add (\"ttf\", \"application/x-font-ttf\");\r\n            mimeTypes.Add (\"turbot\", \"image/florian\");\r\n            mimeTypes.Add (\"txt\", \"text/plain\");\r\n            mimeTypes.Add (\"uil\", \"text/x-uil\");\r\n            mimeTypes.Add (\"uls\", \"text/iuls\");\r\n            mimeTypes.Add (\"unis\", \"text/uri-list\");\r\n            mimeTypes.Add (\"uni\", \"text/uri-list\");\r\n            mimeTypes.Add (\"unv\", \"application/i-deas\");\r\n            mimeTypes.Add (\"uris\", \"text/uri-list\");\r\n            mimeTypes.Add (\"uri\", \"text/uri-list\");\r\n            mimeTypes.Add (\"ustar\", \"multipart/x-ustar\");\r\n            mimeTypes.Add (\"uue\", \"text/x-uuencode\");\r\n            mimeTypes.Add (\"uu\", \"text/x-uuencode\");\r\n            mimeTypes.Add (\"vcd\", \"application/x-cdlink\");\r\n            mimeTypes.Add (\"vcf\", \"text/x-vcard\");\r\n            mimeTypes.Add (\"vcs\", \"text/x-vCalendar\");\r\n            mimeTypes.Add (\"vda\", \"application/vda\");\r\n            mimeTypes.Add (\"vdo\", \"video/vdo\");\r\n            mimeTypes.Add (\"vew\", \"application/groupwise\");\r\n            mimeTypes.Add (\"vivo\", \"video/vivo\");\r\n            mimeTypes.Add (\"viv\", \"video/vivo\");\r\n            mimeTypes.Add (\"vmd\", \"application/vocaltec-media-desc\");\r\n            mimeTypes.Add (\"vmf\", \"application/vocaltec-media-file\");\r\n            mimeTypes.Add (\"voc\", \"audio/voc\");\r\n            mimeTypes.Add (\"vos\", \"video/vosaic\");\r\n            mimeTypes.Add (\"vox\", \"audio/voxware\");\r\n            mimeTypes.Add (\"vqe\", \"audio/x-twinvq-plugin\");\r\n            mimeTypes.Add (\"vqf\", \"audio/x-twinvq\");\r\n            mimeTypes.Add (\"vql\", \"audio/x-twinvq-plugin\");\r\n            mimeTypes.Add (\"vrml\", \"application/x-vrml\");\r\n            mimeTypes.Add (\"vrt\", \"x-world/x-vrt\");\r\n            mimeTypes.Add (\"vsd\", \"application/x-visio\");\r\n            mimeTypes.Add (\"vst\", \"application/x-visio\");\r\n            mimeTypes.Add (\"vsw\", \"application/x-visio\");\r\n            mimeTypes.Add (\"w60\", \"application/wordperfect6.0\");\r\n            mimeTypes.Add (\"w61\", \"application/wordperfect6.1\");\r\n            mimeTypes.Add (\"w6w\", \"application/msword\");\r\n            mimeTypes.Add (\"wav\", \"audio/wav\");\r\n            mimeTypes.Add (\"wb1\", \"application/x-qpro\");\r\n            mimeTypes.Add (\"wbmp\", \"image/vnd.wap.wbmp\");\r\n            mimeTypes.Add (\"wcm\", \"application/vnd.ms-works\");\r\n            mimeTypes.Add (\"wdb\", \"application/vnd.ms-works\");\r\n            mimeTypes.Add (\"web\", \"application/vnd.xara\");\r\n            mimeTypes.Add (\"webm\", \"video/webm\");\r\n            mimeTypes.Add (\"wiz\", \"application/msword\");\r\n            mimeTypes.Add (\"wk1\", \"application/x-123\");\r\n            mimeTypes.Add (\"wks\", \"application/vnd.ms-works\");\r\n            mimeTypes.Add (\"wmf\", \"windows/metafile\");\r\n            mimeTypes.Add (\"wmlc\", \"application/vnd.wap.wmlc\");\r\n            mimeTypes.Add (\"wmlsc\", \"application/vnd.wap.wmlscriptc\");\r\n            mimeTypes.Add (\"wmls\", \"text/vnd.wap.wmlscript\");\r\n            mimeTypes.Add (\"wml\", \"text/vnd.wap.wml\");\r\n            mimeTypes.Add (\"woff\", \"application/font-woff\");\r\n            mimeTypes.Add (\"word\", \"application/msword\");\r\n            mimeTypes.Add (\"wp5\", \"application/wordperfect\");\r\n            mimeTypes.Add (\"wp6\", \"application/wordperfect\");\r\n            mimeTypes.Add (\"wp\", \"application/wordperfect\");\r\n            mimeTypes.Add (\"wpd\", \"application/wordperfect\");\r\n            mimeTypes.Add (\"wps\", \"application/vnd.ms-works\");\r\n            mimeTypes.Add (\"wq1\", \"application/x-lotus\");\r\n            mimeTypes.Add (\"wri\", \"application/mswrite\");\r\n            mimeTypes.Add (\"wrl\", \"application/x-world\");\r\n            mimeTypes.Add (\"wrz\", \"model/vrml\");\r\n            mimeTypes.Add (\"wsc\", \"text/scriplet\");\r\n            mimeTypes.Add (\"wsdl\", \"application/xml\");\r\n            mimeTypes.Add (\"wsrc\", \"application/x-wais-source\");\r\n            mimeTypes.Add (\"wtk\", \"application/x-wintalk\");\r\n            mimeTypes.Add (\"xaf\", \"x-world/x-vrml\");\r\n            mimeTypes.Add (\"xaml\", \"application/xaml+xml\");\r\n            mimeTypes.Add (\"xap\", \"application/x-silverlight-app\");\r\n            mimeTypes.Add (\"xbap\", \"application/x-ms-xbap\");\r\n            mimeTypes.Add (\"xbm\", \"image/x-xbitmap\");\r\n            mimeTypes.Add (\"xdr\", \"video/x-amt-demorun\");\r\n            mimeTypes.Add (\"xgz\", \"xgl/drawing\");\r\n            mimeTypes.Add (\"xhtml\", \"application/xhtml+xml\");\r\n            mimeTypes.Add (\"xht\", \"application/xhtml+xml\");\r\n            mimeTypes.Add (\"xif\", \"image/vnd.xiff\");\r\n            mimeTypes.Add (\"xla\", \"application/excel\");\r\n            mimeTypes.Add (\"xl\", \"application/excel\");\r\n            mimeTypes.Add (\"xlb\", \"application/excel\");\r\n            mimeTypes.Add (\"xlc\", \"application/excel\");\r\n            mimeTypes.Add (\"xld\", \"application/excel\");\r\n            mimeTypes.Add (\"xlk\", \"application/excel\");\r\n            mimeTypes.Add (\"xll\", \"application/excel\");\r\n            mimeTypes.Add (\"xlm\", \"application/excel\");\r\n            mimeTypes.Add (\"xls\", \"application/excel\");\r\n            mimeTypes.Add (\"xlt\", \"application/excel\");\r\n            mimeTypes.Add (\"xlv\", \"application/excel\");\r\n            mimeTypes.Add (\"xlw\", \"application/excel\");\r\n            mimeTypes.Add (\"xm\", \"audio/xm\");\r\n            mimeTypes.Add (\"xml\", \"application/xml\");\r\n            mimeTypes.Add (\"xmz\", \"xgl/movie\");\r\n            mimeTypes.Add (\"xof\", \"x-world/x-vrml\");\r\n            mimeTypes.Add (\"xpi\", \"application/x-xpinstall\");\r\n            mimeTypes.Add (\"xpix\", \"application/x-vnd.ls-xpix\");\r\n            mimeTypes.Add (\"xpm\", \"image/xpm\");\r\n            mimeTypes.Add (\"x-png\", \"image/png\");\r\n            mimeTypes.Add (\"xsd\", \"application/xml\");\r\n            mimeTypes.Add (\"xsl\", \"application/xml\");\r\n            mimeTypes.Add (\"xsr\", \"video/x-amt-showrun\");\r\n            mimeTypes.Add (\"xwd\", \"image/x-xwd\");\r\n            mimeTypes.Add (\"xyz\", \"chemical/x-pdb\");\r\n            mimeTypes.Add (\"z\", \"application/x-compressed\");\r\n            mimeTypes.Add (\"zip\", \"application/zip\");\r\n            mimeTypes.Add (\"zsh\", \"text/x-script.zsh\");\r\n\r\n            // Office Formats\r\n            mimeTypes.Add(\"docm\", \"application/vnd.ms-word.document.macroEnabled.12\");\r\n            mimeTypes.Add(\"docx\", \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\");\r\n            mimeTypes.Add(\"dotm\", \"application/vnd.ms-word.template.macroEnabled.12\");\r\n            mimeTypes.Add(\"dotx\", \"application/vnd.openxmlformats-officedocument.wordprocessingml.template\");\r\n            mimeTypes.Add(\"potm\", \"application/vnd.ms-powerpoint.template.macroEnabled.12\");\r\n            mimeTypes.Add(\"potx\", \"application/vnd.openxmlformats-officedocument.presentationml.template\");\r\n            mimeTypes.Add(\"ppam\", \"application/vnd.ms-powerpoint.addin.macroEnabled.12\");\r\n            mimeTypes.Add(\"ppsm\", \"application/vnd.ms-powerpoint.slideshow.macroEnabled.12\");\r\n            mimeTypes.Add(\"ppsx\", \"application/vnd.openxmlformats-officedocument.presentationml.slideshow\");\r\n            mimeTypes.Add(\"pptm\", \"application/vnd.ms-powerpoint.presentation.macroEnabled.12\");\r\n            mimeTypes.Add(\"pptx\", \"application/vnd.openxmlformats-officedocument.presentationml.presentation\");\r\n            mimeTypes.Add(\"xlam\", \"application/vnd.ms-excel.addin.macroEnabled.12\");\r\n            mimeTypes.Add(\"xlsb\", \"application/vnd.ms-excel.sheet.binary.macroEnabled.12\");\r\n            mimeTypes.Add(\"xlsm\", \"application/vnd.ms-excel.sheet.macroEnabled.12\");\r\n            mimeTypes.Add(\"xlsx\", \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\");\r\n            mimeTypes.Add(\"xltm\", \"application/vnd.ms-excel.template.macroEnabled.12\");\r\n            mimeTypes.Add(\"xltx\", \"application/vnd.openxmlformats-officedocument.spreadsheetml.template\");\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds a new MIME type.\r\n        /// </summary>\r\n        /// <param name=\"extension\">File extension</param>\r\n        /// <param name=\"type\">MIME type</param>\r\n        public static void AddType(string extension, string type) \r\n        {\r\n            mimeTypes.Add(extension, type);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the MIME type for a file name.\r\n        /// </summary>\r\n        /// <param name=\"fileName\">Name of the file.</param>\r\n        /// <returns></returns>\r\n        public static string GetMimeType (string fileName)\r\n        {\r\n            string result = null;\r\n            int dot = fileName.LastIndexOf ('.');\r\n\r\n            if (dot != -1 && fileName.Length > dot + 1)\r\n                mimeTypes.TryGetValue (fileName.Substring (dot + 1), out result);\r\n\r\n            if (result == null)\r\n                result = \"application/octet-stream\";\r\n\r\n            return result;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/ModelBinding/BindingConfig.cs",
    "content": "﻿namespace Nancy.ModelBinding\r\n{\r\n    /// <summary>\r\n    /// Configurations that controls the behavior of the binder at runtime.\r\n    /// </summary>\r\n    public class BindingConfig\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"BindingConfig\"/> class.\r\n        /// </summary>\r\n        public BindingConfig()\r\n        {\r\n            this.Overwrite = true;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Binding configuration that permits that the binder overwrites non-default values.\r\n        /// </summary>\r\n        public static readonly BindingConfig NoOverwrite = new BindingConfig { Overwrite = false };\r\n\r\n        /// <summary>\r\n        /// Default binding configuration.\r\n        /// </summary>\r\n        public static readonly BindingConfig Default = new BindingConfig();\r\n\r\n        /// <summary>\r\n        /// Gets or sets whether the binder should be happy once it has bound to the request body. In this case,\r\n        /// request and context parameters will not be bound to. If there is no body and this option is enabled,\r\n        /// no binding will take place at all.\r\n        /// </summary>\r\n        /// <value><see langword=\"true\" /> if the binder will stop once the body has been bound, otherwise <see langword=\"false\" />.</value>\r\n        public bool BodyOnly { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets whether binding error should be ignored and the binder should continue with the next property.\r\n        /// </summary>\r\n        /// <remarks>Setting this property to <see langword=\"true\" /> means that no <see cref=\"ModelBindingException\"/> will be thrown if an error occurs.</remarks>\r\n        /// <value><see langword=\"true\" />If the binder should ignore errors, otherwise <see langword=\"false\" />.</value>\r\n        public bool IgnoreErrors { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets whether the binder is allowed to overwrite properties that does not have a default value.\r\n        /// </summary>\r\n        /// <value><see langword=\"true\" /> if the binder is allowed to overwrite non-default values, otherwise <see langword=\"false\" />.</value>\r\n        public bool Overwrite { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ModelBinding/BindingContext.cs",
    "content": "﻿namespace Nancy.ModelBinding\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Model binding context object\r\n    /// </summary>\r\n    public class BindingContext\r\n    {\r\n        /// <summary>\r\n        /// The binding configuration\r\n        /// </summary>\r\n        public BindingConfig Configuration { get; set; }\r\n\r\n        /// <summary>\r\n        /// Current Nancy context\r\n        /// </summary>\r\n        public NancyContext Context { get; set; }\r\n\r\n        /// <summary>\r\n        /// Binding destination type\r\n        /// </summary>\r\n        public Type DestinationType { get; set; }\r\n\r\n        /// <summary>\r\n        /// The generic type of a collection is only used when DestinationType is a enumerable.\r\n        /// </summary>\r\n        public Type GenericType { get; set; }\r\n\r\n        /// <summary>\r\n        /// The current model object (or null for body deserialization)\r\n        /// </summary>\r\n        public object Model { get; set; }\r\n\r\n        /// <summary>\r\n        /// DestinationType properties that are not black listed\r\n        /// </summary>\r\n        public IEnumerable<BindingMemberInfo> ValidModelBindingMembers { get; set; }\r\n\r\n        /// <summary>\r\n        /// The incoming data fields\r\n        /// </summary>\r\n        public IDictionary<string, string> RequestData { get; set; }\r\n\r\n        /// <summary>\r\n        /// Available type converters - user converters followed by any defaults\r\n        /// </summary>\r\n        public IEnumerable<ITypeConverter> TypeConverters { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ModelBinding/BindingDefaults.cs",
    "content": "namespace Nancy.ModelBinding\r\n{\r\n    using System.Collections.Generic;\r\n    using Nancy.Configuration;\r\n    using Nancy.ModelBinding.DefaultBodyDeserializers;\r\n    using Nancy.ModelBinding.DefaultConverters;\r\n\r\n    /// <summary>\r\n    /// Provides default binding converters/deserializers\r\n    /// The defaults have less precedence than any user supplied ones\r\n    /// </summary>\r\n    public class BindingDefaults\r\n    {\r\n        private readonly IEnumerable<ITypeConverter> defaultTypeConverters;\r\n        private readonly IEnumerable<IBodyDeserializer> defaultBodyDeserializers;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"BindingDefaults\"/> class,\r\n        /// with the provided <see cref=\"INancyEnvironment\"/>.\r\n        /// </summary>\r\n        /// <param name=\"environment\">An <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        public BindingDefaults(INancyEnvironment environment)\r\n        {\r\n            // Ordering is important - for now we will new just these up\r\n            // as the binding defaults class itself is replaceable if necessary,\r\n            // and none of defaults have any dependencies.\r\n            this.defaultTypeConverters = new ITypeConverter[]\r\n            {\r\n                new CollectionConverter(),\r\n                new FallbackConverter(),\r\n            };\r\n\r\n            this.defaultBodyDeserializers = new IBodyDeserializer[]\r\n            {\r\n                new JsonBodyDeserializer(environment),\r\n                new XmlBodyDeserializer()\r\n            };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the default type converters\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"ITypeConverter\"/> instances.</value>\r\n        public virtual IEnumerable<ITypeConverter> DefaultTypeConverters\r\n        {\r\n            get { return this.defaultTypeConverters; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the default type converters\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"IBodyDeserializer\"/> instances.</value>\r\n        public virtual IEnumerable<IBodyDeserializer> DefaultBodyDeserializers\r\n        {\r\n            get { return this.defaultBodyDeserializers; }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/ModelBinding/BindingMemberInfo.cs",
    "content": "﻿namespace Nancy.ModelBinding\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n\r\n    /// <summary>\r\n    /// Represents a bindable member of a type, which can be a property or a field.\r\n    /// </summary>\r\n    public class BindingMemberInfo\r\n    {\r\n        PropertyInfo propertyInfo;\r\n        FieldInfo fieldInfo;\r\n\r\n        /// <summary>\r\n        /// Gets a reference to the MemberInfo that this BindingMemberInfo represents. This can be a property or a field.\r\n        /// </summary>\r\n        public MemberInfo MemberInfo\r\n        {\r\n            get { return this.propertyInfo ?? (MemberInfo)this.fieldInfo; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the name of the property or field represented by this BindingMemberInfo.\r\n        /// </summary>\r\n        public string Name\r\n        {\r\n            get { return this.MemberInfo.Name; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the data type of the property or field represented by this BindingMemberInfo.\r\n        /// </summary>\r\n        public Type PropertyType\r\n        {\r\n            get\r\n            {\r\n                if (this.propertyInfo != null)\r\n                {\r\n                    return this.propertyInfo.PropertyType;\r\n                }\r\n                else\r\n                {\r\n                    return this.fieldInfo.FieldType;\r\n                }\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Constructs a BindingMemberInfo instance for a property.\r\n        /// </summary>\r\n        /// <param name=\"propertyInfo\">The bindable property to represent.</param>\r\n        public BindingMemberInfo(PropertyInfo propertyInfo)\r\n        {\r\n            if (propertyInfo == null)\r\n            {\r\n                throw new ArgumentNullException(\"propertyInfo\");\r\n            }\r\n\r\n            this.propertyInfo = propertyInfo;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Constructs a BindingMemberInfo instance for a field.\r\n        /// </summary>\r\n        /// <param name=\"fieldInfo\">The bindable field to represent.</param>\r\n        public BindingMemberInfo(FieldInfo fieldInfo)\r\n        {\r\n            if (fieldInfo == null)\r\n            {\r\n                throw new ArgumentNullException(\"fieldInfo\");\r\n            }\r\n\r\n            this.fieldInfo = fieldInfo;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the value from a specified object associated with the property or field represented by this BindingMemberInfo.\r\n        /// </summary>\r\n        /// <param name=\"sourceObject\">The object whose property or field should be retrieved.</param>\r\n        /// <returns>The value for this BindingMemberInfo's property or field in the specified object.</returns>\r\n        public object GetValue(object sourceObject)\r\n        {\r\n            if (this.propertyInfo != null)\r\n            {\r\n                return this.propertyInfo.GetValue(sourceObject, null);\r\n            }\r\n            else\r\n            {\r\n                return this.fieldInfo.GetValue(sourceObject);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Sets the value from a specified object associated with the property or field represented by this BindingMemberInfo.\r\n        /// </summary>\r\n        /// <param name=\"destinationObject\">The object whose property or field should be assigned.</param>\r\n        /// <param name=\"newValue\">The value to assign in the specified object to this BindingMemberInfo's property or field.</param>\r\n        public void SetValue(object destinationObject, object newValue)\r\n        {\r\n            if (this.propertyInfo != null)\r\n            {\r\n                this.propertyInfo.SetValue(destinationObject, newValue, null);\r\n            }\r\n            else\r\n            {\r\n                this.fieldInfo.SetValue(destinationObject, newValue);\r\n            }\r\n        }\r\n\r\n        /// <inherit-doc/>\r\n        public override bool Equals(object obj)\r\n        {\r\n            if (obj == null)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            var other = obj as BindingMemberInfo;\r\n\r\n            if (other == null)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            return this.MemberInfo.Equals(other.MemberInfo);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Compares two BindingMemberInfo's with eachother on their respective values rather then their reference\r\n        /// </summary>\r\n        /// <param name=\"obj\">the other BindingMemberInfo</param>\r\n        /// <returns>true when they are equal and false otherwise</returns>\r\n        public bool Equals(BindingMemberInfo obj)\r\n        {\r\n            if (obj == null)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            return this.MemberInfo.Equals(obj.MemberInfo);\r\n        }\r\n\r\n        /// <inherit-doc/>\r\n        public override int GetHashCode()\r\n        {\r\n            return this.MemberInfo.GetHashCode();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an enumerable sequence of bindable properties for the specified type.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The type to enumerate.</typeparam>\r\n        /// <returns>Bindable properties.</returns>\r\n        public static IEnumerable<BindingMemberInfo> Collect<T>()\r\n        {\r\n            return Collect(typeof(T));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an enumerable sequence of bindable properties for the specified type.\r\n        /// </summary>\r\n        /// <param name=\"type\">The type to enumerate.</param>\r\n        /// <returns>Bindable properties.</returns>\r\n        public static IEnumerable<BindingMemberInfo> Collect(Type type)\r\n        {\r\n            var fromProperties = type\r\n                .GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanRead && p.CanWrite)\r\n                .Where(property => !property.GetIndexParameters().Any())\r\n                .Select(property => new BindingMemberInfo(property));\r\n\r\n            var fromFields = type.GetFields(BindingFlags.Public | BindingFlags.Instance).Where(f => !f.IsInitOnly)\r\n                .Select(field => new BindingMemberInfo(field));\r\n\r\n            return fromProperties.Concat(fromFields);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/ModelBinding/DefaultBinder.cs",
    "content": "namespace Nancy.ModelBinding\r\n{\r\n    using System;\r\n    using System.Collections;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using System.Text.RegularExpressions;\r\n\r\n    using Nancy.Extensions;\r\n    using Nancy.Responses.Negotiation;\r\n\r\n    /// <summary>\r\n    /// Default binder - used as a fallback when a specific modelbinder\r\n    /// is not available.\r\n    /// </summary>\r\n    public class DefaultBinder : IBinder\r\n    {\r\n        private readonly IEnumerable<ITypeConverter> typeConverters;\r\n\r\n        private readonly IEnumerable<IBodyDeserializer> bodyDeserializers;\r\n\r\n        private readonly IFieldNameConverter fieldNameConverter;\r\n\r\n        private readonly BindingDefaults defaults;\r\n\r\n        private static readonly MethodInfo ToListMethodInfo = typeof(Enumerable).GetMethod(\"ToList\", BindingFlags.Public | BindingFlags.Static);\r\n        private static readonly MethodInfo ToArrayMethodInfo = typeof(Enumerable).GetMethod(\"ToArray\", BindingFlags.Public | BindingFlags.Static);\r\n        private static readonly Regex BracketRegex = new Regex(@\"\\[(\\d+)\\]\\z\", RegexOptions.Compiled);\r\n        private static readonly Regex UnderscoreRegex = new Regex(@\"_(\\d+)\\z\", RegexOptions.Compiled);\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultBinder\"/> class, with\r\n        /// the provided <paramref name=\"typeConverters\"/>, <paramref name=\"bodyDeserializers\"/>, \r\n        /// <paramref name=\"fieldNameConverter\"/> and <paramref name=\"defaults\"/>.\r\n        /// </summary>\r\n        /// <param name=\"typeConverters\">The type converters.</param>\r\n        /// <param name=\"bodyDeserializers\">The body deserializers.</param>\r\n        /// <param name=\"fieldNameConverter\">The field name converter.</param>\r\n        /// <param name=\"defaults\">The defaults for bindings.</param>\r\n        /// <exception cref=\"System.ArgumentNullException\">\r\n        /// typeConverters\r\n        /// or\r\n        /// bodyDeserializers\r\n        /// or\r\n        /// fieldNameConverter\r\n        /// or\r\n        /// defaults\r\n        /// </exception>\r\n        public DefaultBinder(IEnumerable<ITypeConverter> typeConverters, IEnumerable<IBodyDeserializer> bodyDeserializers, IFieldNameConverter fieldNameConverter, BindingDefaults defaults)\r\n        {\r\n            if (typeConverters == null)\r\n            {\r\n                throw new ArgumentNullException(\"typeConverters\");\r\n            }\r\n\r\n            if (bodyDeserializers == null)\r\n            {\r\n                throw new ArgumentNullException(\"bodyDeserializers\");\r\n            }\r\n\r\n            if (fieldNameConverter == null)\r\n            {\r\n                throw new ArgumentNullException(\"fieldNameConverter\");\r\n            }\r\n\r\n            if (defaults == null)\r\n            {\r\n                throw new ArgumentNullException(\"defaults\");\r\n            }\r\n\r\n            this.typeConverters = typeConverters;\r\n            this.bodyDeserializers = bodyDeserializers;\r\n            this.fieldNameConverter = fieldNameConverter;\r\n            this.defaults = defaults;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind to the given model type\r\n        /// </summary>\r\n        /// <param name=\"context\">Current context</param>\r\n        /// <param name=\"modelType\">Model type to bind to</param>\r\n        /// <param name=\"instance\">Optional existing instance</param>\r\n        /// <param name=\"configuration\">The <see cref=\"BindingConfig\"/> that should be applied during binding.</param>\r\n        /// <param name=\"blackList\">Blacklisted binding property names</param>\r\n        /// <returns>Bound model</returns>\r\n        public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList)\r\n        {\r\n            Type genericType = null;\r\n            if (modelType.IsArray() || modelType.IsCollection() || modelType.IsEnumerable())\r\n            {\r\n                //make sure it has a generic type\r\n                if (modelType.GetTypeInfo().IsGenericType)\r\n                {\r\n                    genericType = modelType.GetGenericArguments().FirstOrDefault();\r\n                }\r\n                else\r\n                {\r\n                    var ienumerable =\r\n                        modelType.GetInterfaces().Where(i => i.GetTypeInfo().IsGenericType).FirstOrDefault(\r\n                            i => i.GetGenericTypeDefinition() == typeof(IEnumerable<>));\r\n                    genericType = ienumerable == null ? null : ienumerable.GetGenericArguments().FirstOrDefault();\r\n                }\r\n\r\n                if (genericType == null)\r\n                {\r\n                    throw new ArgumentException(\"When modelType is an enumerable it must specify the type.\", \"modelType\");\r\n                }\r\n            }\r\n\r\n            var bindingContext =\r\n                this.CreateBindingContext(context, modelType, instance, configuration, blackList, genericType);\r\n\r\n            try\r\n            {\r\n                var bodyDeserializedModel = this.DeserializeRequestBody(bindingContext);\r\n                if (bodyDeserializedModel != null)\r\n                {\r\n                    UpdateModelWithDeserializedModel(bodyDeserializedModel, bindingContext);\r\n                }\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                if (!bindingContext.Configuration.IgnoreErrors)\r\n                {\r\n                    throw new ModelBindingException(modelType, innerException: exception);\r\n                }\r\n            }\r\n\r\n            var bindingExceptions = new List<PropertyBindingException>();\r\n\r\n            if (!bindingContext.Configuration.BodyOnly)\r\n            {\r\n                if (bindingContext.DestinationType.IsCollection() || bindingContext.DestinationType.IsArray() ||bindingContext.DestinationType.IsEnumerable())\r\n                {\r\n                    var loopCount = this.GetBindingListInstanceCount(context);\r\n                    var model = (IList)bindingContext.Model;\r\n                    for (var i = 0; i < loopCount; i++)\r\n                    {\r\n                        object genericinstance;\r\n                        if (model.Count > i)\r\n                        {\r\n                            genericinstance = model[i];\r\n                        }\r\n                        else\r\n                        {\r\n                            genericinstance = bindingContext.GenericType.CreateInstance();\r\n                            model.Add(genericinstance);\r\n                        }\r\n\r\n                        foreach (var modelProperty in bindingContext.ValidModelBindingMembers)\r\n                        {\r\n                            var existingCollectionValue = modelProperty.GetValue(genericinstance);\r\n\r\n                            var collectionStringValue = GetValue(modelProperty.Name, bindingContext, i);\r\n\r\n                            if (this.BindingValueIsValid(collectionStringValue, existingCollectionValue, modelProperty,\r\n                                                    bindingContext))\r\n                            {\r\n                                try\r\n                                {\r\n                                    BindValue(modelProperty, collectionStringValue, bindingContext, genericinstance);\r\n                                }\r\n                                catch (PropertyBindingException ex)\r\n                                {\r\n                                    bindingExceptions.Add(ex);\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    foreach (var modelProperty in bindingContext.ValidModelBindingMembers)\r\n                    {\r\n                        var existingValue = modelProperty.GetValue(bindingContext.Model);\r\n\r\n                        var stringValue = GetValue(modelProperty.Name, bindingContext);\r\n\r\n                        if (this.BindingValueIsValid(stringValue, existingValue, modelProperty, bindingContext))\r\n                        {\r\n                            try\r\n                            {\r\n                                BindValue(modelProperty, stringValue, bindingContext);\r\n                            }\r\n                            catch (PropertyBindingException ex)\r\n                            {\r\n                                bindingExceptions.Add(ex);\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n\r\n                if (bindingExceptions.Any() && !bindingContext.Configuration.IgnoreErrors)\r\n                {\r\n                    throw new ModelBindingException(modelType, bindingExceptions);\r\n                }\r\n            }\r\n\r\n            if (modelType.IsArray())\r\n            {\r\n                var generictoArrayMethod = ToArrayMethodInfo.MakeGenericMethod(new[] { genericType });\r\n                return generictoArrayMethod.Invoke(null, new[] { bindingContext.Model });\r\n            }\r\n            return bindingContext.Model;\r\n        }\r\n\r\n        private bool BindingValueIsValid(string bindingValue, object existingValue, BindingMemberInfo modelProperty, BindingContext bindingContext)\r\n        {\r\n            return (!string.IsNullOrEmpty(bindingValue) &&\r\n                    (IsDefaultValue(existingValue, modelProperty.PropertyType) ||\r\n                     bindingContext.Configuration.Overwrite));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the number of distinct indexes from context:\r\n        ///\r\n        /// i.e:\r\n        ///  IntProperty_5\r\n        ///  StringProperty_5\r\n        ///  IntProperty_7\r\n        ///  StringProperty_8\r\n        ///  You'll end up with a list of 3 matches: 5,7,8\r\n        ///\r\n        /// </summary>\r\n        /// <param name=\"context\">Current Context </param>\r\n        /// <returns>An int containing the number of elements</returns>\r\n        private int GetBindingListInstanceCount(NancyContext context)\r\n        {\r\n            var dictionary = context.Request.Form as IDictionary<string, object>;\r\n\r\n            if (dictionary == null)\r\n            {\r\n                return 0;\r\n            }\r\n\r\n            return dictionary.Keys.Select(IsMatch).Where(x => x != -1).Distinct().ToArray().Length;\r\n        }\r\n\r\n        private static int IsMatch(string item)\r\n        {\r\n            var bracketMatch = BracketRegex.Match(item);\r\n            if (bracketMatch.Success)\r\n            {\r\n                return int.Parse(bracketMatch.Groups[1].Value);\r\n            }\r\n\r\n            var underscoreMatch = UnderscoreRegex.Match(item);\r\n\r\n            if (underscoreMatch.Success)\r\n            {\r\n                return int.Parse(underscoreMatch.Groups[1].Value);\r\n            }\r\n\r\n            return -1;\r\n        }\r\n\r\n        private static void UpdateModelWithDeserializedModel(object bodyDeserializedModel, BindingContext bindingContext)\r\n        {\r\n            var bodyDeserializedModelType = bodyDeserializedModel.GetType();\r\n\r\n            if (bodyDeserializedModelType.GetTypeInfo().IsValueType)\r\n            {\r\n                bindingContext.Model = bodyDeserializedModel;\r\n                return;\r\n            }\r\n\r\n            if (bodyDeserializedModelType.IsCollection() || bodyDeserializedModelType.IsEnumerable() ||\r\n                bodyDeserializedModelType.IsArray())\r\n            {\r\n                var count = 0;\r\n\r\n                foreach (var o in (IEnumerable)bodyDeserializedModel)\r\n                {\r\n                    var model = (IList)bindingContext.Model;\r\n\r\n                    if (o.GetType().GetTypeInfo().IsValueType || o is string)\r\n                    {\r\n                        HandleValueTypeCollectionElement(model, count, o);\r\n                    }\r\n                    else\r\n                    {\r\n                        HandleReferenceTypeCollectionElement(bindingContext, model, count, o);\r\n                    }\r\n\r\n                    count++;\r\n                }\r\n            }\r\n            else\r\n            {\r\n                foreach (var modelProperty in bindingContext.ValidModelBindingMembers)\r\n                {\r\n                    var existingValue =\r\n                        modelProperty.GetValue(bindingContext.Model);\r\n\r\n                    if (IsDefaultValue(existingValue, modelProperty.PropertyType) || bindingContext.Configuration.Overwrite)\r\n                    {\r\n                        CopyValue(modelProperty, bodyDeserializedModel, bindingContext.Model);\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        private static void HandleValueTypeCollectionElement(IList model, int count, object o)\r\n        {\r\n            // If the instance specified in the binder contains the n-th element use that\r\n            if (model.Count > count)\r\n            {\r\n                return;\r\n            }\r\n\r\n            model.Add(o);\r\n        }\r\n\r\n        private static void HandleReferenceTypeCollectionElement(BindingContext bindingContext, IList model, int count, object o)\r\n        {\r\n            // If the instance specified in the binder contains the n-th element use that otherwise make a new one.\r\n            object genericTypeInstance;\r\n            if (model.Count > count)\r\n            {\r\n                genericTypeInstance = model[count];\r\n            }\r\n            else\r\n            {\r\n                genericTypeInstance = Activator.CreateInstance(bindingContext.GenericType);\r\n                model.Add(genericTypeInstance);\r\n            }\r\n\r\n            foreach (var modelProperty in bindingContext.ValidModelBindingMembers)\r\n            {\r\n                var existingValue = modelProperty.GetValue(genericTypeInstance);\r\n\r\n                if (IsDefaultValue(existingValue, modelProperty.PropertyType) || bindingContext.Configuration.Overwrite)\r\n                {\r\n                    CopyValue(modelProperty, o, genericTypeInstance);\r\n                }\r\n            }\r\n        }\r\n\r\n        private static void CopyValue(BindingMemberInfo modelProperty, object source, object destination)\r\n        {\r\n            var newValue = modelProperty.GetValue(source);\r\n\r\n            modelProperty.SetValue(destination, newValue);\r\n        }\r\n\r\n        private static bool IsDefaultValue(object existingValue, Type propertyType)\r\n        {\r\n            return propertyType.GetTypeInfo().IsValueType\r\n                ? Equals(existingValue, Activator.CreateInstance(propertyType))\r\n                : existingValue == null;\r\n        }\r\n\r\n        private BindingContext CreateBindingContext(NancyContext context, Type modelType, object instance, BindingConfig configuration, IEnumerable<string> blackList, Type genericType)\r\n        {\r\n            return new BindingContext\r\n            {\r\n                Configuration = configuration,\r\n                Context = context,\r\n                DestinationType = modelType,\r\n                Model = CreateModel(modelType, genericType, instance),\r\n                ValidModelBindingMembers = GetBindingMembers(modelType, genericType, blackList).ToList(),\r\n                RequestData = this.GetDataFields(context),\r\n                GenericType = genericType,\r\n                TypeConverters = this.typeConverters.Concat(this.defaults.DefaultTypeConverters),\r\n            };\r\n        }\r\n\r\n        private IDictionary<string, string> GetDataFields(NancyContext context)\r\n        {\r\n            var dictionaries = new IDictionary<string, string>[]\r\n                {\r\n                    ConvertDynamicDictionary(context.Request.Form),\r\n                    ConvertDynamicDictionary(context.Request.Query),\r\n                    ConvertDynamicDictionary(context.Parameters)\r\n                };\r\n\r\n            return dictionaries.Merge();\r\n        }\r\n\r\n        private IDictionary<string, string> ConvertDynamicDictionary(DynamicDictionary dictionary)\r\n        {\r\n            if (dictionary == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            return dictionary.GetDynamicMemberNames().ToDictionary(\r\n                    memberName => this.fieldNameConverter.Convert(memberName),\r\n                    memberName => (string)dictionary[memberName]);\r\n        }\r\n\r\n        private static void BindValue(BindingMemberInfo modelProperty, string stringValue, BindingContext context)\r\n        {\r\n            BindValue(modelProperty, stringValue, context, context.Model);\r\n        }\r\n\r\n        private static void BindValue(BindingMemberInfo modelProperty, string stringValue, BindingContext context, object targetInstance)\r\n        {\r\n            var destinationType = modelProperty.PropertyType;\r\n\r\n            var typeConverter =\r\n                context.TypeConverters.FirstOrDefault(c => c.CanConvertTo(destinationType, context));\r\n\r\n            if (typeConverter != null)\r\n            {\r\n                try\r\n                {\r\n                    SetBindingMemberValue(modelProperty, targetInstance, typeConverter.Convert(stringValue, destinationType, context));\r\n                }\r\n                catch (Exception e)\r\n                {\r\n                    throw new PropertyBindingException(modelProperty.Name, stringValue, e);\r\n                }\r\n            }\r\n            else if (destinationType == typeof(string))\r\n            {\r\n                SetBindingMemberValue(modelProperty, targetInstance, stringValue);\r\n            }\r\n        }\r\n\r\n        private static void SetBindingMemberValue(BindingMemberInfo modelProperty, object model, object value)\r\n        {\r\n            // TODO - catch reflection exceptions?\r\n            modelProperty.SetValue(model, value);\r\n        }\r\n\r\n        private static IEnumerable<BindingMemberInfo> GetBindingMembers(Type modelType, Type genericType, IEnumerable<string> blackList)\r\n        {\r\n            var blackListHash = new HashSet<string>(blackList, StringComparer.Ordinal);\r\n\r\n            return BindingMemberInfo.Collect(genericType ?? modelType)\r\n                .Where(member => !blackListHash.Contains(member.Name));\r\n        }\r\n\r\n        private static object CreateModel(Type modelType, Type genericType, object instance)\r\n        {\r\n            if (modelType.IsArray() || modelType.IsCollection() || modelType.IsEnumerable())\r\n            {\r\n                //make sure instance has a Add method. Otherwise call `.ToList`\r\n                if (instance != null && modelType.IsInstanceOfType(instance))\r\n                {\r\n                    var addMethod = modelType.GetMethod(\"Add\", BindingFlags.Public | BindingFlags.Instance);\r\n                    if (addMethod != null)\r\n                    {\r\n                        return instance;\r\n                    }\r\n                    var genericMethod = ToListMethodInfo.MakeGenericMethod(genericType);\r\n                    return genericMethod.Invoke(null, new[] { instance });\r\n                }\r\n\r\n                //else just make a list\r\n                var listType = typeof(List<>).MakeGenericType(genericType);\r\n                return Activator.CreateInstance(listType);\r\n            }\r\n\r\n            if (instance == null)\r\n            {\r\n                return modelType.CreateInstance(true);\r\n            }\r\n\r\n            return !modelType.IsInstanceOfType(instance) ?\r\n                modelType.CreateInstance(true) :\r\n                instance;\r\n        }\r\n\r\n        private static string GetValue(string propertyName, BindingContext context, int index = -1)\r\n        {\r\n            if (index != -1)\r\n            {\r\n\r\n                var indexindexes = context.RequestData.Keys.Select(IsMatch)\r\n                                           .Where(i => i != -1)\r\n                                           .OrderBy(i => i)\r\n                                           .Distinct()\r\n                                           .Select((k, i) => new KeyValuePair<int, int>(i, k))\r\n                                           .ToDictionary(k => k.Key, v => v.Value);\r\n                int indexValue;\r\n                if (indexindexes.TryGetValue(index, out indexValue))\r\n                {\r\n                    var propertyValue =\r\n                        context.RequestData.Where(c =>\r\n                        {\r\n                            var indexId = IsMatch(c.Key);\r\n                            return c.Key.StartsWith(propertyName, StringComparison.OrdinalIgnoreCase) && indexId != -1 && indexId == indexValue;\r\n                        })\r\n                        .Select(k => k.Value)\r\n                        .FirstOrDefault();\r\n\r\n                    return propertyValue ?? string.Empty;\r\n                }\r\n\r\n                return string.Empty;\r\n            }\r\n\r\n            string value;\r\n            return context.RequestData.TryGetValue(propertyName, out value) ? value : string.Empty;\r\n        }\r\n\r\n        private object DeserializeRequestBody(BindingContext context)\r\n        {\r\n            if (context.Context == null || context.Context.Request == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            var contentType = GetRequestContentType(context.Context);\r\n\r\n            if (contentType == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            var bodyDeserializer = this.bodyDeserializers.FirstOrDefault(b => b.CanDeserialize(contentType, context))\r\n                ?? this.defaults.DefaultBodyDeserializers.FirstOrDefault(b => b.CanDeserialize(contentType, context));\r\n\r\n            return bodyDeserializer != null\r\n                ? bodyDeserializer.Deserialize(contentType, context.Context.Request.Body, context)\r\n                : null;\r\n        }\r\n\r\n        private static MediaRange GetRequestContentType(NancyContext context)\r\n        {\r\n            if (context == null || context.Request == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            return context.Request.Headers.ContentType;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/ModelBinding/DefaultBodyDeserializers/JsonBodyDeserializer.cs",
    "content": "namespace Nancy.ModelBinding.DefaultBodyDeserializers\r\n{\r\n    using System.IO;\r\n    using System.Reflection;\r\n    using Nancy.Configuration;\r\n    using Nancy.Json;\r\n    using Nancy.Responses.Negotiation;\r\n\r\n    /// <summary>\r\n    /// Deserializes request bodies in JSON format\r\n    /// </summary>\r\n    public class JsonBodyDeserializer : IBodyDeserializer\r\n    {\r\n        private readonly MethodInfo deserializeMethod = typeof(JavaScriptSerializer).GetMethod(\"Deserialize\", BindingFlags.Instance | BindingFlags.Public);\r\n        private readonly JsonConfiguration jsonConfiguration;\r\n        private readonly GlobalizationConfiguration globalizationConfiguration;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"JsonBodyDeserializer\"/>,\r\n        /// with the provided <paramref name=\"environment\"/>.\r\n        /// </summary>\r\n        /// <param name=\"environment\">An <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        public JsonBodyDeserializer(INancyEnvironment environment)\r\n        {\r\n            this.jsonConfiguration = environment.GetValue<JsonConfiguration>();\r\n            this.globalizationConfiguration = environment.GetValue<GlobalizationConfiguration>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Whether the deserializer can deserialize the content type\r\n        /// </summary>\r\n        /// <param name=\"mediaRange\">Content type to deserialize</param>\r\n        /// <param name=\"context\">Current <see cref=\"BindingContext\"/>.</param>\r\n        /// <returns>True if supported, false otherwise</returns>\r\n        public bool CanDeserialize(MediaRange mediaRange, BindingContext context)\r\n        {\r\n            return Json.IsJsonContentType(mediaRange);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Deserialize the request body to a model\r\n        /// </summary>\r\n        /// <param name=\"mediaRange\">Content type to deserialize</param>\r\n        /// <param name=\"bodyStream\">Request body stream</param>\r\n        /// <param name=\"context\">Current context</param>\r\n        /// <returns>Model instance</returns>\r\n        public object Deserialize(MediaRange mediaRange, Stream bodyStream, BindingContext context)\r\n        {\r\n            var serializer = new JavaScriptSerializer(this.jsonConfiguration, this.globalizationConfiguration);\r\n\r\n            serializer.RegisterConverters(this.jsonConfiguration.Converters, this.jsonConfiguration.PrimitiveConverters);\r\n\r\n            if (bodyStream.CanSeek)\r\n            {\r\n                bodyStream.Position = 0;\r\n            }\r\n\r\n            string bodyText;\r\n            using (var bodyReader = new StreamReader(bodyStream))\r\n            {\r\n                bodyText = bodyReader.ReadToEnd();\r\n            }\r\n\r\n            var genericDeserializeMethod = this.deserializeMethod.MakeGenericMethod(context.DestinationType);\r\n\r\n            var deserializedObject = genericDeserializeMethod.Invoke(serializer, new object[] { bodyText });\r\n\r\n            return deserializedObject;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/ModelBinding/DefaultBodyDeserializers/XmlBodyDeserializer.cs",
    "content": "namespace Nancy.ModelBinding.DefaultBodyDeserializers\r\n{\r\n    using System;\r\n    using System.IO;\r\n    using System.Xml.Serialization;\r\n    using Nancy.Responses.Negotiation;\r\n\r\n    /// <summary>\r\n    /// Deserializes request bodies in XML format\r\n    /// </summary>\r\n    public class XmlBodyDeserializer : IBodyDeserializer\r\n    {\r\n        /// <summary>\r\n        /// Whether the deserializer can deserialize the content type\r\n        /// </summary>\r\n        /// <param name=\"mediaRange\">Content type to deserialize</param>\r\n        /// <param name=\"context\">Current <see cref=\"BindingContext\"/>.</param>\r\n        /// <returns>True if supported, false otherwise</returns>\r\n        public bool CanDeserialize(MediaRange mediaRange, BindingContext context)\r\n        {\r\n            if (string.IsNullOrEmpty(mediaRange))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            var contentMimeType = mediaRange.ToString().Split(';')[0];\r\n\r\n            return contentMimeType.Equals(\"application/xml\", StringComparison.OrdinalIgnoreCase) ||\r\n                   contentMimeType.Equals(\"text/xml\", StringComparison.OrdinalIgnoreCase) ||\r\n                  (contentMimeType.StartsWith(\"application/vnd\", StringComparison.OrdinalIgnoreCase) &&\r\n                   contentMimeType.EndsWith(\"+xml\", StringComparison.OrdinalIgnoreCase));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Deserialize the request body to a model\r\n        /// </summary>\r\n        /// <param name=\"mediaRange\">Content type to deserialize</param>\r\n        /// <param name=\"bodyStream\">Request body stream</param>\r\n        /// <param name=\"context\">Current <see cref=\"BindingContext\"/>.</param>\r\n        /// <returns>Model instance</returns>\r\n        public object Deserialize(MediaRange mediaRange, Stream bodyStream, BindingContext context)\r\n        {\r\n            if (bodyStream.CanSeek)\r\n            {\r\n                bodyStream.Position = 0;\r\n            }\r\n\r\n            var ser = new XmlSerializer(context.DestinationType);\r\n            return ser.Deserialize(bodyStream);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/ModelBinding/DefaultConverters/CollectionConverter.cs",
    "content": "namespace Nancy.ModelBinding.DefaultConverters\r\n{\r\n    using System;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n\r\n    using Nancy.Extensions;\r\n\r\n    /// <summary>\r\n    /// Converter for handling enumerable types\r\n    /// </summary>\r\n    public class CollectionConverter : ITypeConverter\r\n    {\r\n        private readonly MethodInfo enumerableCastMethod = typeof(Enumerable).GetMethod(\"Cast\", BindingFlags.Public | BindingFlags.Static);\r\n        private readonly MethodInfo enumerableToArrayMethod = typeof(Enumerable).GetMethod(\"ToArray\", BindingFlags.Public | BindingFlags.Static);\r\n        private readonly MethodInfo enumerableToListMethod = typeof(Enumerable).GetMethod(\"ToList\", BindingFlags.Public | BindingFlags.Static);\r\n\r\n        /// <summary>\r\n        /// Whether the converter can convert to the destination type\r\n        /// </summary>\r\n        /// <param name=\"destinationType\">Destination type</param>\r\n        /// <param name=\"context\">The current binding context</param>\r\n        /// <returns>True if conversion supported, false otherwise</returns>\r\n        public bool CanConvertTo(Type destinationType, BindingContext context)\r\n        {\r\n            return destinationType.IsCollection() || destinationType.IsEnumerable() || destinationType.IsArray();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Convert the string representation to the destination type\r\n        /// </summary>\r\n        /// <param name=\"input\">Input string</param>\r\n        /// <param name=\"destinationType\">Destination type</param>\r\n        /// <param name=\"context\">Current context</param>\r\n        /// <returns>Converted object of the destination type</returns>\r\n        public object Convert(string input, Type destinationType, BindingContext context)\r\n        {\r\n            if (string.IsNullOrEmpty(input))\r\n            {\r\n                return null;\r\n            }\r\n\r\n            var items = input.Split(',');\r\n\r\n            // Strategy, schmategy ;-)\r\n            if (destinationType.IsCollection())\r\n            {\r\n                return this.ConvertCollection(items, destinationType, context);\r\n            }\r\n\r\n            if (destinationType.IsArray())\r\n            {\r\n                return this.ConvertArray(items, destinationType, context);\r\n            }\r\n\r\n            if (destinationType.IsEnumerable())\r\n            {\r\n                return this.ConvertEnumerable(items, destinationType, context);\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        private object ConvertCollection(string[] items, Type destinationType, BindingContext context)\r\n        {\r\n            var genericType = destinationType.GetGenericArguments().First();\r\n            var returnCollection = Activator.CreateInstance(destinationType);\r\n\r\n            var converter = context.TypeConverters.FirstOrDefault(c => c.CanConvertTo(genericType, context));\r\n            if (converter == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            var collectionAddMethod = destinationType.GetMethod(\"Add\", BindingFlags.Public | BindingFlags.Instance);\r\n\r\n            foreach (var item in items)\r\n            {\r\n                collectionAddMethod.Invoke(returnCollection, new[] { converter.Convert(item, genericType, context) });\r\n            }\r\n\r\n            return returnCollection;\r\n        }\r\n\r\n        private object ConvertArray(string[] items, Type destinationType, BindingContext context)\r\n        {\r\n            var elementType = destinationType.GetElementType();\r\n\r\n            if (elementType == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            var converter = context.TypeConverters.FirstOrDefault(c => c.CanConvertTo(elementType, context));\r\n\r\n            if (converter == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            var returnArray = items.Select(s => converter.Convert(s, elementType, context));\r\n\r\n            var genericCastMethod = this.enumerableCastMethod.MakeGenericMethod(new[] { elementType });\r\n            var generictoArrayMethod = this.enumerableToArrayMethod.MakeGenericMethod(new[] { elementType });\r\n\r\n            var castArray = genericCastMethod.Invoke(null, new object[] { returnArray });\r\n\r\n            return generictoArrayMethod.Invoke(null, new[] { castArray });\r\n        }\r\n\r\n        private object ConvertEnumerable(string[] items, Type destinationType, BindingContext context)\r\n        {\r\n            var genericType = destinationType.GetGenericArguments().First();\r\n\r\n            var converter = context.TypeConverters.FirstOrDefault(c => c.CanConvertTo(genericType, context));\r\n\r\n            if (converter == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            var returnArray = items.Select(s => converter.Convert(s, genericType, context));\r\n\r\n            // Use ToList rather than AsEnumerable to make sure the collection\r\n            // is materialised and converters are called as appropriate.\r\n            var genericCastMethod = this.enumerableCastMethod.MakeGenericMethod(new[] { genericType });\r\n            var genericToListMethod = this.enumerableToListMethod.MakeGenericMethod(new[] { genericType });\r\n\r\n            var castArray = genericCastMethod.Invoke(null, new object[] { returnArray });\r\n\r\n            return genericToListMethod.Invoke(null, new[] { castArray });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ModelBinding/DefaultConverters/DateTimeConverter.cs",
    "content": "﻿namespace Nancy.ModelBinding.DefaultConverters\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Converter for datetime types\r\n    /// </summary>\r\n    public class DateTimeConverter : ITypeConverter\r\n    {\r\n        /// <summary>\r\n        /// Whether the converter can convert to the destination type\r\n        /// </summary>\r\n        /// <param name=\"destinationType\">Destination type</param>\r\n        /// <param name=\"context\">The current binding context</param>\r\n        /// <returns>True if conversion supported, false otherwise</returns>\r\n        public bool CanConvertTo(Type destinationType, BindingContext context)\r\n        {\r\n            return destinationType == typeof(DateTime);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Convert the string representation to the destination type\r\n        /// </summary>\r\n        /// <param name=\"input\">Input string</param>\r\n        /// <param name=\"destinationType\">Destination type</param>\r\n        /// <param name=\"context\">Current context</param>\r\n        /// <returns>Converted object of the destination type</returns>\r\n        public object Convert(string input, Type destinationType, BindingContext context)\r\n        {\r\n            if (string.IsNullOrEmpty(input))\r\n            {\r\n                return null;\r\n            }\r\n\r\n            return System.Convert.ChangeType(input, destinationType, context.Context.Culture);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/ModelBinding/DefaultConverters/FallbackConverter.cs",
    "content": "namespace Nancy.ModelBinding.DefaultConverters\r\n{\r\n    using System;\r\n    using System.ComponentModel;\r\n\r\n    /// <summary>\r\n    /// A fallback converter that uses TypeDescriptor.GetConverter to try\r\n    /// and convert the value.\r\n    /// </summary>\r\n    public class FallbackConverter : ITypeConverter\r\n    {\r\n        /// <summary>\r\n        /// Whether the converter can convert to the destination type\r\n        /// </summary>\r\n        /// <param name=\"destinationType\">Destination type</param>\r\n        /// <param name=\"context\">The current binding context</param>\r\n        /// <returns>True if conversion supported, false otherwise</returns>\r\n        public bool CanConvertTo(Type destinationType, BindingContext context)\r\n        {\r\n            return true;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Convert the string representation to the destination type\r\n        /// </summary>\r\n        /// <param name=\"input\">Input string</param>\r\n        /// <param name=\"destinationType\">Destination type</param>\r\n        /// <param name=\"context\">Current context</param>\r\n        /// <returns>Converted object of the destination type</returns>\r\n        public object Convert(string input, Type destinationType, BindingContext context)\r\n        {\r\n            var converter = TypeDescriptor.GetConverter(destinationType);\r\n\r\n            if (converter == null || !converter.CanConvertFrom(typeof(string)))\r\n            {\r\n                return null;\r\n            }\r\n\r\n            try\r\n            {\r\n                return converter.ConvertFrom(input);\r\n            }\r\n            catch (FormatException)\r\n            {\r\n                if (destinationType == typeof(bool) && converter.GetType() == typeof(BooleanConverter) && \"on\".Equals(input, StringComparison.OrdinalIgnoreCase))\r\n                {\r\n                    return true;\r\n                }\r\n                return null;\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ModelBinding/DefaultConverters/NumericConverter.cs",
    "content": "﻿namespace Nancy.ModelBinding.DefaultConverters\r\n{\r\n    using System;\r\n\r\n    using Nancy.Extensions;\r\n\r\n    /// <summary>\r\n    /// Converter for numeric types\r\n    /// </summary>\r\n    public class NumericConverter : ITypeConverter\r\n    {\r\n        /// <summary>\r\n        /// Whether the converter can convert to the destination type\r\n        /// </summary>\r\n        /// <param name=\"destinationType\">Destination type</param>\r\n        /// <param name=\"context\">The current binding context</param>\r\n        /// <returns>True if conversion supported, false otherwise</returns>\r\n        public bool CanConvertTo(Type destinationType, BindingContext context)\r\n        {\r\n            return destinationType.IsNumeric();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Convert the string representation to the destination type\r\n        /// </summary>\r\n        /// <param name=\"input\">Input string</param>\r\n        /// <param name=\"destinationType\">Destination type</param>\r\n        /// <param name=\"context\">Current context</param>\r\n        /// <returns>Converted object of the destination type</returns>\r\n        public object Convert(string input, Type destinationType, BindingContext context)\r\n        {\r\n            if (string.IsNullOrEmpty(input))\r\n            {\r\n                return null;\r\n            }\r\n\r\n\r\n            return System.Convert.ChangeType(input, destinationType, context.Context.Culture);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/ModelBinding/DefaultFieldNameConverter.cs",
    "content": "namespace Nancy.ModelBinding\r\n{\r\n    using System.Collections.Concurrent;\r\n\r\n    /// <summary>\r\n    /// Default field name converter\r\n    /// Converts camel case to pascal case\r\n    /// </summary>\r\n    public class DefaultFieldNameConverter : IFieldNameConverter\r\n    {\r\n        private readonly ConcurrentDictionary<string, string> cache;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultFieldNameConverter\"/> class.\r\n        /// </summary>\r\n        public DefaultFieldNameConverter()\r\n        {\r\n            this.cache = new ConcurrentDictionary<string, string>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Converts a field name to a property name\r\n        /// </summary>\r\n        /// <param name=\"fieldName\">Field name</param>\r\n        /// <returns>Property name</returns>\r\n        public string Convert(string fieldName)\r\n        {\r\n            if (string.IsNullOrWhiteSpace(fieldName))\r\n            {\r\n                return fieldName;\r\n            }\r\n\r\n            return this.cache.GetOrAdd(fieldName, name =>\r\n            {\r\n                if (name.Length > 1)\r\n                {\r\n                    return char.ToUpperInvariant(name[0]) + name.Substring(1);\r\n                }\r\n\r\n                return name.ToUpperInvariant();\r\n            });\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/ModelBinding/DefaultModelBinderLocator.cs",
    "content": "namespace Nancy.ModelBinding\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Locates model binders for a particular model\r\n    /// </summary>\r\n    public class DefaultModelBinderLocator : IModelBinderLocator\r\n    {\r\n        /// <summary>\r\n        /// Available model binders\r\n        /// </summary>\r\n        private readonly IReadOnlyCollection<IModelBinder> binders;\r\n\r\n        /// <summary>\r\n        /// Default model binder to fall back on\r\n        /// </summary>\r\n        private readonly IBinder fallbackBinder;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultModelBinderLocator\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"binders\">Available model binders</param>\r\n        /// <param name=\"fallbackBinder\">Fallback binder</param>\r\n        public DefaultModelBinderLocator(IEnumerable<IModelBinder> binders, IBinder fallbackBinder)\r\n        {\r\n            this.fallbackBinder = fallbackBinder;\r\n\r\n            if (binders != null)\r\n            {\r\n                this.binders = binders.ToArray();\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a binder for the given type\r\n        /// </summary>\r\n        /// <param name=\"modelType\">Destination type to bind to</param>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> instance of the current request.</param>\r\n        /// <returns>IModelBinder instance or null if none found</returns>\r\n        public IBinder GetBinderForType(Type modelType, NancyContext context)\r\n        {\r\n            if (this.binders == null)\r\n            {\r\n                return this.fallbackBinder;\r\n            }\r\n\r\n            foreach (var modelBinder in this.binders)\r\n            {\r\n                if (modelBinder.CanBind(modelType))\r\n                {\r\n                    return modelBinder;\r\n                }\r\n            }\r\n\r\n            return this.fallbackBinder;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/ModelBinding/DynamicModelBinderAdapter.cs",
    "content": "﻿namespace Nancy.ModelBinding\r\n{\r\n    using System;\r\n    using System.Dynamic;\r\n\r\n    /// <summary>\r\n    /// Provides wiring up of a model binder when cast to a destination type\r\n    /// </summary>\r\n    public class DynamicModelBinderAdapter : DynamicObject\r\n    {\r\n        private readonly IModelBinderLocator locator;\r\n        private readonly NancyContext context;\r\n        private readonly object instance;\r\n        private readonly BindingConfig configuration;\r\n        private readonly string[] blacklistedProperties;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DynamicModelBinderAdapter\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"locator\">Model binder locator</param>\r\n        /// <param name=\"context\">Nancy context</param>\r\n        /// <param name=\"instance\">Optional existing instance, or null</param>\r\n        /// <param name=\"configuration\">The <see cref=\"BindingConfig\"/> that should be applied during binding.</param>\r\n        /// <param name=\"blacklistedProperties\">Blacklisted property names</param>\r\n        public DynamicModelBinderAdapter(IModelBinderLocator locator, NancyContext context, object instance, BindingConfig configuration, params string[] blacklistedProperties)\r\n        {\r\n            if (locator == null)\r\n            {\r\n                throw new ArgumentNullException(\"locator\");\r\n            }\r\n\r\n            if (context == null)\r\n            {\r\n                throw new ArgumentNullException(\"context\");\r\n            }\r\n\r\n            if (configuration == null)\r\n            {\r\n                throw new ArgumentNullException(\"configuration\");\r\n            }\r\n\r\n            this.locator = locator;\r\n            this.context = context;\r\n            this.instance = instance;\r\n            this.configuration = configuration;\r\n            this.blacklistedProperties = blacklistedProperties;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Provides implementation for type conversion operations. Classes derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class can override this method to specify dynamic behavior for operations that convert an object from one type to another.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.)\r\n        /// </returns>\r\n        /// <param name=\"binder\">Provides information about the conversion operation. The binder.Type property provides the type to which the object must be converted. For example, for the statement (String)sampleObject in C# (CType(sampleObject, Type) in Visual Basic), where sampleObject is an instance of the class derived from the <see cref=\"T:System.Dynamic.DynamicObject\"/> class, binder.Type returns the <see cref=\"T:System.String\"/> type. The binder.Explicit property provides information about the kind of conversion that occurs. It returns true for explicit conversion and false for implicit conversion.</param><param name=\"result\">The result of the type conversion operation.</param>\r\n        public override bool TryConvert(ConvertBinder binder, out object result)\r\n        {\r\n            var instanceType = instance == null ? binder.Type : this.instance.GetType();\r\n\r\n            var modelBinder = this.locator.GetBinderForType(instanceType, this.context);\r\n\r\n            if (modelBinder == null)\r\n            {\r\n                throw new ModelBindingException(instanceType);\r\n            }\r\n\r\n            result = modelBinder.Bind(this.context, instanceType, this.instance, this.configuration, this.blacklistedProperties);\r\n\r\n            return result != null || base.TryConvert(binder, out result);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ModelBinding/ExpressionExtensions.cs",
    "content": "﻿namespace Nancy.ModelBinding\r\n{\r\n    using System.Linq.Expressions;\r\n    using System.Reflection;\r\n\r\n    /// <summary>\r\n    /// Contains extension methods for the <see cref=\"Expression\"/> type.\r\n    /// </summary>\r\n    public static class ExpressionExtensions\r\n    {\r\n        /// <summary>\r\n        /// Retrieves the member that an expression is defined for.\r\n        /// </summary>\r\n        /// <param name=\"expression\">The expression to retrieve the member from.</param>\r\n        /// <returns>A <see cref=\"MemberInfo\"/> instance if the member could be found; otherwise <see langword=\"null\"/>.</returns>\r\n        public static MemberInfo GetTargetMemberInfo(this Expression expression)\r\n        {\r\n            switch (expression.NodeType)\r\n            {\r\n                case ExpressionType.Convert:\r\n                    return GetTargetMemberInfo(((UnaryExpression)expression).Operand);\r\n                case ExpressionType.Lambda:\r\n                    return GetTargetMemberInfo(((LambdaExpression)expression).Body);\r\n                case ExpressionType.Call:\r\n                    return ((MethodCallExpression)expression).Method;\r\n                case ExpressionType.MemberAccess:\r\n                    return ((MemberExpression)expression).Member;\r\n                default:\r\n                    return null;\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ModelBinding/IBinder.cs",
    "content": "﻿namespace Nancy.ModelBinding\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Binds incoming request data to a model type\r\n    /// </summary>\r\n    public interface IBinder\r\n    {\r\n        /// <summary>\r\n        /// Bind to the given model type\r\n        /// </summary>\r\n        /// <param name=\"context\">Current context</param>\r\n        /// <param name=\"modelType\">Model type to bind to</param>\r\n        /// <param name=\"configuration\">The <see cref=\"BindingConfig\"/> that should be applied during binding.</param>\r\n        /// <param name=\"blackList\">Blacklisted property names</param>\r\n        /// <param name=\"instance\">Existing instance of the object</param>\r\n        /// <returns>Bound model</returns>\r\n        object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ModelBinding/IBodyDeserializer.cs",
    "content": "namespace Nancy.ModelBinding\r\n{\r\n    using System.IO;\r\n    using Nancy.Responses.Negotiation;\r\n\r\n    /// <summary>\r\n    /// Provides a way to deserialize the contents of a request\r\n    /// into a bound model.\r\n    /// </summary>\r\n    public interface IBodyDeserializer\r\n    {\r\n        /// <summary>\r\n        /// Whether the deserializer can deserialize the content type\r\n        /// </summary>\r\n        /// <param name=\"mediaRange\">Content type to deserialize</param>\r\n        /// <param name=\"context\">Current <see cref=\"BindingContext\"/>.</param>\r\n        /// <returns>True if supported, false otherwise</returns>\r\n        bool CanDeserialize(MediaRange mediaRange, BindingContext context);\r\n\r\n        /// <summary>\r\n        /// Deserialize the request body to a model\r\n        /// </summary>\r\n        /// <param name=\"mediaRange\">Content type to deserialize</param>\r\n        /// <param name=\"bodyStream\">Request body stream</param>\r\n        /// <param name=\"context\">Current <see cref=\"BindingContext\"/>.</param>\r\n        /// <returns>Model instance</returns>\r\n        object Deserialize(MediaRange mediaRange, Stream bodyStream, BindingContext context);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ModelBinding/IFieldNameConverter.cs",
    "content": "﻿namespace Nancy.ModelBinding\r\n{\r\n    /// <summary>\r\n    /// Provides the capability to supply a convention to\r\n    /// convert form field names to property names if required.\r\n    /// </summary>\r\n    public interface IFieldNameConverter\r\n    {\r\n        /// <summary>\r\n        /// Converts a field name to a property name\r\n        /// </summary>\r\n        /// <param name=\"fieldName\">Field name</param>\r\n        /// <returns>Property name</returns>\r\n        string Convert(string fieldName);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ModelBinding/IModelBinder.cs",
    "content": "namespace Nancy.ModelBinding\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Provides a way to bind an incoming request, via the context, to a model type\r\n    /// </summary>\r\n    public interface IModelBinder : IBinder\r\n    {\r\n        /// <summary>\r\n        /// Whether the binder can bind to the given model type\r\n        /// </summary>\r\n        /// <param name=\"modelType\">Required model type</param>\r\n        /// <returns>True if binding is possible, false otherwise</returns>\r\n        bool CanBind(Type modelType);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ModelBinding/IModelBinderLocator.cs",
    "content": "namespace Nancy.ModelBinding\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Locates model binders for a particular model\r\n    /// </summary>\r\n    public interface IModelBinderLocator\r\n    {\r\n        /// <summary>\r\n        /// Gets a binder for the given type\r\n        /// </summary>\r\n        /// <param name=\"modelType\">Destination type to bind to</param>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> instance of the current request.</param>\r\n        /// <returns>IModelBinder instance or null if none found</returns>\r\n        IBinder GetBinderForType(Type modelType, NancyContext context);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ModelBinding/ITypeConverter.cs",
    "content": "namespace Nancy.ModelBinding\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Provides a way to convert from the incoming string representation\r\n    /// of a type to the type itself.\r\n    /// </summary>\r\n    public interface ITypeConverter\r\n    {\r\n        /// <summary>\r\n        /// Whether the converter can convert to the destination type\r\n        /// </summary>\r\n        /// <param name=\"destinationType\">Destination type</param>\r\n        /// <param name=\"context\">The current binding context</param>\r\n        /// <returns>True if conversion supported, false otherwise</returns>\r\n        bool CanConvertTo(Type destinationType, BindingContext context);\r\n\r\n        /// <summary>\r\n        /// Convert the string representation to the destination type\r\n        /// </summary>\r\n        /// <param name=\"input\">Input string</param>\r\n        /// <param name=\"destinationType\">Destination type</param>\r\n        /// <param name=\"context\">Current context</param>\r\n        /// <returns>Converted object of the destination type</returns>\r\n        object Convert(string input, Type destinationType, BindingContext context);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ModelBinding/ModelBindingException.cs",
    "content": "namespace Nancy.ModelBinding\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Runtime.Serialization;\r\n\r\n    /// <summary>\r\n    /// Represents an exception when attempting to bind to a model\r\n    /// </summary>\r\n    public class ModelBindingException : Exception\r\n    {\r\n        private const string ExceptionMessage = \"Unable to bind to type: {0}\";\r\n\r\n        /// <summary>\r\n        /// Gets all failures\r\n        /// </summary>\r\n        public virtual IEnumerable<PropertyBindingException> PropertyBindingExceptions { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the model type, which caused the exception\r\n        /// </summary>\r\n        public virtual Type BoundType { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ModelBindingException\"/> class, with\r\n        /// the provided <paramref name=\"boundType\"/>, <paramref name=\"propertyBindingExceptions\"/> and <paramref name=\"innerException\"/>.\r\n        /// </summary>\r\n        /// <param name=\"boundType\">the model type to bind to</param>\r\n        /// <param name=\"propertyBindingExceptions\">the original exceptions, thrown while binding the property</param>\r\n        /// <param name=\"innerException\">The inner exception.</param>\r\n        public ModelBindingException(Type boundType, IEnumerable<PropertyBindingException> propertyBindingExceptions = null, Exception innerException = null)\r\n            : base(string.Format(ExceptionMessage, boundType), innerException)\r\n        {\r\n            if (boundType == null)\r\n            {\r\n                throw new ArgumentNullException(\"boundType\");\r\n            }\r\n            this.PropertyBindingExceptions = propertyBindingExceptions ?? new List<PropertyBindingException>();\r\n            this.BoundType = boundType;\r\n        }\r\n#if !NETSTANDARD1_6\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ModelBindingException\" /> class with serialized data.\r\n        /// </summary>\r\n        /// <param name=\"info\">The <see cref=\"T:System.Runtime.Serialization.SerializationInfo\" /> that holds the serialized object data about the exception being thrown.</param>\r\n        /// <param name=\"context\">The <see cref=\"T:System.Runtime.Serialization.StreamingContext\" /> that contains contextual information about the source or destination.</param>\r\n        protected ModelBindingException(SerializationInfo info, StreamingContext context)\r\n            : base(info, context)\r\n        {\r\n        }\r\n#endif\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ModelBinding/ModuleExtensions.cs",
    "content": "namespace Nancy.ModelBinding\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Linq.Expressions;\r\n\r\n    using Nancy.Validation;\r\n\r\n    /// <summary>\r\n    /// A convenience class that contains various extension methods for modules.\r\n    /// </summary>\r\n    public static class ModuleExtensions\r\n    {\r\n        private static readonly string[] NoBlacklistedProperties = ArrayCache.Empty<string>();\r\n\r\n        /// <summary>\r\n        /// Parses an array of expressions like <code>t =&gt; t.Property</code> to a list of strings containing the property names;\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">Type of the model</typeparam>\r\n        /// <param name=\"expressions\">Expressions that tell which property should be ignored</param>\r\n        /// <returns>Array of strings containing the names of the properties.</returns>\r\n        private static string[] ParseBlacklistedPropertiesExpressionTree<T>(this IEnumerable<Expression<Func<T, object>>> expressions)\r\n        {\r\n            return expressions.Select(p => p.GetTargetMemberInfo().Name).ToArray();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind the incoming request to a model\r\n        /// </summary>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <param name=\"blacklistedProperties\">Property names to blacklist from binding</param>\r\n        /// <returns>Model adapter - cast to a model type to bind it</returns>\r\n        public static dynamic Bind(this INancyModule module, params string[] blacklistedProperties)\r\n        {\r\n            return module.Bind(BindingConfig.Default, blacklistedProperties);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind the incoming request to a model\r\n        /// </summary>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <param name=\"configuration\">The <see cref=\"BindingConfig\"/> that should be applied during binding.</param>\r\n        /// <param name=\"blacklistedProperties\">Property names to blacklist from binding</param>\r\n        /// <returns>Model adapter - cast to a model type to bind it</returns>\r\n        public static dynamic Bind(this INancyModule module, BindingConfig configuration, params string[] blacklistedProperties)\r\n        {\r\n            return new DynamicModelBinderAdapter(module.ModelBinderLocator, module.Context, null, configuration, blacklistedProperties);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind the incoming request to a model\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">Model type</typeparam>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <returns>Bound model instance</returns>\r\n        public static TModel Bind<TModel>(this INancyModule module)\r\n        {\r\n            return module.Bind();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind the incoming request to a model\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">Model type</typeparam>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <param name=\"blacklistedProperties\">Property names to blacklist from binding</param>\r\n        /// <returns>Bound model instance</returns>\r\n        public static TModel Bind<TModel>(this INancyModule module, params string[] blacklistedProperties)\r\n        {\r\n            return module.Bind(blacklistedProperties);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind the incoming request to a model\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">Model type</typeparam>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <param name=\"blacklistedProperties\">Expressions that tell which property should be ignored</param>\r\n        /// <example>this.Bind&lt;Person&gt;(p =&gt; p.Name, p =&gt; p.Age)</example>\r\n        /// <returns>Bound model instance</returns>\r\n        public static TModel Bind<TModel>(this INancyModule module, params Expression<Func<TModel, object>>[] blacklistedProperties)\r\n        {\r\n            return module.Bind<TModel>(blacklistedProperties.ParseBlacklistedPropertiesExpressionTree());\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind the incoming request to a model and validate\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">Model type</typeparam>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <param name=\"blacklistedProperties\">Property names to blacklist from binding</param>\r\n        /// <returns>Bound model instance</returns>\r\n        /// <remarks><see cref=\"ModelValidationResult\"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks>\r\n        public static TModel BindAndValidate<TModel>(this INancyModule module, params string[] blacklistedProperties)\r\n        {\r\n            var model = module.Bind<TModel>(blacklistedProperties);\r\n            module.Validate(model);\r\n            return model;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind the incoming request to a model and validate\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">Model type</typeparam>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <param name=\"blacklistedProperties\">Expressions that tell which property should be ignored</param>\r\n        /// <example>this.Bind&lt;Person&gt;(p =&gt; p.Name, p =&gt; p.Age)</example>\r\n        /// <returns>Bound model instance</returns>\r\n        /// <remarks><see cref=\"ModelValidationResult\"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks>\r\n        public static TModel BindAndValidate<TModel>(this INancyModule module, params Expression<Func<TModel, object>>[] blacklistedProperties)\r\n        {\r\n            var model = module.Bind<TModel>(blacklistedProperties.ParseBlacklistedPropertiesExpressionTree());\r\n            module.Validate(model);\r\n            return model;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind the incoming request to a model and validate\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">Model type</typeparam>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <returns>Bound model instance</returns>\r\n        /// <remarks><see cref=\"ModelValidationResult\"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks>\r\n        public static TModel BindAndValidate<TModel>(this INancyModule module)\r\n        {\r\n            var model = module.Bind<TModel>(NoBlacklistedProperties);\r\n            module.Validate(model);\r\n            return model;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind the incoming request to a model\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">Model type</typeparam>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <param name=\"configuration\">The <see cref=\"BindingConfig\"/> that should be applied during binding.</param>\r\n        /// <returns>Bound model instance</returns>\r\n        public static TModel Bind<TModel>(this INancyModule module, BindingConfig configuration)\r\n        {\r\n            return module.Bind(configuration);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind the incoming request to a model\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">Model type</typeparam>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <param name=\"configuration\">The <see cref=\"BindingConfig\"/> that should be applied during binding.</param>\r\n        /// <param name=\"blacklistedProperties\">Property names to blacklist from binding</param>\r\n        /// <returns>Bound model instance</returns>\r\n        public static TModel Bind<TModel>(this INancyModule module, BindingConfig configuration, params string[] blacklistedProperties)\r\n        {\r\n            return module.Bind(configuration, blacklistedProperties);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind the incoming request to a model\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">Model type</typeparam>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <param name=\"configuration\">The <see cref=\"BindingConfig\"/> that should be applied during binding.</param>\r\n        /// <param name=\"blacklistedProperty\">Expressions that tell which property should be ignored</param>\r\n        /// <example>this.Bind&lt;Person&gt;(p =&gt; p.Name, p =&gt; p.Age)</example>\r\n        /// <returns>Bound model instance</returns>\r\n        public static TModel Bind<TModel>(this INancyModule module, BindingConfig configuration, Expression<Func<TModel, object>> blacklistedProperty)\r\n        {\r\n            return module.Bind(configuration, new [] { blacklistedProperty }.ParseBlacklistedPropertiesExpressionTree());\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind the incoming request to a model\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">Model type</typeparam>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <param name=\"configuration\">The <see cref=\"BindingConfig\"/> that should be applied during binding.</param>\r\n        /// <param name=\"blacklistedProperties\">Expressions that tell which property should be ignored</param>\r\n        /// <example>this.Bind&lt;Person&gt;(p =&gt; p.Name, p =&gt; p.Age)</example>\r\n        /// <returns>Bound model instance</returns>\r\n        public static TModel Bind<TModel>(this INancyModule module, BindingConfig configuration, params Expression<Func<TModel, object>>[] blacklistedProperties)\r\n        {\r\n            return module.Bind(configuration, blacklistedProperties.ParseBlacklistedPropertiesExpressionTree());\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind the incoming request to a model and validate\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">Model type</typeparam>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <param name=\"configuration\">The <see cref=\"BindingConfig\"/> that should be applied during binding.</param>\r\n        /// <param name=\"blacklistedProperties\">Property names to blacklist from binding</param>\r\n        /// <returns>Bound model instance</returns>\r\n        /// <remarks><see cref=\"ModelValidationResult\"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks>\r\n        public static TModel BindAndValidate<TModel>(this INancyModule module, BindingConfig configuration, params string[] blacklistedProperties)\r\n        {\r\n            var model = module.Bind<TModel>(configuration, blacklistedProperties);\r\n            module.Validate(model);\r\n            return model;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind the incoming request to a model and validate\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">Model type</typeparam>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <param name=\"configuration\">The <see cref=\"BindingConfig\"/> that should be applied during binding.</param>\r\n        /// <param name=\"blacklistedProperties\">Expressions that tell which property should be ignored</param>\r\n        /// <example>this.Bind&lt;Person&gt;(p =&gt; p.Name, p =&gt; p.Age)</example>\r\n        /// <returns>Bound model instance</returns>\r\n        /// <remarks><see cref=\"ModelValidationResult\"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks>\r\n        public static TModel BindAndValidate<TModel>(this INancyModule module, BindingConfig configuration, params Expression<Func<TModel, object>>[] blacklistedProperties)\r\n        {\r\n            var model = module.Bind<TModel>(configuration, blacklistedProperties.ParseBlacklistedPropertiesExpressionTree());\r\n            module.Validate(model);\r\n            return model;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind the incoming request to a model and validate\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">Model type</typeparam>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <param name=\"configuration\">The <see cref=\"BindingConfig\"/> that should be applied during binding.</param>\r\n        /// <returns>Bound model instance</returns>\r\n        /// <remarks><see cref=\"ModelValidationResult\"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks>\r\n        public static TModel BindAndValidate<TModel>(this INancyModule module, BindingConfig configuration)\r\n        {\r\n            var model = module.Bind<TModel>(configuration, NoBlacklistedProperties);\r\n            module.Validate(model);\r\n            return model;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind the incoming request to an existing instance\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">Model type</typeparam>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <param name=\"instance\">The class instance to bind properties to</param>\r\n        /// <param name=\"blacklistedProperties\">Property names to blacklist from binding</param>\r\n        public static TModel BindTo<TModel>(this INancyModule module, TModel instance, params string[] blacklistedProperties)\r\n        {\r\n            return module.BindTo(instance, BindingConfig.NoOverwrite, blacklistedProperties);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind the incoming request to an existing instance\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">Model type</typeparam>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <param name=\"instance\">The class instance to bind properties to</param>\r\n        /// <param name=\"blacklistedProperties\">Expressions that tell which property should be ignored</param>\r\n        /// <example>this.Bind&lt;Person&gt;(p =&gt; p.Name, p =&gt; p.Age)</example>\r\n        public static TModel BindTo<TModel>(this INancyModule module, TModel instance, params Expression<Func<TModel, object>>[] blacklistedProperties)\r\n        {\r\n            return module.BindTo(instance, BindingConfig.NoOverwrite, blacklistedProperties.ParseBlacklistedPropertiesExpressionTree());\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind the incoming request to an existing instance\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">Model type</typeparam>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <param name=\"instance\">The class instance to bind properties to</param>\r\n        public static TModel BindTo<TModel>(this INancyModule module, TModel instance)\r\n        {\r\n            return module.BindTo(instance, BindingConfig.NoOverwrite, NoBlacklistedProperties);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind the incoming request to an existing instance and validate\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">Model type</typeparam>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <param name=\"instance\">The class instance to bind properties to</param>\r\n        /// <param name=\"blacklistedProperties\">Property names to blacklist from binding</param>\r\n        /// <remarks><see cref=\"ModelValidationResult\"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks>\r\n        public static TModel BindToAndValidate<TModel>(this INancyModule module, TModel instance, params string[] blacklistedProperties)\r\n        {\r\n            var model = module.BindTo(instance, blacklistedProperties);\r\n            module.Validate(model);\r\n            return model;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind the incoming request to an existing instance and validate\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">Model type</typeparam>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <param name=\"instance\">The class instance to bind properties to</param>\r\n        /// <param name=\"blacklistedProperties\">Expressions that tell which property should be ignored</param>\r\n        /// <example>this.Bind&lt;Person&gt;(p =&gt; p.Name, p =&gt; p.Age)</example>\r\n        /// <remarks><see cref=\"ModelValidationResult\"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks>\r\n        public static TModel BindToAndValidate<TModel>(this INancyModule module, TModel instance, params Expression<Func<TModel, object>>[] blacklistedProperties)\r\n        {\r\n            var model = module.BindTo(instance, blacklistedProperties.ParseBlacklistedPropertiesExpressionTree());\r\n            module.Validate(model);\r\n            return model;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind the incoming request to an existing instance and validate\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">Model type</typeparam>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <param name=\"instance\">The class instance to bind properties to</param>\r\n        /// <remarks><see cref=\"ModelValidationResult\"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks>\r\n        public static TModel BindToAndValidate<TModel>(this INancyModule module, TModel instance)\r\n        {\r\n            var model = module.BindTo(instance, NoBlacklistedProperties);\r\n            module.Validate(model);\r\n            return model;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind the incoming request to an existing instance\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">Model type</typeparam>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <param name=\"instance\">The class instance to bind properties to</param>\r\n        /// <param name=\"configuration\">The <see cref=\"BindingConfig\"/> that should be applied during binding.</param>\r\n        /// <param name=\"blacklistedProperties\">Property names to blacklist from binding</param>\r\n        public static TModel BindTo<TModel>(this INancyModule module, TModel instance, BindingConfig configuration, params string[] blacklistedProperties)\r\n        {\r\n            dynamic adapter =\r\n                new DynamicModelBinderAdapter(module.ModelBinderLocator, module.Context, instance, configuration, blacklistedProperties);\r\n\r\n            return adapter;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind the incoming request to an existing instance\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">Model type</typeparam>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <param name=\"instance\">The class instance to bind properties to</param>\r\n        /// <param name=\"configuration\">The <see cref=\"BindingConfig\"/> that should be applied during binding.</param>\r\n        /// <param name=\"blacklistedProperties\">Expressions that tell which property should be ignored</param>\r\n        /// <example>this.Bind&lt;Person&gt;(p =&gt; p.Name, p =&gt; p.Age)</example>\r\n        public static TModel BindTo<TModel>(this INancyModule module, TModel instance, BindingConfig configuration, params Expression<Func<TModel, object>>[] blacklistedProperties)\r\n        {\r\n            return module.BindTo(instance, configuration, blacklistedProperties.ParseBlacklistedPropertiesExpressionTree());\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind the incoming request to an existing instance\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">Model type</typeparam>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <param name=\"instance\">The class instance to bind properties to</param>\r\n        /// <param name=\"configuration\">The <see cref=\"BindingConfig\"/> that should be applied during binding.</param>\r\n        public static TModel BindTo<TModel>(this INancyModule module, TModel instance, BindingConfig configuration)\r\n        {\r\n            return module.BindTo(instance, configuration, NoBlacklistedProperties);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind the incoming request to an existing instance and validate\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">Model type</typeparam>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <param name=\"instance\">The class instance to bind properties to</param>\r\n        /// <param name=\"configuration\">The <see cref=\"BindingConfig\"/> that should be applied during binding.</param>\r\n        /// <param name=\"blacklistedProperties\">Property names to blacklist from binding</param>\r\n        /// <remarks><see cref=\"ModelValidationResult\"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks>\r\n        public static TModel BindToAndValidate<TModel>(this INancyModule module, TModel instance, BindingConfig configuration, params string[] blacklistedProperties)\r\n        {\r\n            var model = module.BindTo(instance, configuration, blacklistedProperties);\r\n            module.Validate(model);\r\n            return model;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind the incoming request to an existing instance and validate\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">Model type</typeparam>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <param name=\"instance\">The class instance to bind properties to</param>\r\n        /// <param name=\"configuration\">The <see cref=\"BindingConfig\"/> that should be applied during binding.</param>\r\n        /// <param name=\"blacklistedProperties\">Expressions that tell which property should be ignored</param>\r\n        /// <remarks><see cref=\"ModelValidationResult\"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks>\r\n        /// <example>this.BindToAndValidate(person, config, p =&gt; p.Name, p =&gt; p.Age)</example>\r\n        public static TModel BindToAndValidate<TModel>(this INancyModule module, TModel instance, BindingConfig configuration, params Expression<Func<TModel, object>>[] blacklistedProperties)\r\n        {\r\n            var model = module.BindTo(instance, configuration, blacklistedProperties.ParseBlacklistedPropertiesExpressionTree());\r\n            module.Validate(model);\r\n            return model;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Bind the incoming request to an existing instance and validate\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">Model type</typeparam>\r\n        /// <param name=\"module\">Current module</param>\r\n        /// <param name=\"instance\">The class instance to bind properties to</param>\r\n        /// <param name=\"configuration\">The <see cref=\"BindingConfig\"/> that should be applied during binding.</param>\r\n        /// <remarks><see cref=\"ModelValidationResult\"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks>\r\n        public static TModel BindToAndValidate<TModel>(this INancyModule module, TModel instance, BindingConfig configuration)\r\n        {\r\n            var model = module.BindTo(instance, configuration, NoBlacklistedProperties);\r\n            module.Validate(model);\r\n            return model;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/ModelBinding/PropertyBindingException.cs",
    "content": "﻿namespace Nancy.ModelBinding\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Represents an exception occurred when binding the properties.\r\n    /// </summary>\r\n    /// <seealso cref=\"System.Exception\" />\r\n    public class PropertyBindingException : Exception\r\n    {\r\n        private const string ExceptionMessage = \"Unable to bind property: {0}; Attempted value: {1}\";\r\n\r\n        /// <summary>\r\n        /// Gets the property name for which the bind failed\r\n        /// </summary>\r\n        public string PropertyName { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the value which was attempted to be assigned to the property\r\n        /// </summary>\r\n        public string AttemptedValue { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Creates new instance\r\n        /// </summary>\r\n        /// <param name=\"propertyName\">the name of the property which failed to bind</param>\r\n        /// <param name=\"attemptedValue\">the value attempted to set</param>\r\n        /// <param name=\"innerException\">the underlying exception</param>\r\n        public PropertyBindingException(string propertyName, string attemptedValue, Exception innerException = null)\r\n            : base(String.Format(ExceptionMessage, propertyName, attemptedValue), innerException)\r\n        {\r\n            this.PropertyName = propertyName;\r\n            this.AttemptedValue = attemptedValue;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/NamedPipelineBase.cs",
    "content": "namespace Nancy\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Abstract base class for named pipelines.\r\n    /// </summary>\r\n    /// <typeparam name=\"TDelegate\">The type of the delegate.</typeparam>\r\n    public abstract class NamedPipelineBase<TDelegate>\r\n    {\r\n        /// <summary>\r\n        /// Pipeline items to execute\r\n        /// </summary>\r\n        protected readonly List<PipelineItem<TDelegate>> pipelineItems;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NamedPipelineBase{TDelegate}\"/> class.\r\n        /// </summary>\r\n        protected NamedPipelineBase()\r\n        {\r\n            this.pipelineItems = new List<PipelineItem<TDelegate>>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NamedPipelineBase{TDelegate}\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"capacity\">The number of pipeline delegates.</param>\r\n        protected NamedPipelineBase(int capacity)\r\n        {\r\n            this.pipelineItems = new List<PipelineItem<TDelegate>>(capacity);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the current pipeline items\r\n        /// </summary>\r\n        public IEnumerable<PipelineItem<TDelegate>> PipelineItems\r\n        {\r\n            get { return this.pipelineItems.AsReadOnly(); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the current pipeline item delegates\r\n        /// </summary>\r\n        public IEnumerable<TDelegate> PipelineDelegates\r\n        {\r\n            get { return this.pipelineItems.Select(pipelineItem => pipelineItem.Delegate); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Add an item to the start of the pipeline\r\n        /// </summary>\r\n        /// <param name=\"item\">Item to add</param>\r\n        public virtual void AddItemToStartOfPipeline(TDelegate item)\r\n        {\r\n            this.AddItemToStartOfPipeline((PipelineItem<TDelegate>)item);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Add an item to the start of the pipeline\r\n        /// </summary>\r\n        /// <param name=\"item\">Item to add</param>\r\n        /// <param name=\"replaceInPlace\">\r\n        /// Whether to replace an existing item with the same name in its current place,\r\n        /// rather than at the position requested. Defaults to false.\r\n        /// </param>\r\n        public virtual void AddItemToStartOfPipeline(PipelineItem<TDelegate> item, bool replaceInPlace = false)\r\n        {\r\n            this.InsertItemAtPipelineIndex(0, item, replaceInPlace);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Add an item to the end of the pipeline\r\n        /// </summary>\r\n        /// <param name=\"item\">Item to add</param>\r\n        public virtual void AddItemToEndOfPipeline(TDelegate item)\r\n        {\r\n            this.AddItemToEndOfPipeline((PipelineItem<TDelegate>)item);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Add an item to the end of the pipeline\r\n        /// </summary>\r\n        /// <param name=\"item\">Item to add</param>\r\n        /// <param name=\"replaceInPlace\">\r\n        /// Whether to replace an existing item with the same name in its current place,\r\n        /// rather than at the position requested. Defaults to false.\r\n        /// </param>\r\n        public virtual void AddItemToEndOfPipeline(PipelineItem<TDelegate> item, bool replaceInPlace = false)\r\n        {\r\n            var existingIndex = this.RemoveByName(item.Name);\r\n\r\n            if (replaceInPlace && existingIndex != -1)\r\n            {\r\n                this.InsertItemAtPipelineIndex(existingIndex, item);\r\n            }\r\n            else\r\n            {\r\n                this.pipelineItems.Add(item);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Add an item to a specific place in the pipeline.\r\n        /// </summary>\r\n        /// <param name=\"index\">Index to add at</param>\r\n        /// <param name=\"item\">Item to add</param>\r\n        public virtual void InsertItemAtPipelineIndex(int index, TDelegate item)\r\n        {\r\n            this.InsertItemAtPipelineIndex(index, (PipelineItem<TDelegate>)item);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Add an item to a specific place in the pipeline.\r\n        /// </summary>\r\n        /// <param name=\"index\">Index to add at</param>\r\n        /// <param name=\"item\">Item to add</param>\r\n        /// <param name=\"replaceInPlace\">\r\n        /// Whether to replace an existing item with the same name in its current place,\r\n        /// rather than at the position requested. Defaults to false.\r\n        /// </param>\r\n        public virtual void InsertItemAtPipelineIndex(int index, PipelineItem<TDelegate> item, bool replaceInPlace = false)\r\n        {\r\n            var existingIndex = this.RemoveByName(item.Name);\r\n\r\n            var newIndex = (replaceInPlace && existingIndex != -1) ? existingIndex : index;\r\n\r\n            this.pipelineItems.Insert(newIndex, item);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Insert an item before a named item.\r\n        /// If the named item does not exist the item is inserted at the start of the pipeline.\r\n        /// </summary>\r\n        /// <param name=\"name\">Name of the item to insert before</param>\r\n        /// <param name=\"item\">Item to insert</param>\r\n        public virtual void InsertBefore(string name, TDelegate item)\r\n        {\r\n            this.InsertBefore(name, (PipelineItem<TDelegate>)item);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Insert an item before a named item.\r\n        /// If the named item does not exist the item is inserted at the start of the pipeline.\r\n        /// </summary>\r\n        /// <param name=\"name\">Name of the item to insert before</param>\r\n        /// <param name=\"item\">Item to insert</param>\r\n        public virtual void InsertBefore(string name, PipelineItem<TDelegate> item)\r\n        {\r\n            var existingIndex =\r\n                this.pipelineItems.FindIndex(i => String.Equals(name, i.Name, StringComparison.Ordinal));\r\n\r\n            if (existingIndex == -1)\r\n            {\r\n                existingIndex = 0;\r\n            }\r\n\r\n            this.InsertItemAtPipelineIndex(existingIndex, item);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Insert an item after a named item.\r\n        /// If the named item does not exist the item is inserted at the end of the pipeline.\r\n        /// </summary>\r\n        /// <param name=\"name\">Name of the item to insert after</param>\r\n        /// <param name=\"item\">Item to insert</param>\r\n        public virtual void InsertAfter(string name, TDelegate item)\r\n        {\r\n            this.InsertAfter(name, (PipelineItem<TDelegate>)item);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Insert an item after a named item.\r\n        /// If the named item does not exist the item is inserted at the end of the pipeline.\r\n        /// </summary>\r\n        /// <param name=\"name\">Name of the item to insert after</param>\r\n        /// <param name=\"item\">Item to insert</param>\r\n        public virtual void InsertAfter(string name, PipelineItem<TDelegate> item)\r\n        {\r\n            var existingIndex =\r\n                this.pipelineItems.FindIndex(i => String.Equals(name, i.Name, StringComparison.Ordinal));\r\n\r\n            if (existingIndex == -1)\r\n            {\r\n                existingIndex = this.pipelineItems.Count;\r\n            }\r\n\r\n            existingIndex++;\r\n\r\n            if (existingIndex > this.pipelineItems.Count)\r\n            {\r\n                this.AddItemToEndOfPipeline(item);\r\n            }\r\n            else\r\n            {\r\n                this.InsertItemAtPipelineIndex(existingIndex, item);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Remove a named pipeline item\r\n        /// </summary>\r\n        /// <param name=\"name\">Name</param>\r\n        /// <returns>Index of item that was removed or -1 if nothing removed</returns>\r\n        public virtual int RemoveByName(string name)\r\n        {\r\n            if (string.IsNullOrEmpty(name))\r\n            {\r\n                return -1;\r\n            }\r\n\r\n            var existingIndex =\r\n                this.pipelineItems.FindIndex(i => String.Equals(name, i.Name, StringComparison.Ordinal));\r\n\r\n            if (existingIndex != -1)\r\n            {\r\n                this.pipelineItems.RemoveAt(existingIndex);\r\n            }\r\n\r\n            return existingIndex;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Nancy.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <Description>Nancy is a lightweight web framework for the .Net platform, inspired by Sinatra. Nancy aim at delivering a low ceremony approach to building light, fast web applications.</Description>\n    <TargetFrameworks>netstandard2.0;net452</TargetFrameworks>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <EmbeddedResource Include=\"ErrorHandling\\Resources\\**\\*.*;Diagnostics\\Resources\\**\\*.*;Diagnostics\\Views\\**\\*.*\" Exclude=\"bin\\**;obj\\**;**\\*.xproj;packages\\**;@(EmbeddedResource)\" />\n  </ItemGroup>\n\n  <ItemGroup Condition=\" '$(TargetFramework)' == 'netstandard2.0' \">\n    <PackageReference Include=\"Microsoft.Extensions.DependencyModel\" Version=\"2.0.4\" />\n    <PackageReference Include=\"Microsoft.Extensions.PlatformAbstractions\" Version=\"1.1.0\" />\n    <PackageReference Include=\"System.Collections.Specialized\" Version=\"4.3.0\" />\n    <PackageReference Include=\"System.ComponentModel.TypeConverter\" Version=\"4.3.0\" />\n    <PackageReference Include=\"System.Net.NameResolution\" Version=\"4.3.0\" />\n    <PackageReference Include=\"System.Security.Claims\" Version=\"4.3.0\" />\n    <PackageReference Include=\"System.Xml.XmlSerializer\" Version=\"4.3.0\" />\n  </ItemGroup>\n\n  <ItemGroup Condition=\" '$(TargetFramework)' == 'net452' \">\n    <Reference Include=\"System.Xml\" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "src/Nancy/NancyContext.cs",
    "content": "\r\nnamespace Nancy\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Globalization;\r\n    using System.Linq;\r\n    using System.Security.Claims;\r\n    using Nancy.Configuration;\r\n    using Nancy.Diagnostics;\r\n    using Nancy.Responses.Negotiation;\r\n    using Nancy.Routing;\r\n    using Nancy.Validation;\r\n\r\n    /// <summary>\r\n    /// Nancy context.\r\n    /// </summary>\r\n    public sealed class NancyContext : IDisposable\r\n    {\r\n        private Request request;\r\n\r\n        private ModelValidationResult modelValidationResult;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancyContext\"/> class.\r\n        /// </summary>\r\n        public NancyContext()\r\n        {\r\n            this.Items = new Dictionary<string, object>();\r\n            this.Trace = new DefaultRequestTrace();\r\n            this.ViewBag = new DynamicDictionary();\r\n            this.NegotiationContext = new NegotiationContext();\r\n\r\n            // TODO - potentially additional logic to lock to ip etc?\r\n            this.ControlPanelEnabled = true;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the dictionary for storage of per-request items. Disposable items will be disposed when the context is.\r\n        /// </summary>\r\n        public IDictionary<string, object> Items { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the resolved route\r\n        /// </summary>\r\n        public Route ResolvedRoute { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the parameters for the resolved route\r\n        /// </summary>\r\n        public dynamic Parameters { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the incoming request\r\n        /// </summary>\r\n        public Request Request\r\n        {\r\n            get\r\n            {\r\n                return this.request;\r\n            }\r\n\r\n            set\r\n            {\r\n                this.request = value;\r\n                this.Trace.RequestData = value;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the outgoing response\r\n        /// </summary>\r\n        public Response Response { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the current user\r\n        /// </summary>\r\n        public ClaimsPrincipal CurrentUser { get; set; }\r\n\r\n        /// <summary>\r\n        /// Diagnostic request tracing\r\n        /// </summary>\r\n        public IRequestTrace Trace { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether control panel access is enabled for this request\r\n        /// </summary>\r\n        public bool ControlPanelEnabled { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Non-model specific data for rendering in the response\r\n        /// </summary>\r\n        public dynamic ViewBag { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the model validation result.\r\n        /// </summary>\r\n        public ModelValidationResult ModelValidationResult\r\n        {\r\n            get { return this.modelValidationResult ?? (this.modelValidationResult = new ModelValidationResult()); }\r\n            set { this.modelValidationResult = value; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the context's culture\r\n        /// </summary>\r\n        public CultureInfo Culture { get; set; }\r\n\r\n        /// <summary>\r\n        /// Context of content negotiation (if relevant)\r\n        /// </summary>\r\n        public NegotiationContext NegotiationContext { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the dynamic object used to locate text resources.\r\n        /// </summary>\r\n        public dynamic Text { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the <see cref=\"INancyEnvironment\"/>.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"INancyEnvironment\"/> instance.</value>\r\n        public INancyEnvironment Environment { get; set; }\r\n\r\n        /// <summary>\r\n        /// Disposes any disposable items in the <see cref=\"Items\"/> dictionary.\r\n        /// </summary>\r\n        public void Dispose()\r\n        {\r\n            foreach (var disposableItem in this.Items.Values.OfType<IDisposable>())\r\n            {\r\n                disposableItem.Dispose();\r\n            }\r\n\r\n            this.Items.Clear();\r\n\r\n            if (this.request != null)\r\n            {\r\n                ((IDisposable) this.request).Dispose();\r\n            }\r\n\r\n            if (this.Response != null)\r\n            {\r\n                this.Response.Dispose();\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/NancyEngine.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n\r\n    using Nancy.Bootstrapper;\r\n    using Cookies;\r\n    using Diagnostics;\r\n    using ErrorHandling;\r\n    using Routing;\r\n\r\n    using Helpers;\r\n    using Nancy.Configuration;\r\n    using Responses.Negotiation;\r\n\r\n    /// <summary>\r\n    /// Default engine for handling Nancy <see cref=\"Request\"/>s.\r\n    /// </summary>\r\n    public class NancyEngine : INancyEngine\r\n    {\r\n        /// <summary>\r\n        /// Key for error type\r\n        /// </summary>\r\n        public const string ERROR_KEY = \"ERROR_TRACE\";\r\n\r\n        /// <summary>\r\n        /// Key for error exception message\r\n        /// </summary>\r\n        public const string ERROR_EXCEPTION = \"ERROR_EXCEPTION\";\r\n\r\n        private readonly IRequestDispatcher dispatcher;\r\n        private readonly INancyContextFactory contextFactory;\r\n        private readonly IRequestTracing requestTracing;\r\n        private readonly IReadOnlyCollection<IStatusCodeHandler> statusCodeHandlers;\r\n        private readonly IStaticContentProvider staticContentProvider;\r\n        private readonly IResponseNegotiator negotiator;\r\n        private readonly CancellationTokenSource engineDisposedCts;\r\n        private readonly TraceConfiguration traceConfiguration;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancyEngine\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"dispatcher\">An <see cref=\"IRouteResolver\"/> instance that will be used to resolve a route, from the modules, that matches the incoming <see cref=\"Request\"/>.</param>\r\n        /// <param name=\"contextFactory\">A factory for creating contexts</param>\r\n        /// <param name=\"statusCodeHandlers\">Error handlers</param>\r\n        /// <param name=\"requestTracing\">The request tracing instance.</param>\r\n        /// <param name=\"staticContentProvider\">The provider to use for serving static content</param>\r\n        /// <param name=\"negotiator\">The response negotiator.</param>\r\n        /// <param name=\"environment\">An <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        public NancyEngine(IRequestDispatcher dispatcher,\r\n            INancyContextFactory contextFactory,\r\n            IEnumerable<IStatusCodeHandler> statusCodeHandlers,\r\n            IRequestTracing requestTracing,\r\n            IStaticContentProvider staticContentProvider,\r\n            IResponseNegotiator negotiator,\r\n            INancyEnvironment environment)\r\n        {\r\n            if (dispatcher == null)\r\n            {\r\n                throw new ArgumentNullException(\"dispatcher\", \"The resolver parameter cannot be null.\");\r\n            }\r\n\r\n            if (contextFactory == null)\r\n            {\r\n                throw new ArgumentNullException(\"contextFactory\");\r\n            }\r\n\r\n            if (statusCodeHandlers == null)\r\n            {\r\n                throw new ArgumentNullException(\"statusCodeHandlers\");\r\n            }\r\n\r\n            if (requestTracing == null)\r\n            {\r\n                throw new ArgumentNullException(\"requestTracing\");\r\n            }\r\n\r\n            if (staticContentProvider == null)\r\n            {\r\n                throw new ArgumentNullException(\"staticContentProvider\");\r\n            }\r\n\r\n            if (negotiator == null)\r\n            {\r\n                throw new ArgumentNullException(\"negotiator\");\r\n            }\r\n\r\n            this.dispatcher = dispatcher;\r\n            this.contextFactory = contextFactory;\r\n            this.statusCodeHandlers = statusCodeHandlers.ToArray();\r\n            this.requestTracing = requestTracing;\r\n            this.staticContentProvider = staticContentProvider;\r\n            this.negotiator = negotiator;\r\n            this.engineDisposedCts = new CancellationTokenSource();\r\n            this.traceConfiguration = environment.GetValue<TraceConfiguration>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Factory for creating an <see cref=\"IPipelines\"/> instance for a incoming request.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IPipelines\"/> instance.</value>\r\n        public Func<NancyContext, IPipelines> RequestPipelinesFactory { get; set; }\r\n\r\n        /// <summary>\r\n        /// Handles an incoming <see cref=\"Request\"/> async.\r\n        /// </summary>\r\n        /// <param name=\"request\">An <see cref=\"Request\"/> instance, containing the information about the current request.</param>\r\n        /// <param name=\"preRequest\">Delegate to call before the request is processed</param>\r\n        /// <param name=\"cancellationToken\">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>\r\n        /// <returns>The task object representing the asynchronous operation.</returns>\r\n        public async Task<NancyContext> HandleRequest(Request request, Func<NancyContext, NancyContext> preRequest, CancellationToken cancellationToken)\r\n        {\r\n            using (var cts = CancellationTokenSource.CreateLinkedTokenSource(this.engineDisposedCts.Token, cancellationToken))\r\n            {\r\n                cts.Token.ThrowIfCancellationRequested();\r\n\r\n                if (request == null)\r\n                {\r\n                    throw new ArgumentNullException(\"request\", \"The request parameter cannot be null.\");\r\n                }\r\n\r\n                var context = this.contextFactory.Create(request);\r\n\r\n                if (preRequest != null)\r\n                {\r\n                    context = preRequest(context);\r\n                }\r\n\r\n                var staticContentResponse = this.staticContentProvider.GetContent(context);\r\n                if (staticContentResponse != null)\r\n                {\r\n                    context.Response = staticContentResponse;\r\n\r\n                    return context;\r\n                }\r\n\r\n                var pipelines = this.RequestPipelinesFactory.Invoke(context);\r\n\r\n                var nancyContext = await this.InvokeRequestLifeCycle(context, cts.Token, pipelines)\r\n                    .ConfigureAwait(false);\r\n\r\n                this.CheckStatusCodeHandler(nancyContext);\r\n\r\n                this.SaveTraceInformation(nancyContext);\r\n\r\n                return nancyContext;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.\r\n        /// </summary>\r\n        public virtual void Dispose()\r\n        {\r\n            this.engineDisposedCts.Cancel();\r\n        }\r\n\r\n        private void SaveTraceInformation(NancyContext ctx)\r\n        {\r\n            if (!this.EnableTracing(ctx))\r\n            {\r\n                return;\r\n            }\r\n\r\n            if (ctx.Request == null || ctx.Response == null)\r\n            {\r\n                return;\r\n            }\r\n\r\n            var sessionGuid = this.GetDiagnosticsSessionGuid(ctx);\r\n\r\n            ctx.Trace.RequestData = ctx.Request;\r\n            ctx.Trace.ResponseData = ctx.Response;\r\n\r\n            this.requestTracing.AddRequestDiagnosticToSession(sessionGuid, ctx);\r\n\r\n            this.UpdateTraceCookie(ctx, sessionGuid);\r\n        }\r\n\r\n        private bool EnableTracing(NancyContext ctx)\r\n        {\r\n            return this.traceConfiguration.Enabled && !ctx.Items.ContainsKey(DiagnosticsHook.ItemsKey);\r\n        }\r\n\r\n        private Guid GetDiagnosticsSessionGuid(NancyContext ctx)\r\n        {\r\n            string sessionId;\r\n            if (!ctx.Request.Cookies.TryGetValue(\"__NCTRACE\", out sessionId))\r\n            {\r\n                return this.requestTracing.CreateSession();\r\n            }\r\n\r\n            Guid sessionGuid;\r\n            if (!Guid.TryParse(sessionId, out sessionGuid))\r\n            {\r\n                return this.requestTracing.CreateSession();\r\n            }\r\n\r\n            if (!this.requestTracing.IsValidSessionId(sessionGuid))\r\n            {\r\n                return this.requestTracing.CreateSession();\r\n            }\r\n\r\n            return sessionGuid;\r\n        }\r\n\r\n        private void UpdateTraceCookie(NancyContext ctx, Guid sessionGuid)\r\n        {\r\n            var cookie = new NancyCookie(\"__NCTRACE\", sessionGuid.ToString(), true)\r\n            {\r\n                Expires = DateTime.Now.AddMinutes(30)\r\n            };\r\n\r\n            ctx.Response = ctx.Response.WithCookie(cookie);\r\n        }\r\n\r\n        private void CheckStatusCodeHandler(NancyContext context)\r\n        {\r\n            if (context.Response == null)\r\n            {\r\n                return;\r\n            }\r\n\r\n            IStatusCodeHandler defaultHandler = null;\r\n            IStatusCodeHandler customHandler = null;\r\n\r\n            foreach (var statusCodeHandler in this.statusCodeHandlers)\r\n            {\r\n                if (!statusCodeHandler.HandlesStatusCode(context.Response.StatusCode, context))\r\n                {\r\n                    continue;\r\n                }\r\n\r\n                if (defaultHandler == null && (statusCodeHandler is DefaultStatusCodeHandler))\r\n                {\r\n                    defaultHandler = statusCodeHandler;\r\n                    continue;\r\n                }\r\n\r\n                if (customHandler == null && !(statusCodeHandler is DefaultStatusCodeHandler))\r\n                {\r\n                    customHandler = statusCodeHandler;\r\n                    continue;\r\n                }\r\n\r\n                if ((defaultHandler != null) && (customHandler != null))\r\n                {\r\n                    break;\r\n                }\r\n            }\r\n\r\n            var handler = customHandler ?? defaultHandler;\r\n\r\n            if (handler == null)\r\n            {\r\n                return;\r\n            }\r\n\r\n            try\r\n            {\r\n                handler.Handle(context.Response.StatusCode, context);\r\n            }\r\n            catch (Exception)\r\n            {\r\n                if (defaultHandler == null)\r\n                {\r\n                    throw;\r\n                }\r\n\r\n                defaultHandler.Handle(context.Response.StatusCode, context);\r\n            }\r\n        }\r\n\r\n        private async Task<NancyContext> InvokeRequestLifeCycle(NancyContext context, CancellationToken cancellationToken, IPipelines pipelines)\r\n        {\r\n            try\r\n            {\r\n                var response = await InvokePreRequestHook(context, cancellationToken, pipelines.BeforeRequest).ConfigureAwait(false) ??\r\n                               await this.dispatcher.Dispatch(context, cancellationToken).ConfigureAwait(false);\r\n\r\n                context.Response = response;\r\n\r\n                await this.InvokePostRequestHook(context, cancellationToken, pipelines.AfterRequest).ConfigureAwait(false);\r\n\r\n                await response.PreExecute(context).ConfigureAwait(false);\r\n            }\r\n            catch (Exception ex)\r\n            {\r\n                this.InvokeOnErrorHook(context, pipelines.OnError, ex);\r\n            }\r\n\r\n            return context;\r\n        }\r\n\r\n        private static Task<Response> InvokePreRequestHook(NancyContext context, CancellationToken cancellationToken, BeforePipeline pipeline)\r\n        {\r\n            return pipeline == null ? Task.FromResult<Response>(null) : pipeline.Invoke(context, cancellationToken);\r\n        }\r\n\r\n        private Task InvokePostRequestHook(NancyContext context, CancellationToken cancellationToken, AfterPipeline pipeline)\r\n        {\r\n            return pipeline == null ? TaskHelpers.CompletedTask : pipeline.Invoke(context, cancellationToken);\r\n        }\r\n\r\n        private void InvokeOnErrorHook(NancyContext context, ErrorPipeline pipeline, Exception ex)\r\n        {\r\n            try\r\n            {\r\n                if (pipeline == null)\r\n                {\r\n                    throw new RequestExecutionException(ex);\r\n                }\r\n\r\n                var onErrorResult = pipeline.Invoke(context, ex);\r\n\r\n                if (onErrorResult == null)\r\n                {\r\n                    throw new RequestExecutionException(ex);\r\n                }\r\n\r\n                context.Response = this.negotiator.NegotiateResponse(onErrorResult, context);\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                context.Response = new Response { StatusCode = HttpStatusCode.InternalServerError };\r\n                context.Items[ERROR_KEY] = e.ToString();\r\n                context.Items[ERROR_EXCEPTION] = e;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/NancyEngineExtensions.cs",
    "content": "namespace Nancy\r\n{\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n\r\n    /// <summary>\r\n    /// Extensions for Nancy engine\r\n    /// </summary>\r\n    public static class NancyEngineExtensions\r\n    {\r\n        /// <summary>\r\n        /// Handles an incoming <see cref=\"Request\"/>.\r\n        /// </summary>\r\n        /// <param name=\"nancyEngine\">The <see cref=\"INancyEngine\"/> instance.</param>\r\n        /// <param name=\"request\">An <see cref=\"Request\"/> instance, containing the information about the current request.</param>\r\n        /// <returns>A <see cref=\"NancyContext\"/> instance containing the request/response context.</returns>\r\n        public static Task<NancyContext> HandleRequest(this INancyEngine nancyEngine, Request request)\r\n        {\r\n            return nancyEngine.HandleRequest(request, context => context, CancellationToken.None);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/NancyModule.cs",
    "content": "namespace Nancy\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.ComponentModel;\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n    using Nancy.ModelBinding;\r\n    using Nancy.Responses.Negotiation;\r\n    using Nancy.Routing;\r\n    using Nancy.Session;\r\n    using Nancy.Validation;\r\n    using Nancy.ViewEngines;\r\n\r\n    /// <summary>\r\n    /// Basic class containing the functionality for defining routes and actions in Nancy.\r\n    /// </summary>\r\n    public abstract class NancyModule : INancyModule, IHideObjectMembers\r\n    {\r\n        private readonly List<Route> routes;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancyModule\"/> class.\r\n        /// </summary>\r\n        protected NancyModule()\r\n            : this(string.Empty)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancyModule\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"modulePath\">A <see cref=\"string\"/> containing the root relative path that all paths in the module will be a subset of.</param>\r\n        protected NancyModule(string modulePath)\r\n        {\r\n            this.After = new AfterPipeline();\r\n            this.Before = new BeforePipeline();\r\n            this.OnError = new ErrorPipeline();\r\n\r\n            this.ModulePath = modulePath;\r\n            this.routes = new List<Route>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Non-model specific data for rendering in the response\r\n        /// </summary>\r\n        public dynamic ViewBag\r\n        {\r\n            get { return this.Context == null ? null : this.Context.ViewBag; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Dynamic access to text resources.\r\n        /// </summary>\r\n        public dynamic Text\r\n        {\r\n            get { return this.Context.Text; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for DELETE requests.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Delete(string path, Func<dynamic, object> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Delete<object>(path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for DELETE requests.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The return type of the <paramref name=\"action\"/></typeparam>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Delete<T>(string path, Func<dynamic, T> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Delete(path, args => Task.FromResult(action((DynamicDictionary)args)), condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for DELETE requests.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Delete(string path, Func<dynamic, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Delete<object>(path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for DELETE requests.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The return type of the <paramref name=\"action\"/></typeparam>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Delete<T>(string path, Func<dynamic, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Delete(path, (args, ct) => action((DynamicDictionary)args), condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for DELETE requests.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Delete(string path, Func<dynamic, CancellationToken, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Delete<object>(path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for DELETE requests.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The return type of the <paramref name=\"action\"/></typeparam>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Delete<T>(string path, Func<dynamic, CancellationToken, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.AddRoute(\"DELETE\", path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for GET requests.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Get(string path, Func<dynamic, object> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Get<object>(path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for GET requests.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The return type of the <paramref name=\"action\"/></typeparam>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Get<T>(string path, Func<dynamic, T> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Get(path, args => Task.FromResult(action((DynamicDictionary)args)), condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for GET requests.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Get(string path, Func<dynamic, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Get<object>(path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for GET requests.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The return type of the <paramref name=\"action\"/></typeparam>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Get<T>(string path, Func<dynamic, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Get(path, (args, ct) => action((DynamicDictionary)args), condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for GET requests.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Get(string path, Func<dynamic, CancellationToken, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Get<object>(path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for GET requests.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The return type of the <paramref name=\"action\"/></typeparam>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Get<T>(string path, Func<dynamic, CancellationToken, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.AddRoute(\"GET\", path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for HEAD requests.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Head(string path, Func<dynamic, object> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Head<object>(path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for HEAD requests.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The return type of the <paramref name=\"action\"/></typeparam>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Head<T>(string path, Func<dynamic, T> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Head(path, args => Task.FromResult(action((DynamicDictionary)args)), condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for HEAD requests.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Head(string path, Func<dynamic, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Head<object>(path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for HEAD requests.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The return type of the <paramref name=\"action\"/></typeparam>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Head<T>(string path, Func<dynamic, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Head(path, (args, ct) => action((DynamicDictionary)args), condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for HEAD requests.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Head(string path, Func<dynamic, CancellationToken, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Head<object>(path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for HEAD requests.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The return type of the <paramref name=\"action\"/></typeparam>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Head<T>(string path, Func<dynamic, CancellationToken, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.AddRoute(\"HEAD\", path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for OPTIONS requests.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Options(string path, Func<dynamic, object> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Options<object>(path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for OPTIONS requests.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The return type of the <paramref name=\"action\"/></typeparam>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Options<T>(string path, Func<dynamic, T> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Options(path, args => Task.FromResult(action((DynamicDictionary)args)), condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for OPTIONS requests.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Options(string path, Func<dynamic, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Options<object>(path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for OPTIONS requests.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The return type of the <paramref name=\"action\"/></typeparam>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Options<T>(string path, Func<dynamic, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Options(path, (args, ct) => action((DynamicDictionary)args), condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for OPTIONS requests.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Options(string path, Func<dynamic, CancellationToken, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Options<object>(path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for OPTIONS requests.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The return type of the <paramref name=\"action\"/></typeparam>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Options<T>(string path, Func<dynamic, CancellationToken, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.AddRoute(\"OPTIONS\", path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for PATCH requests.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Patch(string path, Func<dynamic, object> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Patch<object>(path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for PATCH requests.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The return type of the <paramref name=\"action\"/></typeparam>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Patch<T>(string path, Func<dynamic, T> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Patch(path, args => Task.FromResult(action((DynamicDictionary)args)), condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for PATCH requests.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Patch(string path, Func<dynamic, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Patch<object>(path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for PATCH requests.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The return type of the <paramref name=\"action\"/></typeparam>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Patch<T>(string path, Func<dynamic, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Patch(path, (args, ct) => action((DynamicDictionary)args), condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for PATCH requests.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Patch(string path, Func<dynamic, CancellationToken, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Patch<object>(path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for PATCH requests.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The return type of the <paramref name=\"action\"/></typeparam>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Patch<T>(string path, Func<dynamic, CancellationToken, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.AddRoute(\"PATCH\", path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for POST requests.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Post(string path, Func<dynamic, object> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Post<object>(path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for POST requests.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The return type of the <paramref name=\"action\"/></typeparam>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Post<T>(string path, Func<dynamic, T> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Post(path, args => Task.FromResult(action((DynamicDictionary)args)), condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for POST requests.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Post(string path, Func<dynamic, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Post<object>(path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for POST requests.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The return type of the <paramref name=\"action\"/></typeparam>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Post<T>(string path, Func<dynamic, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Post(path, (args, ct) => action((DynamicDictionary)args), condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for POST requests.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Post(string path, Func<dynamic, CancellationToken, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Post<object>(path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for POST requests.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The return type of the <paramref name=\"action\"/></typeparam>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Post<T>(string path, Func<dynamic, CancellationToken, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.AddRoute(\"POST\", path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for PUT requests.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Put(string path, Func<dynamic, object> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Put<object>(path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for PUT requests.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The return type of the <paramref name=\"action\"/></typeparam>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Put<T>(string path, Func<dynamic, T> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Put(path, args => Task.FromResult(action((DynamicDictionary)args)), condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for PUT requests.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Put(string path, Func<dynamic, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Put<object>(path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for PUT requests.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The return type of the <paramref name=\"action\"/></typeparam>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Put<T>(string path, Func<dynamic, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Put(path, (args, ct) => action((DynamicDictionary)args), condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for PUT requests.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Put(string path, Func<dynamic, CancellationToken, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.Put<object>(path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for PUT requests.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The return type of the <paramref name=\"action\"/></typeparam>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        public virtual void Put<T>(string path, Func<dynamic, CancellationToken, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n        {\r\n            this.AddRoute(\"PUT\", path, action, condition, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the root path of the routes in the current module.\r\n        /// </summary>\r\n        /// <value>\r\n        /// A <see cref=\"T:System.String\" /> containing the root path of the module or <see langword=\"null\" />\r\n        /// if no root path should be used.</value><remarks>All routes will be relative to this root path.\r\n        /// </remarks>\r\n        public string ModulePath { get; protected set; }\r\n\r\n        /// <summary>\r\n        /// Gets all declared routes by the module.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"IEnumerable{T}\"/> instance, containing all <see cref=\"Route\"/> instances declared by the module.</value>\r\n        /// <remarks>This is automatically set by Nancy at runtime.</remarks>\r\n        [EditorBrowsable(EditorBrowsableState.Never)]\r\n        public virtual IEnumerable<Route> Routes\r\n        {\r\n            get { return this.routes.AsReadOnly(); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the current session.\r\n        /// </summary>\r\n        public ISession Session\r\n        {\r\n            get { return this.Request.Session; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Renders a view from inside a route handler.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"ViewRenderer\"/> instance that is used to determine which view that should be rendered.</value>\r\n        public ViewRenderer View\r\n        {\r\n            get { return new ViewRenderer(this); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Used to negotiate the content returned based on Accepts header.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"Negotiator\"/> instance that is used to negotiate the content returned.</value>\r\n        public Negotiator Negotiate\r\n        {\r\n            get { return new Negotiator(this.Context); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the validator locator.\r\n        /// </summary>\r\n        /// <remarks>This is automatically set by Nancy at runtime.</remarks>\r\n        [EditorBrowsable(EditorBrowsableState.Never)]\r\n        public IModelValidatorLocator ValidatorLocator { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets an <see cref=\"Request\"/> instance that represents the current request.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"Request\"/> instance.</value>\r\n        public virtual Request Request\r\n        {\r\n            get { return this.Context.Request; }\r\n            set { this.Context.Request = value; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// The extension point for accessing the view engines in Nancy.\r\n        /// </summary><value>An <see cref=\"IViewFactory\" /> instance.</value>\r\n        /// <remarks>This is automatically set by Nancy at runtime.</remarks>\r\n        [EditorBrowsable(EditorBrowsableState.Never)]\r\n        public IViewFactory ViewFactory { get; set; }\r\n\r\n        /// <summary><para>\r\n        /// The post-request hook\r\n        /// </para><para>\r\n        /// The post-request hook is called after the response is created by the route execution.\r\n        /// It can be used to rewrite the response or add/remove items from the context.\r\n        /// </para>\r\n        /// <remarks>This is automatically set by Nancy at runtime.</remarks>\r\n        /// </summary>\r\n        public AfterPipeline After { get; set; }\r\n\r\n        /// <summary>\r\n        /// <para>\r\n        /// The pre-request hook\r\n        /// </para>\r\n        /// <para>\r\n        /// The PreRequest hook is called prior to executing a route. If any item in the\r\n        /// pre-request pipeline returns a response then the route is not executed and the\r\n        /// response is returned.\r\n        /// </para>\r\n        /// <remarks>This is automatically set by Nancy at runtime.</remarks>\r\n        /// </summary>\r\n        public BeforePipeline Before { get; set; }\r\n\r\n        /// <summary>\r\n        /// <para>\r\n        /// The error hook\r\n        /// </para>\r\n        /// <para>\r\n        /// The error hook is called if an exception is thrown at any time during executing\r\n        /// the PreRequest hook, a route and the PostRequest hook. It can be used to set\r\n        /// the response and/or finish any ongoing tasks (close database session, etc).\r\n        /// </para>\r\n        /// <remarks>This is automatically set by Nancy at runtime.</remarks>\r\n        /// </summary>\r\n        public ErrorPipeline OnError { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the current Nancy context\r\n        /// </summary>\r\n        /// <value>A <see cref=\"NancyContext\" /> instance.</value>\r\n        /// <remarks>This is automatically set by Nancy at runtime.</remarks>\r\n        public NancyContext Context { get; set; }\r\n\r\n        /// <summary>\r\n        /// An extension point for adding support for formatting response contents.\r\n        /// </summary><value>This property will always return <see langword=\"null\" /> because it acts as an extension point.</value><remarks>Extension methods to this property should always return <see cref=\"P:Nancy.NancyModuleBase.Response\" /> or one of the types that can implicitly be types into a <see cref=\"P:Nancy.NancyModuleBase.Response\" />.</remarks>\r\n        public IResponseFormatter Response { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the model binder locator\r\n        /// </summary>\r\n        /// <remarks>This is automatically set by Nancy at runtime.</remarks>\r\n        [EditorBrowsable(EditorBrowsableState.Never)]\r\n        public IModelBinderLocator ModelBinderLocator { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the model validation result\r\n        /// </summary>\r\n        /// <remarks>This is automatically set by Nancy at runtime when you run validation.</remarks>\r\n        public virtual ModelValidationResult ModelValidationResult\r\n        {\r\n            get { return this.Context == null ? null : this.Context.ModelValidationResult; }\r\n            set\r\n            {\r\n                if (this.Context != null)\r\n                {\r\n                    this.Context.ModelValidationResult = value;\r\n                }\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Declares a route for the module\r\n        /// </summary>\r\n        /// <typeparam name=\"T\"></typeparam>\r\n        /// <param name=\"name\">Name of the route</param>\r\n        /// <param name=\"method\">The HTTP method that the route will response to</param>\r\n        /// <param name=\"path\">The path that the route will respond to</param>\r\n        /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n        /// <param name=\"condition\">A condition to determine if the route can be hit</param>\r\n        protected void AddRoute<T>(string method, string path, Func<dynamic, CancellationToken, Task<T>> action, Func<NancyContext, bool> condition, string name)\r\n        {\r\n            this.routes.Add(new Route<T>(name ?? string.Empty, method, this.GetFullPath(path), condition, action));\r\n        }\r\n\r\n        private string GetFullPath(string path)\r\n        {\r\n            var relativePath = (path ?? string.Empty).Trim('/');\r\n            var parentPath = (this.ModulePath ?? string.Empty).Trim('/');\r\n\r\n            if (string.IsNullOrEmpty(parentPath))\r\n            {\r\n                return string.Concat(\"/\", relativePath);\r\n            }\r\n\r\n            if (string.IsNullOrEmpty(relativePath))\r\n            {\r\n                return string.Concat(\"/\", parentPath);\r\n            }\r\n\r\n            return string.Concat(\"/\", parentPath, \"/\", relativePath);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/NegotiatorExtensions.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using Nancy.Cookies;\r\n    using Nancy.Responses.Negotiation;\r\n\r\n    /// <summary>\r\n    /// Extensions for negotioator\r\n    /// </summary>\r\n    public static class NegotiatorExtensions\r\n    {\r\n        /// <summary>\r\n        /// Add a cookie to the response.\r\n        /// </summary>\r\n        /// <param name=\"negotiator\">The <see cref=\"Negotiator\"/> instance.</param>\r\n        /// <param name=\"cookie\">The <see cref=\"INancyCookie\"/> instance that should be added.</param>\r\n        /// <returns>The modified <see cref=\"Negotiator\"/> instance.</returns>\r\n        public static Negotiator WithCookie(this Negotiator negotiator, INancyCookie cookie)\r\n        {\r\n            negotiator.NegotiationContext.Cookies.Add(cookie);\r\n            return negotiator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Add a collection of cookies to the response.\r\n        /// </summary>\r\n        /// <param name=\"negotiator\">The <see cref=\"Negotiator\"/> instance.</param>\r\n        /// <param name=\"cookies\">The <see cref=\"INancyCookie\"/> instances that should be added.</param>\r\n        /// <returns>The modified <see cref=\"Negotiator\"/> instance.</returns>\r\n        public static Negotiator WithCookies(this Negotiator negotiator, IEnumerable<INancyCookie> cookies)\r\n        {\r\n            foreach (var cookie in cookies)\r\n            {\r\n                negotiator.WithCookie(cookie);\r\n            }\r\n\r\n            return negotiator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Add a header to the response\r\n        /// </summary>\r\n        /// <param name=\"negotiator\">Negotiator object</param>\r\n        /// <param name=\"header\">Header name</param>\r\n        /// <param name=\"value\">Header value</param>\r\n        /// <returns>Modified negotiator</returns>\r\n        public static Negotiator WithHeader(this Negotiator negotiator, string header, string value)\r\n        {\r\n            return negotiator.WithHeaders(new { Header = header, Value = value });\r\n        }\r\n\r\n        /// <summary>\r\n        /// Add a content type to the response\r\n        /// </summary>\r\n        /// <param name=\"negotiator\">Negotiator object</param>\r\n        /// <param name=\"contentType\">Content type value</param>\r\n        /// <returns>Modified negotiator</returns>\r\n        public static Negotiator WithContentType(this Negotiator negotiator, string contentType)\r\n        {\r\n          return negotiator.WithHeaders(new { Header = \"Content-Type\", Value = contentType });\r\n        }\r\n        /// <summary>\r\n        /// Adds headers to the response using anonymous types\r\n        /// </summary>\r\n        /// <param name=\"negotiator\">Negotiator object</param>\r\n        /// <param name=\"headers\">\r\n        /// Array of headers - each header should be an anonymous type with two string properties\r\n        /// 'Header' and 'Value' to represent the header name and its value.\r\n        /// </param>\r\n        /// <returns>Modified negotiator</returns>\r\n        public static Negotiator WithHeaders(this Negotiator negotiator, params object[] headers)\r\n        {\r\n            return negotiator.WithHeaders(headers.Select(GetTuple).ToArray());\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds headers to the response using anonymous types\r\n        /// </summary>\r\n        /// <param name=\"negotiator\">Negotiator object</param>\r\n        /// <param name=\"headers\">\r\n        /// Array of headers - each header should be a Tuple with two string elements\r\n        /// for header name and header value\r\n        /// </param>\r\n        /// <returns>Modified negotiator</returns>\r\n        public static Negotiator WithHeaders(this Negotiator negotiator, params Tuple<string, string>[] headers)\r\n        {\r\n            foreach (var keyValuePair in headers)\r\n            {\r\n                negotiator.NegotiationContext.Headers[keyValuePair.Item1] = keyValuePair.Item2;\r\n            }\r\n\r\n            return negotiator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Allows the response to be negotiated with any processors available for any content type\r\n        /// </summary>\r\n        /// <param name=\"negotiator\">Negotiator object</param>\r\n        /// <returns>Modified negotiator</returns>\r\n        public static Negotiator WithFullNegotiation(this Negotiator negotiator)\r\n        {\r\n            negotiator.NegotiationContext.PermissableMediaRanges.Clear();\r\n            negotiator.NegotiationContext.PermissableMediaRanges.Add(\"*/*\");\r\n\r\n            return negotiator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Allows the response to be negotiated with a specific media range\r\n        /// This will remove the wildcard range if it is already specified\r\n        /// </summary>\r\n        /// <param name=\"negotiator\">Negotiator object</param>\r\n        /// <param name=\"mediaRange\">Media range to add</param>\r\n        /// <returns>Modified negotiator</returns>\r\n        public static Negotiator WithAllowedMediaRange(this Negotiator negotiator, MediaRange mediaRange)\r\n        {\r\n            var wildcards =\r\n                negotiator.NegotiationContext.PermissableMediaRanges.Where(\r\n                    mr => mr.Type.IsWildcard && mr.Subtype.IsWildcard).ToArray();\r\n\r\n            foreach (var wildcard in wildcards)\r\n            {\r\n                negotiator.NegotiationContext.PermissableMediaRanges.Remove(wildcard);\r\n            }\r\n\r\n            negotiator.NegotiationContext.PermissableMediaRanges.Add(mediaRange);\r\n\r\n            return negotiator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Uses the specified model as the default model for negotiation\r\n        /// </summary>\r\n        /// <param name=\"negotiator\">Negotiator object</param>\r\n        /// <param name=\"model\">Model object</param>\r\n        /// <returns>Modified negotiator</returns>\r\n        public static Negotiator WithModel(this Negotiator negotiator, dynamic model)\r\n        {\r\n            negotiator.NegotiationContext.DefaultModel = model;\r\n\r\n            return negotiator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Uses the specified view for html output\r\n        /// </summary>\r\n        /// <param name=\"negotiator\">Negotiator object</param>\r\n        /// <param name=\"viewName\">View name</param>\r\n        /// <returns>Modified negotiator</returns>\r\n        public static Negotiator WithView(this Negotiator negotiator, string viewName)\r\n        {\r\n            negotiator.NegotiationContext.ViewName = viewName;\r\n\r\n            return negotiator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Sets the model to use for a particular media range.\r\n        /// Will also add the MediaRange to the allowed list\r\n        /// </summary>\r\n        /// <param name=\"negotiator\">Negotiator object</param>\r\n        /// <param name=\"range\">Range to match against</param>\r\n        /// <param name=\"model\">Model object</param>\r\n        /// <returns>Updated negotiator object</returns>\r\n        public static Negotiator WithMediaRangeModel(this Negotiator negotiator, MediaRange range, object model)\r\n        {\r\n            return negotiator.WithMediaRangeModel(range, () => model);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Sets the model to use for a particular media range.\r\n        /// Will also add the MediaRange to the allowed list\r\n        /// </summary>\r\n        /// <param name=\"negotiator\">Negotiator object</param>\r\n        /// <param name=\"range\">Range to match against</param>\r\n        /// <param name=\"modelFactory\">Model factory for returning the model object</param>\r\n        /// <returns>Updated negotiator object</returns>\r\n        public static Negotiator WithMediaRangeModel(this Negotiator negotiator, MediaRange range, Func<object> modelFactory)\r\n        {\r\n            negotiator.NegotiationContext.PermissableMediaRanges.Add(range);\r\n            negotiator.NegotiationContext.MediaRangeModelMappings.Add(range, modelFactory);\r\n\r\n            return negotiator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Sets the <see cref=\"Response\"/> to use for a particular media range.\r\n        /// Will also add the MediaRange to the allowed list\r\n        /// </summary>\r\n        /// <param name=\"negotiator\">Negotiator object</param>\r\n        /// <param name=\"range\">Range to match against</param>\r\n        /// <param name=\"response\">A <see cref=\"Response\"/> object</param>\r\n        /// <returns>Updated negotiator object</returns>\r\n        public static Negotiator WithMediaRangeResponse(this Negotiator negotiator, MediaRange range, Response response)\r\n        {\r\n            return negotiator.WithMediaRangeResponse(range, () => response);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Sets the <see cref=\"Response\"/> to use for a particular media range.\r\n        /// Will also add the MediaRange to the allowed list\r\n        /// </summary>\r\n        /// <param name=\"negotiator\">Negotiator object</param>\r\n        /// <param name=\"range\">Range to match against</param>\r\n        /// <param name=\"responseFactory\">Factory for returning the <see cref=\"Response\"/> object</param>\r\n        /// <returns>Updated negotiator object</returns>\r\n        public static Negotiator WithMediaRangeResponse(this Negotiator negotiator, MediaRange range, Func<Response> responseFactory)\r\n        {\r\n            return negotiator.WithMediaRangeModel(range, responseFactory);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Sets the status code that should be assigned to the final response.\r\n        /// </summary>\r\n        /// <param name=\"negotiator\">Negotiator object</param>\r\n        /// <param name=\"statusCode\">The status code that should be used.</param>\r\n        /// <returns>Updated negotiator object</returns>\r\n        public static Negotiator WithStatusCode(this Negotiator negotiator, int statusCode)\r\n        {\r\n            negotiator.NegotiationContext.StatusCode = (HttpStatusCode)statusCode;\r\n            return negotiator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Sets the description of the status code that should be assigned to the final response.\r\n        /// </summary>\r\n        /// <param name=\"negotiator\">Negotiator object</param>\r\n        /// <param name=\"reasonPhrase\">The status code description that should be used.</param>\r\n        /// <returns>Updated negotiator object</returns>\r\n        public static Negotiator WithReasonPhrase(this Negotiator negotiator, string reasonPhrase)\r\n        {\r\n            negotiator.NegotiationContext.ReasonPhrase = reasonPhrase;\r\n            return negotiator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Sets the status code that should be assigned to the final response.\r\n        /// </summary>\r\n        /// <param name=\"negotiator\">Negotiator object</param>\r\n        /// <param name=\"statusCode\">The status code that should be used.</param>\r\n        /// <returns>Updated negotiator object</returns>\r\n        public static Negotiator WithStatusCode(this Negotiator negotiator, HttpStatusCode statusCode)\r\n        {\r\n            negotiator.NegotiationContext.StatusCode = statusCode;\r\n            return negotiator;\r\n        }\r\n\r\n        private static Tuple<string, string> GetTuple(object header)\r\n        {\r\n            var properties = header.GetType()\r\n                                   .GetProperties()\r\n                                   .Where(prop => prop.CanRead && prop.PropertyType == typeof(string))\r\n                                   .ToArray();\r\n\r\n            var headerProperty = properties\r\n                                    .Where(p => string.Equals(p.Name, \"Header\", StringComparison.OrdinalIgnoreCase))\r\n                                    .FirstOrDefault();\r\n\r\n            var valueProperty = properties\r\n                                    .Where(p => string.Equals(p.Name, \"Value\", StringComparison.OrdinalIgnoreCase))\r\n                                    .FirstOrDefault();\r\n\r\n            if (headerProperty == null || valueProperty == null)\r\n            {\r\n                throw new ArgumentException(\"Unable to extract 'Header' or 'Value' properties from anonymous type.\");\r\n            }\r\n\r\n            return Tuple.Create(\r\n                (string)headerProperty.GetValue(header, null),\r\n                (string)valueProperty.GetValue(header, null));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/NotFoundResponse.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    /// <summary>\r\n    /// Not Found response\r\n    /// </summary>\r\n    /// <seealso cref=\"Nancy.Response\" />\r\n    public class NotFoundResponse : Response\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NotFoundResponse\"/> class.\r\n        /// </summary>\r\n        public NotFoundResponse()\r\n        {\r\n            this.ContentType = \"text/html\";\r\n            this.StatusCode = HttpStatusCode.NotFound;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Owin/DelegateExtensions.cs",
    "content": "﻿namespace Nancy.Owin\r\n{\r\n    using System;\r\n\r\n    using AppFunc = System.Func<System.Collections.Generic.IDictionary<string, object>,\r\n        System.Threading.Tasks.Task>;\r\n\r\n    using MidFunc = System.Func<System.Func<System.Collections.Generic.IDictionary<string, object>,\r\n            System.Threading.Tasks.Task>, System.Func<System.Collections.Generic.IDictionary<string, object>,\r\n            System.Threading.Tasks.Task>>;\r\n\r\n    /// <summary>\r\n    /// OWIN extensions for the delegate-based approach.\r\n    /// </summary>\r\n    public static class DelegateExtensions\r\n    {\r\n        /// <summary>\r\n        /// Adds Nancy to the OWIN pipeline.\r\n        /// </summary>\r\n        /// <param name=\"builder\">The application builder delegate.</param>\r\n        /// <param name=\"action\">A configuration builder action.</param>\r\n        /// <returns>The application builder delegate.</returns>\r\n        public static Action<MidFunc> UseNancy(this Action<MidFunc> builder, Action<NancyOptions> action)\r\n        {\r\n            var options = new NancyOptions();\r\n\r\n            action(options);\r\n\r\n            return builder.UseNancy(options);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds Nancy to the OWIN pipeline.\r\n        /// </summary>\r\n        /// <param name=\"builder\">The application builder delegate.</param>\r\n        /// <param name=\"options\">The Nancy options.</param>\r\n        /// <returns>The application builder delegate.</returns>\r\n        public static Action<MidFunc> UseNancy(this Action<MidFunc> builder, NancyOptions options = null)\r\n        {\r\n            var nancyOptions = options ?? new NancyOptions();\r\n\r\n            builder(NancyMiddleware.UseNancy(nancyOptions).Invoke);\r\n\r\n            return builder;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Owin/NancyContextExtensions.cs",
    "content": "﻿namespace Nancy.Owin\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// OWIN extensions for the NancyContext.\r\n    /// </summary>\r\n    public static class NancyContextExtensions\r\n    {\r\n        /// <summary>\r\n        /// Gets the OWIN environment dictionary.\r\n        /// </summary>\r\n        /// <param name=\"context\">The Nancy context.</param>\r\n        /// <returns>The OWIN environment dictionary.</returns>\r\n        public static IDictionary<string, object> GetOwinEnvironment(this NancyContext context)\r\n        {\r\n            object environment;\r\n            if (context.Items.TryGetValue(NancyMiddleware.RequestEnvironmentKey, out environment))\r\n            {\r\n                return environment as IDictionary<string, object>;\r\n            }\r\n\r\n            return null;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Owin/NancyMiddleware.cs",
    "content": "﻿namespace Nancy.Owin\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Globalization;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Net;\r\n    using System.Security.Claims;\r\n    using System.Security.Cryptography.X509Certificates;\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n\r\n    using Nancy.Helpers;\r\n    using Nancy.IO;\r\n\r\n    using AppFunc = System.Func<System.Collections.Generic.IDictionary<string, object>,\r\n       System.Threading.Tasks.Task>;\r\n\r\n    using MidFunc = System.Func<System.Func<System.Collections.Generic.IDictionary<string, object>,\r\n            System.Threading.Tasks.Task>, System.Func<System.Collections.Generic.IDictionary<string, object>,\r\n            System.Threading.Tasks.Task>>;\r\n\r\n    /// <summary>\r\n    /// Nancy middleware for OWIN.\r\n    /// </summary>\r\n    public static class NancyMiddleware\r\n    {\r\n        /// <summary>\r\n        /// The request environment key\r\n        /// </summary>\r\n        public const string RequestEnvironmentKey = \"OWIN_REQUEST_ENVIRONMENT\";\r\n\r\n        /// <summary>\r\n        /// Use Nancy in an OWIN pipeline\r\n        /// </summary>\r\n        /// <param name=\"configuration\">A delegate to configure the <see cref=\"NancyOptions\"/>.</param>\r\n        /// <returns>An OWIN middleware delegate.</returns>\r\n        public static MidFunc UseNancy(Action<NancyOptions> configuration)\r\n        {\r\n            var options = new NancyOptions();\r\n            configuration(options);\r\n            return UseNancy(options);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Use Nancy in an OWIN pipeline\r\n        /// </summary>\r\n        /// <param name=\"options\">An <see cref=\"NancyOptions\"/> to configure the Nancy middleware</param>\r\n        /// <returns>An OWIN middleware delegate.</returns>\r\n        public static MidFunc UseNancy(NancyOptions options = null)\r\n        {\r\n            options = options ?? new NancyOptions();\r\n            options.Bootstrapper.Initialise();\r\n            var engine = options.Bootstrapper.GetEngine();\r\n\r\n            return\r\n                next =>\r\n                    async environment =>\r\n                    {\r\n                        var owinRequestMethod = Get<string>(environment, \"owin.RequestMethod\");\r\n                        var owinRequestScheme = Get<string>(environment, \"owin.RequestScheme\");\r\n                        var owinRequestHeaders = Get<IDictionary<string, string[]>>(environment, \"owin.RequestHeaders\");\r\n                        var owinRequestPathBase = Get<string>(environment, \"owin.RequestPathBase\");\r\n                        var owinRequestPath = Get<string>(environment, \"owin.RequestPath\");\r\n                        var owinRequestQueryString = Get<string>(environment, \"owin.RequestQueryString\");\r\n                        var owinRequestBody = Get<Stream>(environment, \"owin.RequestBody\");\r\n                        var owinRequestProtocol = Get<string>(environment, \"owin.RequestProtocol\");\r\n                        var owinCallCancelled = Get<CancellationToken>(environment, \"owin.CallCancelled\");\r\n                        var owinRequestHost = GetHeader(owinRequestHeaders, \"Host\") ?? Dns.GetHostName();\r\n                        var owinUser = GetUser(environment);\r\n\r\n                        X509Certificate2 certificate = null;\r\n                        if (options.EnableClientCertificates)\r\n                        {\r\n                            certificate = new X509Certificate2(Get<X509Certificate>(environment, \"ssl.ClientCertificate\").Export(X509ContentType.Cert));\r\n                        }\r\n\r\n                        var serverClientIp = Get<string>(environment, \"server.RemoteIpAddress\");\r\n\r\n                        var url = CreateUrl(owinRequestHost, owinRequestScheme, owinRequestPathBase, owinRequestPath, owinRequestQueryString);\r\n\r\n                        var expectedLength = ExpectedLength(owinRequestHeaders);\r\n                        // If length is 0 just use empty memory stream; as there is no body\r\n                        var nancyRequestStream = (expectedLength == 0) ?\r\n                            (Stream)new MemoryStream() :\r\n                            new RequestStream(owinRequestBody, expectedLength ?? 0, StaticConfiguration.DisableRequestStreamSwitching ?? false);\r\n\r\n                        var nancyRequest = new Request(\r\n                                owinRequestMethod,\r\n                                url,\r\n                                nancyRequestStream,\r\n                                owinRequestHeaders.ToDictionary(kv => kv.Key, kv => (IEnumerable<string>)kv.Value, StringComparer.OrdinalIgnoreCase),\r\n                                serverClientIp,\r\n                                certificate,\r\n                                owinRequestProtocol);\r\n\r\n                        var nancyContext = await engine.HandleRequest(\r\n                            nancyRequest,\r\n                            StoreEnvironment(environment, owinUser),\r\n                            owinCallCancelled).ConfigureAwait(false);\r\n\r\n                        await RequestComplete(nancyContext, environment, options.PerformPassThrough, next).ConfigureAwait(false);\r\n                    };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a delegate to handle converting a nancy response\r\n        /// to the format required by OWIN and signals that the we are\r\n        /// now complete.\r\n        /// </summary>\r\n        /// <param name=\"context\">The Nancy Context.</param>\r\n        /// <param name=\"environment\">OWIN environment.</param>\r\n        /// <param name=\"next\">The next stage in the OWIN pipeline.</param>\r\n        /// <param name=\"performPassThrough\">A predicate that will allow the caller to determine if the request passes through to the \r\n        /// next stage in the owin pipeline.</param>\r\n        /// <returns>Delegate</returns>\r\n        private static Task RequestComplete(\r\n            NancyContext context,\r\n            IDictionary<string, object> environment,\r\n            Func<NancyContext, bool> performPassThrough,\r\n            AppFunc next)\r\n        {\r\n            var owinResponseHeaders = Get<IDictionary<string, string[]>>(environment, \"owin.ResponseHeaders\");\r\n            var owinResponseBody = Get<Stream>(environment, \"owin.ResponseBody\");\r\n\r\n            var nancyResponse = context.Response;\r\n            if (!performPassThrough(context))\r\n            {\r\n                environment[\"owin.ResponseStatusCode\"] = (int)nancyResponse.StatusCode;\r\n\r\n                if (nancyResponse.ReasonPhrase != null)\r\n                {\r\n                    environment[\"owin.ResponseReasonPhrase\"] = nancyResponse.ReasonPhrase;\r\n                }\r\n\r\n                foreach (var responseHeader in nancyResponse.Headers)\r\n                {\r\n                    owinResponseHeaders[responseHeader.Key] = new[] { responseHeader.Value };\r\n                }\r\n\r\n                if (!string.IsNullOrWhiteSpace(nancyResponse.ContentType))\r\n                {\r\n                    owinResponseHeaders[\"Content-Type\"] = new[] { nancyResponse.ContentType };\r\n                }\r\n\r\n                if (nancyResponse.Cookies != null && nancyResponse.Cookies.Count != 0)\r\n                {\r\n                    const string setCookieHeaderKey = \"Set-Cookie\";\r\n                    string[] cookieHeader;\r\n                    string[] setCookieHeader = owinResponseHeaders.TryGetValue(setCookieHeaderKey, out cookieHeader)\r\n                                                    ? cookieHeader\r\n                                                    : ArrayCache.Empty<string>();\r\n                    owinResponseHeaders[setCookieHeaderKey] = setCookieHeader\r\n                        .Concat(nancyResponse.Cookies.Select(cookie => cookie.ToString()))\r\n                        .ToArray();\r\n                }\r\n\r\n                nancyResponse.Contents(owinResponseBody);\r\n            }\r\n            else\r\n            {\r\n                return next(environment);\r\n            }\r\n\r\n            context.Dispose();\r\n\r\n            return TaskHelpers.CompletedTask;\r\n        }\r\n\r\n        private static T Get<T>(IDictionary<string, object> env, string key)\r\n        {\r\n            object value;\r\n            return env.TryGetValue(key, out value) && value is T ? (T)value : default(T);\r\n        }\r\n\r\n        private static string GetHeader(IDictionary<string, string[]> headers, string key)\r\n        {\r\n            string[] value;\r\n            return headers.TryGetValue(key, out value) && value != null ? string.Join(\",\", value.ToArray()) : null;\r\n        }\r\n\r\n        private static ClaimsPrincipal GetUser(IDictionary<string, object> environment)\r\n        {\r\n            // OWIN 1.1\r\n            object user;\r\n            if (environment.TryGetValue(\"owin.RequestUser\", out user))\r\n            {\r\n                return user as ClaimsPrincipal;\r\n            }\r\n\r\n            // check for Katana User\r\n            if (environment.TryGetValue(\"server.User\", out user))\r\n            {\r\n                return user as ClaimsPrincipal;\r\n            }\r\n            return null;\r\n        }\r\n\r\n        private static long? ExpectedLength(IDictionary<string, string[]> headers)\r\n        {\r\n            var header = GetHeader(headers, \"Content-Length\");\r\n\r\n            if (string.IsNullOrWhiteSpace(header))\r\n            {\r\n                header = GetHeader(headers, \"Transfer-Encoding\");\r\n                if (string.IsNullOrWhiteSpace(header))\r\n                {\r\n                    // No content-length or transfer-encoding means the length is definately 0\r\n                    return 0;\r\n                }\r\n                // Has transfer-encoding, length is unknown\r\n                return null;\r\n            }\r\n\r\n            // If length cannot be converted to an int, treat it as unknown\r\n            return int.TryParse(header, NumberStyles.Any, CultureInfo.InvariantCulture, out int contentLength) ? contentLength : (long?)null;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates the Nancy URL\r\n        /// </summary>\r\n        /// <param name=\"owinRequestHost\">OWIN Hostname</param>\r\n        /// <param name=\"owinRequestScheme\">OWIN Scheme</param>\r\n        /// <param name=\"owinRequestPathBase\">OWIN Base path</param>\r\n        /// <param name=\"owinRequestPath\">OWIN Path</param>\r\n        /// <param name=\"owinRequestQueryString\">OWIN Querystring</param>\r\n        /// <returns></returns>\r\n        private static Url CreateUrl(\r\n            string owinRequestHost,\r\n            string owinRequestScheme,\r\n            string owinRequestPathBase,\r\n            string owinRequestPath,\r\n            string owinRequestQueryString)\r\n        {\r\n            int? port = null;\r\n\r\n            var hostnameParts = owinRequestHost.Split(':');\r\n            if (hostnameParts.Length == 2)\r\n            {\r\n                owinRequestHost = hostnameParts[0];\r\n\r\n                int tempPort;\r\n                if (int.TryParse(hostnameParts[1], out tempPort))\r\n                {\r\n                    port = tempPort;\r\n                }\r\n            }\r\n\r\n            var url = new Url\r\n            {\r\n                Scheme = owinRequestScheme,\r\n                HostName = owinRequestHost,\r\n                Port = port,\r\n                BasePath = owinRequestPathBase,\r\n                Path = owinRequestPath,\r\n                Query = owinRequestQueryString,\r\n            };\r\n            return url;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a delegate to store the OWIN environment and flow the user into the NancyContext\r\n        /// </summary>\r\n        /// <param name=\"environment\">The OWIN environment.</param>\r\n        /// <param name=\"user\">The user as a ClaimsPrincipal.</param>\r\n        /// <returns>Delegate</returns>\r\n        private static Func<NancyContext, NancyContext> StoreEnvironment(IDictionary<string, object> environment, ClaimsPrincipal user)\r\n        {\r\n            return context =>\r\n            {\r\n                context.CurrentUser = user;\r\n                environment[\"nancy.NancyContext\"] = context;\r\n                context.Items[RequestEnvironmentKey] = environment;\r\n                return context;\r\n            };\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Owin/NancyOptions.cs",
    "content": "﻿namespace Nancy.Owin\r\n{\r\n    using System;\r\n\r\n    using Nancy.Bootstrapper;\r\n\r\n    /// <summary>\r\n    /// Options for hosting Nancy with OWIN.\r\n    /// </summary>\r\n    public class NancyOptions\r\n    {\r\n        private INancyBootstrapper bootstrapper;\r\n        private Func<NancyContext, bool> performPassThrough;\r\n\r\n        /// <summary>\r\n        /// Gets or sets the bootstrapper. If none is set, NancyBootstrapperLocator.Bootstrapper is used.\r\n        /// </summary>\r\n        public INancyBootstrapper Bootstrapper\r\n        {\r\n            get { return this.bootstrapper ?? NancyBootstrapperLocator.Bootstrapper; }\r\n            set { this.bootstrapper = value; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the delegate that determines if NancyMiddleware performs pass through.\r\n        /// </summary>\r\n        public Func<NancyContext, bool> PerformPassThrough\r\n        {\r\n            get { return this.performPassThrough ?? (context => false); }\r\n            set { this.performPassThrough = value; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets a value indicating whether to request a client certificate or not.\r\n        /// Defaults to false.\r\n        /// </summary>\r\n        public bool EnableClientCertificates { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Owin/NancyOptionsExtensions.cs",
    "content": "﻿namespace Nancy.Owin\r\n{\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Extensions for the NancyOptions class.\r\n    /// </summary>\r\n    public static class NancyOptionsExtensions\r\n    {\r\n        /// <summary>\r\n        /// Tells the NancyMiddleware to pass through when\r\n        /// response has one of the given status codes.\r\n        /// </summary>\r\n        /// <param name=\"nancyOptions\">The Nancy options.</param>\r\n        /// <param name=\"httpStatusCode\">The HTTP status code.</param>\r\n        public static void PassThroughWhenStatusCodesAre(this NancyOptions nancyOptions, params HttpStatusCode[] httpStatusCode)\r\n        {\r\n            nancyOptions.PerformPassThrough = context => httpStatusCode.Any(code => context.Response.StatusCode == code);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/PipelineItem.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    /// <summary>\r\n    /// Defines a pipeline item\r\n    /// </summary>\r\n    /// <typeparam name=\"TDelegate\">The type of the delegate.</typeparam>\r\n    public class PipelineItem<TDelegate>\r\n    {\r\n        /// <summary>\r\n        /// Gets or sets the pipeline item name.\r\n        /// </summary>\r\n        /// <value>\r\n        /// The name.\r\n        /// </value>\r\n        public string Name { get; protected set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the delegate.\r\n        /// </summary>\r\n        /// <value>\r\n        /// The delegate.\r\n        /// </value>\r\n        public TDelegate Delegate { get; protected set; }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"PipelineItem{TDelegate}\"/> class, with\r\n        /// the provided <paramref name=\"name\"/> and <paramref name=\"delegate\"/>.\r\n        /// </summary>\r\n        /// <param name=\"name\">The name.</param>\r\n        /// <param name=\"delegate\">The delegate.</param>\r\n        public PipelineItem(string name, TDelegate @delegate)\r\n        {\r\n            this.Name = name;\r\n            this.Delegate = @delegate;\r\n        }\r\n\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <typeparamref name=\"TDelegate\"/> cref=\"TDelegate\"/> to <see cref=\"PipelineItem{TDelegate}\"/>.\r\n        /// </summary>\r\n        /// <param name=\"action\">The action.</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator PipelineItem<TDelegate>(TDelegate action)\r\n        {\r\n            return new PipelineItem<TDelegate>(null, action);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"PipelineItem{TDelegate}\"/> to <typeparamref name=\"TDelegate\"/>.\r\n        /// </summary>\r\n        /// <param name=\"pipelineItem\">The pipeline item.</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator TDelegate(PipelineItem<TDelegate> pipelineItem)\r\n        {\r\n            return pipelineItem.Delegate;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Properties/InternalsVisibleTo.cs",
    "content": "﻿using System.Runtime.CompilerServices;\r\n\r\n[assembly: InternalsVisibleTo(\"Nancy.Tests\")]\r\n[assembly: InternalsVisibleTo(\"Nancy.Hosting.Self.Tests\")]\r\n"
  },
  {
    "path": "src/Nancy/Request.cs",
    "content": "namespace Nancy\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Collections.Specialized;\r\n    using System.Diagnostics;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Security.Cryptography.X509Certificates;\r\n    using System.Text.RegularExpressions;\r\n    using Extensions;\r\n    using Helpers;\r\n    using IO;\r\n    using Session;\r\n\r\n    /// <summary>\r\n    /// Encapsulates HTTP-request information to an Nancy application.\r\n    /// </summary>\r\n    [DebuggerDisplay(\"{DebuggerDisplay, nq}\")]\r\n    public class Request : IDisposable\r\n    {\r\n        private readonly List<HttpFile> files = new List<HttpFile>();\r\n        private dynamic form = new DynamicDictionary();\r\n\r\n        private IDictionary<string, string> cookies;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"Request\"/> class, with\r\n        /// the provided <paramref name=\"method\"/>, <paramref name=\"path\"/> and <paramref name=\"scheme\"/>.\r\n        /// </summary>\r\n        /// <param name=\"method\">The HTTP data transfer method used by the client.</param>\r\n        /// <param name=\"path\">The path of the requested resource, relative to the \"Nancy root\". This should not include the scheme, host name, or query portion of the URI.</param>\r\n        /// <param name=\"scheme\">The HTTP protocol that was used by the client.</param>\r\n        public Request(string method, string path, string scheme)\r\n            : this(method, new Url { Path = path, Scheme = scheme })\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"Request\"/> class, with\r\n        /// the provided <paramref name=\"method\"/>, <paramref name=\"url\"/>, <paramref name=\"headers\"/>, \r\n        /// <paramref name=\"body\"/>, <paramref name=\"ip\"/>, <paramref name=\"certificate\"/> and <paramref name=\"protocolVersion\"/>.\r\n        /// </summary>\r\n        /// <param name=\"method\">The HTTP data transfer method used by the client.</param>\r\n        /// <param name=\"url\">The <see cref=\"Url\"/> of the requested resource</param>\r\n        /// <param name=\"headers\">The headers that was passed in by the client.</param>\r\n        /// <param name=\"body\">The <see cref=\"Stream\"/> that represents the incoming HTTP body.</param>\r\n        /// <param name=\"ip\">The client's IP address</param>\r\n        /// <param name=\"certificate\">The client's certificate when present.</param>\r\n        /// <param name=\"protocolVersion\">The HTTP protocol version.</param>\r\n        public Request(string method,\r\n            Url url,\r\n            Stream body = null,\r\n            IDictionary<string, IEnumerable<string>> headers = null,\r\n            string ip = null,\r\n            X509Certificate certificate = null,\r\n            string protocolVersion = null)\r\n        {\r\n            if (string.IsNullOrEmpty(method))\r\n            {\r\n                throw new ArgumentOutOfRangeException(\"method\");\r\n            }\r\n\r\n            if (url == null)\r\n            {\r\n                throw new ArgumentNullException(\"url\");\r\n            }\r\n\r\n            if (url.Path == null)\r\n            {\r\n                throw new ArgumentNullException(\"url.Path\");\r\n            }\r\n\r\n            if (string.IsNullOrEmpty(url.Scheme))\r\n            {\r\n                throw new ArgumentOutOfRangeException(\"url.Scheme\");\r\n            }\r\n\r\n            this.UserHostAddress = ip;\r\n\r\n            this.Url = url;\r\n\r\n            this.Method = method;\r\n\r\n            this.Query = url.Query.AsQueryDictionary();\r\n\r\n            this.Body = body ?? RequestStream.FromStream(new MemoryStream());\r\n\r\n            this.Headers = new RequestHeaders(headers ?? new Dictionary<string, IEnumerable<string>>());\r\n\r\n            this.Session = new NullSessionProvider();\r\n\r\n            if (certificate != null)\r\n            {\r\n                this.ClientCertificate = certificate;\r\n            }\r\n\r\n            this.ProtocolVersion = protocolVersion ?? string.Empty;\r\n\r\n            if (string.IsNullOrEmpty(this.Url.Path))\r\n            {\r\n                this.Url.Path = \"/\";\r\n            }\r\n\r\n            this.ParseFormData();\r\n            this.RewriteMethod();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the certificate sent by the client.\r\n        /// </summary>\r\n        public X509Certificate ClientCertificate { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the HTTP protocol version.\r\n        /// </summary>\r\n        public string ProtocolVersion { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the IP address of the client\r\n        /// </summary>\r\n        public string UserHostAddress { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the HTTP data transfer method used by the client.\r\n        /// </summary>\r\n        /// <value>The method.</value>\r\n        public string Method { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the url\r\n        /// </summary>\r\n        public Url Url { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the request path, relative to the base path.\r\n        /// Used for route matching etc.\r\n        /// </summary>\r\n        public string Path\r\n        {\r\n            get\r\n            {\r\n                return this.Url.Path;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the query string data of the requested resource.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"DynamicDictionary\"/>instance, containing the key/value pairs of query string data.</value>\r\n        public dynamic Query { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets a <see cref=\"Stream\"/> that can be used to read the incoming HTTP body\r\n        /// </summary>\r\n        /// <value>A <see cref=\"Stream\"/> object representing the incoming HTTP body.</value>\r\n        public Stream Body { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the request cookies.\r\n        /// </summary>\r\n        public IDictionary<string, string> Cookies\r\n        {\r\n            get { return this.cookies ?? (this.cookies = this.GetCookieData()); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the current session.\r\n        /// </summary>\r\n        public ISession Session { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets the cookie data from the request header if it exists\r\n        /// </summary>\r\n        /// <returns>Cookies dictionary</returns>\r\n        private IDictionary<string, string> GetCookieData()\r\n        {\r\n            var cookieDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);\r\n\r\n            if (!this.Headers.Cookie.Any())\r\n            {\r\n                return cookieDictionary;\r\n            }\r\n\r\n            var values = this.Headers[\"cookie\"].First().TrimEnd(';').Split(';');\r\n            foreach (var parts in values.Select(c => c.Split(new[] { '=' }, 2)))\r\n            {\r\n                var cookieName = parts[0].Trim();\r\n\r\n                string cookieValue;\r\n\r\n                if (parts.Length == 1)\r\n                {\r\n                    //Cookie attribute\r\n                    cookieValue = string.Empty;\r\n                }\r\n                else\r\n                {\r\n                    cookieValue = HttpUtility.UrlDecode(parts[1]);\r\n                }\r\n\r\n                cookieDictionary[cookieName] = cookieValue;\r\n            }\r\n\r\n            return cookieDictionary;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a collection of files sent by the client-\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> instance, containing an <see cref=\"HttpFile\"/> instance for each uploaded file.</value>\r\n        public IEnumerable<HttpFile> Files\r\n        {\r\n            get { return this.files; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the form data of the request.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"DynamicDictionary\"/>instance, containing the key/value pairs of form data.</value>\r\n        /// <remarks>Currently Nancy will only parse form data sent using the application/x-www-url-encoded mime-type.</remarks>\r\n        public dynamic Form\r\n        {\r\n            get { return this.form; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the HTTP headers sent by the client.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IDictionary{TKey,TValue}\"/> containing the name and values of the headers.</value>\r\n        /// <remarks>The values are stored in an <see cref=\"IEnumerable{T}\"/> of string to be compliant with multi-value headers.</remarks>\r\n        public RequestHeaders Headers { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.\r\n        /// </summary>\r\n        public void Dispose()\r\n        {\r\n            ((IDisposable)this.Body).Dispose();\r\n        }\r\n\r\n        private void ParseFormData()\r\n        {\r\n            if (this.Headers.ContentType == null)\r\n            {\r\n                return;\r\n            }\r\n\r\n            var contentType = this.Headers.ContentType;\r\n            if (contentType.Matches(\"application/x-www-form-urlencoded\"))\r\n            {\r\n                var reader = new StreamReader(this.Body);\r\n                this.form = reader.ReadToEnd().AsQueryDictionary();\r\n                this.Body.Position = 0;\r\n            }\r\n\r\n            if (!contentType.Matches(\"multipart/form-data\"))\r\n            {\r\n                return;\r\n            }\r\n\r\n            var boundary = Regex.Match(contentType, @\"boundary=\"\"?(?<token>[^\\n\\;\\\"\" ]*)\").Groups[\"token\"].Value;\r\n            var multipart = new HttpMultipart(this.Body, boundary);\r\n\r\n            var formValues =\r\n                new NameValueCollection(StaticConfiguration.CaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase);\r\n\r\n            foreach (var httpMultipartBoundary in multipart.GetBoundaries())\r\n            {\r\n                if (string.IsNullOrEmpty(httpMultipartBoundary.Filename))\r\n                {\r\n                    var reader =\r\n                        new StreamReader(httpMultipartBoundary.Value);\r\n                    formValues.Add(httpMultipartBoundary.Name, reader.ReadToEnd());\r\n\r\n                }\r\n                else\r\n                {\r\n                    this.files.Add(new HttpFile(httpMultipartBoundary));\r\n                }\r\n            }\r\n\r\n            foreach (var key in formValues.AllKeys.Where(key => key != null))\r\n            {\r\n                this.form[key] = formValues[key];\r\n            }\r\n\r\n            this.Body.Position = 0;\r\n        }\r\n\r\n        private void RewriteMethod()\r\n        {\r\n            if (!this.Method.Equals(\"POST\", StringComparison.OrdinalIgnoreCase))\r\n            {\r\n                return;\r\n            }\r\n\r\n            var overrides =\r\n                new List<Tuple<string, string>>\r\n                {\r\n                    Tuple.Create(\"_method form input element\", (string)this.Form[\"_method\"]),\r\n                    Tuple.Create(\"X-HTTP-Method-Override form input element\", (string)this.Form[\"X-HTTP-Method-Override\"]),\r\n                    Tuple.Create(\"X-HTTP-Method-Override header\", this.Headers[\"X-HTTP-Method-Override\"].FirstOrDefault())\r\n                };\r\n\r\n            var providedOverride =\r\n                overrides.Where(x => !string.IsNullOrEmpty(x.Item2))\r\n                         .ToList();\r\n\r\n            if (!providedOverride.Any())\r\n            {\r\n                return;\r\n            }\r\n\r\n            if (providedOverride.Count > 1)\r\n            {\r\n                var overrideSources =\r\n                    string.Join(\", \", providedOverride);\r\n\r\n                var errorMessage =\r\n                    string.Format(\"More than one HTTP method override was provided. The provided values where: {0}\", overrideSources);\r\n\r\n                throw new InvalidOperationException(errorMessage);\r\n            }\r\n\r\n            this.Method = providedOverride.Single().Item2;\r\n        }\r\n\r\n        private string DebuggerDisplay\r\n        {\r\n            get { return string.Format(\"{0} {1} {2}\", this.Method, this.Url, this.ProtocolVersion).Trim(); }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/RequestExecutionException.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Exception that is thrown when an unhandled exception occurred during\r\n    /// the execution of the current request.\r\n    /// </summary>\r\n    public class RequestExecutionException : Exception\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"RequestExecutionException\"/>, with\r\n        /// the specified <paramref name=\"innerException\"/>.\r\n        /// </summary>\r\n        /// <param name=\"innerException\"></param>\r\n        public RequestExecutionException(Exception innerException)\r\n            : base(\"Oh noes!\", innerException)\r\n        {\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/RequestHeaders.cs",
    "content": "namespace Nancy\r\n{\r\n    using System;\r\n    using System.Collections;\r\n    using System.Collections.Concurrent;\r\n    using System.Collections.Generic;\r\n    using System.Globalization;\r\n    using System.Linq;\r\n    using Nancy.Cookies;\r\n    using Nancy.Responses.Negotiation;\r\n\r\n\r\n    /// <summary>\r\n    /// Provides strongly-typed access to HTTP request headers.\r\n    /// </summary>\r\n    public class RequestHeaders : IEnumerable<KeyValuePair<string, IEnumerable<string>>>\r\n    {\r\n        private readonly IDictionary<string, IEnumerable<string>> headers;\r\n        private readonly ConcurrentDictionary<string, IEnumerable<Tuple<string, decimal>>> cache;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"RequestHeaders\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"headers\">The headers.</param>\r\n        public RequestHeaders(IDictionary<string, IEnumerable<string>> headers)\r\n        {\r\n            this.headers = new Dictionary<string, IEnumerable<string>>(headers, StringComparer.OrdinalIgnoreCase);\r\n            this.cache = new ConcurrentDictionary<string, IEnumerable<Tuple<string, decimal>>>(StringComparer.OrdinalIgnoreCase);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Content-types that are acceptable.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> that contains the header values if they are available; otherwise it will be empty.</value>\r\n        public IEnumerable<Tuple<string, decimal>> Accept\r\n        {\r\n            get { return this.GetWeightedValues(\"Accept\"); }\r\n            set { this.SetHeaderValues(\"Accept\", value, GetWeightedValuesAsStrings); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Character sets that are acceptable.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> that contains the header values if they are available; otherwise it will be empty.</value>\r\n        public IEnumerable<Tuple<string, decimal>> AcceptCharset\r\n        {\r\n            get { return this.GetWeightedValues(\"Accept-Charset\"); }\r\n            set { this.SetHeaderValues(\"Accept-Charset\", value, GetWeightedValuesAsStrings); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Acceptable encodings.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> that contains the header values if they are available; otherwise it will be empty.</value>\r\n        public IEnumerable<string> AcceptEncoding\r\n        {\r\n            get { return this.GetSplitValues(\"Accept-Encoding\"); }\r\n            set { this.SetHeaderValues(\"Accept-Encoding\", value, x => x); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Acceptable languages for response.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> that contains the header values if they are available; otherwise it will be empty.</value>\r\n        public IEnumerable<Tuple<string, decimal>> AcceptLanguage\r\n        {\r\n            get { return this.GetWeightedValues(\"Accept-Language\"); }\r\n            set { this.SetHeaderValues(\"Accept-Language\", value, GetWeightedValuesAsStrings); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Authorization header value for request.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the header value if it is available; otherwise <see cref=\"string.Empty\"/>.</value>\r\n        public string Authorization\r\n        {\r\n            get { return this.GetValue(\"Authorization\", x => x.First(), string.Empty); }\r\n            set { this.SetHeaderValues(\"Authorization\", value, x => new[] { x }); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Used to specify directives that MUST be obeyed by all caching mechanisms along the request/response chain.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> that contains the header values if they are available; otherwise it will be empty.</value>\r\n        public IEnumerable<string> CacheControl\r\n        {\r\n            get { return this.GetValue(\"Cache-Control\"); }\r\n            set { this.SetHeaderValues(\"Cache-Control\", value, x => x); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Contains name/value pairs of information stored for that URL.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> that contains <see cref=\"INancyCookie\"/> instances if they are available; otherwise it will be empty.</value>\r\n        public IEnumerable<INancyCookie> Cookie\r\n        {\r\n            get { return this.GetValue(\"Cookie\", GetNancyCookies, Enumerable.Empty<INancyCookie>()); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// What type of connection the user-agent would prefer.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the header value if it is available; otherwise <see cref=\"string.Empty\"/>.</value>\r\n        public string Connection\r\n        {\r\n            get { return this.GetValue(\"Connection\", x => x.First(), string.Empty); }\r\n            set { this.SetHeaderValues(\"Connection\", value, x => new[] { x }); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// The length of the request body in octets (8-bit bytes).\r\n        /// </summary>\r\n        /// <value>The length of the contents if it is available; otherwise 0.</value>\r\n        public long ContentLength\r\n        {\r\n            get { return this.GetValue(\"Content-Length\", x => Convert.ToInt64(x.First()), 0); }\r\n            set { this.SetHeaderValues(\"Content-Length\", value, x => new[] { x.ToString(CultureInfo.InvariantCulture) }); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// The mime type of the body of the request (used with POST and PUT requests).\r\n        /// </summary>\r\n        /// <value>A <see cref=\"MediaRange\"/> containing the header value if it is available; otherwise <see langword=\"null\"/>.</value>\r\n        public MediaRange ContentType\r\n        {\r\n            get { return this.GetValue(\"Content-Type\", x => new MediaRange(x.First()), null); }\r\n            set { this.SetHeaderValues(\"Content-Type\", value, x => new[] { x.ToString() }); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// The date and time that the message was sent.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"DateTime\"/> instance that specifies when the message was sent. If not available then <see langword=\"null\"/> will be returned.</value>\r\n        public DateTime? Date\r\n        {\r\n            get { return this.GetValue(\"Date\", x => ParseDateTime(x.First()), null); }\r\n            set { this.SetHeaderValues(\"Date\", value, x => new[] { GetDateAsString(value) }); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// The domain name of the server (for virtual hosting), mandatory since HTTP/1.1\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the header value if it is available; otherwise <see cref=\"string.Empty\"/>.</value>\r\n        public string Host\r\n        {\r\n            get { return this.GetValue(\"Host\", x => x.First(), string.Empty); }\r\n            set { this.SetHeaderValues(\"Host\", value, x => new[] { x }); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Only perform the action if the client supplied entity matches the same entity on the server. This is mainly for methods like PUT to only update a resource if it has not been modified since the user last updated it.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> that contains the header values if they are available; otherwise it will be empty.</value>\r\n        public IEnumerable<string> IfMatch\r\n        {\r\n            get { return this.GetValue(\"If-Match\"); }\r\n            set { this.SetHeaderValues(\"If-Match\", value, x => x); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Allows a 304 Not Modified to be returned if content is unchanged\r\n        /// </summary>\r\n        /// <value>A <see cref=\"DateTime\"/> instance that specifies when the requested resource must have been changed since. If not available then <see langword=\"null\"/> will be returned.</value>\r\n        public DateTime? IfModifiedSince\r\n        {\r\n            get { return this.GetValue(\"If-Modified-Since\", x => ParseDateTime(x.First()), null); }\r\n            set { this.SetHeaderValues(\"If-Modified-Since\", value, x => new[] { GetDateAsString(value) }); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Allows a 304 Not Modified to be returned if content is unchanged\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> that contains the header values if they are available; otherwise it will be empty.</value>\r\n        public IEnumerable<string> IfNoneMatch\r\n        {\r\n            get { return this.GetValue(\"If-None-Match\"); }\r\n            set { this.SetHeaderValues(\"If-None-Match\", value, x => x); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// If the entity is unchanged, send me the part(s) that I am missing; otherwise, send me the entire new entity.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the header value if it is available; otherwise <see cref=\"string.Empty\"/>.</value>\r\n        public string IfRange\r\n        {\r\n            get { return this.GetValue(\"If-Range\", x => x.First(), string.Empty); }\r\n            set { this.SetHeaderValues(\"If-Range\", value, x => new[] { x }); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Only send the response if the entity has not been modified since a specific time.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"DateTime\"/> instance that specifies when the requested resource may not have been changed since. If not available then <see langword=\"null\"/> will be returned.</value>\r\n        public DateTime? IfUnmodifiedSince\r\n        {\r\n            get { return this.GetValue(\"If-Unmodified-Since\", x => ParseDateTime(x.First()), null); }\r\n            set { this.SetHeaderValues(\"If-Unmodified-Since\", value, x => new[] { GetDateAsString(value) }); }\r\n\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the names of the available request headers.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> containing the names of the headers.</value>\r\n        public IEnumerable<string> Keys\r\n        {\r\n            get { return this.headers.Keys; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Limit the number of times the message can be forwarded through proxies or gateways.\r\n        /// </summary>\r\n        /// <value>The number of the maximum allowed number of forwards if it is available; otherwise 0.</value>\r\n        public int MaxForwards\r\n        {\r\n            get { return this.GetValue(\"Max-Forwards\", x => Convert.ToInt32(x.First()), 0); }\r\n            set { this.SetHeaderValues(\"Max-Forwards\", value, x => new[] { x.ToString(CultureInfo.InvariantCulture) }); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// This is the address of the previous web page from which a link to the currently requested page was followed.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the header value if it is available; otherwise <see cref=\"string.Empty\"/>.</value>\r\n        public string Referrer\r\n        {\r\n            get { return this.GetValue(\"Referer\", x => x.First(), string.Empty); }\r\n            set { this.SetHeaderValues(\"Referer\", value, x => new[] { x }); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// The user agent string of the user agent\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the header value if it is available; otherwise <see cref=\"string.Empty\"/>.</value>\r\n        public string UserAgent\r\n        {\r\n            get { return this.GetValue(\"User-Agent\", x => x.First(), string.Empty); }\r\n            set { this.SetHeaderValues(\"User-Agent\", value, x => new[] { x }); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all the header values.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> that contains all the header values.</value>\r\n        public IEnumerable<IEnumerable<string>> Values\r\n        {\r\n            get { return this.headers.Values; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an enumerator that iterates through the collection.\r\n        /// </summary>\r\n        /// <returns>A <see cref=\"IEnumerator{T}\"/> that can be used to iterate through the collection.</returns>\r\n        public IEnumerator<KeyValuePair<string, IEnumerable<string>>> GetEnumerator()\r\n        {\r\n            return this.headers.GetEnumerator();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an enumerator that iterates through a collection.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerator\"/> object that can be used to iterate through the collection.</returns>\r\n        IEnumerator IEnumerable.GetEnumerator()\r\n        {\r\n            return this.GetEnumerator();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the values for the header identified by the <paramref name=\"name\"/> parameter.\r\n        /// </summary>\r\n        /// <param name=\"name\">The name of the header to return the values for.</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> that contains the values for the header. If the header is not defined then <see cref=\"Enumerable.Empty{TResult}\"/> is returned.</returns>\r\n        public IEnumerable<string> this[string name]\r\n        {\r\n            get\r\n            {\r\n                IEnumerable<string> value;\r\n                return this.headers.TryGetValue(name, out value) ?\r\n                    value :\r\n                    Enumerable.Empty<string>();\r\n            }\r\n        }\r\n\r\n        private static string GetDateAsString(DateTime? value)\r\n        {\r\n            return !value.HasValue ? null : value.Value.ToString(\"R\", CultureInfo.InvariantCulture);\r\n        }\r\n\r\n        private IEnumerable<string> GetSplitValues(string header)\r\n        {\r\n            var values = this.GetValue(header);\r\n\r\n            return values\r\n                .SelectMany(x => x.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))\r\n                .Select(x => x.Trim())\r\n                .ToList();\r\n        }\r\n\r\n        private IEnumerable<Tuple<string, decimal>> GetWeightedValues(string headerName)\r\n        {\r\n            return this.cache.GetOrAdd(headerName, r =>\r\n            {\r\n                var values = this.GetValue(r);\r\n                var result = new List<Tuple<string, decimal>>();\r\n\r\n                foreach (var header in values)\r\n                {\r\n                    var buffer = string.Empty;\r\n                    var name = string.Empty;\r\n                    var quality = string.Empty;\r\n                    var isReadingQuality = false;\r\n                    var isInQuotedSection = false;\r\n\r\n                    for (var index = 0; index < header.Length; index++)\r\n                    {\r\n                        var character = header[index];\r\n\r\n                        if (character.Equals(' ') && (index != header.Length - 1) && !isInQuotedSection)\r\n                        {\r\n                            continue;\r\n                        }\r\n\r\n                        if (character.Equals('\"'))\r\n                        {\r\n                            isInQuotedSection = !isInQuotedSection;\r\n                        }\r\n\r\n                        if (isInQuotedSection)\r\n                        {\r\n                            buffer += character;\r\n\r\n                            if (index != header.Length - 1)\r\n                            {\r\n                                continue; ;\r\n                            }\r\n                        }\r\n\r\n                        if (character.Equals(';') || character.Equals(',') || (index == header.Length - 1))\r\n                        {\r\n                            if (!(character.Equals(';') || character.Equals(',')))\r\n                            {\r\n                                buffer += character;\r\n                            }\r\n\r\n                            if (isReadingQuality)\r\n                            {\r\n                                quality = buffer;\r\n                            }\r\n                            else\r\n                            {\r\n                                if (name.Length > 0)\r\n                                {\r\n                                    name += ';';\r\n                                }\r\n\r\n                                name += buffer;\r\n                            }\r\n\r\n                            buffer = string.Empty;\r\n                            isReadingQuality = false;\r\n                            isInQuotedSection = false;\r\n                        }\r\n\r\n                        if (character.Equals(';'))\r\n                        {\r\n                            continue;\r\n                        }\r\n\r\n                        if ((character.Equals('q') || character.Equals('Q')) && (index != header.Length - 1))\r\n                        {\r\n                            if (header[index + 1].Equals('='))\r\n                            {\r\n                                isReadingQuality = true;\r\n                                continue;\r\n                            }\r\n                        }\r\n\r\n                        if (isReadingQuality && character.Equals('='))\r\n                        {\r\n                            continue;\r\n                        }\r\n\r\n                        if (character.Equals(',') || (index == header.Length - 1))\r\n                        {\r\n                            var actualQuality = 1m;\r\n                            decimal temp;\r\n\r\n                            if (decimal.TryParse(quality, NumberStyles.Number, CultureInfo.InvariantCulture, out temp))\r\n                            {\r\n                                actualQuality = temp;\r\n                            }\r\n\r\n                            result.Add(new Tuple<string, decimal>(name, actualQuality));\r\n\r\n                            name = string.Empty;\r\n                            quality = string.Empty;\r\n                            buffer = string.Empty;\r\n                            isReadingQuality = false;\r\n\r\n                            continue;\r\n                        }\r\n\r\n                        buffer += character;\r\n                    }\r\n                }\r\n\r\n                return result.OrderByDescending(x => x.Item2);\r\n            });\r\n        }\r\n\r\n        private static IEnumerable<INancyCookie> GetNancyCookies(IEnumerable<string> cookies)\r\n        {\r\n            if (cookies == null)\r\n            {\r\n                yield break;\r\n            }\r\n\r\n            foreach (var cookie in cookies)\r\n            {\r\n                var cookieStrings = cookie.Split(';');\r\n                foreach (var cookieString in cookieStrings)\r\n                {\r\n                    var equalPos = cookieString.IndexOf('=');\r\n                    if (equalPos >= 0)\r\n                    {\r\n                        yield return new NancyCookie(cookieString.Substring(0, equalPos).TrimStart(), cookieString.Substring(equalPos+1).TrimEnd());\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        private IEnumerable<string> GetValue(string name)\r\n        {\r\n            return this.GetValue(name, x => x, new string[] {});\r\n        }\r\n\r\n        private T GetValue<T>(string name, Func<IEnumerable<string>, T> converter, T defaultValue)\r\n        {\r\n            IEnumerable<string> values;\r\n\r\n            if (!this.headers.TryGetValue(name, out values))\r\n            {\r\n                return defaultValue;\r\n            }\r\n\r\n            return converter.Invoke(values);\r\n        }\r\n\r\n        private static IEnumerable<string> GetWeightedValuesAsStrings(IEnumerable<Tuple<string, decimal>> values)\r\n        {\r\n            return values.Select(x => string.Concat(x.Item1, \";q=\", x.Item2.ToString(CultureInfo.InvariantCulture)));\r\n        }\r\n\r\n        private static DateTime? ParseDateTime(string value)\r\n        {\r\n            DateTime result;\r\n            // note CultureInfo.InvariantCulture is ignored\r\n            if (DateTime.TryParseExact(value, \"R\", CultureInfo.InvariantCulture, DateTimeStyles.None, out result))\r\n            {\r\n                return result;\r\n            }\r\n            return null;\r\n        }\r\n\r\n        private void SetHeaderValues<T>(string header, T value, Func<T, IEnumerable<string>> valueTransformer)\r\n        {\r\n            this.InvalidateCacheEntry(header);\r\n\r\n            if (EqualityComparer<T>.Default.Equals(value, default(T)))\r\n            {\r\n                if (this.headers.ContainsKey(header))\r\n                {\r\n                    this.headers.Remove(header);\r\n                }\r\n            }\r\n            else\r\n            {\r\n                this.headers[header] = valueTransformer.Invoke(value);\r\n            }\r\n        }\r\n\r\n        private void InvalidateCacheEntry(string header)\r\n        {\r\n            IEnumerable<Tuple<string, decimal>> values;\r\n            this.cache.TryRemove(header, out values);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/ResourceAssemblyProvider.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n\r\n    /// <summary>\r\n    /// Default set of assemblies that should be scanned for items (views, text, content etc)\r\n    /// embedded as resources.\r\n    /// </summary>\r\n    /// <remarks>The default convention will scan all assemblies that references another assemblies that has a name that starts with Nancy*</remarks>\r\n    public class ResourceAssemblyProvider : IResourceAssemblyProvider\r\n    {\r\n        private readonly IAssemblyCatalog assemblyCatalog;\r\n        private IEnumerable<Assembly> filteredAssemblies;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ResourceAssemblyProvider\"/>\r\n        /// </summary>\r\n        /// <param name=\"assemblyCatalog\">An <see cref=\"IAssemblyCatalog\"/> instance.</param>\r\n        public ResourceAssemblyProvider(IAssemblyCatalog assemblyCatalog)\r\n        {\r\n            this.assemblyCatalog = assemblyCatalog;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a list of assemblies that should be scanned for views.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"Assembly\"/> instances.</returns>\r\n        public IEnumerable<Assembly> GetAssembliesToScan()\r\n        {\r\n            return (this.filteredAssemblies ?? (this.filteredAssemblies = this.GetFilteredAssemblies()));\r\n        }\r\n\r\n        private IEnumerable<Assembly> GetFilteredAssemblies()\r\n        {\r\n            return this.assemblyCatalog\r\n                .GetAssemblies()\r\n                .Where(x => !x.GetName().Name.StartsWith(\"Nancy\", StringComparison.OrdinalIgnoreCase));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Response.cs",
    "content": "namespace Nancy\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Diagnostics;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Cookies;\r\n    using Nancy.Helpers;\r\n    using Nancy.Responses;\r\n\r\n    /// <summary>\r\n    /// Encapsulates HTTP-response information from an Nancy operation.\r\n    /// </summary>\r\n    [DebuggerDisplay(\"{DebuggerDisplay, nq}\")]\r\n    public class Response: IDisposable\r\n    {\r\n        /// <summary>\r\n        /// Null object representing no body\r\n        /// </summary>\r\n        public static Action<Stream> NoBody = s => { };\r\n\r\n        private string contentType;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"Response\"/> class.\r\n        /// </summary>\r\n        public Response()\r\n        {\r\n            this.Contents = NoBody;\r\n            this.ContentType = \"text/html\";\r\n            this.Headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);\r\n            this.StatusCode = HttpStatusCode.OK;\r\n            this.Cookies = new List<INancyCookie>(2);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the type of the content.\r\n        /// </summary>\r\n        /// <value>The type of the content.</value>\r\n        /// <remarks>The default value is <c>text/html</c>.</remarks>\r\n        public string ContentType\r\n        {\r\n            get\r\n            {\r\n                string value;\r\n                return Headers.TryGetValue(\"content-type\", out value) ? value : this.contentType;\r\n            }\r\n            set { this.contentType = value; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the delegate that will render contents to the response stream.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"Action{T}\"/> delegate, containing the code that will render contents to the response stream.</value>\r\n        /// <remarks>The host of Nancy will pass in the output stream after the response has been handed back to it by Nancy.</remarks>\r\n        public Action<Stream> Contents { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets the collection of HTTP response headers that should be sent back to the client.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IDictionary{TKey,TValue}\"/> instance, containing the key/value pair of headers.</value>\r\n        public IDictionary<string, string> Headers { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the HTTP status code that should be sent back to the client.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"HttpStatusCode\"/> value.</value>\r\n        public HttpStatusCode StatusCode { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets a text description of the HTTP status code returned to the client.\r\n        /// </summary>\r\n        /// <value>The HTTP status code description.</value>\r\n        public string ReasonPhrase { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"INancyCookie\"/> instances that are associated with the response.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"IList{T}\"/> instance, containing <see cref=\"INancyCookie\"/> instances.</value>\r\n        public IList<INancyCookie> Cookies { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Executes at the end of the nancy execution pipeline and before control is passed back to the hosting.\r\n        /// Can be used to pre-render/validate views while still inside the main pipeline/error handling.\r\n        /// </summary>\r\n        /// <param name=\"context\">Nancy context</param>\r\n        /// <returns>Task for completion/erroring</returns>\r\n        public virtual Task PreExecute(NancyContext context)\r\n        {\r\n            return TaskHelpers.CompletedTask;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Implicitly cast an <see cref=\"HttpStatusCode\"/> value to a <see cref=\"Response\"/> instance, with the <see cref=\"StatusCode\"/>\r\n        /// set to the value of the <see cref=\"HttpStatusCode\"/>.\r\n        /// </summary>\r\n        /// <param name=\"statusCode\">The <see cref=\"HttpStatusCode\"/> value that is being cast from.</param>\r\n        /// <returns>A <see cref=\"Response\"/> instance.</returns>\r\n        public static implicit operator Response(HttpStatusCode statusCode)\r\n        {\r\n            return new Response { StatusCode = statusCode };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Implicitly cast an int value to a <see cref=\"Response\"/> instance, with the <see cref=\"StatusCode\"/>\r\n        /// set to the value of the int.\r\n        /// </summary>\r\n        /// <param name=\"statusCode\">The int value that is being cast from.</param>\r\n        /// <returns>A <see cref=\"Response\"/> instance.</returns>\r\n        public static implicit operator Response(int statusCode)\r\n        {\r\n            return new Response { StatusCode = (HttpStatusCode)statusCode };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Implicitly cast an string instance to a <see cref=\"Response\"/> instance, with the <see cref=\"Contents\"/>\r\n        /// set to the value of the string.\r\n        /// </summary>\r\n        /// <param name=\"contents\">The string that is being cast from.</param>\r\n        /// <returns>A <see cref=\"Response\"/> instance.</returns>\r\n        public static implicit operator Response(string contents)\r\n        {\r\n            return new TextResponse(contents);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Implicitly cast an <see cref=\"Action{T}\"/>, where T is a <see cref=\"Stream\"/>, instance to\r\n        /// a <see cref=\"Response\"/> instance, with the <see cref=\"Contents\"/> set to the value of the action.\r\n        /// </summary>\r\n        /// <param name=\"streamFactory\">The <see cref=\"Action{T}\"/> instance that is being cast from.</param>\r\n        /// <returns>A <see cref=\"Response\"/> instance.</returns>\r\n        public static implicit operator Response(Action<Stream> streamFactory)\r\n        {\r\n            return new Response { Contents = streamFactory };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Implicitly cast a <see cref=\"DynamicDictionaryValue\"/> instance to a <see cref=\"Response\"/> instance,\r\n        /// with the <see cref=\"Contents\"/> set to the value of the <see cref=\"DynamicDictionaryValue\"/>.\r\n        /// </summary>\r\n        /// <param name=\"value\">The <see cref=\"DynamicDictionaryValue\"/> instance that is being cast from.</param>\r\n        /// <returns>A <see cref=\"Response\"/> instance.</returns>\r\n        public static implicit operator Response(DynamicDictionaryValue value)\r\n        {\r\n            return new Response { Contents = GetStringContents(value) };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Converts a string content value to a response action.\r\n        /// </summary>\r\n        /// <param name=\"contents\">The string containing the content.</param>\r\n        /// <returns>A response action that will write the content of the string to the response stream.</returns>\r\n        protected static Action<Stream> GetStringContents(string contents)\r\n        {\r\n            return stream =>\r\n            {\r\n                var writer = new StreamWriter(stream) { AutoFlush = true };\r\n                writer.Write(contents);\r\n            };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.\r\n        /// </summary>\r\n        /// <remarks>This method can be overridden in sub-classes to dispose of response specific resources.</remarks>\r\n        public virtual void Dispose()\r\n        {\r\n        }\r\n\r\n        private string DebuggerDisplay\r\n        {\r\n            get { return string.Join(\" \", new string[] { this.StatusCode.ToString(), this.ReasonPhrase, this.ContentType }.Where(x => !string.IsNullOrEmpty(x)).ToArray()); }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/ResponseExtensions.cs",
    "content": "namespace Nancy\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using Nancy.Cookies;\r\n    using Nancy.Responses;\r\n\r\n    /// <summary>\r\n    /// Containing extensions for the <see cref=\"Response\"/> object.\r\n    /// </summary>\r\n    public static class ResponseExtensions\r\n    {\r\n        /// <summary>\r\n        /// Force the response to be downloaded as an attachment\r\n        /// </summary>\r\n        /// <param name=\"response\">Response object</param>\r\n        /// <param name=\"fileName\">Filename for the download</param>\r\n        /// <param name=\"contentType\">Optional content type</param>\r\n        /// <returns>Modified Response object</returns>\r\n        public static Response AsAttachment(this Response response, string fileName = null, string contentType = null)\r\n        {\r\n            var actualFilename = fileName;\r\n\r\n            if (actualFilename == null && response is GenericFileResponse)\r\n            {\r\n                actualFilename = ((GenericFileResponse)response).Filename;\r\n            }\r\n\r\n            if (string.IsNullOrEmpty(actualFilename))\r\n            {\r\n                throw new ArgumentException(\"fileName cannot be null or empty\");\r\n            }\r\n\r\n            if (contentType != null)\r\n            {\r\n                response.ContentType = contentType;\r\n            }\r\n\r\n            return response.WithHeader(\"Content-Disposition\", \"attachment; filename=\" + actualFilename);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds a <see cref=\"INancyCookie\"/> to the response.\r\n        /// </summary>\r\n        /// <param name=\"response\">Response object</param>\r\n        /// <param name=\"name\">The name of the cookie.</param>\r\n        /// <param name=\"value\">The value of the cookie.</param>\r\n        /// <returns>The <see cref=\"Response\"/> instance.</returns>\r\n        public static Response WithCookie(this Response response, string name, string value)\r\n        {\r\n            return WithCookie(response, name, value, null, null, null);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds a <see cref=\"INancyCookie\"/> to the response.\r\n        /// </summary>\r\n        /// <param name=\"response\">Response object</param>\r\n        /// <param name=\"name\">The name of the cookie.</param>\r\n        /// <param name=\"value\">The value of the cookie.</param>\r\n        /// <param name=\"expires\">The expiration date of the cookie. Can be <see langword=\"null\" /> if it should expire at the end of the session.</param>\r\n        /// <returns>The <see cref=\"Response\"/> instance.</returns>\r\n        public static Response WithCookie(this Response response, string name, string value, DateTime? expires)\r\n        {\r\n            return WithCookie(response, name, value, expires, null, null);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds a <see cref=\"INancyCookie\"/> to the response.\r\n        /// </summary>\r\n        /// <param name=\"response\">Response object</param>\r\n        /// <param name=\"name\">The name of the cookie.</param>\r\n        /// <param name=\"value\">The value of the cookie.</param>\r\n        /// <param name=\"expires\">The expiration date of the cookie. Can be <see langword=\"null\" /> if it should expire at the end of the session.</param>\r\n        /// <param name=\"domain\">The domain of the cookie.</param>\r\n        /// <param name=\"path\">The path of the cookie.</param>\r\n        /// <returns>The <see cref=\"Response\"/> instance.</returns>\r\n        public static Response WithCookie(this Response response, string name, string value, DateTime? expires, string domain, string path)\r\n        {\r\n            return WithCookie(response, new NancyCookie(name, value) { Expires = expires, Domain = domain, Path = path });\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds a <see cref=\"INancyCookie\"/> to the response.\r\n        /// </summary>\r\n        /// <param name=\"response\">Response object</param>\r\n        /// <param name=\"nancyCookie\">A <see cref=\"INancyCookie\"/> instance.</param>\r\n        /// <returns></returns>\r\n        public static Response WithCookie(this Response response, INancyCookie nancyCookie)\r\n        {\r\n            response.Cookies.Add(nancyCookie);\r\n            return response;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Add a header to the response\r\n        /// </summary>\r\n        /// <param name=\"response\">Response object</param>\r\n        /// <param name=\"header\">Header name</param>\r\n        /// <param name=\"value\">Header value</param>\r\n        /// <returns>Modified response</returns>\r\n        public static Response WithHeader(this Response response, string header, string value)\r\n        {\r\n            return response.WithHeaders(new { Header = header, Value = value });\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds headers to the response using anonymous types\r\n        /// </summary>\r\n        /// <param name=\"response\">Response object</param>\r\n        /// <param name=\"headers\">\r\n        /// Array of headers - each header should be an anonymous type with two string properties\r\n        /// 'Header' and 'Value' to represent the header name and its value.\r\n        /// </param>\r\n        /// <returns>Modified response</returns>\r\n        public static Response WithHeaders(this Response response, params object[] headers)\r\n        {\r\n            return response.WithHeaders(headers.Select(GetTuple).ToArray());\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds headers to the response using anonymous types\r\n        /// </summary>\r\n        /// <param name=\"response\">Response object</param>\r\n        /// <param name=\"headers\">\r\n        /// Array of headers - each header should be a Tuple with two string elements\r\n        /// for header name and header value\r\n        /// </param>\r\n        /// <returns>Modified response</returns>\r\n        public static Response WithHeaders(this Response response, params Tuple<string, string>[] headers)\r\n        {\r\n            if (response.Headers == null)\r\n            {\r\n                response.Headers = new Dictionary<string, string>();\r\n            }\r\n\r\n            foreach (var keyValuePair in headers)\r\n            {\r\n                response.Headers[keyValuePair.Item1] = keyValuePair.Item2;\r\n            }\r\n\r\n            return response;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Sets the content type of the response\r\n        /// </summary>\r\n        /// <param name=\"response\">Response object</param>\r\n        /// <param name=\"contentType\">The type of the content</param>\r\n        /// <returns>Modified response</returns>\r\n        public static Response WithContentType(this Response response, string contentType)\r\n        {\r\n            response.ContentType = contentType;\r\n            return response;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Sets the status code of the response\r\n        /// </summary>\r\n        /// <param name=\"response\">Response object</param>\r\n        /// <param name=\"statusCode\">The http status code</param>\r\n        /// <returns>Modified response</returns>\r\n        public static Response WithStatusCode(this Response response, HttpStatusCode statusCode)\r\n        {\r\n            response.StatusCode = statusCode;\r\n            return response;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Sets the status code of the response\r\n        /// </summary>\r\n        /// <param name=\"response\">Response object</param>\r\n        /// <param name=\"statusCode\">The http status code</param>\r\n        /// <returns>Modified response</returns>\r\n        public static Response WithStatusCode(this Response response, int statusCode)\r\n        {\r\n            response.StatusCode = (HttpStatusCode) statusCode;\r\n            return response;\r\n        }\r\n\r\n        private static Tuple<string, string> GetTuple(object header)\r\n        {\r\n            var properties = header.GetType()\r\n                .GetTypeInfo()\r\n                .DeclaredProperties\r\n                .Where(prop => prop.CanRead && prop.PropertyType == typeof(string))\r\n                .ToArray();\r\n\r\n            var headerProperty = properties\r\n                .Where(p => string.Equals(p.Name, \"Header\", StringComparison.OrdinalIgnoreCase))\r\n                .FirstOrDefault();\r\n\r\n            var valueProperty = properties\r\n                .Where(p => string.Equals(p.Name, \"Value\", StringComparison.OrdinalIgnoreCase))\r\n                .FirstOrDefault();\r\n\r\n            if (headerProperty == null || valueProperty == null)\r\n            {\r\n                throw new ArgumentException(\"Unable to extract 'Header' or 'Value' properties from anonymous type.\");\r\n            }\r\n\r\n            return Tuple.Create(\r\n                (string)headerProperty.GetValue(header, null),\r\n                (string)valueProperty.GetValue(header, null));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Responses/DefaultJsonSerializer.cs",
    "content": "﻿namespace Nancy.Responses\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using Nancy.Configuration;\r\n    using Nancy.IO;\r\n    using Nancy.Json;\r\n    using Nancy.Responses.Negotiation;\r\n\r\n    /// <summary>\r\n    /// Default <see cref=\"ISerializer\"/> implementation for JSON serialization.\r\n    /// </summary>\r\n    public class DefaultJsonSerializer : ISerializer\r\n    {\r\n        private readonly JsonConfiguration jsonConfiguration;\r\n        private readonly TraceConfiguration traceConfiguration;\r\n        private readonly GlobalizationConfiguration globalizationConfiguration;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultJsonSerializer\"/> class,\r\n        /// with the provided <see cref=\"INancyEnvironment\"/>.\r\n        /// </summary>\r\n        /// <param name=\"environment\">An <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        public DefaultJsonSerializer(INancyEnvironment environment)\r\n        {\r\n            this.jsonConfiguration = environment.GetValue<JsonConfiguration>();\r\n            this.traceConfiguration = environment.GetValue<TraceConfiguration>();\r\n            this.globalizationConfiguration = environment.GetValue<GlobalizationConfiguration>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Whether the serializer can serialize the content type\r\n        /// </summary>\r\n        /// <param name=\"mediaRange\">Content type to serialise</param>\r\n        /// <returns>True if supported, false otherwise</returns>\r\n        public bool CanSerialize(MediaRange mediaRange)\r\n        {\r\n            return Json.IsJsonContentType(mediaRange);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the list of extensions that the serializer can handle.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> of extensions if any are available, otherwise an empty enumerable.</value>\r\n        public IEnumerable<string> Extensions\r\n        {\r\n            get { yield return \"json\"; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Serialize the given model with the given contentType\r\n        /// </summary>\r\n        /// <param name=\"mediaRange\">Content type to serialize into</param>\r\n        /// <param name=\"model\">Model to serialize</param>\r\n        /// <param name=\"outputStream\">Stream to serialize to</param>\r\n        /// <returns>Serialised object</returns>\r\n        public void Serialize<TModel>(MediaRange mediaRange, TModel model, Stream outputStream)\r\n        {\r\n            using (var writer = new StreamWriter(new UnclosableStreamWrapper(outputStream)))\r\n            {\r\n                var serializer = new JavaScriptSerializer(this.jsonConfiguration, this.globalizationConfiguration);\r\n\r\n                serializer.RegisterConverters(this.jsonConfiguration.Converters,\r\n                    this.jsonConfiguration.PrimitiveConverters);\r\n\r\n                try\r\n                {\r\n                    serializer.Serialize(model, writer);\r\n                }\r\n                catch (Exception exception)\r\n                {\r\n                    if (this.traceConfiguration.DisplayErrorTraces)\r\n                    {\r\n                        writer.Write(exception.Message);\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Responses/DefaultXmlSerializer.cs",
    "content": "﻿namespace Nancy.Responses\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Text;\r\n    using System.Xml.Serialization;\r\n    using Nancy.Configuration;\r\n    using Nancy.Responses.Negotiation;\r\n    using Nancy.Xml;\r\n\r\n    /// <summary>\r\n    /// Default <see cref=\"ISerializer\"/> implementation for XML serialization.\r\n    /// </summary>\r\n    public class DefaultXmlSerializer : ISerializer\r\n    {\r\n        private readonly XmlConfiguration configuration;\r\n        private readonly TraceConfiguration traceConfiguration;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultXmlSerializer\"/> class,\r\n        /// with the provided <see cref=\"INancyEnvironment\"/>.\r\n        /// </summary>\r\n        /// <param name=\"environment\">An <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        public DefaultXmlSerializer(INancyEnvironment environment)\r\n        {\r\n            this.configuration = environment.GetValue<XmlConfiguration>();\r\n            this.traceConfiguration = environment.GetValue<TraceConfiguration>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Whether the serializer can serialize the content type\r\n        /// </summary>\r\n        /// <param name=\"mediaRange\">Content type to serialise</param>\r\n        /// <returns>True if supported, false otherwise</returns>\r\n        public bool CanSerialize(MediaRange mediaRange)\r\n        {\r\n            return IsXmlType(mediaRange);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the list of extensions that the serializer can handle.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> of extensions if any are available, otherwise an empty enumerable.</value>\r\n        public IEnumerable<string> Extensions\r\n        {\r\n            get { yield return \"xml\"; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Serialize the given model with the given contentType\r\n        /// </summary>\r\n        /// <param name=\"mediaRange\">Content type to serialize into</param>\r\n        /// <param name=\"model\">Model to serialize</param>\r\n        /// <param name=\"outputStream\">Output stream to serialize to</param>\r\n        /// <returns>Serialised object</returns>\r\n        public void Serialize<TModel>(MediaRange mediaRange, TModel model, Stream outputStream)\r\n        {\r\n            try\r\n            {\r\n                var serializer = new XmlSerializer(typeof(TModel));\r\n\r\n                if (this.configuration.EncodingEnabled)\r\n                {\r\n                    serializer.Serialize(new StreamWriter(outputStream, this.configuration.DefaultEncoding), model);\r\n                }\r\n                else\r\n                {\r\n                    serializer.Serialize(outputStream, model);\r\n                }\r\n            }\r\n            catch (Exception exception)\r\n            {\r\n                if (this.traceConfiguration.DisplayErrorTraces)\r\n                {\r\n                    var bytes = Encoding.UTF8.GetBytes(exception.Message);\r\n                    outputStream.Write(bytes, 0, exception.Message.Length);\r\n                }\r\n            }\r\n        }\r\n\r\n        private static bool IsXmlType(string contentType)\r\n        {\r\n            if (string.IsNullOrEmpty(contentType))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            var contentMimeType = contentType.Split(';')[0];\r\n\r\n            return contentMimeType.StartsWith(\"application/xml\", StringComparison.OrdinalIgnoreCase)\r\n                || contentMimeType.Equals(\"text/xml\", StringComparison.OrdinalIgnoreCase)\r\n                || contentMimeType.EndsWith(\"+xml\", StringComparison.OrdinalIgnoreCase);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Responses/EmbeddedFileResponse.cs",
    "content": "﻿namespace Nancy.Responses\r\n{\r\n    using System;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using System.Security.Cryptography;\r\n    using System.Text;\r\n    using System.Text.RegularExpressions;\r\n\r\n    /// <summary>\r\n    /// Represent an HTML response with embeded file content.\r\n    /// </summary>\r\n    /// <seealso cref=\"Nancy.Response\" />\r\n    public class EmbeddedFileResponse : Response\r\n    {\r\n        private static readonly byte[] ErrorText;\r\n\r\n        static EmbeddedFileResponse()\r\n        {\r\n            ErrorText = Encoding.UTF8.GetBytes(\"NOT FOUND\");\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"EmbeddedFileResponse\"/> class, with\r\n        /// the provided <paramref name=\"assembly\"/>, <paramref name=\"resourcePath\"/> and <paramref name=\"name\"/>.\r\n        /// </summary>\r\n        /// <param name=\"assembly\">The assembly.</param>\r\n        /// <param name=\"resourcePath\">The resource path.</param>\r\n        /// <param name=\"name\">The name.</param>\r\n        public EmbeddedFileResponse(Assembly assembly, string resourcePath, string name)\r\n        {\r\n            this.ContentType = MimeTypes.GetMimeType(name);\r\n            this.StatusCode = HttpStatusCode.OK;\r\n\r\n            var content =\r\n                    GetResourceContent(assembly, resourcePath, name);\r\n\r\n            if (content != null)\r\n            {\r\n                this.WithHeader(\"ETag\", GenerateETag(content));\r\n                content.Seek(0, SeekOrigin.Begin);\r\n            }\r\n\r\n            this.Contents = stream =>\r\n            {\r\n                if (content != null)\r\n                {\r\n                    content.CopyTo(stream);\r\n                }\r\n                else\r\n                {\r\n                    stream.Write(ErrorText, 0, ErrorText.Length);\r\n                }\r\n            };\r\n        }\r\n\r\n        private Stream GetResourceContent(Assembly assembly, string resourcePath, string name)\r\n        {\r\n            var resourceName = assembly\r\n                .GetManifestResourceNames()\r\n                .FirstOrDefault(x => GetFileNameFromResourceName(resourcePath, x).Equals(name, StringComparison.OrdinalIgnoreCase));\r\n\r\n            if (resourceName == null)\r\n                return null;\r\n\r\n            return assembly.GetManifestResourceStream(resourceName);\r\n        }\r\n\r\n        private static string GetFileNameFromResourceName(string resourcePath, string resourceName)\r\n        {\r\n            return Regex.Replace(resourceName, resourcePath, string.Empty, RegexOptions.IgnoreCase).Substring(1);\r\n        }\r\n\r\n        private static string GenerateETag(Stream stream)\r\n        {\r\n            using (var sha1 = SHA1.Create())\r\n            {\r\n                var hash = sha1.ComputeHash(stream);\r\n                return string.Concat(\"\\\"\", ByteArrayToString(hash), \"\\\"\");\r\n            }\r\n        }\r\n\r\n        private static string ByteArrayToString(byte[] data)\r\n        {\r\n            var output = new StringBuilder(data.Length);\r\n            for (int i = 0; i < data.Length; i++)\r\n            {\r\n                output.Append(data[i].ToString(\"X2\"));\r\n            }\r\n\r\n            return output.ToString();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Responses/GenericFileResponse.cs",
    "content": "﻿namespace Nancy.Responses\r\n{\r\n    using System;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using Nancy.Configuration;\r\n    using Nancy.Helpers;\r\n\r\n    /// <summary>\r\n    /// A response representing a file.\r\n    /// </summary>\r\n    /// <remarks>If the response contains an invalid file (not found, empty name, missing extension and so on) the status code of the response will be set to <see cref=\"HttpStatusCode.NotFound\"/>.</remarks>\r\n    public class GenericFileResponse : Response\r\n    {\r\n        private readonly StaticContentConfiguration configuration;\r\n\r\n        /// <summary>\r\n        ///  Size of buffer for transmitting file. Default size 4 Mb\r\n        /// </summary>\r\n        public static int BufferSize = 4 * 1024 * 1024;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"GenericFileResponse\"/> for the file specified\r\n        /// by the <paramref name=\"filePath\"/> parameter and <paramref name=\"context\"/>.\r\n        /// </summary>\r\n        /// <param name=\"filePath\">The name of the file, including path relative to the root of the application, that should be returned.</param>\r\n        /// <remarks>The <see cref=\"MimeTypes.GetMimeType\"/> method will be used to determine the mimetype of the file and will be used as the content-type of the response. If no match if found the content-type will be set to application/octet-stream.</remarks>\r\n        /// <param name=\"context\">Current context</param>\r\n        public GenericFileResponse(string filePath, NancyContext context)\r\n            : this(filePath, MimeTypes.GetMimeType(filePath), context)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"GenericFileResponse\"/> for the file specified\r\n        /// by the <paramref name=\"filePath\"/> parameter, the content-type specified by the <paramref name=\"contentType\"/> parameter \r\n        /// and <paramref name=\"context\"/>.\r\n        /// </summary>\r\n        /// <param name=\"filePath\">The name of the file, including path relative to the root of the application, that should be returned.</param>\r\n        /// <param name=\"contentType\">The content-type of the response.</param>\r\n        /// <param name=\"context\">Current context</param>\r\n        public GenericFileResponse(string filePath, string contentType, NancyContext context)\r\n        {\r\n            var environment = context.Environment;\r\n            this.configuration = environment.GetValue<StaticContentConfiguration>();\r\n            this.InitializeGenericFileResponse(filePath, contentType, context);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the filename of the file response\r\n        /// </summary>\r\n        /// <value>A string containing the name of the file.</value>\r\n        public string Filename { get; protected set; }\r\n\r\n        private static Action<Stream> GetFileContent(string filePath, long length)\r\n        {\r\n            return stream =>\r\n            {\r\n                using (var file = File.OpenRead(filePath))\r\n                {\r\n                    file.CopyTo(stream, (int)(length < BufferSize ? length : BufferSize));\r\n                }\r\n            };\r\n        }\r\n\r\n        static bool IsSafeFilePath(string rootPath, string filePath)\r\n        {\r\n            if (!File.Exists(filePath))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            var fullPath = Path.GetFullPath(filePath);\r\n\r\n            return fullPath.StartsWith(Path.GetFullPath(rootPath), StringComparison.OrdinalIgnoreCase);\r\n        }\r\n\r\n        private void InitializeGenericFileResponse(string filePath, string contentType, NancyContext context)\r\n        {\r\n            if (string.IsNullOrEmpty(filePath))\r\n            {\r\n                StatusCode = HttpStatusCode.NotFound;\r\n                return;\r\n            }\r\n\r\n            if (this.configuration.SafePaths == null || !this.configuration.SafePaths.Any())\r\n            {\r\n                throw new InvalidOperationException(\"No SafePaths defined.\");\r\n            }\r\n            foreach (var rootPath in this.configuration.SafePaths)\r\n            {\r\n                string fullPath;\r\n                if (Path.IsPathRooted(filePath))\r\n                {\r\n                    fullPath = filePath;\r\n                }\r\n                else\r\n                {\r\n                    fullPath = Path.Combine(rootPath, filePath);\r\n                }\r\n\r\n                if (IsSafeFilePath(rootPath, fullPath))\r\n                {\r\n                    this.Filename = Path.GetFileName(fullPath);\r\n\r\n                    this.SetResponseValues(contentType, fullPath, context);\r\n\r\n                    return;\r\n                }\r\n            }\r\n\r\n            StatusCode = HttpStatusCode.NotFound;\r\n        }\r\n\r\n        private void SetResponseValues(string contentType, string fullPath, NancyContext context)\r\n        {\r\n            // TODO - set a standard caching time and/or public?\r\n            var fi = new FileInfo(fullPath);\r\n\r\n            var lastWriteTimeUtc = fi.LastWriteTimeUtc;\r\n            var etag = string.Concat(\"\\\"\", lastWriteTimeUtc.Ticks.ToString(\"x\"), \"\\\"\");\r\n            var lastModified = lastWriteTimeUtc.ToString(\"R\");\r\n            var length = fi.Length;\r\n\r\n            if (CacheHelpers.ReturnNotModified(etag, lastWriteTimeUtc, context))\r\n            {\r\n                this.StatusCode = HttpStatusCode.NotModified;\r\n                this.ContentType = null;\r\n                this.Contents = NoBody;\r\n\r\n                return;\r\n            }\r\n\r\n            this.Headers[\"ETag\"] = etag;\r\n            this.Headers[\"Last-Modified\"] = lastModified;\r\n            this.Headers[\"Content-Length\"] = length.ToString();\r\n\r\n            if (length > 0)\r\n            {\r\n                this.Contents = GetFileContent(fullPath, length);\r\n            }\r\n\r\n            this.ContentType = contentType;\r\n            this.StatusCode = HttpStatusCode.OK;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Responses/HtmlResponse.cs",
    "content": "﻿namespace Nancy.Responses\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n\r\n    using Nancy.Cookies;\r\n\r\n    /// <summary>\r\n    /// Represents a HTML (text/html) response\r\n    /// </summary>\r\n    public class HtmlResponse : Response\r\n    {\r\n        /// <summary>\r\n        /// Creates a new instance of the  <see cref=\"HtmlResponse\"/> class, with\r\n        /// the provided <paramref name=\"statusCode\"/>, <paramref name=\"contents\"/>,\r\n        /// <paramref name=\"headers\"/> and <paramref name=\"cookies\"/>\r\n        /// </summary>\r\n        /// <param name=\"statusCode\">Status code - defaults to OK</param>\r\n        /// <param name=\"contents\">Response body delegate - defaults to empty if null</param>\r\n        /// <param name=\"headers\">Headers if required</param>\r\n        /// <param name=\"cookies\">Cookies if required</param>\r\n        public HtmlResponse(HttpStatusCode statusCode = HttpStatusCode.OK, Action<Stream> contents = null, IDictionary<string, string> headers = null, IEnumerable<INancyCookie> cookies = null)\r\n        {\r\n            this.ContentType = \"text/html\";\r\n            this.StatusCode = statusCode;\r\n\r\n            if (contents != null)\r\n            {\r\n                this.Contents = contents;\r\n            }\r\n\r\n            if (headers != null)\r\n            {\r\n                this.Headers = headers;\r\n            }\r\n\r\n            if (cookies != null)\r\n            {\r\n                foreach (var nancyCookie in cookies)\r\n                {\r\n                    this.Cookies.Add(nancyCookie);\r\n                }\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Responses/JsonResponse.cs",
    "content": "﻿namespace Nancy.Responses\r\n{\r\n    using System;\r\n    using System.IO;\r\n    using Nancy.Configuration;\r\n    using Nancy.Json;\r\n\r\n    /// <summary>\r\n    /// Represents a JSON response of the type <typeparamref name=\"TModel\"/>.\r\n    /// </summary>\r\n    /// <typeparam name=\"TModel\">The type of the model.</typeparam>\r\n    public class JsonResponse<TModel> : Response\r\n    {\r\n        private readonly JsonConfiguration configuration;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"JsonResponse{TModel}\"/> class,\r\n        /// with the provided <paramref name=\"model\"/>, <paramref name=\"serializer\"/>\r\n        /// and <paramref name=\"environment\"/>.\r\n        /// </summary>\r\n        /// <param name=\"model\">The model that should be returned as JSON.</param>\r\n        /// <param name=\"serializer\">The <see cref=\"ISerializer\"/> to use for the serialization.</param>\r\n        /// <param name=\"environment\">An <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        public JsonResponse(TModel model, ISerializer serializer, INancyEnvironment environment)\r\n        {\r\n            if (serializer == null)\r\n            {\r\n                throw new InvalidOperationException(\"JSON Serializer not set\");\r\n            }\r\n\r\n            this.configuration = environment.GetValue<JsonConfiguration>();\r\n            this.Contents = model == null ? NoBody : this.GetJsonContents(model, serializer);\r\n            this.ContentType = this.DefaultContentType;\r\n            this.StatusCode = HttpStatusCode.OK;\r\n        }\r\n\r\n        private string DefaultContentType\r\n        {\r\n            get { return string.Concat(\"application/json\", this.Encoding); }\r\n        }\r\n\r\n        private string Encoding\r\n        {\r\n            get { return string.Concat(\"; charset=\", this.configuration.DefaultEncoding.WebName); }\r\n        }\r\n\r\n        private Action<Stream> GetJsonContents(TModel model, ISerializer serializer)\r\n        {\r\n            return stream => serializer.Serialize(this.DefaultContentType, model, stream);\r\n        }\r\n    }\r\n\r\n    /// <summary>\r\n    /// Represents a JSON response\r\n    /// </summary>\r\n    public class JsonResponse : JsonResponse<object>\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"JsonResponse{TModel}\"/> class,\r\n        /// with the provided <paramref name=\"model\"/>, <paramref name=\"serializer\"/>\r\n        /// and <paramref name=\"environment\"/>.\r\n        /// </summary>\r\n        /// <param name=\"model\">The model that should be returned as JSON.</param>\r\n        /// <param name=\"serializer\">The <see cref=\"ISerializer\"/> to use for the serialization.</param>\r\n        /// <param name=\"environment\">An <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        public JsonResponse(object model, ISerializer serializer, INancyEnvironment environment) : base(model, serializer, environment)\r\n        {\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Responses/MaterialisingResponse.cs",
    "content": "﻿namespace Nancy.Responses\r\n{\r\n    using System;\r\n    using System.IO;\r\n    using System.Threading.Tasks;\r\n\r\n    using Nancy.Helpers;\r\n\r\n    /// <summary>\r\n    /// Takes an existing response and materialises the body.\r\n    /// Can be used as a wrapper to force execution of the deferred body for\r\n    /// error checking etc.\r\n    /// Copies the existing response into memory, so use with caution.\r\n    /// </summary>\r\n    public class MaterialisingResponse : Response\r\n    {\r\n        private readonly Response sourceResponse;\r\n        private byte[] oldResponseOutput;\r\n\r\n        /// <summary>\r\n        /// Executes at the end of the nancy execution pipeline and before control is passed back to the hosting.\r\n        /// Can be used to pre-render/validate views while still inside the main pipeline/error handling.\r\n        /// </summary>\r\n        /// <param name=\"context\">Nancy context</param>\r\n        /// <returns>\r\n        /// Task for completion/erroring\r\n        /// </returns>\r\n        public override Task PreExecute(NancyContext context)\r\n        {\r\n            using (var memoryStream = new MemoryStream())\r\n            {\r\n                this.sourceResponse.Contents.Invoke(memoryStream);\r\n                this.oldResponseOutput = memoryStream.ToArray();\r\n            }\r\n\r\n            return base.PreExecute(context);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"MaterialisingResponse\"/> class, with\r\n        /// the provided <paramref name=\"sourceResponse\"/>.\r\n        /// </summary>\r\n        /// <param name=\"sourceResponse\">The source response.</param>\r\n        public MaterialisingResponse(Response sourceResponse)\r\n        {\r\n            this.sourceResponse = sourceResponse;\r\n            this.ContentType = sourceResponse.ContentType;\r\n            this.Headers = sourceResponse.Headers;\r\n            this.StatusCode = sourceResponse.StatusCode;\r\n            this.ReasonPhrase = sourceResponse.ReasonPhrase;\r\n\r\n            this.Contents = WriteContents;\r\n        }\r\n\r\n        private void WriteContents(Stream stream)\r\n        {\r\n            if (this.oldResponseOutput == null)\r\n            {\r\n                this.sourceResponse.Contents.Invoke(stream);\r\n            }\r\n            else\r\n            {\r\n                stream.Write(this.oldResponseOutput, 0, this.oldResponseOutput.Length);\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Responses/NegotiatedResponse.cs",
    "content": "﻿namespace Nancy.Responses\r\n{\r\n    /// <summary>\r\n    /// Response that indicates that the response format should be negotiated between the client and the server.\r\n    /// </summary>\r\n    public class NegotiatedResponse : Response\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NegotiatedResponse\"/> response for the\r\n        /// provided <paramref name=\"value\"/>.\r\n        /// </summary>\r\n        /// <param name=\"value\">The response value that should be negotiated.</param>\r\n        public NegotiatedResponse(dynamic value)\r\n        {\r\n            Value = value;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the value that should be negotiated.\r\n        /// </summary>\r\n        public dynamic Value { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Responses/Negotiation/DefaultResponseNegotiator.cs",
    "content": "﻿namespace Nancy.Responses.Negotiation\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using System.Text;\r\n\r\n    using Nancy.Conventions;\r\n    using Nancy.Extensions;\r\n    using Nancy.Helpers;\r\n\r\n    /// <summary>\r\n    /// The default implementation for a response negotiator.\r\n    /// </summary>\r\n    public class DefaultResponseNegotiator : IResponseNegotiator\r\n    {\r\n        private readonly IReadOnlyCollection<IResponseProcessor> processors;\r\n        private readonly AcceptHeaderCoercionConventions coercionConventions;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultResponseNegotiator\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"processors\">The response processors.</param>\r\n        /// <param name=\"coercionConventions\">The Accept header coercion conventions.</param>\r\n        public DefaultResponseNegotiator(IEnumerable<IResponseProcessor> processors, AcceptHeaderCoercionConventions coercionConventions)\r\n        {\r\n            this.processors = processors.ToArray();\r\n            this.coercionConventions = coercionConventions;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Negotiates the response based on the given result and context.\r\n        /// </summary>\r\n        /// <param name=\"routeResult\">The route result.</param>\r\n        /// <param name=\"context\">The context.</param>\r\n        /// <returns>A <see cref=\"Response\" />.</returns>\r\n        public Response NegotiateResponse(dynamic routeResult, NancyContext context)\r\n        {\r\n            Response response;\r\n            if (TryCastResultToResponse(routeResult, out response))\r\n            {\r\n                context.WriteTraceLog(sb =>\r\n                    sb.AppendLine(\"[DefaultResponseNegotiator] Processing as real response\"));\r\n\r\n                return response;\r\n            }\r\n\r\n            context.WriteTraceLog(sb =>\r\n                sb.AppendLine(\"[DefaultResponseNegotiator] Processing as negotiation\"));\r\n\r\n            NegotiationContext negotiationContext = GetNegotiationContext(routeResult, context);\r\n\r\n            var coercedAcceptHeaders = this.GetCoercedAcceptHeaders(context).ToArray();\r\n\r\n            context.WriteTraceLog(sb => GetAccepHeaderTraceLog(context, negotiationContext, coercedAcceptHeaders, sb));\r\n\r\n            var compatibleHeaders = this.GetCompatibleHeaders(coercedAcceptHeaders, negotiationContext, context).ToArray();\r\n\r\n            if (!compatibleHeaders.Any())\r\n            {\r\n                context.WriteTraceLog(sb =>\r\n                    sb.AppendLine(\"[DefaultResponseNegotiator] Unable to negotiate response - no headers compatible\"));\r\n\r\n                return new NotAcceptableResponse();\r\n            }\r\n\r\n            return CreateResponse(compatibleHeaders, negotiationContext, context);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tries to cast the dynamic result to a <see cref=\"Response\"/>.\r\n        /// </summary>\r\n        /// <param name=\"routeResult\">The result.</param>\r\n        /// <param name=\"response\">The response.</param>\r\n        /// <returns><c>true</c> if the result is a <see cref=\"Response\"/>, <c>false</c> otherwise.</returns>\r\n        private static bool TryCastResultToResponse(dynamic routeResult, out Response response)\r\n        {\r\n            var targetType = routeResult.GetType();\r\n            var responseType = typeof(Response);\r\n\r\n            if (routeResult is Response)\r\n            {\r\n                response = (Response)routeResult;\r\n                return true;\r\n            }\r\n\r\n            var methods = responseType.GetMethods(BindingFlags.Public | BindingFlags.Static);\r\n\r\n            foreach (var method in methods)\r\n            {\r\n                if (!method.Name.Equals(\"op_Implicit\", StringComparison.Ordinal))\r\n                {\r\n                    continue;\r\n                }\r\n\r\n                if (method.ReturnType != responseType)\r\n                {\r\n                    continue;\r\n                }\r\n\r\n                var parameters = method.GetParameters();\r\n\r\n                if (parameters.Length != 1)\r\n                {\r\n                    continue;\r\n                }\r\n\r\n                if (parameters[0].ParameterType != targetType)\r\n                {\r\n                    continue;\r\n                }\r\n\r\n                response = (Response)routeResult;\r\n                return true;\r\n            }\r\n\r\n            response = null;\r\n            return false;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a <see cref=\"NegotiationContext\"/> based on the given result and context.\r\n        /// </summary>\r\n        /// <param name=\"routeResult\">The route result.</param>\r\n        /// <param name=\"context\">The context.</param>\r\n        /// <returns>A <see cref=\"NegotiationContext\"/>.</returns>\r\n        private static NegotiationContext GetNegotiationContext(object routeResult, NancyContext context)\r\n        {\r\n            var negotiator = routeResult as Negotiator;\r\n\r\n            if (negotiator == null)\r\n            {\r\n                context.WriteTraceLog(sb =>\r\n                    sb.AppendFormat(\"[DefaultResponseNegotiator] Wrapping result of type {0} in negotiator\\n\", routeResult.GetType()));\r\n\r\n                negotiator = new Negotiator(context).WithModel(routeResult);\r\n            }\r\n\r\n            return negotiator.NegotiationContext;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the coerced accept headers based on the <see cref=\"AcceptHeaderCoercionConventions\"/>.\r\n        /// </summary>\r\n        /// <param name=\"context\">The context.</param>\r\n        /// <returns>IEnumerable{Tuple{System.String, System.Decimal}}.</returns>\r\n        private IEnumerable<Tuple<string, decimal>> GetCoercedAcceptHeaders(NancyContext context)\r\n        {\r\n            return this.coercionConventions.Aggregate(context.Request.Headers.Accept, (current, coercion) => coercion.Invoke(current, context));\r\n        }\r\n\r\n        private static void GetAccepHeaderTraceLog(\r\n            NancyContext context,\r\n            NegotiationContext negotiationContext,\r\n            Tuple<string, decimal>[] coercedAcceptHeaders,\r\n            StringBuilder sb)\r\n        {\r\n            var allowableFormats = negotiationContext.PermissableMediaRanges\r\n                .Select(mr => mr.ToString())\r\n                .Aggregate((t1, t2) => t1 + \", \" + t2);\r\n\r\n            var originalAccept = context.Request.Headers[\"accept\"].Any()\r\n                ? string.Join(\", \", context.Request.Headers[\"accept\"])\r\n                : \"None\";\r\n\r\n            var coercedAccept = coercedAcceptHeaders.Any()\r\n                ? coercedAcceptHeaders.Select(h => h.Item1).Aggregate((t1, t2) => t1 + \", \" + t2)\r\n                : \"None\";\r\n\r\n            sb.AppendFormat(\"[DefaultResponseNegotiator] Original accept header: {0}\\n\", originalAccept);\r\n            sb.AppendFormat(\"[DefaultResponseNegotiator] Coerced accept header: {0}\\n\", coercedAccept);\r\n            sb.AppendFormat(\"[DefaultResponseNegotiator] Acceptable media ranges: {0}\\n\", allowableFormats);\r\n        }\r\n\r\n        private IEnumerable<CompatibleHeader> GetCompatibleHeaders(\r\n            IEnumerable<Tuple<string, decimal>> coercedAcceptHeaders,\r\n            NegotiationContext negotiationContext,\r\n            NancyContext context)\r\n        {\r\n            var acceptHeaders = GetCompatibleHeaders(coercedAcceptHeaders, negotiationContext);\r\n\r\n            foreach (var header in acceptHeaders)\r\n            {\r\n                var mediaRangeModel = negotiationContext.GetModelForMediaRange(header.Item1);\r\n\r\n                IEnumerable<Tuple<IResponseProcessor, ProcessorMatch>> compatibleProcessors =\r\n                    this.GetCompatibleProcessorsByHeader(header.Item1, mediaRangeModel, context);\r\n\r\n                if (compatibleProcessors.Any())\r\n                {\r\n                    yield return new CompatibleHeader(header.Item1, compatibleProcessors);\r\n                }\r\n            }\r\n        }\r\n\r\n        private static IEnumerable<Tuple<string, decimal>> GetCompatibleHeaders(\r\n            IEnumerable<Tuple<string, decimal>> coercedAcceptHeaders,\r\n            NegotiationContext negotiationContext)\r\n        {\r\n            var permissableMediaRanges = negotiationContext.PermissableMediaRanges;\r\n            if (permissableMediaRanges.Any(mr => mr.IsWildcard))\r\n            {\r\n                return coercedAcceptHeaders.Where(header => header.Item2 > 0m);\r\n            }\r\n\r\n            return coercedAcceptHeaders\r\n                .Where(header => header.Item2 > 0m)\r\n                .SelectMany(header => permissableMediaRanges\r\n                    .Where(mr => mr.Matches(header.Item1))\r\n                    .Select(mr => Tuple.Create(mr.ToString(), header.Item2)));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets compatible response processors by header.\r\n        /// </summary>\r\n        /// <param name=\"acceptHeader\">The accept header.</param>\r\n        /// <param name=\"model\">The model.</param>\r\n        /// <param name=\"context\">The context.</param>\r\n        /// <returns>IEnumerable{Tuple{IResponseProcessor, ProcessorMatch}}.</returns>\r\n        private IEnumerable<Tuple<IResponseProcessor, ProcessorMatch>> GetCompatibleProcessorsByHeader(\r\n            string acceptHeader, dynamic model, NancyContext context)\r\n        {\r\n            foreach (var processor in this.processors)\r\n            {\r\n                ProcessorMatch match = processor.CanProcess(acceptHeader, model, context);\r\n\r\n                if (match.ModelResult != MatchResult.NoMatch && match.RequestedContentTypeResult != MatchResult.NoMatch)\r\n                {\r\n                    yield return new Tuple<IResponseProcessor, ProcessorMatch>(processor, match);\r\n                }\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a response from the compatible headers.\r\n        /// </summary>\r\n        /// <param name=\"compatibleHeaders\">The compatible headers.</param>\r\n        /// <param name=\"negotiationContext\">The negotiation context.</param>\r\n        /// <param name=\"context\">The context.</param>\r\n        /// <returns>A <see cref=\"Response\"/>.</returns>\r\n        private Response CreateResponse(IList<CompatibleHeader> compatibleHeaders,\r\n                                        NegotiationContext negotiationContext,\r\n                                        NancyContext context)\r\n        {\r\n            var response = NegotiateResponse(compatibleHeaders, negotiationContext, context);\r\n\r\n            if (response == null)\r\n            {\r\n                context.WriteTraceLog(sb =>\r\n                    sb.AppendLine(\"[DefaultResponseNegotiator] Unable to negotiate response - no processors returned valid response\"));\r\n\r\n                response = new NotAcceptableResponse();\r\n            }\r\n\r\n            response.WithHeader(\"Vary\", \"Accept\");\r\n\r\n            this.AddLinkHeader(compatibleHeaders, response, context.Request.Url);\r\n            SetStatusCode(negotiationContext, response);\r\n            SetReasonPhrase(negotiationContext, response);\r\n            AddCookies(negotiationContext, response);\r\n\r\n            if (response is NotAcceptableResponse)\r\n            {\r\n                return response;\r\n            }\r\n\r\n            AddContentTypeHeader(negotiationContext, response);\r\n            AddNegotiatedHeaders(negotiationContext, response);\r\n\r\n            return response;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Prioritizes the response processors and tries to negotiate a response.\r\n        /// </summary>\r\n        /// <param name=\"compatibleHeaders\">The compatible headers.</param>\r\n        /// <param name=\"negotiationContext\">The negotiation context.</param>\r\n        /// <param name=\"context\">The context.</param>\r\n        /// <returns>Response.</returns>\r\n        private static Response NegotiateResponse(\r\n            IEnumerable<CompatibleHeader> compatibleHeaders,\r\n            NegotiationContext negotiationContext,\r\n            NancyContext context)\r\n        {\r\n            foreach (var compatibleHeader in compatibleHeaders)\r\n            {\r\n                var prioritizedProcessors = compatibleHeader.Processors\r\n                    .OrderByDescending(x => x.Item2.ModelResult)\r\n                    .ThenByDescending(x => x.Item2.RequestedContentTypeResult);\r\n\r\n                foreach (var prioritizedProcessor in prioritizedProcessors)\r\n                {\r\n                    var processorType = prioritizedProcessor.Item1.GetType();\r\n\r\n                    context.WriteTraceLog(sb =>\r\n                        sb.AppendFormat(\"[DefaultResponseNegotiator] Invoking processor: {0}\\n\", processorType));\r\n\r\n                    var mediaRangeModel = negotiationContext.GetModelForMediaRange(compatibleHeader.MediaRange);\r\n\r\n                    var response = prioritizedProcessor.Item1.Process(compatibleHeader.MediaRange, mediaRangeModel, context);\r\n                    if (response != null)\r\n                    {\r\n                        return response;\r\n                    }\r\n                }\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds a link header to the <see cref=\"Response\"/>.\r\n        /// </summary>\r\n        /// <param name=\"compatibleHeaders\">The compatible headers.</param>\r\n        /// <param name=\"response\">The response.</param>\r\n        /// <param name=\"requestUrl\">The request URL.</param>\r\n        private void AddLinkHeader(IEnumerable<CompatibleHeader> compatibleHeaders, Response response, Url requestUrl)\r\n        {\r\n            var linkProcessors = GetLinkProcessors(compatibleHeaders, response.ContentType);\r\n            if (linkProcessors.Any())\r\n            {\r\n                string existingLinkHeader;\r\n                response.Headers.TryGetValue(\"Link\", out existingLinkHeader);\r\n                response.Headers[\"Link\"] = this.CreateLinkHeader(requestUrl, linkProcessors, existingLinkHeader);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the link processors based on the compatible headers and content-type.\r\n        /// </summary>\r\n        /// <param name=\"compatibleHeaders\">The compatible headers.</param>\r\n        /// <param name=\"contentType\">The content-type of the response.</param>\r\n        /// <returns>Dictionary{System.String, MediaRange}.</returns>\r\n        private static IDictionary<string, MediaRange> GetLinkProcessors(\r\n            IEnumerable<CompatibleHeader> compatibleHeaders,\r\n            string contentType)\r\n        {\r\n            var linkProcessors = new Dictionary<string, MediaRange>();\r\n\r\n            foreach (var header in compatibleHeaders)\r\n            {\r\n                foreach (var processor in header.Processors)\r\n                {\r\n                    foreach (var mapping in processor.Item1.ExtensionMappings)\r\n                    {\r\n                        if (!mapping.Item2.Matches(contentType))\r\n                        {\r\n                            linkProcessors[mapping.Item1] = mapping.Item2;\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n\r\n            return linkProcessors;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates the link header with the different media ranges.\r\n        /// </summary>\r\n        /// <param name=\"requestUrl\">The request URL.</param>\r\n        /// <param name=\"linkProcessors\">The link processors.</param>\r\n        /// <param name=\"existingLinkHeader\">The existing Link HTTP Header.</param>\r\n        /// <returns>The link header.</returns>\r\n        protected virtual string CreateLinkHeader(Url requestUrl, IEnumerable<KeyValuePair<string, MediaRange>> linkProcessors, string existingLinkHeader)\r\n        {\r\n            var fileName = HttpUtility.UrlEncode(Path.GetFileNameWithoutExtension(requestUrl.Path));\r\n            var baseUrl = string.Concat(requestUrl.BasePath, \"/\", fileName);\r\n            var linkBuilder = new HttpLinkBuilder();\n\r\n            if (existingLinkHeader != null)\n            {\r\n                linkBuilder.Add(existingLinkHeader);\n            }\r\n\n            foreach (var linkProcessor in linkProcessors)\n            {\r\n                var uri = string.Concat(baseUrl, '.', linkProcessor.Key);\n                linkBuilder.Add(new HttpLink(uri, \"alternate\", linkProcessor.Value));\n            }\r\n\r\n            return linkBuilder.ToString();\n        }\r\n\r\n        /// <summary>\r\n        /// Adds the content type header from the <see cref=\"NegotiationContext\"/> to the <see cref=\"Response\"/>.\r\n        /// </summary>\r\n        /// <param name=\"negotiationContext\">The negotiation context.</param>\r\n        /// <param name=\"response\">The response.</param>\r\n        private static void AddContentTypeHeader(NegotiationContext negotiationContext, Response response)\r\n        {\r\n            string contentType;\r\n            if (negotiationContext.Headers.TryGetValue(\"Content-Type\", out contentType))\r\n            {\r\n                response.ContentType = contentType;\r\n                negotiationContext.Headers.Remove(\"Content-Type\");\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds the negotiated headers from the <see cref=\"NegotiationContext\"/> to the <see cref=\"Response\"/>.\r\n        /// </summary>\r\n        /// <param name=\"negotiationContext\">The negotiation context.</param>\r\n        /// <param name=\"response\">The response.</param>\r\n        private static void AddNegotiatedHeaders(NegotiationContext negotiationContext, Response response)\r\n        {\r\n            foreach (var header in negotiationContext.Headers)\r\n            {\r\n                response.Headers[header.Key] = header.Value;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Sets the status code from the <see cref=\"NegotiationContext\"/> on the <see cref=\"Response\"/>.\r\n        /// </summary>\r\n        /// <param name=\"negotiationContext\">The negotiation context.</param>\r\n        /// <param name=\"response\">The response.</param>\r\n        private static void SetStatusCode(NegotiationContext negotiationContext, Response response)\r\n        {\r\n            if (negotiationContext.StatusCode.HasValue)\r\n            {\r\n                response.StatusCode = negotiationContext.StatusCode.Value;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Sets the reason phrase from the <see cref=\"NegotiationContext\"/> on the <see cref=\"Response\"/>.\r\n        /// </summary>\r\n        /// <param name=\"negotiationContext\">The negotiation context.</param>\r\n        /// <param name=\"response\">The response.</param>\r\n        private static void SetReasonPhrase(NegotiationContext negotiationContext, Response response)\r\n        {\r\n            if (negotiationContext.ReasonPhrase != null)\r\n            {\r\n                response.ReasonPhrase = negotiationContext.ReasonPhrase;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds the cookies from the <see cref=\"NegotiationContext\"/> to the <see cref=\"Response\"/>.\r\n        /// </summary>\r\n        /// <param name=\"negotiationContext\">The negotiation context.</param>\r\n        /// <param name=\"response\">The response.</param>\r\n        private static void AddCookies(NegotiationContext negotiationContext, Response response)\r\n        {\r\n            foreach (var cookie in negotiationContext.Cookies)\r\n            {\r\n                response.Cookies.Add(cookie);\r\n            }\r\n        }\r\n\r\n        private class CompatibleHeader\r\n        {\r\n            public CompatibleHeader(\r\n                string mediaRange,\r\n                IEnumerable<Tuple<IResponseProcessor, ProcessorMatch>> processors)\r\n            {\r\n                this.MediaRange = mediaRange;\r\n                this.Processors = processors;\r\n            }\r\n\r\n            public string MediaRange { get; private set; }\r\n\r\n            public IEnumerable<Tuple<IResponseProcessor, ProcessorMatch>> Processors { get; private set; }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Responses/Negotiation/IResponseNegotiator.cs",
    "content": "﻿namespace Nancy.Responses.Negotiation\r\n{\r\n    /// <summary>\r\n    /// Creates a response from a given result and context.\r\n    /// </summary>\r\n    public interface IResponseNegotiator\r\n    {\r\n        /// <summary>\r\n        /// Negotiates the response based on the given result and context.\r\n        /// </summary>\r\n        /// <param name=\"routeResult\">The route result.</param>\r\n        /// <param name=\"context\">The context.</param>\r\n        /// <returns>A <see cref=\"Response\"/>.</returns>\r\n        Response NegotiateResponse(dynamic routeResult, NancyContext context);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Responses/Negotiation/IResponseProcessor.cs",
    "content": "﻿namespace Nancy.Responses.Negotiation\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Content negotiation response processor\r\n    /// </summary>\r\n    public interface IResponseProcessor\r\n    {\r\n        /// <summary>\r\n        /// Gets a set of mappings that map a given extension (such as .json)\r\n        /// to a media range that can be sent to the client in a vary header.\r\n        /// </summary>\r\n        IEnumerable<Tuple<string, MediaRange>> ExtensionMappings { get; }\r\n\r\n        /// <summary>\r\n        /// Determines whether the processor can handle a given content type and model.\r\n        /// </summary>\r\n        /// <param name=\"requestedMediaRange\">Content type requested by the client.</param>\r\n        /// <param name=\"model\">The model for the given media range.</param>\r\n        /// <param name=\"context\">The nancy context.</param>\r\n        /// <returns>A <see cref=\"ProcessorMatch\"/> result that determines the priority of the processor.</returns>\r\n        ProcessorMatch CanProcess(MediaRange requestedMediaRange, dynamic model, NancyContext context);\r\n\r\n        /// <summary>\r\n        /// Process the response.\r\n        /// </summary>\r\n        /// <param name=\"requestedMediaRange\">Content type requested by the client.</param>\r\n        /// <param name=\"model\">The model for the given media range.</param>\r\n        /// <param name=\"context\">The nancy context.</param>\r\n        /// <returns>A <see cref=\"Response\"/> instance.</returns>\r\n        Response Process(MediaRange requestedMediaRange, dynamic model, NancyContext context);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Responses/Negotiation/JsonProcessor.cs",
    "content": "﻿namespace Nancy.Responses.Negotiation\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using Nancy.Configuration;\r\n\r\n    /// <summary>\r\n    /// Processes the model for json media types and extension.\r\n    /// </summary>\r\n    public class JsonProcessor : IResponseProcessor\r\n    {\r\n        private readonly ISerializer serializer;\r\n        private readonly INancyEnvironment environment;\r\n\r\n        private static readonly IEnumerable<Tuple<string, MediaRange>> extensionMappings =\r\n            new[] { new Tuple<string, MediaRange>(\"json\", new MediaRange(\"application/json\")) };\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"JsonProcessor\"/> class,\r\n        /// with the provided <paramref name=\"serializers\"/>.\r\n        /// </summary>\r\n        /// <param name=\"serializers\">The serializes that the processor will use to process the request.</param>\r\n        /// <param name=\"environment\">An <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        public JsonProcessor(IEnumerable<ISerializer> serializers, INancyEnvironment environment)\r\n        {\r\n            this.serializer = serializers.FirstOrDefault(x => x.CanSerialize(\"application/json\"));\r\n            this.environment = environment;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a set of mappings that map a given extension (such as .json)\r\n        /// to a media range that can be sent to the client in a vary header.\r\n        /// </summary>\r\n        public IEnumerable<Tuple<string, MediaRange>> ExtensionMappings\r\n        {\r\n            get { return extensionMappings; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determines whether the processor can handle a given content type and model\r\n        /// </summary>\r\n        /// <param name=\"requestedMediaRange\">Content type requested by the client</param>\r\n        /// <param name=\"model\">The model for the given media range</param>\r\n        /// <param name=\"context\">The nancy context</param>\r\n        /// <returns>A ProcessorMatch result that determines the priority of the processor</returns>\r\n        public ProcessorMatch CanProcess(MediaRange requestedMediaRange, dynamic model, NancyContext context)\r\n        {\r\n            if (IsExactJsonContentType(requestedMediaRange))\r\n            {\r\n                return new ProcessorMatch\r\n                {\r\n                    ModelResult = MatchResult.DontCare,\r\n                    RequestedContentTypeResult = MatchResult.ExactMatch\r\n                };\r\n            }\r\n\r\n            if (IsWildcardJsonContentType(requestedMediaRange))\r\n            {\r\n                return new ProcessorMatch\r\n                {\r\n                    ModelResult = MatchResult.DontCare,\r\n                    RequestedContentTypeResult = MatchResult.NonExactMatch\r\n                };\r\n            }\r\n\r\n            return new ProcessorMatch\r\n            {\r\n                ModelResult = MatchResult.DontCare,\r\n                RequestedContentTypeResult = MatchResult.NoMatch\r\n            };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Process the response\r\n        /// </summary>\r\n        /// <param name=\"requestedMediaRange\">Content type requested by the client</param>\r\n        /// <param name=\"model\">The model for the given media range</param>\r\n        /// <param name=\"context\">The nancy context</param>\r\n        /// <returns>A response</returns>\r\n        public Response Process(MediaRange requestedMediaRange, dynamic model, NancyContext context)\r\n        {\r\n            return new JsonResponse(model, this.serializer, this.environment);\r\n        }\r\n\r\n        private static bool IsExactJsonContentType(MediaRange requestedContentType)\r\n        {\r\n            if (requestedContentType.Type.IsWildcard && requestedContentType.Subtype.IsWildcard)\r\n            {\r\n                return true;\r\n            }\r\n\r\n            return requestedContentType.Matches(\"application/json\") || requestedContentType.Matches(\"text/json\");\r\n        }\r\n\r\n        private static bool IsWildcardJsonContentType(MediaRange requestedContentType)\r\n        {\r\n            if (!requestedContentType.Type.IsWildcard && !string.Equals(\"application\", requestedContentType.Type, StringComparison.OrdinalIgnoreCase))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            if (requestedContentType.Subtype.IsWildcard)\r\n            {\r\n                return true;\r\n            }\r\n\r\n            var subtypeString = requestedContentType.Subtype.ToString();\r\n\r\n            return subtypeString.EndsWith(\"+json\", StringComparison.OrdinalIgnoreCase);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Responses/Negotiation/MatchResult.cs",
    "content": "namespace Nancy.Responses.Negotiation\r\n{\r\n    /// <summary>\r\n    /// Represents whether a processor has matched/can handle processing the response.\r\n    /// Values are of increasing priority.\r\n    /// </summary>\r\n    public enum MatchResult\r\n    {\r\n        /// <summary>\r\n        /// No match, nothing to see here, move along\r\n        /// </summary>\r\n        NoMatch,\r\n\r\n        /// <summary>\r\n        /// Will accept anything\r\n        /// </summary>\r\n        DontCare,\r\n\r\n        /// <summary>\r\n        /// Matched, but in a non-specific way such as a wildcard match or fallback\r\n        /// </summary>\r\n        NonExactMatch,\r\n\r\n        /// <summary>\r\n        /// Exact specific match\r\n        /// </summary>\r\n        ExactMatch\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Responses/Negotiation/MediaRange.cs",
    "content": "namespace Nancy.Responses.Negotiation\r\n{\r\n    using System;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Represents a media range from an accept header\r\n    /// </summary>\r\n    public class MediaRange : IEquatable<MediaRange>\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"MediaRange\"/> class, with\r\n        /// the provided <paramref name=\"contentType\"/>.\r\n        /// </summary>\r\n        /// <param name=\"contentType\">string representation of a media range</param>\r\n        public MediaRange(string contentType)\r\n        {\r\n            this.ParseContentType(contentType);\r\n        }\r\n\r\n        private void ParseContentType(string contentType)\r\n        {\r\n            if (string.IsNullOrEmpty(contentType))\r\n            {\r\n                this.Type = string.Empty;\r\n                this.Subtype = string.Empty;\r\n                this.Parameters = new MediaRangeParameters();\r\n                return;\r\n            }\r\n\r\n            if (contentType.Equals(\"*\"))\r\n            {\r\n                contentType = \"*/*\";\r\n            }\r\n\r\n            var parts = contentType.Split('/', ';');\r\n\r\n            if (parts.Length < 2)\r\n            {\r\n                {\r\n                    throw new ArgumentException(\"inputString not in correct Type/SubType format\", contentType);\r\n                }\r\n            }\r\n\r\n            this.Type = parts[0];\r\n            this.Subtype = parts[1].TrimEnd();\r\n\r\n            if (parts.Length <= 2)\r\n            {\r\n                this.Parameters = new MediaRangeParameters();\r\n                return;\r\n            }\r\n\r\n            var separator = contentType.IndexOf(';');\r\n            this.Parameters = MediaRangeParameters.FromString(contentType.Substring(separator));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Media range type\r\n        /// </summary>\r\n        public MediaType Type { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Media range subtype\r\n        /// </summary>\r\n        public MediaType Subtype { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Media range parameters\r\n        /// </summary>\r\n        public MediaRangeParameters Parameters { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating if the media range is the */* wildcard\r\n        /// </summary>\r\n        public bool IsWildcard\r\n        {\r\n            get\r\n            {\r\n                return this.Type.IsWildcard && this.Subtype.IsWildcard;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Whether or not a media range matches another, taking into account wildcards\r\n        /// </summary>\r\n        /// <param name=\"other\">Other media range</param>\r\n        /// <returns>True if matching, false if not</returns>\r\n        public bool Matches(MediaRange other)\r\n        {\r\n            return this.Type.Matches(other.Type) && this.Subtype.Matches(other.Subtype);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Whether or not a media range matches another, taking into account wildcards and parameters\r\n        /// </summary>\r\n        /// <param name=\"other\">Other media range</param>\r\n        /// <returns>True if matching, false if not</returns>\r\n        public bool MatchesWithParameters(MediaRange other)\r\n        {\r\n            return this.Matches(other) && this.Parameters.Matches(other.Parameters);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"System.String\"/> to <see cref=\"MediaRange\"/>.\r\n        /// </summary>\r\n        /// <param name=\"contentType\">Type of the content.</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator MediaRange(string contentType)\r\n        {\r\n            return new MediaRange(contentType);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"MediaRange\"/> to <see cref=\"System.String\"/>.\r\n        /// </summary>\r\n        /// <param name=\"mediaRange\">The media range.</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator string(MediaRange mediaRange)\r\n        {\r\n            if (null == mediaRange)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            if (mediaRange.Parameters.Any())\r\n            {\r\n                return string.Concat(mediaRange.Type, \"/\", mediaRange.Subtype, \";\", mediaRange.Parameters);\r\n            }\r\n\r\n            return string.Concat(mediaRange.Type, \"/\",  mediaRange.Subtype);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Indicates whether the current object is equal to another object of the same type.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// true if the current object is equal to the <paramref name=\"other\"/> parameter; otherwise, false.\r\n        /// </returns>\r\n        /// <param name=\"other\">An object to compare with this object.</param>\r\n        public bool Equals(MediaRange other)\r\n        {\r\n            return this.Matches(other);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns a <see cref=\"System.String\" /> that represents this instance.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// A <see cref=\"System.String\" /> that represents this instance.\r\n        /// </returns>\r\n        public override string ToString()\r\n        {\r\n            return this;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Responses/Negotiation/MediaRangeParameters.cs",
    "content": "﻿namespace Nancy.Responses.Negotiation\r\n{\r\n    using System;\r\n    using System.Collections;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Provides strongly-typed access to media range parameters.\r\n    /// </summary>\r\n    public class MediaRangeParameters : IEnumerable<KeyValuePair<string, string>>\r\n    {\r\n        private readonly IDictionary<string, string> parameters;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"MediaRangeParameters\"/> class.\r\n        /// </summary>\r\n        public MediaRangeParameters()\r\n        {\r\n            this.parameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"MediaRangeParameters\"/> class, with\r\n        /// the provided <paramref name=\"parameters\"/>.\r\n        /// </summary>\r\n        /// <param name=\"parameters\">The parameters.</param>\r\n        public MediaRangeParameters(IDictionary<string, string> parameters)\r\n        {\r\n            this.parameters = new Dictionary<string, string>(parameters, StringComparer.OrdinalIgnoreCase);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the names of the available parameters.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> containing the names of the parameters.</value>\r\n        public IEnumerable<string> Keys\r\n        {\r\n            get { return this.parameters.Keys; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all the parameters values.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> that contains all the parameters values.</value>\r\n        public IEnumerable<string> Values\r\n        {\r\n            get { return this.parameters.Values; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an enumerator that iterates through the collection.\r\n        /// </summary>\r\n        /// <returns>A <see cref=\"IEnumerator{T}\"/> that can be used to iterate through the collection.</returns>\r\n        public IEnumerator<KeyValuePair<string, string>> GetEnumerator()\r\n        {\r\n            return this.parameters.GetEnumerator();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Whether or not a set of media range parameters matches another, regardless of order\r\n        /// </summary>\r\n        /// <param name=\"other\">Other media range parameters</param>\r\n        /// <returns>True if matching, false if not</returns>\r\n        public bool Matches(MediaRangeParameters other)\r\n        {\r\n            return this.parameters.OrderBy(p => p.Key).SequenceEqual(other.parameters.OrderBy(p => p.Key));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an enumerator that iterates through a collection.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerator\"/> object that can be used to iterate through the collection.</returns>\r\n        IEnumerator IEnumerable.GetEnumerator()\r\n        {\r\n            return this.GetEnumerator();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the value for the parameter identified by the <paramref name=\"name\"/> parameter.\r\n        /// </summary>\r\n        /// <param name=\"name\">The name of the parameter to return the value for.</param>\r\n        /// <returns>The value for the parameter. If the parameter is not defined then null is returned.</returns>\r\n        public string this[string name]\r\n        {\r\n            get\r\n            {\r\n                string value;\r\n                return this.parameters.TryGetValue(name, out value) ? value : null;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"MediaRangeParameters\"/> to <see cref=\"System.String\"/>.\r\n        /// </summary>\r\n        /// <param name=\"mediaRangeParameters\">The media range parameters.</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator string(MediaRangeParameters mediaRangeParameters)\r\n        {\r\n            return string.Join(\";\", mediaRangeParameters.parameters.Select(p => p.Key + \"=\" + p.Value));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a MediaRangeParameters collection from a \"a=1,b=2\" string\r\n        /// </summary>\r\n        /// <param name=\"parameters\"></param>\r\n        /// <returns></returns>\r\n        public static MediaRangeParameters FromString(string parameters)\r\n        {\r\n            var dictionary = parameters.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)\r\n               .Select(part => part.Split('='))\r\n               .ToDictionary(split => split[0].Trim(), split => split[1].Trim());\r\n\r\n            return new MediaRangeParameters(dictionary);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns a <see cref=\"System.String\" /> that represents this instance.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// A <see cref=\"System.String\" /> that represents this instance.\r\n        /// </returns>\r\n        public override string ToString()\r\n        {\r\n            return this;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Responses/Negotiation/MediaType.cs",
    "content": "namespace Nancy.Responses.Negotiation\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Represents a media type or subtype in a <see cref=\"MediaRange\"/>.\r\n    /// </summary>\r\n    public class MediaType\r\n    {\r\n        private readonly string type;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"MediaType\"/> class, with\r\n        /// the provided <paramref name=\"type\"/>.\r\n        /// </summary>\r\n        /// <param name=\"type\">the media type part</param>\r\n        public MediaType(string type)\r\n        {\r\n            this.type = type;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether the media type is a wildcard or not\r\n        /// </summary>\r\n        /// <value><see langword=\"true\" /> if the media type is a wildcard, otherwise <see langword=\"false\" />.</value>\r\n        public bool IsWildcard\r\n        {\r\n            get\r\n            {\r\n                return this.type != null && string.Equals(this.type, \"*\", StringComparison.Ordinal);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Matched the media type with another media type.\r\n        /// </summary>\r\n        /// <param name=\"other\">The media type that should be matched against.</param>\r\n        /// <returns><see langword=\"true\" /> if the media types match, otherwise <see langword=\"false\" />.</returns>\r\n        public bool Matches(MediaType other)\r\n        {\r\n            return this.IsWildcard ||\r\n                   other.IsWildcard ||\r\n                   this.type.Equals(other.type, StringComparison.OrdinalIgnoreCase);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"System.String\"/> to <see cref=\"MediaType\"/>.\r\n        /// </summary>\r\n        /// <param name=\"inputString\">The input string.</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator MediaType(string inputString)\r\n        {\r\n            return new MediaType(inputString);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs an implicit conversion from <see cref=\"MediaType\"/> to <see cref=\"System.String\"/>.\r\n        /// </summary>\r\n        /// <param name=\"inputMediaType\">Type of the input media.</param>\r\n        /// <returns>\r\n        /// The result of the conversion.\r\n        /// </returns>\r\n        public static implicit operator string(MediaType inputMediaType)\r\n        {\r\n            return inputMediaType.type;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns the type as a <see cref=\"System.String\" /> that represents this instance.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// A <see cref=\"System.String\" /> that represents this instance.\r\n        /// </returns>\r\n        public override string ToString()\r\n        {\r\n            return this.type;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Responses/Negotiation/NegotiationContext.cs",
    "content": "﻿namespace Nancy.Responses.Negotiation\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    using Nancy.Cookies;\r\n\r\n    using Nancy.Extensions;\r\n\r\n    /// <summary>\r\n    /// Context for content negotiation.\r\n    /// </summary>\r\n    public class NegotiationContext\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NegotiationContext\"/> class.\r\n        /// </summary>\r\n        public NegotiationContext()\r\n        {\r\n            this.Cookies = new List<INancyCookie>();\r\n            this.PermissableMediaRanges = new List<MediaRange>(new[] { (MediaRange)\"*/*\" });\r\n            this.MediaRangeModelMappings = new Dictionary<MediaRange, Func<dynamic>>();\r\n            this.Headers = new Dictionary<string, string>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets additional cookies to assign to the response.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IList{T}\"/> of <see cref=\"INancyCookie\"/> instances.</value>\r\n        public IList<INancyCookie> Cookies { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the default model that will be used if a content type specific model is not specified.\r\n        /// </summary>\r\n        /// <value>The default model instance.</value>\r\n        public dynamic DefaultModel { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the additional response headers required.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IDictionary{TKey,TValue}\"/> containing the headers.</value>\r\n        public IDictionary<string, string> Headers { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the model mappings for media ranges.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IDictionary{TKey,TValue}\"/> containing the media range model mappings.</value>\r\n        public IDictionary<MediaRange, Func<dynamic>> MediaRangeModelMappings { get; set; }\r\n\r\n        /// <summary>\r\n        /// The name of the <see cref=\"INancyModule\"/> that is locating a view.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the name of the module.</value>\r\n        public string ModuleName { get; set; }\r\n\r\n        /// <summary>\r\n        /// The module path of the <see cref=\"INancyModule\"/> that is locating a view.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the module path.</value>\r\n        public string ModulePath { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets allowed media ranges.\r\n        /// </summary>\r\n        /// <value>A list of the allowed media ranges.</value>\r\n        public IList<MediaRange> PermissableMediaRanges { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the status code of the response.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"HttpStatusCode\"/> value.</value>\r\n        public HttpStatusCode? StatusCode { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets a text description of the HTTP status code returned to the client.\r\n        /// </summary>\r\n        /// <value>The HTTP status code description.</value>\r\n        public string ReasonPhrase { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the view name if one is required.\r\n        /// </summary>\r\n        /// <value>The name of the view that should be rendered.</value>\r\n        public string ViewName { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets the correct model for the given media range\r\n        /// </summary>\r\n        /// <param name=\"mediaRange\">The <see cref=\"MediaRange\"/> to get the model for.</param>\r\n        /// <returns>The model for the provided <paramref name=\"mediaRange\"/> if it has been mapped, otherwise the <see cref=\"DefaultModel\"/> will be returned.</returns>\r\n        public dynamic GetModelForMediaRange(MediaRange mediaRange)\r\n        {\r\n            var matching = this.MediaRangeModelMappings.Any(m => mediaRange.Matches(m.Key));\r\n\r\n            return matching ?\r\n                this.MediaRangeModelMappings.First(m => mediaRange.Matches(m.Key)).Value.Invoke() :\r\n                this.DefaultModel;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Sets the given Nancy module.\r\n        /// </summary>\r\n        /// <param name=\"module\">The Nancy module instance.</param>\r\n        /// <exception cref=\"System.ArgumentNullException\">module</exception>\r\n        public void SetModule(INancyModule module)\r\n        {\r\n            if (module == null)\r\n            {\r\n                throw new ArgumentNullException(\"module\");\r\n            }\r\n\r\n            this.ModuleName = module.GetModuleName();\r\n            this.ModulePath = module.ModulePath;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Responses/Negotiation/Negotiator.cs",
    "content": "namespace Nancy.Responses.Negotiation\r\n{\r\n    using System;\r\n    using System.Runtime.CompilerServices;\r\n    using System.Threading.Tasks;\r\n\r\n    /// <summary>\r\n    /// Request response content negotiator.\r\n    /// </summary>\r\n    /// <seealso cref=\"Nancy.IHideObjectMembers\" />\r\n    public class Negotiator : IHideObjectMembers\r\n    {\r\n        // TODO - this perhaps should be an interface, along with the view thing above\r\n        // that would then wrap this to give more granular extension point for things like\r\n        // AsNegotiated\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"Negotiator\"/> class,\r\n        /// with the provided <paramref name=\"context\"/>.\r\n        /// </summary>\r\n        /// <param name=\"context\">The context that should be negotiated.</param>\r\n        public Negotiator(NancyContext context)\r\n        {\r\n            if (context == null)\r\n            {\r\n                throw new ArgumentNullException(\"context\");\r\n            }\r\n\r\n            this.NegotiationContext = context.NegotiationContext;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the awaiter.\r\n        /// </summary>\r\n        /// <returns><see cref=\"TaskAwaiter{Negotiator}\"/></returns>\r\n        public TaskAwaiter<Negotiator> GetAwaiter()\r\n        {\r\n            return Task.FromResult(this).GetAwaiter();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"NegotiationContext\"/> used by the negotiator.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"NegotiationContext\"/> instance.</value>\r\n        public NegotiationContext NegotiationContext { get; private set; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Responses/Negotiation/ProcessorMatch.cs",
    "content": "namespace Nancy.Responses.Negotiation\r\n{\r\n    /// <summary>\r\n    /// Represents whether a processor has matched / can handle a requested response\r\n    /// </summary>\r\n    public class ProcessorMatch\r\n    {\r\n        /// <summary>\r\n        /// A <see cref=\"ProcessorMatch\"/> with both <see cref=\"ModelResult\"/> and <see cref=\"RequestedContentTypeResult\"/> set to <see cref=\"MatchResult.NoMatch\"/>.\r\n        /// </summary>\r\n        public static ProcessorMatch None = new ProcessorMatch\r\n        {\r\n            ModelResult = MatchResult.NoMatch,\r\n            RequestedContentTypeResult = MatchResult.NoMatch\r\n        };\r\n\r\n        /// <summary>\r\n        /// Gets or sets the match result based on the content type\r\n        /// </summary>\r\n        public MatchResult RequestedContentTypeResult { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the match result based on the model\r\n        /// </summary>\r\n        public MatchResult ModelResult { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Responses/Negotiation/ResponseProcessor.cs",
    "content": "﻿namespace Nancy.Responses.Negotiation\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Processes negotiated responses of model type <see cref=\"Response\"/>.\r\n    /// </summary>\r\n    public class ResponseProcessor : IResponseProcessor\r\n    {\r\n        /// <summary>\r\n        /// Gets a set of mappings that map a given extension (such as .json)\r\n        /// to a media range that can be sent to the client in a vary header.\r\n        /// </summary>\r\n        public IEnumerable<Tuple<string, MediaRange>> ExtensionMappings\r\n        {\r\n            get\r\n            {\r\n                return Enumerable.Empty<Tuple<string, MediaRange>>();\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determines whether the processor can handle a given content type and model.\r\n        /// </summary>\r\n        /// <param name=\"requestedMediaRange\">Content type requested by the client.</param>\r\n        /// <param name=\"model\">The model for the given media range.</param>\r\n        /// <param name=\"context\">The nancy context.</param>\r\n        /// <returns>A <see cref=\"ProcessorMatch\"/> result that determines the priority of the processor.</returns>\r\n        public ProcessorMatch CanProcess(MediaRange requestedMediaRange, dynamic model, NancyContext context)\r\n        {\r\n            return new ProcessorMatch\r\n            {\r\n                ModelResult = (model is Response) ? MatchResult.ExactMatch : MatchResult.NoMatch,\r\n                RequestedContentTypeResult = MatchResult.DontCare\r\n            };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Process the response.\r\n        /// </summary>\r\n        /// <param name=\"requestedMediaRange\">Content type requested by the client.</param>\r\n        /// <param name=\"model\">The model for the given media range.</param>\r\n        /// <param name=\"context\">The nancy context.</param>\r\n        /// <returns>A <see cref=\"Response\"/> instance.</returns>\r\n        public Response Process(MediaRange requestedMediaRange, dynamic model, NancyContext context)\r\n        {\r\n            return (Response)model;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Responses/Negotiation/ViewProcessor.cs",
    "content": "﻿namespace Nancy.Responses.Negotiation\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using Nancy.Configuration;\r\n    using Nancy.ViewEngines;\r\n\r\n    /// <summary>\r\n    /// Processes the model for view requests.\r\n    /// </summary>\r\n    public class ViewProcessor : IResponseProcessor\r\n    {\r\n        private readonly IViewFactory viewFactory;\r\n        private readonly TraceConfiguration traceConfiguration;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ViewProcessor\"/> class,\r\n        /// with the provided <paramref name=\"viewFactory\"/>.\r\n        /// </summary>\r\n        /// <param name=\"viewFactory\">The view factory that should be used to render views.</param>\r\n        /// <param name=\"environment\">An <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        public ViewProcessor(IViewFactory viewFactory, INancyEnvironment environment)\r\n        {\r\n            this.viewFactory = viewFactory;\r\n            this.traceConfiguration = environment.GetValue<TraceConfiguration>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a set of mappings that map a given extension (such as .json)\r\n        /// to a media range that can be sent to the client in a vary header.\r\n        /// </summary>\r\n        public IEnumerable<Tuple<string, MediaRange>> ExtensionMappings\r\n        {\r\n            get { yield break; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determines whether the processor can handle a given content type and model.\r\n        /// </summary>\r\n        /// <param name=\"requestedMediaRange\">Content type requested by the client.</param>\r\n        /// <param name=\"model\">The model for the given media range.</param>\r\n        /// <param name=\"context\">The nancy context.</param>\r\n        /// <returns>A <see cref=\"ProcessorMatch\"/> result that determines the priority of the processor.</returns>\r\n        public ProcessorMatch CanProcess(MediaRange requestedMediaRange, dynamic model, NancyContext context)\r\n        {\r\n            var matchingContentType =\r\n                requestedMediaRange.Matches(\"text/html\");\r\n\r\n            return matchingContentType\r\n                ? new ProcessorMatch { ModelResult = MatchResult.DontCare, RequestedContentTypeResult = MatchResult.ExactMatch }\r\n                : new ProcessorMatch();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Process the response.\r\n        /// </summary>\r\n        /// <param name=\"requestedMediaRange\">Content type requested by the client.</param>\r\n        /// <param name=\"model\">The model for the given media range.</param>\r\n        /// <param name=\"context\">The nancy context.</param>\r\n        /// <returns>A <see cref=\"Response\"/> instance.</returns>\r\n        public Response Process(MediaRange requestedMediaRange, dynamic model, NancyContext context)\r\n        {\r\n            var viewResponse = this.viewFactory.RenderView(context.NegotiationContext.ViewName, model, GetViewLocationContext(context));\r\n\r\n            return this.traceConfiguration.DisplayErrorTraces\r\n                ? new MaterialisingResponse(viewResponse)\r\n                : viewResponse;\r\n        }\r\n\r\n        private static ViewLocationContext GetViewLocationContext(NancyContext context)\r\n        {\r\n            return new ViewLocationContext\r\n            {\r\n                Context = context,\r\n                ModuleName = context.NegotiationContext.ModuleName,\r\n                ModulePath = context.NegotiationContext.ModulePath\r\n            };\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Responses/Negotiation/XmlProcessor.cs",
    "content": "﻿namespace Nancy.Responses.Negotiation\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Processes the model for xml media types and extension.\r\n    /// </summary>\r\n    public class XmlProcessor : IResponseProcessor\r\n    {\r\n        private readonly ISerializer serializer;\r\n\r\n        private static readonly IEnumerable<Tuple<string, MediaRange>> extensionMappings =\r\n            new[] { new Tuple<string, MediaRange>(\"xml\", new MediaRange(\"application/xml\")) };\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"XmlProcessor\"/> class,\r\n        /// with the provided <see paramref=\"serializers\"/>.\r\n        /// </summary>\r\n        /// <param name=\"serializers\">The serializes that the processor will use to process the request.</param>\r\n        public XmlProcessor(IEnumerable<ISerializer> serializers)\r\n        {\r\n            this.serializer = serializers.FirstOrDefault(x => x.CanSerialize(\"application/xml\"));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a set of mappings that map a given extension (such as .json)\r\n        /// to a media range that can be sent to the client in a vary header.\r\n        /// </summary>\r\n        public IEnumerable<Tuple<string, MediaRange>> ExtensionMappings\r\n        {\r\n            get { return extensionMappings; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determines whether the processor can handle a given content type and model.\r\n        /// </summary>\r\n        /// <param name=\"requestedMediaRange\">Content type requested by the client.</param>\r\n        /// <param name=\"model\">The model for the given media range.</param>\r\n        /// <param name=\"context\">The nancy context.</param>\r\n        /// <returns>A <see cref=\"ProcessorMatch\"/> result that determines the priority of the processor.</returns>\r\n        public ProcessorMatch CanProcess(MediaRange requestedMediaRange, dynamic model, NancyContext context)\r\n        {\r\n            if (IsExactXmlContentType(requestedMediaRange))\r\n            {\r\n                return new ProcessorMatch\r\n                {\r\n                    ModelResult = MatchResult.DontCare,\r\n                    RequestedContentTypeResult = MatchResult.ExactMatch\r\n                };\r\n            }\r\n\r\n            if (IsWildcardXmlContentType(requestedMediaRange))\r\n            {\r\n                return new ProcessorMatch\r\n                {\r\n                    ModelResult = MatchResult.DontCare,\r\n                    RequestedContentTypeResult = MatchResult.NonExactMatch\r\n                };\r\n            }\r\n\r\n            return new ProcessorMatch\r\n            {\r\n                ModelResult = MatchResult.DontCare,\r\n                RequestedContentTypeResult = MatchResult.NoMatch\r\n            };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Process the response.\r\n        /// </summary>\r\n        /// <param name=\"requestedMediaRange\">Content type requested by the client.</param>\r\n        /// <param name=\"model\">The model for the given media range.</param>\r\n        /// <param name=\"context\">The nancy context.</param>\r\n        /// <returns>A <see cref=\"Response\"/> instance.</returns>\r\n        public Response Process(MediaRange requestedMediaRange, dynamic model, NancyContext context)\r\n        {\r\n            return CreateResponse(model, serializer);\r\n        }\r\n\r\n        private static Response CreateResponse(dynamic model, ISerializer serializer)\r\n        {\r\n            return new Response\r\n            {\r\n                Contents = stream =>\r\n                {\r\n                    if (model != null)\r\n                    {\r\n                        serializer.Serialize(\"application/xml\", model, stream);\r\n                    }\r\n                },\r\n                ContentType = \"application/xml\",\r\n                StatusCode = HttpStatusCode.OK\r\n            };\r\n        }\r\n\r\n        private static bool IsExactXmlContentType(MediaRange requestedContentType)\r\n        {\r\n            if (requestedContentType.Type.IsWildcard && requestedContentType.Subtype.IsWildcard)\r\n            {\r\n                return true;\r\n            }\r\n\r\n            return requestedContentType.Matches(\"application/xml\") || requestedContentType.Matches(\"text/xml\");\r\n        }\r\n\r\n        private static bool IsWildcardXmlContentType(MediaRange requestedContentType)\r\n        {\r\n            if (!requestedContentType.Type.IsWildcard && !string.Equals(\"application\", requestedContentType.Type, StringComparison.OrdinalIgnoreCase))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            if (requestedContentType.Subtype.IsWildcard)\r\n            {\r\n                return true;\r\n            }\r\n\r\n            var subtypeString = requestedContentType.Subtype.ToString();\r\n\r\n            return subtypeString.EndsWith(\"+xml\", StringComparison.OrdinalIgnoreCase);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Responses/NotAcceptableResponse.cs",
    "content": "namespace Nancy.Responses\r\n{\r\n    /// <summary>\r\n    /// Response with status code 406 (Not Acceptable).\r\n    /// </summary>\r\n    public class NotAcceptableResponse : Response\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NotAcceptableResponse\"/> class.\r\n        /// </summary>\r\n        public NotAcceptableResponse()\r\n        {\r\n            this.StatusCode = HttpStatusCode.NotAcceptable;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Responses/RedirectResponse.cs",
    "content": "namespace Nancy.Responses\r\n{\r\n    /// <summary>\r\n    /// A response representing an HTTP redirect\r\n    /// <seealso cref=\"Nancy.Extensions.ContextExtensions.ToFullPath\"/>\r\n    /// <seealso cref=\"Nancy.Extensions.ContextExtensions.GetRedirect\"/>\r\n    /// </summary>\r\n    public class RedirectResponse : Response\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"RedirectResponse\"/> class, with\r\n        /// the provided <paramref name=\"location\"/> and <paramref name=\"type\"/>.\r\n        /// </summary>\r\n        /// <param name=\"location\">Location to redirect to</param>\r\n        /// <param name=\"type\">Type of redirection to perform</param>\r\n        public RedirectResponse(string location, RedirectType type = RedirectType.SeeOther)\r\n        {\r\n            this.Headers.Add(\"Location\", location);\r\n            this.Contents = GetStringContents(string.Empty);\r\n            this.ContentType = \"text/html\";\r\n            switch (type)\r\n            {\r\n                case RedirectType.Permanent:\r\n                    this.StatusCode = HttpStatusCode.MovedPermanently;\r\n                    break;\r\n                case RedirectType.Temporary:\r\n                    this.StatusCode = HttpStatusCode.TemporaryRedirect;\r\n                    break;\r\n                default:\r\n                    this.StatusCode = HttpStatusCode.SeeOther;\r\n                    break;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Which type of redirect\r\n        /// </summary>\r\n        public enum RedirectType\r\n        {\r\n            /// <summary>\r\n            /// HTTP 301 - All future requests should be to this URL\r\n            /// </summary>\r\n            Permanent,\r\n            /// <summary>\r\n            /// HTTP 307 - Redirect this request but allow future requests to the original URL\r\n            /// </summary>\r\n            Temporary,\r\n            /// <summary>\r\n            /// HTTP 303 - Redirect this request using an HTTP GET\r\n            /// </summary>\r\n            SeeOther\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Responses/StreamResponse.cs",
    "content": "﻿namespace Nancy.Responses\r\n{\r\n    using System;\r\n    using System.IO;\r\n\r\n    /// <summary>\r\n    /// Response that returns the contents of a stream of a given content-type.\r\n    /// </summary>\r\n    public class StreamResponse : Response\r\n    {\r\n        private Stream source;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"StreamResponse\"/>, with\r\n        /// the provided <paramref name=\"source\"/> and <paramref name=\"contentType\"/>.\r\n        /// </summary>\r\n        /// <param name=\"source\">The value producer for the response.</param>\r\n        /// <param name=\"contentType\">The content-type of the stream contents.</param>\r\n        public StreamResponse(Func<Stream> source, string contentType)\r\n        {\r\n            this.Contents = GetResponseBodyDelegate(source);\r\n            this.ContentType = contentType;\r\n            this.StatusCode = HttpStatusCode.OK;\r\n        }\r\n\r\n        private Action<Stream> GetResponseBodyDelegate(Func<Stream> sourceDelegate)\r\n        {\r\n            return stream =>\r\n            {\r\n                using (this.source = sourceDelegate.Invoke())\r\n                {\r\n                    this.source.CopyTo(stream);\r\n                }\r\n            };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.\r\n        /// </summary>\r\n        public override void Dispose()\r\n        {\r\n            if (this.source != null)\r\n            {\r\n                this.source.Dispose();\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Responses/TextResponse.cs",
    "content": "﻿namespace Nancy.Responses\r\n{\r\n    using System.Collections.Generic;\r\n    using System.Text;\r\n\r\n    using Nancy.Cookies;\r\n\r\n    /// <summary>\r\n    /// Represents a text (text/plain) response\r\n    /// </summary>\r\n    public class TextResponse : Response\r\n    {\r\n        private const string TextPlainContentType = \"text/plain\";\r\n\r\n        /// <summary>\r\n        /// Creates a new instance of the TextResponse class, with\r\n        /// the provided <paramref name=\"contents\"/>, <paramref name=\"contentType\"/> and <paramref name=\"encoding\"/>.\r\n        /// </summary>\r\n        /// <param name=\"contents\">Text content - defaults to empty if null</param>\r\n        /// <param name=\"contentType\">Content Type - defaults to text/plain</param>\r\n        /// <param name=\"encoding\">String encoding - UTF8 if null</param>\r\n        public TextResponse(string contents, string contentType = null, Encoding encoding = null)\r\n        {\r\n            if (encoding == null)\r\n            {\r\n                encoding = Encoding.UTF8;\r\n            }\r\n\r\n            if (string.IsNullOrEmpty(contentType))\r\n            {\r\n                contentType = TextPlainContentType;\r\n            }\r\n\r\n            this.ContentType = GetContentType(contentType, encoding);\r\n            this.StatusCode = HttpStatusCode.OK;\r\n\r\n            if (contents != null)\r\n            {\r\n                this.Contents = stream =>\r\n                {\r\n                    var data = encoding.GetBytes(contents);\r\n                    stream.Write(data, 0, data.Length);\r\n                };\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a new instance of the TextResponse class, with\r\n        /// the provided <paramref name=\"statusCode\"/>, <paramref name=\"contents\"/>, <paramref name=\"encoding\"/>, \r\n        /// <paramref name=\"headers\"/> and <paramref name=\"cookies\"/>.\r\n        /// </summary>\r\n        /// <param name=\"statusCode\">Status code - defaults to OK</param>\r\n        /// <param name=\"contents\">Text content - defaults to empty if null</param>\r\n        /// <param name=\"encoding\">String encoding - UTF8 if null</param>\r\n        /// <param name=\"headers\">Headers if required</param>\r\n        /// <param name=\"cookies\">Cookies if required</param>\r\n        public TextResponse(HttpStatusCode statusCode = HttpStatusCode.OK, string contents = null, Encoding encoding = null, IDictionary<string, string> headers = null, IEnumerable<INancyCookie> cookies = null)\r\n        {\r\n            if (encoding == null)\r\n            {\r\n                encoding = Encoding.UTF8;\r\n            }\r\n\r\n            this.ContentType = GetContentType(TextPlainContentType, encoding);\r\n            this.StatusCode = statusCode;\r\n\r\n            if (contents != null)\r\n            {\r\n                this.Contents = stream =>\r\n                {\r\n                    var data = encoding.GetBytes(contents);\r\n                    stream.Write(data, 0, data.Length);\r\n                };\r\n            }\r\n\r\n            if (headers != null)\r\n            {\r\n                this.Headers = headers;\r\n            }\r\n\r\n            if (cookies != null)\r\n            {\r\n                foreach (var nancyCookie in cookies)\r\n                {\r\n                    this.Cookies.Add(nancyCookie);\r\n                }\r\n            }\r\n        }\r\n\r\n        private static string GetContentType(string contentType, Encoding encoding)\r\n        {\r\n            return !contentType.Contains(\"charset\") \r\n                ? string.Concat(contentType, \"; charset=\", encoding.WebName)\r\n                : contentType;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Responses/XmlResponse.cs",
    "content": "﻿namespace Nancy.Responses\r\n{\r\n    using System;\r\n    using System.IO;\r\n    using Nancy.Configuration;\r\n    using Nancy.Xml;\r\n\r\n    /// <summary>\r\n    /// Represents an HTTP response with XML content.\r\n    /// </summary>\r\n    /// <typeparam name=\"TModel\">The type of the model.</typeparam>\r\n    /// <seealso cref=\"Nancy.Response\" />\r\n    public class XmlResponse<TModel> : Response\r\n    {\r\n        private readonly XmlConfiguration configuration;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"XmlResponse{TModel}\"/> class, with\r\n        /// the provided <paramref name=\"model\"/>, <paramref name=\"serializer\"/> and <paramref name=\"environment\"/>.\r\n        /// </summary>\r\n        /// <param name=\"model\">The model.</param>\r\n        /// <param name=\"serializer\">The serializer.</param>\r\n        /// <param name=\"environment\">The environment.</param>\r\n        /// <exception cref=\"System.InvalidOperationException\">XML Serializer not set</exception>\r\n        public XmlResponse(TModel model, ISerializer serializer, INancyEnvironment environment)\r\n        {\r\n            if (serializer == null)\r\n            {\r\n                throw new InvalidOperationException(\"XML Serializer not set\");\r\n            }\r\n\r\n            this.configuration = environment.GetValue<XmlConfiguration>();\r\n\r\n            this.Contents = GetXmlContents(model, serializer);\r\n            this.ContentType = DefaultContentType;\r\n            this.StatusCode = HttpStatusCode.OK;\r\n        }\r\n\r\n        private string DefaultContentType\r\n        {\r\n            get { return string.Concat(\"application/xml\", this.Encoding); }\r\n        }\r\n\r\n        private string Encoding\r\n        {\r\n            get\r\n            {\r\n                return this.configuration.EncodingEnabled\r\n                    ? string.Concat(\"; charset=\", this.configuration.DefaultEncoding.WebName)\r\n                    : string.Empty;\r\n            }\r\n        }\r\n\r\n        private Action<Stream> GetXmlContents(TModel model, ISerializer serializer)\r\n        {\r\n            return stream => serializer.Serialize(this.DefaultContentType, model, stream);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/RouteConfiguration.cs",
    "content": "namespace Nancy\r\n{\r\n    /// <summary>\r\n    /// Configuration for the default routing.\r\n    /// </summary>\r\n    public class RouteConfiguration\r\n    {\r\n        /// <summary>\r\n        /// A default instance of the <see cref=\"ViewConfiguration\"/> class.\r\n        /// </summary>\r\n        public static readonly RouteConfiguration Default = new RouteConfiguration(\r\n            disableMethodNotAllowedResponses: false,\r\n            explicitHeadRouting: false);\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"RouteConfiguration\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"disableMethodNotAllowedResponses\">Determins is 405 responses are allowed.</param>\r\n        /// <param name=\"explicitHeadRouting\">Enabled support for explicit HEAD route declarations.</param>\r\n        public RouteConfiguration(bool disableMethodNotAllowedResponses = false, bool explicitHeadRouting = false)\r\n        {\r\n            this.DisableMethodNotAllowedResponses = disableMethodNotAllowedResponses;\r\n            this.ExplicitHeadRouting = explicitHeadRouting;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether or not to respond with 405 responses.\r\n        /// </summary>\r\n        /// <value><see langword=\"true\"/>If 405 responses are allowed, otherwise <see langword=\"false\"/>.</value>\r\n        public bool DisableMethodNotAllowedResponses { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether or not to route HEAD requests explicitly.\r\n        /// </summary>\r\n        /// <value><see langword=\"true\"/>If explicit HEAD route requests are allowed, otherwise <see langword=\"false\"/>.</value>\r\n        public bool ExplicitHeadRouting { get; private set; }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/RouteConfigurationExtensions.cs",
    "content": "namespace Nancy\r\n{\r\n    using Nancy.Configuration;\r\n\r\n    /// <summary>\r\n    /// Contains <see cref=\"RouteConfiguration\"/> configuration extensions for <see cref=\"INancyEnvironment\"/>.\r\n    /// </summary>\r\n    public static class RouteConfigurationExtensions\r\n    {\r\n        /// <summary>\r\n        /// Configures <see cref=\"RouteConfiguration\"/>.\r\n        /// </summary>\r\n        /// <param name=\"environment\"><see cref=\"INancyEnvironment\"/> that should be configured.</param>\r\n        /// <param name=\"disableMethodNotAllowedResponses\"><see langword=\"true\"/>If 405 responses are allowed, otherwise <see langword=\"false\"/>.</param>\r\n        /// <param name=\"explicitHeadRouting\"><see langword=\"true\"/>If explicit HEAD route requests are allowed, otherwise <see langword=\"false\"/>.</param>\r\n        public static void Routing(this INancyEnvironment environment, bool? disableMethodNotAllowedResponses = false, bool? explicitHeadRouting = false)\r\n        {\r\n            environment.AddValue(new RouteConfiguration(\r\n                disableMethodNotAllowedResponses: disableMethodNotAllowedResponses ?? RouteConfiguration.Default.DisableMethodNotAllowedResponses,\r\n                explicitHeadRouting: explicitHeadRouting ?? RouteConfiguration.Default.ExplicitHeadRouting));\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Constraints/AlphaRouteSegmentConstraint.cs",
    "content": "﻿namespace Nancy.Routing.Constraints\r\n{\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Constraint for alphabetical route segments.\r\n    /// </summary>\r\n    public class AlphaRouteSegmentConstraint : RouteSegmentConstraintBase<string>\r\n    {\r\n        /// <summary>\r\n        /// Gets the name of the constraint.\r\n        /// </summary>\r\n        /// <value>The constraint's name.</value>\r\n        public override string Name\r\n        {\r\n            get { return \"alpha\"; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tries to match the given segment against the constraint.\r\n        /// </summary>\r\n        /// <param name=\"constraint\">The constraint.</param>\r\n        /// <param name=\"segment\">The segment to match.</param>\r\n        /// <param name=\"matchedValue\">The matched value.</param>\r\n        /// <returns>\r\n        /// <see langword=\"true\"/> if the segment matches the constraint, <see langword=\"false\"/> otherwise.\r\n        /// </returns>\r\n        protected override bool TryMatch(string constraint, string segment, out string matchedValue)\r\n        {\r\n            if (!segment.All(char.IsLetter))\r\n            {\r\n                matchedValue = null;\r\n                return false;\r\n            }\r\n\r\n            matchedValue = segment;\r\n            return true;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Constraints/BoolRouteSegmentConstraint.cs",
    "content": "﻿namespace Nancy.Routing.Constraints\r\n{\r\n    /// <summary>\r\n    /// Constraint for <see cref=\"bool\"/> route segments.\r\n    /// </summary>\r\n    public class BoolRouteSegmentConstraint : RouteSegmentConstraintBase<bool>\r\n    {\r\n        /// <summary>\r\n        /// Gets the name of the constraint.\r\n        /// </summary>\r\n        /// <value>The constraint's name.</value>\r\n        public override string Name\r\n        {\r\n            get { return \"bool\"; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tries to match the given segment against the constraint.\r\n        /// </summary>\r\n        /// <param name=\"constraint\">The constraint.</param>\r\n        /// <param name=\"segment\">The segment to match.</param>\r\n        /// <param name=\"matchedValue\">The matched value.</param>\r\n        /// <returns>\r\n        /// <see langword=\"true\"/> if the segment matches the constraint, <see langword=\"false\"/> otherwise.\r\n        /// </returns>\r\n        protected override bool TryMatch(string constraint, string segment, out bool matchedValue)\r\n        {\r\n            return bool.TryParse(segment, out matchedValue);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Constraints/CustomDateTimeRouteSegmentConstraint.cs",
    "content": "﻿namespace Nancy.Routing.Constraints\r\n{\r\n    using System;\r\n    using System.Globalization;\r\n\r\n    /// <summary>\r\n    /// Constraint for <see cref=\"DateTime\"/> route segments with custom format.\r\n    /// </summary>\r\n    public class CustomDateTimeRouteSegmentConstraint : ParameterizedRouteSegmentConstraintBase<DateTime>\r\n    {\r\n        /// <summary>\r\n        /// Gets the name of the constraint.\r\n        /// </summary>\r\n        /// <value>The constraint's name.</value>\r\n        public override string Name\r\n        {\r\n            get { return \"datetime\"; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tries to match the given segment and parameters against the constraint.\r\n        /// </summary>\r\n        /// <param name=\"segment\">The segment to match.</param>\r\n        /// <param name=\"parameters\">The parameters to match.</param>\r\n        /// <param name=\"matchedValue\">The matched value.</param>\r\n        /// <returns>\r\n        /// <see langword=\"true\"/> if the segment matches the constraint, <see langword=\"false\"/> otherwise.\r\n        /// </returns>\r\n        protected override bool TryMatch(string segment, string[] parameters, out DateTime matchedValue)\r\n        {\r\n            return DateTime.TryParseExact(segment,\r\n                parameters[0],\r\n                CultureInfo.InvariantCulture,\r\n                DateTimeStyles.None,\r\n                out matchedValue);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Constraints/DateTimeRouteSegmentConstraint.cs",
    "content": "﻿namespace Nancy.Routing.Constraints\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Constraint for <see cref=\"DateTime\"/> route segments.\r\n    /// </summary>\r\n    public class DateTimeRouteSegmentConstraint : RouteSegmentConstraintBase<DateTime>\r\n    {\r\n        /// <summary>\r\n        /// Gets the name of the constraint.\r\n        /// </summary>\r\n        /// <value>The constraint's name.</value>\r\n        public override string Name\r\n        {\r\n            get { return \"datetime\"; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tries to match the given segment against the constraint.\r\n        /// </summary>\r\n        /// <param name=\"constraint\">The constraint.</param>\r\n        /// <param name=\"segment\">The segment to match.</param>\r\n        /// <param name=\"matchedValue\">The matched value.</param>\r\n        /// <returns>\r\n        /// <see langword=\"true\"/> if the segment matches the constraint, <see langword=\"false\"/> otherwise.\r\n        /// </returns>\r\n        protected override bool TryMatch(string constraint, string segment, out DateTime matchedValue)\r\n        {\r\n            return DateTime.TryParse(segment, out matchedValue);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Constraints/DecimalRouteSegmentConstraint.cs",
    "content": "﻿namespace Nancy.Routing.Constraints\r\n{\r\n    using System.Globalization;\r\n\r\n    /// <summary>\r\n    /// Constraint for <see cref=\"decimal\"/> route segments.\r\n    /// </summary>\r\n    public class DecimalRouteSegmentConstraint : RouteSegmentConstraintBase<decimal>\r\n    {\r\n        /// <summary>\r\n        /// Gets the name of the constraint.\r\n        /// </summary>\r\n        /// <value>The constraint's name.</value>\r\n        public override string Name\r\n        {\r\n            get { return \"decimal\"; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tries to match the given segment against the constraint.\r\n        /// </summary>\r\n        /// <param name=\"constraint\">The constraint.</param>\r\n        /// <param name=\"segment\">The segment to match.</param>\r\n        /// <param name=\"matchedValue\">The matched value.</param>\r\n        /// <returns>\r\n        /// <see langword=\"true\"/> if the segment matches the constraint, <see langword=\"false\"/> otherwise.\r\n        /// </returns>\r\n        protected override bool TryMatch(string constraint, string segment, out decimal matchedValue)\r\n        {\r\n            return decimal.TryParse(segment, NumberStyles.Number, CultureInfo.InvariantCulture, out matchedValue);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Constraints/GuidRouteSegmentConstraint.cs",
    "content": "﻿namespace Nancy.Routing.Constraints\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Constraint for <see cref=\"Guid\"/> route segments.\r\n    /// </summary>\r\n    public class GuidRouteSegmentConstraint : RouteSegmentConstraintBase<Guid>\r\n    {\r\n        /// <summary>\r\n        /// Gets the name of the constraint.\r\n        /// </summary>\r\n        /// <value>The constraint's name.</value>\r\n        public override string Name\r\n        {\r\n            get { return \"guid\"; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tries to match the given segment against the constraint.\r\n        /// </summary>\r\n        /// <param name=\"constraint\">The constraint.</param>\r\n        /// <param name=\"segment\">The segment to match.</param>\r\n        /// <param name=\"matchedValue\">The matched value.</param>\r\n        /// <returns>\r\n        /// <see langword=\"true\"/> if the segment matches the constraint, <see langword=\"false\"/> otherwise.\r\n        /// </returns>\r\n        protected override bool TryMatch(string constraint, string segment, out Guid matchedValue)\r\n        {\r\n            return Guid.TryParse(segment, out matchedValue);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Constraints/IRouteSegmentConstraint.cs",
    "content": "﻿namespace Nancy.Routing.Constraints\r\n{\r\n    using Nancy.Routing.Trie;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality to constrain route matching.\r\n    /// </summary>\r\n    public interface IRouteSegmentConstraint\r\n    {\r\n        /// <summary>\r\n        /// Determines whether the given constraint should be matched.\r\n        /// </summary>\r\n        /// <param name=\"constraint\">The route constraint.</param>\r\n        /// <returns><c>true</c> if the constraint matches, <c>false</c> otherwise.</returns>\r\n        bool Matches(string constraint);\r\n\r\n        /// <summary>\r\n        /// Matches the segment and parameter name against the constraint.\r\n        /// </summary>\r\n        /// <param name=\"constraint\">The constraint.</param>\r\n        /// <param name=\"segment\">The segment.</param>\r\n        /// <param name=\"parameterName\">Name of the parameter.</param>\r\n        /// <returns>A <see cref=\"SegmentMatch\"/> containing information about the captured parameters.</returns>\r\n        SegmentMatch GetMatch(string constraint, string segment, string parameterName);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Constraints/IntRouteSegmentConstraint.cs",
    "content": "﻿namespace Nancy.Routing.Constraints\r\n{\r\n    using System.Globalization;\r\n\r\n    /// <summary>\r\n    /// Constraint for <see cref=\"int\"/> route segments.\r\n    /// </summary>\r\n    public class IntRouteSegmentConstraint : RouteSegmentConstraintBase<int>\r\n    {\r\n        /// <summary>\r\n        /// Gets the name of the constraint.\r\n        /// </summary>\r\n        /// <value>The constraint's name.</value>\r\n        public override string Name\r\n        {\r\n            get { return \"int\"; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tries to match the given segment against the constraint.\r\n        /// </summary>\r\n        /// <param name=\"constraint\">The constraint.</param>\r\n        /// <param name=\"segment\">The segment to match.</param>\r\n        /// <param name=\"matchedValue\">The matched value.</param>\r\n        /// <returns>\r\n        /// <see langword=\"true\"/> if the segment matches the constraint, <see langword=\"false\"/> otherwise.\r\n        /// </returns>\r\n        protected override bool TryMatch(string constraint, string segment, out int matchedValue)\r\n        {\r\n            return int.TryParse(segment, NumberStyles.Integer, CultureInfo.InvariantCulture, out matchedValue);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Constraints/LengthRouteSegmentConstraint.cs",
    "content": "﻿namespace Nancy.Routing.Constraints\r\n{\r\n    /// <summary>\r\n    /// Constraint for route segments with a specific length.\r\n    /// </summary>\r\n    public class LengthRouteSegmentConstraint : ParameterizedRouteSegmentConstraintBase<string>\r\n    {\r\n        /// <summary>\r\n        /// Gets the name of the constraint.\r\n        /// </summary>\r\n        /// <value>The constraint's name.</value>\r\n        public override string Name\r\n        {\r\n            get { return \"length\"; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tries to match the given segment and parameters against the constraint.\r\n        /// </summary>\r\n        /// <param name=\"segment\">The segment to match.</param>\r\n        /// <param name=\"parameters\">The parameters to match.</param>\r\n        /// <param name=\"matchedValue\">The matched value.</param>\r\n        /// <returns>\r\n        /// <see langword=\"true\"/> if the segment matches the constraint, <see langword=\"false\"/> otherwise.\r\n        /// </returns>\r\n        protected override bool TryMatch(string segment, string[] parameters, out string matchedValue)\r\n        {\r\n            int minLength;\r\n            int maxLength;\r\n\r\n            if (parameters.Length == 2)\r\n            {\r\n                if (!this.TryParseInt(parameters[0], out minLength) ||\r\n                    !this.TryParseInt(parameters[1], out maxLength))\r\n                {\r\n                    matchedValue = null;\r\n                    return false;\r\n                }\r\n            }\r\n            else if (parameters.Length == 1)\r\n            {\r\n                minLength = 0;\r\n\r\n                if (!this.TryParseInt(parameters[0], out maxLength))\r\n                {\r\n                    matchedValue = null;\r\n                    return false;\r\n                }\r\n            }\r\n            else\r\n            {\r\n                matchedValue = null;\r\n                return false;\r\n            }\r\n\r\n            if (segment.Length < minLength || segment.Length > maxLength)\r\n            {\r\n                matchedValue = null;\r\n                return false;\r\n            }\r\n\r\n            matchedValue = segment;\r\n            return true;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Constraints/LongRouteSegmentConstraint.cs",
    "content": "﻿namespace Nancy.Routing.Constraints\r\n{\r\n    using System.Globalization;\r\n\r\n    /// <summary>\r\n    /// Constraint for <see cref=\"long\"/> route segments.\r\n    /// </summary>\r\n    public class LongRouteSegmentConstraint : RouteSegmentConstraintBase<long>\r\n    {\r\n        /// <summary>\r\n        /// Gets the name of the constraint.\r\n        /// </summary>\r\n        /// <value>\r\n        /// The constraint's name.\r\n        /// </value>\r\n        public override string Name\r\n        {\r\n            get { return \"long\"; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tries to match the given segment against the constraint.\r\n        /// </summary>\r\n        /// <param name=\"constraint\">The constraint.</param>\r\n        /// <param name=\"segment\">The segment to match.</param>\r\n        /// <param name=\"matchedValue\">The matched value.</param>\r\n        /// <returns>\r\n        /// <see langword=\"true\"/> if the segment matches the constraint, <see langword=\"false\"/> otherwise.\r\n        /// </returns>\r\n        protected override bool TryMatch(string constraint, string segment, out long matchedValue)\r\n        {\r\n            return long.TryParse(segment, NumberStyles.Integer, CultureInfo.InvariantCulture, out matchedValue);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Constraints/MaxLengthRouteSegmentConstraint.cs",
    "content": "﻿namespace Nancy.Routing.Constraints\r\n{\r\n    /// <summary>\r\n    /// Constraint for route segments with a maximum length.\r\n    /// </summary>\r\n    public class MaxLengthRouteSegmentConstraint : ParameterizedRouteSegmentConstraintBase<string>\r\n    {\r\n        /// <summary>\r\n        /// Gets the name of the constraint.\r\n        /// </summary>\r\n        /// <value>\r\n        /// The constraint's name.\r\n        /// </value>\r\n        public override string Name\r\n        {\r\n            get { return \"maxlength\"; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tries to match the given segment and parameters against the constraint.\r\n        /// </summary>\r\n        /// <param name=\"segment\">The segment to match.</param>\r\n        /// <param name=\"parameters\">The parameters to match.</param>\r\n        /// <param name=\"matchedValue\">The matched value.</param>\r\n        /// <returns>\r\n        /// <see langword=\"true\"/> if the segment matches the constraint, <see langword=\"false\"/> otherwise.\r\n        /// </returns>\r\n        protected override bool TryMatch(string segment, string[] parameters, out string matchedValue)\r\n        {\r\n            int maxLength;\r\n\r\n            if (!this.TryParseInt(parameters[0], out maxLength))\r\n            {\r\n                matchedValue = null;\r\n                return false;\r\n            }\r\n\r\n            if (segment.Length > maxLength)\r\n            {\r\n                matchedValue = null;\r\n                return false;\r\n            }\r\n\r\n            matchedValue = segment;\r\n            return true;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Constraints/MaxRouteSegmentConstraint.cs",
    "content": "﻿namespace Nancy.Routing.Constraints\r\n{\r\n    /// <summary>\r\n    /// Constraint for <see cref=\"int\"/> route segments with a maximum value.\r\n    /// </summary>\r\n    public class MaxRouteSegmentConstraint : ParameterizedRouteSegmentConstraintBase<int>\r\n    {\r\n        /// <summary>\r\n        /// Gets the name of the constraint.\r\n        /// </summary>\r\n        /// <value>The constraint's name.</value>\r\n        public override string Name\r\n        {\r\n            get { return \"max\"; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tries to match the given segment and parameters against the constraint.\r\n        /// </summary>\r\n        /// <param name=\"segment\">The segment to match.</param>\r\n        /// <param name=\"parameters\">The parameters to match.</param>\r\n        /// <param name=\"matchedValue\">The matched value.</param>\r\n        /// <returns>\r\n        /// <see langword=\"true\"/> if the segment matches the constraint, <see langword=\"false\"/> otherwise.\r\n        /// </returns>\r\n        protected override bool TryMatch(string segment, string[] parameters, out int matchedValue)\r\n        {\r\n            int minValue;\r\n            int intValue;\r\n\r\n            if (!this.TryParseInt(parameters[0], out minValue) ||\r\n                !this.TryParseInt(segment, out intValue))\r\n            {\r\n                matchedValue = default(int);\r\n                return false;\r\n            }\r\n\r\n            if (intValue > minValue)\r\n            {\r\n                matchedValue = default(int);\r\n                return false;\r\n            }\r\n\r\n            matchedValue = intValue;\r\n            return true;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Constraints/MinLengthRouteSegmentConstraint.cs",
    "content": "﻿namespace Nancy.Routing.Constraints\r\n{\r\n    /// <summary>\r\n    /// Constraint for route segments with a minimum length.\r\n    /// </summary>\r\n    public class MinLengthRouteSegmentConstraint : ParameterizedRouteSegmentConstraintBase<string>\r\n    {\r\n        /// <summary>\r\n        /// Gets the name of the constraint.\r\n        /// </summary>\r\n        /// <value>The constraint's name.</value>\r\n        public override string Name\r\n        {\r\n            get { return \"minlength\"; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tries to match the given segment and parameters against the constraint.\r\n        /// </summary>\r\n        /// <param name=\"segment\">The segment to match.</param>\r\n        /// <param name=\"parameters\">The parameters to match.</param>\r\n        /// <param name=\"matchedValue\">The matched value.</param>\r\n        /// <returns>\r\n        /// <see langword=\"true\"/> if the segment matches the constraint, <see langword=\"false\"/> otherwise.\r\n        /// </returns>\r\n        protected override bool TryMatch(string segment, string[] parameters, out string matchedValue)\r\n        {\r\n            int minLength;\r\n\r\n            if (!this.TryParseInt(parameters[0], out minLength))\r\n            {\r\n                matchedValue = null;\r\n                return false;\r\n            }\r\n\r\n            if (segment.Length < minLength)\r\n            {\r\n                matchedValue = null;\r\n                return false;\r\n            }\r\n\r\n            matchedValue = segment;\r\n            return true;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Constraints/MinRouteSegmentConstraint.cs",
    "content": "﻿namespace Nancy.Routing.Constraints\r\n{\r\n    /// <summary>\r\n    /// Constraint for <see cref=\"int\"/> route segments with a minimum length.\r\n    /// </summary>\r\n    public class MinRouteSegmentConstraint : ParameterizedRouteSegmentConstraintBase<int>\r\n    {\r\n        /// <summary>\r\n        /// Gets the name of the constraint.\r\n        /// </summary>\r\n        /// <value>\r\n        /// The constraint's name.\r\n        /// </value>\r\n        public override string Name\r\n        {\r\n            get { return \"min\"; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tries to match the given segment and parameters against the constraint.\r\n        /// </summary>\r\n        /// <param name=\"segment\">The segment to match.</param>\r\n        /// <param name=\"parameters\">The parameters to match.</param>\r\n        /// <param name=\"matchedValue\">The matched value.</param>\r\n        /// <returns>\r\n        /// <see langword=\"true\"/> if the segment matches the constraint, <see langword=\"false\"/> otherwise.\r\n        /// </returns>\r\n        protected override bool TryMatch(string segment, string[] parameters, out int matchedValue)\r\n        {\r\n            int minValue;\r\n            int intValue;\r\n\r\n            if (!this.TryParseInt(parameters[0], out minValue) ||\r\n                !this.TryParseInt(segment, out intValue))\r\n            {\r\n                matchedValue = default(int);\r\n                return false;\r\n            }\r\n\r\n            if (intValue < minValue)\r\n            {\r\n                matchedValue = default(int);\r\n                return false;\r\n            }\r\n\r\n            matchedValue = intValue;\r\n            return true;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Constraints/ParameterizedRouteSegmentConstraintBase.cs",
    "content": "﻿namespace Nancy.Routing.Constraints\r\n{\r\n    using System.Globalization;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Convenience class for implementing a route segment constraint that expects parameters.\r\n    /// </summary>\r\n    /// <typeparam name=\"T\">The type of parameter to capture.</typeparam>\r\n    public abstract class ParameterizedRouteSegmentConstraintBase<T> : RouteSegmentConstraintBase<T>\r\n    {\r\n        /// <summary>\r\n        /// Determines whether the given constraint matches the name of this constraint.\r\n        /// </summary>\r\n        /// <param name=\"constraint\">The route constraint.</param>\r\n        /// <returns>\r\n        /// <see langword=\"true\"/> if the segment matches the constraint, <see langword=\"false\"/> otherwise.\r\n        /// </returns>\r\n        public override bool Matches(string constraint)\r\n        {\r\n            return constraint.Contains('(') && constraint.Contains(')') && base.Matches(constraint.Substring(0, constraint.IndexOf('(')));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tries to match the given segment against the constraint.\r\n        /// </summary>\r\n        /// <param name=\"constraint\">The constraint.</param>\r\n        /// <param name=\"segment\">The segment to match.</param>\r\n        /// <param name=\"matchedValue\">The matched value.</param>\r\n        /// <returns>\r\n        /// <see langword=\"true\"/> if the segment matches the constraint, <see langword=\"false\"/> otherwise.\r\n        /// </returns>\r\n        protected override bool TryMatch(string constraint, string segment, out T matchedValue)\r\n        {\r\n            var parameters = constraint.Substring(constraint.IndexOf('(')).Trim('(', ')').Split(',');\r\n\r\n            return TryMatch(segment, parameters, out matchedValue);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tries to parse an integer using <see cref=\"CultureInfo.InvariantCulture\"/>.\r\n        /// </summary>\r\n        /// <param name=\"string\">The string value.</param>\r\n        /// <param name=\"result\">The resulting integer.</param>\r\n        /// <returns>\r\n        /// <see langword=\"true\"/> if the segment matches the constraint, <see langword=\"false\"/> otherwise.\r\n        /// </returns>\r\n        protected bool TryParseInt(string @string, out int result)\r\n        {\r\n            return int.TryParse(@string, NumberStyles.Integer, CultureInfo.InvariantCulture, out result);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tries to match the given segment and parameters against the constraint.\r\n        /// </summary>\r\n        /// <param name=\"segment\">The segment to match.</param>\r\n        /// <param name=\"parameters\">The parameters to match.</param>\r\n        /// <param name=\"matchedValue\">The matched value.</param>\r\n        /// <returns>\r\n        /// <see langword=\"true\"/> if the segment matches the constraint, <see langword=\"false\"/> otherwise.\r\n        /// </returns>\r\n        protected abstract bool TryMatch(string segment, string[] parameters, out T matchedValue);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Constraints/RangeRouteSegmentConstraint.cs",
    "content": "﻿namespace Nancy.Routing.Constraints\r\n{\r\n    /// <summary>\r\n    /// Constraint for <see cref=\"int\"/> route segments with value within a specified range.\r\n    /// </summary>\r\n    public class RangeRouteSegmentConstraint : ParameterizedRouteSegmentConstraintBase<int>\r\n    {\r\n        /// <summary>\r\n        /// Gets the name of the constraint.\r\n        /// </summary>\r\n        /// <value>\r\n        /// The constraint's name.\r\n        /// </value>\r\n        public override string Name\r\n        {\r\n            get { return \"range\"; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tries to match the given segment and parameters against the constraint.\r\n        /// </summary>\r\n        /// <param name=\"segment\">The segment to match.</param>\r\n        /// <param name=\"parameters\">The parameters to match.</param>\r\n        /// <param name=\"matchedValue\">The matched value.</param>\r\n        /// <returns>\r\n        ///   <c>true</c> if the segment and parameters matches the constraint, <c>false</c> otherwise.\r\n        /// </returns>\r\n        protected override bool TryMatch(string segment, string[] parameters, out int matchedValue)\r\n        {\r\n            int minRange;\r\n            int maxRange;\r\n            int intValue;\r\n\r\n            if (parameters.Length == 2)\r\n            {\r\n                if (!this.TryParseInt(parameters[0], out minRange) ||\r\n                    !this.TryParseInt(parameters[1], out maxRange) ||\r\n                    !this.TryParseInt(segment, out intValue))\r\n                {\r\n                    matchedValue = default(int);\r\n                    return false;\r\n                }\r\n            }\r\n            else\r\n            {\r\n                matchedValue = default(int);\r\n                return false;\r\n            }\r\n\r\n            if (intValue < minRange || intValue > maxRange)\r\n            {\r\n                matchedValue = default(int);\r\n                return false;\r\n            }\r\n\r\n            matchedValue = intValue;\r\n            return true;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Constraints/RouteSegmentConstraintBase.cs",
    "content": "﻿namespace Nancy.Routing.Constraints\r\n{\r\n    using System;\r\n\r\n    using Nancy.Routing.Trie;\r\n\r\n    /// <summary>\r\n    /// Convenience class for implementing a route segment constraint.\r\n    /// </summary>\r\n    /// <typeparam name=\"T\">The type of parameter to capture.</typeparam>\r\n    public abstract class RouteSegmentConstraintBase<T> : IRouteSegmentConstraint\r\n    {\r\n        /// <summary>\r\n        /// Gets the name of the constraint.\r\n        /// </summary>\r\n        /// <value>The constraint's name.</value>\r\n        public abstract string Name { get; }\r\n\r\n        /// <summary>\r\n        /// Determines whether the given constraint matches the name of this constraint.\r\n        /// </summary>\r\n        /// <param name=\"constraint\">The route constraint.</param>\r\n        /// <returns>\r\n        /// <see langword=\"true\"/> if the segment matches the constraint, <see langword=\"false\"/> otherwise.\r\n        /// </returns>\r\n        public virtual bool Matches(string constraint)\r\n        {\r\n            return constraint.Equals(Name, StringComparison.OrdinalIgnoreCase);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Matches the segment and parameter name against the constraint.\r\n        /// </summary>\r\n        /// <param name=\"constraint\">The constraint.</param>\r\n        /// <param name=\"segment\">The segment.</param>\r\n        /// <param name=\"parameterName\">Name of the parameter.</param>\r\n        /// <returns>\r\n        /// A <see cref=\"SegmentMatch\" /> containing information about the captured parameters \r\n        /// stating whether there is a match or not.\r\n        /// </returns>\r\n        public SegmentMatch GetMatch(string constraint, string segment, string parameterName)\r\n        {\r\n            T value;\r\n            if (this.TryMatch(constraint, segment, out value))\r\n            {\r\n                return CreateMatch(parameterName, value);\r\n            }\r\n\r\n            return SegmentMatch.NoMatch;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tries to match the given segment against the constraint.\r\n        /// </summary>\r\n        /// <param name=\"constraint\">The constraint.</param>\r\n        /// <param name=\"segment\">The segment to match.</param>\r\n        /// <param name=\"matchedValue\">The matched value.</param>\r\n        /// <returns>\r\n        /// <see langword=\"true\"/> if the segment matches the constraint, <see langword=\"false\"/> otherwise.\r\n        /// </returns>\r\n        protected abstract bool TryMatch(string constraint, string segment, out T matchedValue);\r\n\r\n        private static SegmentMatch CreateMatch(string parameterName, object matchedValue)\r\n        {\r\n            var match = new SegmentMatch(true);\r\n            match.CapturedParameters.Add(parameterName, matchedValue);\r\n            return match;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Routing/Constraints/VersionRouteSegmentConstraint.cs",
    "content": "﻿namespace Nancy.Routing.Constraints\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Constraint for version route segments.\r\n    /// </summary>\r\n    public class VersionRouteSegmentConstraint : RouteSegmentConstraintBase<Version>\r\n    {\r\n        /// <summary>\r\n        /// Gets the name of the constraint.\r\n        /// </summary>\r\n        /// <value>The constraint's name.</value>\r\n        public override string Name\r\n        {\r\n            get { return \"version\"; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tries to match the given segment against the constraint.\r\n        /// </summary>\r\n        /// <param name=\"constraint\">The constraint.</param>\r\n        /// <param name=\"segment\">The segment to match.</param>\r\n        /// <param name=\"matchedValue\">The matched value.</param>\r\n        /// <returns>\r\n        /// <see langword=\"true\"/> if the segment matches the constraint, <see langword=\"false\"/> otherwise.\r\n        /// </returns>\r\n        protected override bool TryMatch(string constraint, string segment, out Version matchedValue)\r\n        {\r\n            return Version.TryParse(segment, out matchedValue);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Routing/DefaultNancyModuleBuilder.cs",
    "content": "﻿namespace Nancy.Routing\r\n{\r\n    using Nancy.Extensions;\r\n    using Nancy.ModelBinding;\r\n    using Nancy.Responses.Negotiation;\r\n    using Nancy.Validation;\r\n    using Nancy.ViewEngines;\r\n\r\n    /// <summary>\r\n    /// Default implementation for building a full configured <see cref=\"INancyModule\"/> instance.\r\n    /// </summary>\r\n    public class DefaultNancyModuleBuilder : INancyModuleBuilder\r\n    {\r\n        private readonly IViewFactory viewFactory;\r\n        private readonly IResponseFormatterFactory responseFormatterFactory;\r\n        private readonly IModelBinderLocator modelBinderLocator;\r\n        private readonly IModelValidatorLocator validatorLocator;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultNancyModuleBuilder\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"viewFactory\">The <see cref=\"IViewFactory\"/> instance that should be assigned to the module.</param>\r\n        /// <param name=\"responseFormatterFactory\">An <see cref=\"IResponseFormatterFactory\"/> instance that should be used to create a response formatter for the module.</param>\r\n        /// <param name=\"modelBinderLocator\">A <see cref=\"IModelBinderLocator\"/> instance that should be assigned to the module.</param>\r\n        /// <param name=\"validatorLocator\">A <see cref=\"IModelValidatorLocator\"/> instance that should be assigned to the module.</param>\r\n        public DefaultNancyModuleBuilder(IViewFactory viewFactory, IResponseFormatterFactory responseFormatterFactory, IModelBinderLocator modelBinderLocator, IModelValidatorLocator validatorLocator)\r\n        {\r\n            this.viewFactory = viewFactory;\r\n            this.responseFormatterFactory = responseFormatterFactory;\r\n            this.modelBinderLocator = modelBinderLocator;\r\n            this.validatorLocator = validatorLocator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Builds a fully configured <see cref=\"INancyModule\"/> instance, based upon the provided <paramref name=\"module\"/>.\r\n        /// </summary>\r\n        /// <param name=\"module\">The <see cref=\"INancyModule\"/> that should be configured.</param>\r\n        /// <param name=\"context\">The current request context.</param>\r\n        /// <returns>A fully configured <see cref=\"INancyModule\"/> instance.</returns>\r\n        public INancyModule BuildModule(INancyModule module, NancyContext context)\r\n        {\r\n            module.Context = context;\r\n            module.Response = this.responseFormatterFactory.Create(context);\r\n            module.ViewFactory = this.viewFactory;\r\n            module.ModelBinderLocator = this.modelBinderLocator;\r\n            module.ValidatorLocator = this.validatorLocator;\r\n\r\n            return module;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/DefaultRequestDispatcher.cs",
    "content": "namespace Nancy.Routing\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n    using Helpers;\r\n    using Responses.Negotiation;\r\n\r\n    /// <summary>\r\n    /// Default implementation of a request dispatcher.\r\n    /// </summary>\r\n    public class DefaultRequestDispatcher : IRequestDispatcher\r\n    {\r\n        private readonly IRouteResolver routeResolver;\r\n        private readonly IEnumerable<IResponseProcessor> responseProcessors;\r\n        private readonly IRouteInvoker routeInvoker;\r\n        private readonly IResponseNegotiator negotiator;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultRequestDispatcher\"/> class, with\r\n        /// the provided <paramref name=\"routeResolver\"/>, <paramref name=\"responseProcessors\"/> and <paramref name=\"routeInvoker\"/>.\r\n        /// </summary>\r\n        /// <param name=\"routeResolver\"></param>\r\n        /// <param name=\"responseProcessors\"></param>\r\n        /// <param name=\"routeInvoker\"></param>\r\n        /// <param name=\"negotiator\"></param>\r\n        public DefaultRequestDispatcher(IRouteResolver routeResolver,\r\n            IEnumerable<IResponseProcessor> responseProcessors,\r\n            IRouteInvoker routeInvoker,\r\n            IResponseNegotiator negotiator)\r\n        {\r\n            this.routeResolver = routeResolver;\r\n            this.responseProcessors = responseProcessors;\r\n            this.routeInvoker = routeInvoker;\r\n            this.negotiator = negotiator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Dispatches a requests.\r\n        /// </summary>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> for the current request.</param>\r\n        /// <param name=\"cancellationToken\">A cancellation token.</param>\r\n        public async Task<Response> Dispatch(NancyContext context, CancellationToken cancellationToken)\r\n        {\r\n            // TODO - May need to make this run off context rather than response .. seems a bit icky currently\r\n            var resolveResult = this.Resolve(context);\r\n\r\n            context.Parameters = resolveResult.Parameters;\r\n            context.ResolvedRoute = resolveResult.Route;\r\n\r\n            try\r\n            {\r\n                context.Response = await ExecuteRoutePreReq(context, cancellationToken, resolveResult.Before)\r\n                    .ConfigureAwait(false);\r\n\r\n                if(context.Response == null)\r\n                {\r\n                    context.Response = await this.routeInvoker.Invoke(resolveResult.Route, cancellationToken,\r\n                        resolveResult.Parameters, context)\r\n                        .ConfigureAwait(false);\r\n\r\n                    if (context.Request.Method.Equals(\"HEAD\", StringComparison.OrdinalIgnoreCase))\r\n                    {\r\n                        context.Response = new HeadResponse(context.Response);\r\n                    }\r\n                }\r\n\r\n                await this.ExecutePost(context, cancellationToken, resolveResult.After, resolveResult.OnError)\r\n                    .ConfigureAwait(false);\r\n            }\r\n            catch(Exception ex)\r\n            {\r\n                context.Response = this.ResolveErrorResult(context, resolveResult.OnError, ex);\r\n\r\n                if (context.Response == null)\r\n                {\r\n                    throw;\r\n                }\r\n            }\r\n\r\n            return context.Response;\r\n        }\r\n\r\n        private async Task ExecutePost(NancyContext context, CancellationToken cancellationToken, AfterPipeline postHook, Func<NancyContext, Exception, dynamic> onError)\r\n        {\r\n            if (postHook == null)\r\n            {\r\n                return;\r\n            }\r\n\r\n            try\r\n            {\r\n                await postHook.Invoke(context, cancellationToken)\r\n                    .ConfigureAwait(false);\r\n            }\r\n            catch(Exception ex)\r\n            {\r\n                context.Response = this.ResolveErrorResult(context, onError, ex);\r\n\r\n                if(context.Response == null)\r\n                {\r\n                    throw;\r\n                }\r\n            }\r\n        }\r\n\r\n        private static Task<Response> ExecuteRoutePreReq(NancyContext context, CancellationToken cancellationToken, BeforePipeline resolveResultPreReq)\r\n        {\r\n            if (resolveResultPreReq == null)\r\n            {\r\n                return Task.FromResult<Response>(null);\r\n            }\r\n\r\n            return resolveResultPreReq.Invoke(context, cancellationToken);\r\n        }\r\n\r\n        private Response ResolveErrorResult(NancyContext context, Func<NancyContext, Exception, dynamic> resolveResultOnError, Exception exception)\r\n        {\r\n            if (resolveResultOnError != null)\r\n            {\r\n                var flattenedException = exception.FlattenInnerExceptions();\r\n\r\n                var result = resolveResultOnError.Invoke(context, flattenedException);\r\n                if (result != null)\r\n                {\r\n                    return this.negotiator.NegotiateResponse(result, context);\r\n                }\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        private ResolveResult Resolve(NancyContext context)\r\n        {\r\n            var extension = context.Request.Path.IndexOfAny(Path.GetInvalidPathChars()) >= 0 ? null\r\n               : Path.GetExtension(context.Request.Path);\r\n\r\n            var originalAcceptHeaders = context.Request.Headers.Accept;\r\n            var originalRequestPath = context.Request.Path;\r\n\r\n            if (!string.IsNullOrEmpty(extension))\r\n            {\r\n                var mappedMediaRanges = this.GetMediaRangesForExtension(extension.Substring(1))\r\n                    .ToArray();\r\n\r\n                if (mappedMediaRanges.Any())\r\n                {\r\n                    var newMediaRanges =\r\n                        mappedMediaRanges.Where(x => !context.Request.Headers.Accept.Any(header => header.Equals(x)));\r\n\r\n                    var index = context.Request.Path.LastIndexOf(extension, StringComparison.Ordinal);\r\n\r\n                    var modifiedRequestPath =\r\n                        context.Request.Path.Remove (index, extension.Length);\r\n\r\n                    var match =\r\n                        this.InvokeRouteResolver(context, modifiedRequestPath, newMediaRanges);\r\n\r\n                    if (!(match.Route is NotFoundRoute))\r\n                    {\r\n                        return match;\r\n                    }\r\n                }\r\n            }\r\n\r\n            return this.InvokeRouteResolver(context, originalRequestPath, originalAcceptHeaders);\r\n        }\r\n\r\n        private IEnumerable<Tuple<string, decimal>> GetMediaRangesForExtension(string extension)\r\n        {\r\n            return this.responseProcessors\r\n                .SelectMany(processor => processor.ExtensionMappings)\r\n                .Where(mapping => mapping != null)\r\n                .Where(mapping => mapping.Item1.Equals(extension, StringComparison.OrdinalIgnoreCase))\r\n                .Select(mapping => new Tuple<string, decimal>(mapping.Item2, Decimal.MaxValue))\r\n                .Distinct();\r\n        }\r\n\r\n        private ResolveResult InvokeRouteResolver(NancyContext context, string path, IEnumerable<Tuple<string, decimal>> acceptHeaders)\r\n        {\r\n            context.Request.Headers.Accept = acceptHeaders.ToList();\r\n            context.Request.Url.Path = path;\r\n\r\n            return this.routeResolver.Resolve(context);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Routing/DefaultRouteCacheProvider.cs",
    "content": "﻿namespace Nancy.Routing\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    using Nancy.Diagnostics;\r\n\r\n    /// <summary>\r\n    /// It's not safe for a module to take a dependency on the cache (cyclic dependency)\r\n    ///\r\n    /// We provide an IRouteCacheProvider instead - the default implementation uses\r\n    /// TinyIoC'd Func based lazy factory.\r\n    /// </summary>\r\n    public class DefaultRouteCacheProvider : IRouteCacheProvider, IDiagnosticsProvider\r\n    {\r\n        /// <summary>\r\n        /// The route cache factory\r\n        /// </summary>\r\n        protected readonly Func<IRouteCache> RouteCacheFactory;\r\n\r\n        /// <summary>\r\n        /// Gets the name of the provider.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the name of the provider.</value>\r\n        public string Name\r\n        {\r\n            get { return \"Route Cache\"; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the description of the provider.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the description of the provider.</value>\r\n        public string Description\r\n        {\r\n            get { return \"Provides methods for viewing and querying the route cache.\"; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the object that contains the interactive diagnostics methods.\r\n        /// </summary>\r\n        /// <value>An instance of the interactive diagnostics object.</value>\r\n        public object DiagnosticObject { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the DefaultRouteCacheProvider class.\r\n        /// </summary>\r\n        /// <param name=\"routeCacheFactory\"></param>\r\n        public DefaultRouteCacheProvider(Func<IRouteCache> routeCacheFactory)\r\n        {\r\n            this.RouteCacheFactory = routeCacheFactory;\r\n\r\n            this.DiagnosticObject = new RouteCacheDiagnostics(this);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets an instance of the route cache.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IRouteCache\"/> instance.</returns>\r\n        public IRouteCache GetCache()\r\n        {\r\n            return this.RouteCacheFactory();\r\n        }\r\n\r\n        private class RouteCacheDiagnostics\r\n        {\r\n            private readonly DefaultRouteCacheProvider cacheProvider;\r\n\r\n            public RouteCacheDiagnostics(DefaultRouteCacheProvider cacheProvider)\r\n            {\r\n                this.cacheProvider = cacheProvider;\r\n            }\r\n\r\n            // ReSharper disable once UnusedMember.Local\r\n            public IDictionary<string, IList<object>> GetAllRoutes()\r\n            {\r\n                var result = new Dictionary<string, IList<object>>();\r\n\r\n                foreach (var entry in this.cacheProvider.GetCache().Values.SelectMany(t => t.Select(t1 => t1.Item2)))\r\n                {\r\n                    IList<object> value;\r\n                    if (!result.TryGetValue(entry.Method, out value))\r\n                    {\r\n                        value = new List<object>();\r\n                        result[entry.Method] = value;\r\n                    }\r\n\r\n                    value.Add(new { Name = entry.Name, Path = entry.Path });\r\n                }\r\n\r\n                return result;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Routing/DefaultRouteDescriptionProvider.cs",
    "content": "namespace Nancy.Routing\r\n{\r\n    using System;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using System.Resources;\r\n\r\n    /// <summary>\r\n    /// Default implementation of the <see cref=\"IRouteDescriptionProvider\"/> interface. Will look for\r\n    /// route descriptions in resource files. The resource files should have the same name as the module\r\n    /// for which it defines routes.\r\n    /// </summary>\r\n    public class DefaultRouteDescriptionProvider : IRouteDescriptionProvider\r\n    {\r\n        /// <summary>\r\n        /// Get the description for a route.\r\n        /// </summary>\r\n        /// <param name=\"module\">The module that the route is defined in.</param>\r\n        /// <param name=\"path\">The path of the route that the description should be retrieved for.</param>\r\n        /// <returns>A <see cref=\"string\"/> containing the description of the route if it could be found, otherwise <see cref=\"string.Empty\"/>.</returns>\r\n        public string GetDescription(INancyModule module, string path)\r\n        {\r\n            var assembly =\r\n                module.GetType().GetTypeInfo().Assembly;\r\n\r\n            if (assembly.IsDynamic)\r\n            {\r\n                return string.Empty;\r\n            }\r\n\r\n            var moduleName =\r\n                string.Concat(module.GetType().FullName, \".resources\");\r\n\r\n            var resourceName = assembly\r\n                .GetManifestResourceNames()\r\n                .FirstOrDefault(x => x.Equals(moduleName, StringComparison.OrdinalIgnoreCase));\r\n\r\n            if (resourceName != null)\r\n            {\r\n                var manager =\r\n                    new ResourceManager(resourceName.Replace(\".resources\", string.Empty), assembly);\r\n\r\n                return manager.GetString(path);\r\n            }\r\n\r\n            return string.Empty;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/DefaultRouteInvoker.cs",
    "content": "namespace Nancy.Routing\r\n{\r\n    using System;\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n    using Nancy.ErrorHandling;\r\n    using Nancy.Extensions;\r\n    using Nancy.Responses.Negotiation;\r\n\r\n    /// <summary>\r\n    /// Default route invoker implementation.\r\n    /// </summary>\r\n    public class DefaultRouteInvoker : IRouteInvoker\r\n    {\r\n        private readonly IResponseNegotiator negotiator;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultRouteInvoker\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"negotiator\">The response negotiator.</param>\r\n        public DefaultRouteInvoker(IResponseNegotiator negotiator)\r\n        {\r\n            this.negotiator = negotiator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Invokes the specified <paramref name=\"route\"/> with the provided <paramref name=\"parameters\"/>.\r\n        /// </summary>\r\n        /// <param name=\"route\">The route that should be invoked.</param>\r\n        /// <param name=\"cancellationToken\">Cancellation token</param>\r\n        /// <param name=\"parameters\">The parameters that the route should be invoked with.</param>\r\n        /// <param name=\"context\">The context of the route that is being invoked.</param>\r\n        /// <returns>A <see cref=\"Response\"/> instance that represents the result of the invoked route.</returns>\r\n        public async Task<Response> Invoke(Route route, CancellationToken cancellationToken, DynamicDictionary parameters, NancyContext context)\r\n        {\r\n            object result;\r\n\r\n            try\r\n            {\r\n                result = await route.Invoke(parameters, cancellationToken).ConfigureAwait(false);\r\n            }\r\n            catch(RouteExecutionEarlyExitException earlyExitException)\r\n            {\r\n                context.WriteTraceLog(\r\n                    sb => sb.AppendFormat(\r\n                            \"[DefaultRouteInvoker] Caught RouteExecutionEarlyExitException - reason {0}\",\r\n                            earlyExitException.Reason));\r\n                return earlyExitException.Response;\r\n            }\r\n\r\n            if (!(result is ValueType) && result == null)\r\n            {\r\n                context.WriteTraceLog(\r\n                    sb => sb.AppendLine(\"[DefaultRouteInvoker] Invocation of route returned null\"));\r\n\r\n                result = new Response();\r\n            }\r\n\r\n            return this.negotiator.NegotiateResponse(result, context);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Routing/DefaultRouteResolver.cs",
    "content": "﻿namespace Nancy.Routing\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using Helpers;\r\n    using Nancy.Configuration;\r\n    using Trie;\r\n\r\n    /// <summary>\r\n    /// Default implementation of the <see cref=\"IRouteResolver\"/> interface.\r\n    /// </summary>\r\n    public class DefaultRouteResolver : IRouteResolver\r\n    {\r\n        private readonly INancyModuleCatalog catalog;\r\n        private readonly INancyModuleBuilder moduleBuilder;\r\n        private readonly IRouteCache routeCache;\r\n        private readonly IRouteResolverTrie trie;\r\n        private readonly Lazy<RouteConfiguration> configuration;\r\n        private readonly GlobalizationConfiguration globalizationConfiguraton;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultRouteResolver\"/> class, using\r\n        /// the provided <paramref name=\"catalog\"/>, <paramref name=\"moduleBuilder\"/>,\r\n        /// <paramref name=\"routeCache\"/> and <paramref name=\"trie\"/>.\r\n        /// </summary>\r\n        /// <param name=\"catalog\">An <see cref=\"INancyModuleCatalog\"/> instance.</param>\r\n        /// <param name=\"moduleBuilder\">An <see cref=\"INancyModuleBuilder\"/> instance.</param>\r\n        /// <param name=\"routeCache\">An <see cref=\"IRouteCache\"/> instance.</param>\r\n        /// <param name=\"trie\">An <see cref=\"IRouteResolverTrie\"/> instance.</param>\r\n        /// <param name=\"environment\">An <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        public DefaultRouteResolver(INancyModuleCatalog catalog, INancyModuleBuilder moduleBuilder, IRouteCache routeCache, IRouteResolverTrie trie, INancyEnvironment environment)\r\n        {\r\n            this.catalog = catalog;\r\n            this.moduleBuilder = moduleBuilder;\r\n            this.routeCache = routeCache;\r\n            this.trie = trie;\r\n            this.configuration = new Lazy<RouteConfiguration>(environment.GetValue<RouteConfiguration>);\r\n            this.globalizationConfiguraton = environment.GetValue<GlobalizationConfiguration>();\r\n\r\n            this.BuildTrie();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the route, and the corresponding parameter dictionary from the URL\r\n        /// </summary>\r\n        /// <param name=\"context\">Current context</param>\r\n        /// <returns>A <see cref=\"ResolveResult\"/> containing the resolved route information.</returns>\r\n        public ResolveResult Resolve(NancyContext context)\r\n        {\r\n            var pathDecoded =\r\n                HttpUtility.UrlDecode(context.Request.Path);\r\n\r\n            var results = this.trie.GetMatches(this.GetMethod(context), pathDecoded, context);\r\n\r\n            if (!results.Any())\r\n            {\r\n                var allowedMethods =\r\n                    this.trie.GetOptions(pathDecoded, context).ToArray();\r\n\r\n                if (IsOptionsRequest(context))\r\n                {\r\n                    return BuildOptionsResult(allowedMethods, context);\r\n                }\r\n\r\n                return this.IsMethodNotAllowed(allowedMethods) ?\r\n                    BuildMethodNotAllowedResult(context, allowedMethods) :\r\n                    GetNotFoundResult(context);\r\n            }\r\n\r\n            // Sort in descending order\r\n            Array.Sort(results, (m1, m2) => -m1.CompareTo(m2));\r\n\r\n            for (var index = 0; index < results.Length; index++)\r\n            {\r\n                var matchResult = results[index];\r\n                if (matchResult.Condition == null || matchResult.Condition.Invoke(context))\r\n                {\r\n                    return this.BuildResult(context, matchResult);\r\n                }\r\n            }\r\n\r\n            return GetNotFoundResult(context);\r\n        }\r\n\r\n        private static ResolveResult BuildMethodNotAllowedResult(NancyContext context, IEnumerable<string> allowedMethods)\r\n        {\r\n            var route =\r\n                new MethodNotAllowedRoute(context.Request.Path, context.Request.Method, allowedMethods);\r\n\r\n            return new ResolveResult(route, new DynamicDictionary(), null, null, null);\r\n        }\r\n\r\n        private bool IsMethodNotAllowed(IEnumerable<string> allowedMethods)\r\n        {\r\n            return allowedMethods.Any() && !this.configuration.Value.DisableMethodNotAllowedResponses;\r\n        }\r\n\r\n        private static bool IsOptionsRequest(NancyContext context)\r\n        {\r\n            return context.Request.Method.Equals(\"OPTIONS\", StringComparison.OrdinalIgnoreCase);\r\n        }\r\n\r\n        private void BuildTrie()\r\n        {\r\n            this.trie.BuildTrie(this.routeCache);\r\n        }\r\n\r\n        private static ResolveResult BuildOptionsResult(IEnumerable<string> allowedMethods, NancyContext context)\r\n        {\r\n            var path =\r\n                context.Request.Path;\r\n\r\n            var optionsResult =\r\n                new OptionsRoute(path, allowedMethods);\r\n\r\n            return new ResolveResult(\r\n                optionsResult,\r\n                new DynamicDictionary(),\r\n                null,\r\n                null,\r\n                null);\r\n        }\r\n\r\n        private ResolveResult BuildResult(NancyContext context, MatchResult result)\r\n        {\r\n            var associatedModule = this.GetModuleFromMatchResult(context, result);\r\n\r\n            context.NegotiationContext.SetModule(associatedModule);\r\n\r\n            var route = associatedModule.Routes.ElementAt(result.RouteIndex);\r\n            var parameters = DynamicDictionary.Create(result.Parameters, this.globalizationConfiguraton);\r\n\r\n            return new ResolveResult\r\n            {\r\n                Route = route,\r\n                Parameters = parameters,\r\n                Before = associatedModule.Before,\r\n                After = associatedModule.After,\r\n                OnError = associatedModule.OnError\r\n            };\r\n        }\r\n\r\n        private INancyModule GetModuleFromMatchResult(NancyContext context, MatchResult result)\r\n        {\r\n            var module =\r\n                this.catalog.GetModule(result.ModuleType, context);\r\n\r\n            return this.moduleBuilder.BuildModule(module, context);\r\n        }\r\n\r\n        private static ResolveResult GetNotFoundResult(NancyContext context)\r\n        {\r\n            return new ResolveResult\r\n            {\r\n                Route = new NotFoundRoute(context.Request.Method, context.Request.Path),\r\n                Parameters = DynamicDictionary.Empty,\r\n                Before = null,\r\n                After = null,\r\n                OnError = null\r\n            };\r\n        }\r\n\r\n        private string GetMethod(NancyContext context)\r\n        {\r\n            var requestedMethod =\r\n                context.Request.Method;\r\n\r\n            if (!this.configuration.Value.ExplicitHeadRouting)\r\n            {\r\n                return requestedMethod.Equals(\"HEAD\", StringComparison.OrdinalIgnoreCase) ?\r\n                    \"GET\" :\r\n                    requestedMethod;\r\n            }\r\n\r\n            return requestedMethod;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Routing/DefaultRouteSegmentExtractor.cs",
    "content": "﻿namespace Nancy.Routing\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Default implementation of the <see cref=\"IRouteSegmentExtractor\"/> interface.\r\n    /// </summary>\r\n    public class DefaultRouteSegmentExtractor : IRouteSegmentExtractor\r\n    {\r\n        /// <summary>\r\n        /// Extracts the segments from the <paramref name=\"path\"/>;\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that the segments should be extracted from.</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/>, containing the extracted segments.</returns>\r\n        public IEnumerable<string> Extract(string path)\r\n        {\r\n            var currentSegment = string.Empty;\r\n            var openingParenthesesCount = 0;\r\n\r\n            for (var index = 0; index < path.Length; index++)\r\n            {\r\n                var token =\r\n                    path[index];\r\n\r\n                if (token.Equals('('))\r\n                {\r\n                    openingParenthesesCount++;\r\n                }\r\n\r\n                if (token.Equals(')'))\r\n                {\r\n                    openingParenthesesCount--;\r\n                }\r\n\r\n                if (!token.Equals('/') || openingParenthesesCount > 0)\r\n                {\r\n                    currentSegment += token;\r\n                }\r\n\r\n                if ((token.Equals('/') || index == path.Length - 1) && currentSegment.Length > 0 && openingParenthesesCount == 0)\r\n                {\r\n                    yield return currentSegment;\r\n                    currentSegment = string.Empty;\r\n                }\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/INancyModuleBuilder.cs",
    "content": "﻿namespace Nancy.Routing\r\n{\r\n    /// <summary>\r\n    /// Defines the functionality to build a fully configured NancyModule instance.\r\n    /// </summary>\r\n    public interface INancyModuleBuilder\r\n    {\r\n        /// <summary>\r\n        /// Builds a fully configured <see cref=\"INancyModule\"/> instance, based upon the provided <paramref name=\"module\"/>.\r\n        /// </summary>\r\n        /// <param name=\"module\">The <see cref=\"INancyModule\"/> that should be configured.</param>\r\n        /// <param name=\"context\">The current request context.</param>\r\n        /// <returns>A fully configured <see cref=\"INancyModule\"/> instance.</returns>\r\n        INancyModule BuildModule(INancyModule module, NancyContext context);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/IRequestDispatcher.cs",
    "content": "﻿namespace Nancy.Routing\r\n{\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n\r\n    /// <summary>\r\n    /// Functionality for processing an incoming request.\r\n    /// </summary>\r\n    public interface IRequestDispatcher\r\n    {\r\n        /// <summary>\r\n        /// Dispatches a requests.\r\n        /// </summary>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> for the current request.</param>\r\n        /// <param name=\"cancellationToken\">Cancellation token</param>\r\n        Task<Response> Dispatch(NancyContext context, CancellationToken cancellationToken);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/IRouteCache.cs",
    "content": "namespace Nancy.Routing\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Contains a cache of all routes registered in the system\r\n    /// </summary>\r\n    public interface IRouteCache : IDictionary<Type, List<Tuple<int, RouteDescription>>>\r\n    {\r\n        /// <summary>\r\n        /// Gets a boolean value that indicates of the cache is empty or not.\r\n        /// </summary>\r\n        /// <returns><see langword=\"true\"/> if the cache is empty, otherwise <see langword=\"false\"/>.</returns>\r\n        bool IsEmpty();\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Routing/IRouteCacheProvider.cs",
    "content": "﻿namespace Nancy.Routing\r\n{\r\n    /// <summary>\r\n    /// It's not safe for a module to take a dependency on the cache (cyclic dependency)\r\n    ///\r\n    /// We provide an <see cref=\"IRouteCacheProvider\"/> instead.\r\n    ///\r\n    /// It is *not* safe to call GetCache() inside a NancyModule constructor, although that shouldn't be necessary anyway.\r\n    /// </summary>\r\n    public interface IRouteCacheProvider\r\n    {\r\n        /// <summary>\r\n        /// Gets an instance of the route cache.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IRouteCache\"/> instance.</returns>\r\n        IRouteCache GetCache();\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Routing/IRouteDescriptionProvider.cs",
    "content": "﻿namespace Nancy.Routing\r\n{\r\n    /// <summary>\r\n    /// Defines the functionality for retrieving a description for a specific route.\r\n    /// </summary>\r\n    public interface IRouteDescriptionProvider\r\n    {\r\n        /// <summary>\r\n        /// Get the description for a route.\r\n        /// </summary>\r\n        /// <param name=\"module\">The module that the route is defined in.</param>\r\n        /// <param name=\"path\">The path of the route that the description should be retrieved for.</param>\r\n        /// <returns>A <see cref=\"string\"/> containing the description of the route if it could be found, otherwise <see cref=\"string.Empty\"/>.</returns>\r\n        string GetDescription(INancyModule module, string path);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/IRouteInvoker.cs",
    "content": "﻿namespace Nancy.Routing\r\n{\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality for invoking a <see cref=\"Route\"/> and returning a <see cref=\"Response\"/>\r\n    /// </summary>\r\n    public interface IRouteInvoker\r\n    {\r\n        /// <summary>\r\n        /// Invokes the specified <paramref name=\"route\"/> with the provided <paramref name=\"parameters\"/>.\r\n        /// </summary>\r\n        /// <param name=\"route\">The route that should be invoked.</param>\r\n        /// <param name=\"cancellationToken\">Cancellation token</param>\r\n        /// <param name=\"parameters\">The parameters that the route should be invoked with.</param>\r\n        /// <param name=\"context\">The context of the route that is being invoked.</param>\r\n        /// <returns>A <see cref=\"Response\"/> instance that represents the result of the invoked route.</returns>\r\n        Task<Response> Invoke(Route route, CancellationToken cancellationToken, DynamicDictionary parameters, NancyContext context);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/IRouteMetadataProvider.cs",
    "content": "namespace Nancy.Routing\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality for retrieving metadata for routes.\r\n    /// </summary>\r\n    public interface IRouteMetadataProvider\r\n    {\r\n        /// <summary>\r\n        /// Gets the <see cref=\"Type\"/> of the metadata that is created by the provider.\r\n        /// </summary>\r\n        /// <param name=\"module\">The <see cref=\"INancyModule\"/> instance that the route is declared in.</param>\r\n        /// <param name=\"routeDescription\">A <see cref=\"RouteDescription\"/> for the route.</param>\r\n        /// <returns>A <see cref=\"Type\"/> instance, or <see langword=\"null\" /> if nothing is found.</returns>\r\n        Type GetMetadataType(INancyModule module, RouteDescription routeDescription);\r\n\r\n        /// <summary>\r\n        /// Gets the metadata for the provided route.\r\n        /// </summary>\r\n        /// <param name=\"module\">The <see cref=\"INancyModule\"/> instance that the route is declared in.</param>\r\n        /// <param name=\"routeDescription\">A <see cref=\"RouteDescription\"/> for the route.</param>\r\n        /// <returns>An object representing the metadata for the given route, or <see langword=\"null\" /> if nothing is found.</returns>\r\n        object GetMetadata(INancyModule module, RouteDescription routeDescription);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/IRouteResolver.cs",
    "content": "﻿namespace Nancy.Routing\r\n{\r\n    /// <summary>\r\n    /// Returns a route that matches the request\r\n    /// </summary>\r\n    public interface IRouteResolver\r\n    {\r\n        /// <summary>\r\n        /// Gets the route, and the corresponding parameter dictionary from the URL\r\n        /// </summary>\r\n        /// <param name=\"context\">Current context</param>\r\n        /// <returns>A <see cref=\"ResolveResult\"/> containing the resolved route information.</returns>\r\n        ResolveResult Resolve(NancyContext context);\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Routing/IRouteSegmentExtractor.cs",
    "content": "namespace Nancy.Routing\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality for extracting the individual segments from a route path.\r\n    /// </summary>\r\n    public interface IRouteSegmentExtractor\r\n    {\r\n        /// <summary>\r\n        /// Extracts the segments from the <paramref name=\"path\"/>;\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that the segments should be extracted from.</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/>, containing the extracted segments.</returns>\r\n        IEnumerable<string> Extract(string path);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/MethodNotAllowedRoute.cs",
    "content": "﻿namespace Nancy.Routing\r\n{\r\n    using System.Collections.Generic;\r\n    using System.Threading.Tasks;\r\n\r\n    /// <summary>\r\n    /// Route that is returned when the path could be matched but it was for the wrong request method.\r\n    /// </summary>\r\n    /// <remarks>This is equal to sending back the 405 HTTP status code.</remarks>\r\n    public class MethodNotAllowedRoute : Route<Response>\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"MethodNotAllowedRoute\"/> type, for the\r\n        /// specified <paramref name=\"path\"/>, <paramref name=\"method\"/> and <paramref name=\"allowedMethods\"/>.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path of the route.</param>\r\n        /// <param name=\"method\">The HTTP method of the route.</param>\r\n        /// <param name=\"allowedMethods\">The HTTP methods that can be used to invoke the route.</param>\r\n        public MethodNotAllowedRoute(string path, string method, IEnumerable<string> allowedMethods)\r\n            : base(method, path, null, (x,c) => CreateMethodNotAllowedResponse(allowedMethods))\r\n        {\r\n        }\r\n\r\n        private static Task<Response> CreateMethodNotAllowedResponse(IEnumerable<string> allowedMethods)\r\n        {\r\n            var response = new Response();\r\n            response.Headers[\"Allow\"] = string.Join(\", \", allowedMethods);\r\n            response.StatusCode = HttpStatusCode.MethodNotAllowed;\r\n\r\n            return Task.FromResult(response);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/NotFoundRoute.cs",
    "content": "﻿namespace Nancy.Routing\r\n{\r\n    using System.Threading.Tasks;\r\n\r\n    /// <summary>\r\n    /// Route that is returned when the path could not be matched.\r\n    /// </summary>\r\n    /// <remarks>This is equal to sending back the 404 HTTP status code.</remarks>\r\n    public class NotFoundRoute : Route<Response>\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NotFoundRoute\"/> type, for the\r\n        /// specified <paramref name=\"path\"/> and <paramref name=\"method\"/>.\r\n        /// </summary>\r\n        /// <param name=\"method\">The HTTP method of the route.</param>\r\n        /// <param name=\"path\">The path of the route.</param>\r\n        public NotFoundRoute(string method, string path)\r\n            : base(method, path, null, (x,c) => Task.FromResult<Response>(new NotFoundResponse()))\r\n        {\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/OptionsRoute.cs",
    "content": "﻿namespace Nancy.Routing\r\n{\r\n    using System.Collections.Generic;\r\n    using System.Threading.Tasks;\r\n\r\n    /// <summary>\r\n    /// Route that is returned when the path could be matched but, the method was OPTIONS and there was no user defined handler for OPTIONS.\r\n    /// </summary>\r\n    public class OptionsRoute : Route<Response>\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"OptionsRoute\"/> class, with\r\n        /// the provided <paramref name=\"path\"/> and <paramref name=\"allowedMethods\"/>.\r\n        /// </summary>\r\n        /// <param name=\"path\">The request path.</param>\r\n        /// <param name=\"allowedMethods\">The list of allowed methods.</param>\r\n        public OptionsRoute(string path, IEnumerable<string> allowedMethods)\r\n            : base(\"OPTIONS\", path, null, (x,c) => CreateMethodOptionsResponse(allowedMethods))\r\n        {\r\n        }\r\n\r\n        private static Task<Response> CreateMethodOptionsResponse(IEnumerable<string> allowedMethods)\r\n        {\r\n            var response = new Response();\r\n            response.Headers[\"Allow\"] = string.Join(\", \", allowedMethods);\r\n            response.StatusCode = HttpStatusCode.OK;\r\n\r\n            return Task.FromResult(response);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/ParameterSegmentInformation.cs",
    "content": "﻿namespace Nancy.Routing\r\n{\r\n    /// <summary>\r\n    /// Information about a segment parameter.\r\n    /// </summary>\r\n    public class ParameterSegmentInformation\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ParameterSegmentInformation\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"name\">The name of the parameter</param>\r\n        /// <param name=\"defaultValue\">The default value, if any, of the parameter.</param>\r\n        /// <param name=\"isOptional\"><see langword=\"true\"/> if the parameter is optional, otherwise <see langword=\"false\" />.</param>\r\n        public ParameterSegmentInformation(string name, string defaultValue, bool isOptional)\r\n        {\r\n            this.Name = name;\r\n            this.DefaultValue = defaultValue;\r\n            this.IsOptional = isOptional;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the default value for the parameter.\r\n        /// </summary>\r\n        public string DefaultValue { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the full name of the segment.\r\n        /// </summary>\r\n        /// <remarks>Returns a string in one of the formats: {name}, {name?}, {name?defaultValue} depending on the kind of parameter.</remarks>\r\n        public string FullSegmentName\r\n        {\r\n            get\r\n            {\r\n                return (this.IsOptional) ?\r\n                    string.Concat(this.Name, \"?\", this.DefaultValue) :\r\n                    this.Name;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets whether or not the parameter is optional.\r\n        /// </summary>\r\n        /// <value><see langword=\"true\"/> if the parameter is optional, otherwise <see langword=\"false\" />.</value>\r\n        public bool IsOptional { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the name of the parameter.\r\n        /// </summary>\r\n        public string Name { get; private set; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/ResolveResult.cs",
    "content": "﻿namespace Nancy.Routing\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// A class representing a route resolution result\r\n    /// </summary>\r\n    public class ResolveResult\r\n    {\r\n        /// <summary>\r\n        /// Gets or sets the route\r\n        /// </summary>\r\n        public Route Route { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the captured parameters\r\n        /// </summary>\r\n        public DynamicDictionary Parameters { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the before module pipeline\r\n        /// </summary>\r\n        public BeforePipeline Before { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the after module pipeline\r\n        /// </summary>\r\n        public AfterPipeline After { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the on error module pipeline\r\n        /// </summary>\r\n        public Func<NancyContext, Exception, dynamic> OnError { get; set; }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ResolveResult\"/> class.\r\n        /// </summary>\r\n        public ResolveResult()\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ResolveResult\"/> class, with\r\n        /// the provided <paramref name=\"route\"/>, <paramref name=\"parameters\"/>, <paramref name=\"before\"/>, \r\n        /// <paramref name=\"after\"/> and <paramref name=\"onError\"/>.\r\n        /// </summary>\r\n        /// <param name=\"route\">The request route instance.</param>\r\n        /// <param name=\"parameters\">The parameters.</param>\r\n        /// <param name=\"before\">The before pipeline instance</param>\r\n        /// <param name=\"after\">The after pipeline instace.</param>\r\n        /// <param name=\"onError\">The on error interceptor instance.</param>\r\n        public ResolveResult(Route route, DynamicDictionary parameters, BeforePipeline before, AfterPipeline after, Func<NancyContext, Exception, dynamic> onError)\r\n        {\r\n            this.Route = route;\r\n            this.Parameters = parameters;\r\n            this.Before = before;\r\n            this.After = after;\r\n            this.OnError = onError;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Route.cs",
    "content": "﻿namespace Nancy.Routing\r\n{\r\n    using System;\r\n    using System.Diagnostics;\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n\r\n    /// <summary>\r\n    /// Defines the core functionality of a route.\r\n    /// </summary>\r\n    public abstract class Route\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"Route\"/> type, with the specified <see cref=\"RouteDescription\"/>.\r\n        /// </summary>\r\n        /// <param name=\"description\">An <see cref=\"RouteDescription\"/> instance.</param>\r\n        protected Route(RouteDescription description)\r\n        {\r\n            this.Description = description;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"Route{T}\"/> type, with the specified definition.\r\n        /// </summary>\r\n        /// <param name=\"name\">Route name</param>\r\n        /// <param name=\"method\">The HTTP method that the route is declared for.</param>\r\n        /// <param name=\"path\">The path that the route is declared for.</param>\r\n        /// <param name=\"condition\">A condition that needs to be satisfied inorder for the route to be eligible for invocation.</param>\r\n        /// <param name=\"returnType\">The <see cref=\"Type\"/> of the value returned by the route.</param>\r\n        protected Route(string name, string method, string path, Func<NancyContext, bool> condition, Type returnType)\r\n            : this(new RouteDescription(name, method, path, condition, returnType))\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the description of the route.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"RouteDescription\"/> instance.</value>\r\n        public RouteDescription Description { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Invokes the route with the provided <paramref name=\"parameters\"/>.\r\n        /// </summary>\r\n        /// <param name=\"parameters\">A <see cref=\"DynamicDictionary\"/> that contains the parameters that should be passed to the route.</param>\r\n        /// <param name=\"cancellationToken\">Cancellation token</param>\r\n        /// <returns>The value that was produced by the route.</returns>\r\n        public abstract Task<object> Invoke(DynamicDictionary parameters, CancellationToken cancellationToken);\r\n    }\r\n\r\n    /// <summary>\r\n    /// Stores information about a declared route in Nancy.\r\n    /// </summary>\r\n    [DebuggerDisplay(\"{Description.DebuggerDisplay, nq}\")]\r\n    public class Route<T> : Route\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"Route{T}\"/> type, with the specified <see cref=\"RouteDescription\"/>.\r\n        /// </summary>\r\n        /// <param name=\"description\"></param>\r\n        /// <param name=\"action\">The action that should take place when the route is invoked.</param>\r\n        public Route(RouteDescription description, Func<object, CancellationToken, Task<T>> action)\r\n            : base(description)\r\n        {\r\n            this.Action = action;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"Route{T}\"/> type, with the specified definition.\r\n        /// </summary>\r\n        /// <param name=\"name\">Route name</param>\r\n        /// <param name=\"method\">The HTTP method that the route is declared for.</param>\r\n        /// <param name=\"path\">The path that the route is declared for.</param>\r\n        /// <param name=\"condition\">A condition that needs to be satisfied inorder for the route to be eligible for invocation.</param>\r\n        /// <param name=\"action\">The action that should take place when the route is invoked.</param>\r\n        public Route(string name, string method, string path, Func<NancyContext, bool> condition, Func<object, CancellationToken, Task<T>> action)\r\n            : this(new RouteDescription(name, method, path, condition, typeof(T)), action)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"Route{T}\"/> type, with the specified definition.\r\n        /// </summary>\r\n        /// <param name=\"method\">The HTTP method that the route is declared for.</param>\r\n        /// <param name=\"path\">The path that the route is declared for.</param>\r\n        /// <param name=\"condition\">A condition that needs to be satisfied inorder for the route to be eligiable for invocation.</param>\r\n        /// <param name=\"action\">The action that should take place when the route is invoked.</param>\r\n        public Route(string method, string path, Func<NancyContext, bool> condition, Func<object, CancellationToken, Task<T>> action)\r\n            : this(string.Empty, method, path, condition, action)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the action that should take place when the route is invoked.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"Func{T,K}\"/> that represents the action of the route.</value>\r\n        public Func<object, CancellationToken, Task<T>> Action { get; set; }\r\n\r\n        /// <summary>\r\n        /// Invokes the route with the provided <paramref name=\"parameters\"/>.\r\n        /// </summary>\r\n        /// <param name=\"parameters\">A <see cref=\"DynamicDictionary\"/> that contains the parameters that should be passed to the route.</param>\r\n        /// <param name=\"cancellationToken\">Cancellation token</param>\r\n        /// <returns>A (hot) task of <see cref=\"Response\"/> instance.</returns>\r\n        public override async Task<object> Invoke(DynamicDictionary parameters, CancellationToken cancellationToken)\r\n        {\r\n            return await this.Action.Invoke(parameters, cancellationToken).ConfigureAwait(false); \r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Routing/RouteCache.cs",
    "content": "﻿namespace Nancy.Routing\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    using Nancy.Culture;\r\n\r\n    /// <summary>\r\n    /// Caches information about all the available routes that was discovered by the bootstrapper.\r\n    /// </summary>\r\n    public class RouteCache : Dictionary<Type, List<Tuple<int, RouteDescription>>>, IRouteCache\r\n    {\r\n        private readonly IRouteSegmentExtractor routeSegmentExtractor;\r\n        private readonly IRouteDescriptionProvider routeDescriptionProvider;\r\n        private readonly IEnumerable<IRouteMetadataProvider> routeMetadataProviders;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"RouteCache\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"moduleCatalog\">The <see cref=\"INancyModuleCatalog\"/> that should be used by the cache.</param>\r\n        /// <param name=\"contextFactory\">The <see cref=\"INancyContextFactory\"/> that should be used to create a context instance.</param>\r\n        /// <param name=\"routeSegmentExtractor\"> </param>\r\n        /// <param name=\"cultureService\"></param>\r\n        /// <param name=\"routeMetadataProviders\"></param>\r\n        /// <param name=\"routeDescriptionProvider\"></param>\r\n        public RouteCache(\r\n            INancyModuleCatalog moduleCatalog,\r\n            INancyContextFactory contextFactory,\r\n            IRouteSegmentExtractor routeSegmentExtractor,\r\n            IRouteDescriptionProvider routeDescriptionProvider,\r\n            ICultureService cultureService,\r\n            IEnumerable<IRouteMetadataProvider> routeMetadataProviders)\r\n        {\r\n            this.routeSegmentExtractor = routeSegmentExtractor;\r\n            this.routeDescriptionProvider = routeDescriptionProvider;\r\n            this.routeMetadataProviders = routeMetadataProviders;\r\n\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n\r\n            using (var context = contextFactory.Create(request))\r\n            {\r\n                this.BuildCache(moduleCatalog.GetAllModules(context));\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a boolean value that indicates of the cache is empty or not.\r\n        /// </summary>\r\n        /// <returns><see langword=\"true\"/> if the cache is empty, otherwise <see langword=\"false\"/>.</returns>\r\n        public bool IsEmpty()\r\n        {\r\n            return !this.Values.SelectMany(r => r).Any();\r\n        }\r\n\r\n        private void BuildCache(IEnumerable<INancyModule> modules)\r\n        {\r\n            foreach (var module in modules)\r\n            {\r\n                var moduleType = module.GetType();\r\n\r\n                var routes =\r\n                    module.Routes.Select(r => r.Description).ToArray();\r\n\r\n                foreach (var routeDescription in routes)\r\n                {\r\n                    routeDescription.Description = this.routeDescriptionProvider.GetDescription(module, routeDescription.Path);\r\n                    routeDescription.Segments = this.routeSegmentExtractor.Extract(routeDescription.Path).ToArray();\r\n                    routeDescription.Metadata = this.GetRouteMetadata(module, routeDescription);\r\n                }\r\n\r\n                this.AddRoutesToCache(routes, moduleType);\r\n            }\r\n        }\r\n\r\n        private RouteMetadata GetRouteMetadata(INancyModule module, RouteDescription routeDescription)\r\n        {\r\n            var data = new Dictionary<Type, object>();\r\n\r\n            foreach (var provider in this.routeMetadataProviders)\r\n            {\r\n                var type = provider.GetMetadataType(module, routeDescription);\r\n                var metadata = provider.GetMetadata(module, routeDescription);\r\n\r\n                if (type != null && metadata != null)\r\n                {\r\n                    data.Add(type, metadata);\r\n                }\r\n            }\r\n\r\n            return new RouteMetadata(data);\r\n        }\r\n\r\n        private void AddRoutesToCache(IEnumerable<RouteDescription> routes, Type moduleType)\r\n        {\r\n            List<Tuple<int, RouteDescription>> routeDescriptions;\r\n            if (!this.TryGetValue(moduleType, out routeDescriptions))\r\n            {\r\n                routeDescriptions = new List<Tuple<int, RouteDescription>>();\r\n                this[moduleType] = routeDescriptions;\r\n            }\r\n\r\n            routeDescriptions.AddRange(routes.Select((r, i) => new Tuple<int, RouteDescription>(i, r)));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Routing/RouteCacheExtensions.cs",
    "content": "namespace Nancy.Routing\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Contains extensions for the <see cref=\"IRouteCache\"/> type.\r\n    /// </summary>\r\n    public static class RouteCacheExtensions\r\n    {\r\n        /// <summary>\r\n        /// Retrieves metadata for all declared routes.\r\n        /// </summary>\r\n        /// <typeparam name=\"TMetadata\">The type of the metadata to retrieve.</typeparam>\r\n        /// <param name=\"cache\">The <see cref=\"IRouteCache\"/> to retrieve the metadata.</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> containing instances of the <typeparamref name=\"TMetadata\"/> type.</returns>\r\n        public static IEnumerable<TMetadata> RetrieveMetadata<TMetadata>(this IDictionary<Type, List<Tuple<int, RouteDescription>>> cache)\r\n        {\r\n            return cache.Values.SelectMany(x => x.Select(y => y.Item2.Metadata.Retrieve<TMetadata>()));\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/RouteDescription.cs",
    "content": "namespace Nancy.Routing\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Diagnostics;\r\n    using System.Linq;\r\n    using System.Text;\r\n\r\n    /// <summary>\r\n    /// Represents the various parts of a route lambda.\r\n    /// </summary>\r\n    [DebuggerDisplay(\"{DebuggerDisplay, nq}\")]\r\n    public sealed class RouteDescription\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"RouteDescription\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"name\">Route name</param>\r\n        /// <param name=\"method\">The request method of the route.</param>\r\n        /// <param name=\"path\">The path that the route will be invoked for.</param>\r\n        /// <param name=\"condition\">The condition that has to be fulfilled for the route to be a valid match.</param>\r\n        /// <param name=\"returnType\">The <see cref=\"Type\"/> of the value returned by the route.</param>\r\n        public RouteDescription(string name, string method, string path, Func<NancyContext, bool> condition, Type returnType)\r\n        {\r\n            if (string.IsNullOrEmpty(method))\r\n            {\r\n                throw new ArgumentException(\"Method must be specified\", \"method\");\r\n            }\r\n\r\n            if (string.IsNullOrEmpty(path))\r\n            {\r\n                throw new ArgumentException(\"Path must be specified\", \"path\");\r\n            }\r\n\r\n            this.Name = name ?? string.Empty;\r\n            this.Method = method;\r\n            this.Path = path;\r\n            this.Condition = condition;\r\n            this.ReturnType = returnType;\r\n        }\r\n\r\n        /// <summary>\r\n        /// The name of the route\r\n        /// </summary>\r\n        public string Name { get; set; }\r\n\r\n        /// <summary>\r\n        /// The condition that has to be fulfilled inorder for the route to be a valid match.\r\n        /// </summary>\r\n        /// <value>A function that evaluates the condition when a <see cref=\"NancyContext\"/> instance is passed in.</value>\r\n        public Func<NancyContext, bool> Condition { get; private set; }\r\n\r\n        /// <summary>\r\n        /// The description of what the route is for.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the description of the route.</value>\r\n        public string Description { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the metadata information for a route.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"RouteMetadata\"/> instance.</value>\r\n        public RouteMetadata Metadata { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets the method of the route.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the method of the route.</value>\r\n        public string Method { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the path that the route will be invoked for.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the path of the route.</value>\r\n        public string Path { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets or set the segments, for the route, that was returned by the <see cref=\"IRouteSegmentExtractor\"/>.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/>, containing the segments for the route.</value>\r\n        public IEnumerable<string> Segments { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"Type\"/> of the value returned by the route.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"Type\"/> instance.</value>\r\n        public Type ReturnType { get; private set; }\r\n\r\n        private string DebuggerDisplay\r\n        {\r\n            get\r\n            {\r\n                var builder = new StringBuilder();\r\n\r\n                if (!string.IsNullOrEmpty(this.Name))\r\n                {\r\n                    builder.AppendFormat(\"{0} - \", this.Name);\r\n                }\r\n\r\n                builder.AppendFormat(\"{0} {1}\", this.Method, this.Path);\r\n\r\n                return builder.ToString();\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/RouteMetadata.cs",
    "content": "namespace Nancy.Routing\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Stores metadata created by <see cref=\"IRouteMetadataProvider\"/> instances.\r\n    /// </summary>\r\n    public class RouteMetadata\r\n    {\r\n        /// <summary>\r\n        /// Creates a new instance of the <see cref=\"RouteMetadata\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"metadata\">An <see cref=\"IDictionary{TKey,TValue}\"/> containing the metadata, organised by the type that it is stored in.</param>\r\n        public RouteMetadata(IDictionary<Type, object> metadata)\r\n        {\r\n            this.Raw = metadata;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the raw metadata <see cref=\"IDictionary{TKey,TValue}\"/>.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IDictionary{TKey,TValue}\"/> instance.</value>\r\n        public IDictionary<Type, object> Raw { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets a boolean that indicates if the specific type of metadata is stored.\r\n        /// </summary>\r\n        /// <typeparam name=\"TMetadata\">The type of the metadata to check for.</typeparam>\r\n        /// <returns><see langword=\"true\"/> if metadata, of the requested type is stored, otherwise <see langword=\"false\"/>.</returns>\r\n        public bool Has<TMetadata>()\r\n        {\r\n            return this.Raw.ContainsKey(typeof (TMetadata));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Retrieves metadata of the provided type.\r\n        /// </summary>\r\n        /// <typeparam name=\"TMetadata\">The type of the metadata to retrieve.</typeparam>\r\n        /// <returns>The metadata instance if available, otherwise <see langword=\"null\"/>.</returns>\r\n        public TMetadata Retrieve<TMetadata>()\r\n        {\r\n            var key = typeof(TMetadata);\r\n            object value;\r\n            return this.Raw.TryGetValue(key, out value) ?\r\n                (TMetadata)value :\r\n                default(TMetadata);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Routing/RouteMetadataProvider.cs",
    "content": "namespace Nancy.Routing\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality for retrieving metadata for routes.\r\n    /// </summary>\r\n    /// <typeparam name=\"TMetadata\">The metadata type.</typeparam>\r\n    public abstract class RouteMetadataProvider<TMetadata> : IRouteMetadataProvider\r\n    {\r\n        /// <summary>\r\n        /// Gets the <see cref=\"Type\"/> of the metadata that is created by the provider.\r\n        /// </summary>\r\n        /// <param name=\"module\">The <see cref=\"INancyModule\"/> instance that the route is declared in.</param>\r\n        /// <param name=\"routeDescription\">A <see cref=\"RouteDescription\"/> for the route.</param>\r\n        /// <returns>A <see cref=\"Type\"/> instance, or null if none are found.</returns>\r\n        public Type GetMetadataType(INancyModule module, RouteDescription routeDescription)\r\n        {\r\n            return typeof(TMetadata);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the metadata for the provided route.\r\n        /// </summary>\r\n        /// <param name=\"module\">The <see cref=\"INancyModule\" /> instance that the route is declared in.</param>\r\n        /// <param name=\"routeDescription\">A <see cref=\"RouteDescription\" /> for the route.</param>\r\n        /// <returns>An instance of <typeparamref name=\"TMetadata\"/>.</returns>\r\n        public object GetMetadata(INancyModule module, RouteDescription routeDescription)\r\n        {\r\n            return this.GetRouteMetadata(module, routeDescription);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the metadata for the provided route.\r\n        /// </summary>\r\n        /// <param name=\"module\">The <see cref=\"INancyModule\"/> instance that the route is declared in.</param>\r\n        /// <param name=\"routeDescription\">A <see cref=\"RouteDescription\"/> for the route.</param>\r\n        /// <returns>An instance of <typeparamref name=\"TMetadata\"/>.</returns>\r\n        protected abstract TMetadata GetRouteMetadata(INancyModule module, RouteDescription routeDescription);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Trie/IRouteResolverTrie.cs",
    "content": "namespace Nancy.Routing.Trie\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Trie structure for resolving routes\r\n    /// </summary>\r\n    public interface IRouteResolverTrie\r\n    {\r\n        /// <summary>\r\n        /// Build the trie from the route cache\r\n        /// </summary>\r\n        /// <param name=\"cache\">The route cache</param>\r\n        void BuildTrie(IRouteCache cache);\r\n\r\n        /// <summary>\r\n        /// Get all matches for the given method and path\r\n        /// </summary>\r\n        /// <param name=\"method\">HTTP method</param>\r\n        /// <param name=\"path\">Requested path</param>\r\n        /// <param name=\"context\">Current Nancy context</param>\r\n        /// <returns>An array of <see cref=\"MatchResult\"/> elements</returns>\r\n        MatchResult[] GetMatches(string method, string path, NancyContext context);\r\n\r\n        /// <summary>\r\n        /// Get all method options for the given path\r\n        /// </summary>\r\n        /// <param name=\"path\">Requested path</param>\r\n        /// <param name=\"context\">Current Nancy context</param>\r\n        /// <returns>A collection of strings, each representing an allowed method</returns>\r\n        IEnumerable<string> GetOptions(string path, NancyContext context);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Trie/ITrieNodeFactory.cs",
    "content": "namespace Nancy.Routing.Trie\r\n{\r\n    using Nancy.Routing.Trie.Nodes;\r\n\r\n    /// <summary>\r\n    /// Factory for creating trie nodes from route definition segments\r\n    /// </summary>\r\n    public interface ITrieNodeFactory\r\n    {\r\n        /// <summary>\r\n        /// Gets the correct Trie node type for the given segment\r\n        /// </summary>\r\n        /// <param name=\"parent\">Parent node</param>\r\n        /// <param name=\"segment\">Segment</param>\r\n        /// <returns>Corresponding TrieNode instance</returns>\r\n        TrieNode GetNodeForSegment(TrieNode parent, string segment);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Trie/MatchResult.cs",
    "content": "namespace Nancy.Routing.Trie\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Match result for a matched route\r\n    /// </summary>\r\n    public class MatchResult : NodeData, IComparable<MatchResult>\r\n    {\r\n        private static readonly MatchResult noMatch = new MatchResult();\r\n\r\n        private static readonly MatchResult[] noMatches = ArrayCache.Empty<MatchResult>();\r\n\r\n        /// <summary>\r\n        /// Gets or sets the captured parameters\r\n        /// </summary>\r\n        public IDictionary<string, object> Parameters { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets the \"no match\" <see cref=\"MatchResult\"/>\r\n        /// </summary>\r\n        public static MatchResult NoMatch\r\n        {\r\n            get\r\n            {\r\n                return noMatch;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the \"no matches\" <see cref=\"MatchResult\"/> collection\r\n        /// </summary>\r\n        public static MatchResult[] NoMatches\r\n        {\r\n            get\r\n            {\r\n                return noMatches;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"MatchResult\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"parameters\">The parameters.</param>\r\n        public MatchResult(IDictionary<string, object> parameters)\r\n        {\r\n            this.Parameters = parameters;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"MatchResult\"/> class.\r\n        /// </summary>\r\n        public MatchResult()\r\n            : this(new Dictionary<string, object>())\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Compares the current object with another object of the same type.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// A value that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name=\"other\"/> parameter.Zero This object is equal to <paramref name=\"other\"/>. Greater than zero This object is greater than <paramref name=\"other\"/>. \r\n        /// </returns>\r\n        /// <param name=\"other\">An object to compare with this object.</param>\r\n        public int CompareTo(MatchResult other)\r\n        {\r\n            // Length of the route takes precedence over score\r\n            if (this.RouteLength < other.RouteLength)\r\n            {\r\n                return -1;\r\n            }\r\n\r\n            if (this.RouteLength > other.RouteLength)\r\n            {\r\n                return 1;\r\n            }\r\n\r\n            if (this.Score < other.Score)\r\n            {\r\n                return -1;\r\n            }\r\n\r\n            if (this.Score > other.Score)\r\n            {\r\n                return 1;\r\n            }\r\n\r\n            if (Equals(this.ModuleType, other.ModuleType))\r\n            {\r\n                if (this.RouteIndex < other.RouteIndex)\r\n                {\r\n                    return -1;\r\n                }\r\n\r\n                if (this.RouteIndex > other.RouteIndex)\r\n                {\r\n                    return 1;\r\n                }\r\n            }\r\n\r\n            return 0;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Trie/NodeData.cs",
    "content": "namespace Nancy.Routing.Trie\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Represents a route that ends at a particular node.\r\n    /// We store/calculate as much as we can at build time to save\r\n    /// time during route matching.\r\n    /// </summary>\r\n    public class NodeData\r\n    {\r\n        /// <summary>\r\n        /// Gets or sets the module type from the matching module\r\n        /// </summary>\r\n        public Type ModuleType { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the route method\r\n        /// </summary>\r\n        public string Method { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the index in the module routing table\r\n        /// </summary>\r\n        public int RouteIndex { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the number of segments in the route\r\n        /// </summary>\r\n        public int RouteLength { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the route score\r\n        /// </summary>\r\n        public int Score { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the route condition delegate\r\n        /// </summary>\r\n        public Func<NancyContext, bool> Condition { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Trie/NodeDataExtensions.cs",
    "content": "﻿namespace Nancy.Routing.Trie\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Helpers methods for NodeData\r\n    /// </summary>\r\n    public static class NodeDataExtensions\r\n    {\r\n        /// <summary>\r\n        /// Converts a <see cref=\"NodeData\"/> instance into a <see cref=\"MatchResult\"/>\r\n        /// </summary>\r\n        /// <param name=\"data\">Node data</param>\r\n        /// <param name=\"parameters\">Captured parameters</param>\r\n        /// <returns>A <see cref=\"MatchResult\"/> instance</returns>\r\n        public static MatchResult ToResult(this NodeData data, IDictionary<string, object> parameters)\r\n        {\r\n            return new MatchResult(parameters)\r\n            {\r\n                ModuleType = data.ModuleType,\r\n                Method = data.Method,\r\n                RouteIndex = data.RouteIndex,\r\n                RouteLength = data.RouteLength,\r\n                Condition = data.Condition,\r\n                Score = data.Score\r\n            };\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Trie/Nodes/CaptureNode.cs",
    "content": "namespace Nancy.Routing.Trie.Nodes\r\n{\r\n    /// <summary>\r\n    /// A node for standard captures e.g. {foo}\r\n    /// </summary>\r\n    public class CaptureNode : TrieNode\r\n    {\r\n        private string parameterName;\r\n\r\n        /// <summary>\r\n        /// Score for this node\r\n        /// </summary>\r\n        public override int Score\r\n        {\r\n            get { return 1000; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"CaptureNode\"/> class, with\r\n        /// the provided <paramref name=\"parent\"/>, <paramref name=\"segment\"/> and <paramref name=\"nodeFactory\"/>.\r\n        /// </summary>\r\n        /// <param name=\"parent\">Parent node</param>\r\n        /// <param name=\"segment\">Segment of the route definition</param>\r\n        /// <param name=\"nodeFactory\">Factory for creating new nodes</param>\r\n        public CaptureNode(TrieNode parent, string segment, ITrieNodeFactory nodeFactory)\r\n            : base(parent, segment, nodeFactory)\r\n        {\r\n            this.ExtractParameterName();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Matches the segment for a requested route\r\n        /// </summary>\r\n        /// <param name=\"segment\">Segment string</param>\r\n        /// <returns>A <see cref=\"SegmentMatch\"/> instance representing the result of the match</returns>\r\n        public override SegmentMatch Match(string segment)\r\n        {\r\n            var match = new SegmentMatch(true);\r\n            match.CapturedParameters.Add(this.parameterName, segment);\r\n            return match;\r\n        }\r\n\r\n        private void ExtractParameterName()\r\n        {\r\n            this.parameterName = this.RouteDefinitionSegment.Trim('{', '}');\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Trie/Nodes/CaptureNodeWithConstraint.cs",
    "content": "﻿namespace Nancy.Routing.Trie.Nodes\r\n{\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    using Nancy.Routing.Constraints;\r\n\r\n    /// <summary>\r\n    /// A node for constraint captures e.g. {foo:alpha}, {foo:datetime}\r\n    /// </summary>\r\n    public class CaptureNodeWithConstraint : TrieNode\r\n    {\r\n        private readonly IEnumerable<IRouteSegmentConstraint> routeSegmentConstraints;\r\n        private string parameterName;\r\n        private string constraint;\r\n\r\n        /// <summary>\r\n        /// Score for this node\r\n        /// </summary>\r\n        public override int Score\r\n        {\r\n            get { return 2000; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"CaptureNodeWithConstraint\"/> class, with\r\n        /// the provided <paramref name=\"parent\"/>, <paramref name=\"segment\"/> and <paramref name=\"nodeFactory\"/>.\r\n        /// </summary>\r\n        /// <param name=\"parent\">The parent.</param>\r\n        /// <param name=\"segment\">The segment.</param>\r\n        /// <param name=\"nodeFactory\">The node factory.</param>\r\n        /// <param name=\"routeSegmentConstraints\">The route segment constraints.</param>\r\n        public CaptureNodeWithConstraint(TrieNode parent, string segment, ITrieNodeFactory nodeFactory, IEnumerable<IRouteSegmentConstraint> routeSegmentConstraints)\r\n            : base(parent, segment, nodeFactory)\r\n        {\r\n            this.routeSegmentConstraints = routeSegmentConstraints;\r\n            this.ExtractParameterName();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Matches the segment for a requested route\r\n        /// </summary>\r\n        /// <param name=\"segment\">Segment string</param>\r\n        /// <returns>A <see cref=\"SegmentMatch\"/> instance representing the result of the match</returns>\r\n        public override SegmentMatch Match(string segment)\r\n        {\r\n            var routeSegmentConstraint = routeSegmentConstraints.FirstOrDefault(x => x.Matches(constraint));\r\n            if (routeSegmentConstraint == null)\r\n            {\r\n                return SegmentMatch.NoMatch;\r\n            }\r\n\r\n            return routeSegmentConstraint.GetMatch(this.constraint, segment, this.parameterName);\r\n        }\r\n\r\n        private void ExtractParameterName()\r\n        {\r\n            var segmentSplit = this.RouteDefinitionSegment.Trim('{', '}').Split(':');\r\n\r\n            this.parameterName = segmentSplit[0];\r\n            this.constraint = segmentSplit[1];\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Routing/Trie/Nodes/CaptureNodeWithDefaultValue.cs",
    "content": "namespace Nancy.Routing.Trie.Nodes\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// A capture node with a default value e.g. {foo?default}\r\n    /// </summary>\r\n    public class CaptureNodeWithDefaultValue : CaptureNode\r\n    {\r\n        private string parameterName;\r\n\r\n        private string defaultValue;\r\n\r\n        /// <summary>\r\n        /// Score for this node\r\n        /// </summary>\r\n        public override int Score\r\n        {\r\n            get { return 1000; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"CaptureNodeWithDefaultValue\"/> class, with\r\n        /// the provided <paramref name=\"parent\"/>, <paramref name=\"segment\"/> and <paramref name=\"nodeFactory\"/>.\r\n        /// </summary>\r\n        /// <param name=\"parent\">The parent.</param>\r\n        /// <param name=\"segment\">The segment.</param>\r\n        /// <param name=\"nodeFactory\">The node factory.</param>\r\n        public CaptureNodeWithDefaultValue(TrieNode parent, string segment, ITrieNodeFactory nodeFactory)\r\n            : base(parent, segment, nodeFactory)\r\n        {\r\n            this.ExtractParameterNameAndDefaultValue();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Add a new route to the trie\r\n        /// Adds itself as a normal capture node, but also sets a default capture\r\n        /// on the parent and adds this node's children as children of the parent\r\n        /// too (so it can effectively be \"skipped\" during matching)\r\n        /// </summary>\r\n        /// <param name=\"segments\">The segments of the route definition</param>\r\n        /// <param name=\"currentIndex\">Current index in the segments array</param>\r\n        /// <param name=\"currentScore\">Current score for this route</param>\r\n        /// <param name=\"nodeCount\">Number of nodes added for this route</param>\r\n        /// <param name=\"moduleType\">The module key the route comes from</param>\r\n        /// <param name=\"routeIndex\">The route index in the module</param>\r\n        /// <param name=\"routeDescription\">The route description</param>\r\n        public override void Add(string[] segments, int currentIndex, int currentScore, int nodeCount, Type moduleType, int routeIndex, RouteDescription routeDescription)\r\n        {\r\n            base.Add(segments, currentIndex, currentScore, nodeCount, moduleType, routeIndex, routeDescription);\r\n\r\n            this.Parent.AdditionalParameters[this.parameterName] = this.defaultValue;\r\n\r\n            // Keep the same index, reduce the node count and the score\r\n            this.Parent.Add(segments, currentIndex, currentScore - this.Parent.Score, nodeCount - 1, moduleType, routeIndex, routeDescription);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Matches the segment for a requested route\r\n        /// </summary>\r\n        /// <param name=\"segment\">Segment string</param>\r\n        /// <returns>A <see cref=\"SegmentMatch\"/> instance representing the result of the match</returns>\r\n        public override SegmentMatch Match(string segment)\r\n        {\r\n            var match = new SegmentMatch(true);\r\n            match.CapturedParameters[this.parameterName] = segment;\r\n            return match;\r\n        }\r\n\r\n        private void ExtractParameterNameAndDefaultValue()\r\n        {\r\n            var elements = this.RouteDefinitionSegment.Trim('{', '}').Split('?');\r\n\r\n            if (elements.Length != 2)\r\n            {\r\n                throw new InvalidOperationException(string.Format(\"Invalid capture route: {0}\", this.RouteDefinitionSegment));\r\n            }\r\n\r\n            this.parameterName = elements[0];\r\n            this.defaultValue = elements[1];\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Trie/Nodes/CaptureNodeWithMultipleParameters.cs",
    "content": "﻿namespace Nancy.Routing.Trie.Nodes\r\n{\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Text.RegularExpressions;\r\n\r\n    using Nancy.Routing.Constraints;\r\n\r\n    /// <summary>\r\n    /// A node multiple standard captures combined with a literal e.g. {id}.png.{thing}.{otherthing}\r\n    /// Captures parameters within segments that contain literals.\r\n    ///     i.e:\r\n    ///         /{file}.{name}\r\n    ///         /{file}.html\r\n    ///         /{major}.{minor}.{revision}B{build}\r\n    /// </summary>\r\n    public class CaptureNodeWithMultipleParameters : TrieNode\r\n    {\r\n        private static readonly Regex MatchRegex = new Regex(@\"({?[^{}]*}?)\", RegexOptions.Compiled);\r\n\r\n\r\n        private readonly List<string> parameterNames = new List<string>();\r\n        private readonly List<string> constraints = new List<string>();\r\n\r\n        private string builtRegex = string.Empty;\r\n        private IEnumerable<IRouteSegmentConstraint> routeSegmentConstraints;\r\n\r\n        private const string AssertStart = \"^\";\r\n        private const string MatchParameter = \"(.*)\";\r\n        private const string AssertEnd = \"$\";\r\n\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"CaptureNodeWithMultipleParameters\"/> class, with\r\n        /// the provided <paramref name=\"parent\"/>, <paramref name=\"segment\"/>, <paramref name=\"nodeFactory\"/> and <paramref name=\"routeSegmentConstraints\"/>.\r\n        /// </summary>\r\n        /// <param name=\"parent\">The parent node</param>\r\n        /// <param name=\"segment\">The segment to match upon</param>\r\n        /// <param name=\"nodeFactory\">The node factory.</param>\r\n        /// <param name=\"routeSegmentConstraints\">The route segment constraints.</param>\r\n        public CaptureNodeWithMultipleParameters(TrieNode parent, string segment, ITrieNodeFactory nodeFactory, IEnumerable<IRouteSegmentConstraint> routeSegmentConstraints)\r\n            : base(parent, segment, nodeFactory)\r\n        {\r\n            this.routeSegmentConstraints = routeSegmentConstraints;\r\n            this.ExtractParameterNames();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determines whether this TrieNode should be used for the given segment.\r\n        /// </summary>\r\n        /// <param name=\"segment\">The route segment</param>\r\n        /// <returns>a boolean</returns>\r\n        public static bool IsMatch(string segment)\r\n        {\r\n            return MatchRegex.Matches(segment).Cast<Group>().Count(g => g.Value != string.Empty) > 1;\r\n        }\r\n\r\n        private static bool IsParameterCapture(Capture match)\r\n        {\r\n            return match.Value.StartsWith(\"{\") && match.Value.EndsWith(\"}\");\r\n        }\r\n\r\n        /// <summary>\r\n        /// Score for this node\r\n        /// </summary>\r\n        public override int Score\r\n        {\r\n            get { return 100; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Matches the segment for a requested route\r\n        /// </summary>\r\n        /// <param name=\"segment\">Segment string</param>\r\n        /// <returns>A <see cref=\"SegmentMatch\"/> instance representing the result of the match</returns>\r\n        public override SegmentMatch Match(string segment)\r\n        {\r\n            var match = SegmentMatch.NoMatch;\r\n            var regex = new Regex(this.builtRegex, StaticConfiguration.CaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase);\r\n\r\n            if (regex.IsMatch(segment))\r\n            {\r\n                match = new SegmentMatch(true);\r\n                var regexMatch = regex.Match(segment);\r\n                for (var i = 1; i < regexMatch.Groups.Count; i++)\r\n                {\r\n                    match.CapturedParameters.Add(this.parameterNames[i - 1], regexMatch.Groups[i].Value);\r\n                    if (!string.IsNullOrEmpty(this.constraints[i - 1]))\r\n                    {\r\n                        var routeSegmentConstraint = this.routeSegmentConstraints.FirstOrDefault(x => x.Matches(constraints[i-1]));\r\n                        if (routeSegmentConstraint == null || !routeSegmentConstraint.GetMatch(this.constraints[i - 1], regexMatch.Groups[i].Value, this.parameterNames[i - 1]).Matches)\r\n                        {\r\n                            return SegmentMatch.NoMatch;\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n            return match;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Extracts the parameter name and the literals for the segment\r\n        /// </summary>\r\n        private void ExtractParameterNames()\r\n        {\r\n            var matches = MatchRegex.Matches(this.RouteDefinitionSegment);\r\n            this.BuildRegex(AssertStart);\r\n            foreach (Match match in matches)\r\n            {\r\n                if (IsParameterCapture(match))\r\n                {\r\n                    if (match.Value.Contains(\":\"))\r\n                    {\r\n                        var segmentSplit = match.Value.Trim('{', '}').Split(':');\r\n                        this.parameterNames.Add(segmentSplit[0]);\r\n                        this.constraints.Add(segmentSplit[1]);\r\n                    }\r\n                    else\r\n                    {\r\n                        this.parameterNames.Add(match.Value.Trim('{', '}'));\r\n                        this.constraints.Add(string.Empty);\r\n                    }\r\n                    this.BuildRegex(MatchParameter);\r\n                }\r\n                else\r\n                {\r\n                    this.BuildRegex(Regex.Escape(match.Value));\r\n                }\r\n            }\r\n            this.BuildRegex(AssertEnd);\r\n        }\r\n\r\n        private void BuildRegex(string regexSegment)\r\n        {\r\n            this.builtRegex += regexSegment;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Trie/Nodes/GreedyCaptureNode.cs",
    "content": "﻿namespace Nancy.Routing.Trie.Nodes\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Text;\r\n\r\n    /// <summary>\r\n    /// A greedy capture node e.g. {greedy*}\r\n    /// e.g. /foo/bar/{greedy*} - this node will be hit for /foo/bar/[anything that doesn't match another route], but\r\n    /// not for just /foo/bar\r\n    /// e.g. /foo/{greedy*}/bar - this node will be hit for /foo/[anything that doesn't match another route]/bar\r\n    /// </summary>\r\n    public class GreedyCaptureNode : TrieNode\r\n    {\r\n        private string parameterName;\r\n\r\n        /// <summary>\r\n        /// Score for this node\r\n        /// </summary>\r\n        public override int Score\r\n        {\r\n            get { return 0; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"GreedyCaptureNode\"/> class with\r\n        /// the provided <paramref name=\"parent\"/>, <paramref name=\"segment\"/> and <paramref name=\"nodeFactory\"/>.\r\n        /// </summary>\r\n        /// <param name=\"parent\">Parent node</param>\r\n        /// <param name=\"segment\">Segment of the route definition</param>\r\n        /// <param name=\"nodeFactory\">Factory for creating new nodes</param>\r\n        public GreedyCaptureNode(TrieNode parent, string segment, ITrieNodeFactory nodeFactory)\r\n            : base(parent, segment, nodeFactory)\r\n        {\r\n            this.GetParameterName();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all matches for a given requested route\r\n        /// Overridden to handle greedy capturing\r\n        /// </summary>\r\n        /// <param name=\"segments\">Requested route segments</param>\r\n        /// <param name=\"currentIndex\">Current index in the route segments</param>\r\n        /// <param name=\"capturedParameters\">Currently captured parameters</param>\r\n        /// <param name=\"context\">Current Nancy context</param>\r\n        /// <returns>A collection of <see cref=\"MatchResult\"/> objects</returns>\r\n        public override IEnumerable<MatchResult> GetMatches(string[] segments, int currentIndex, IDictionary<string, object> capturedParameters, NancyContext context)\r\n        {\r\n            var fullGreedy = this.GetFullGreedy(segments, currentIndex, capturedParameters);\r\n            if (!this.Children.Any())\r\n            {\r\n                return fullGreedy;\r\n            }\r\n\r\n            var sb = new StringBuilder(segments[currentIndex]);\r\n            var results = new List<MatchResult>();\r\n            currentIndex++;\r\n\r\n            while (!this.NoMoreSegments(segments, currentIndex - 1))\r\n            {\r\n                var currentSegment = segments[currentIndex];\r\n\r\n                TrieNode matchingChild;\r\n                if (this.Children.TryGetValue(currentSegment, out matchingChild))\r\n                {\r\n                    var parameters = new Dictionary<string, object>(capturedParameters);\r\n                    parameters[this.parameterName] = sb.ToString();\r\n                    results.AddRange(matchingChild.GetMatches(segments, currentIndex, parameters, context));\r\n                }\r\n\r\n                sb.AppendFormat(\"/{0}\", currentSegment);\r\n                currentIndex++;\r\n            }\r\n\r\n            if (!results.Any())\r\n            {\r\n                results.AddRange(fullGreedy);\r\n            }\r\n\r\n            return results;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Matches the segment for a requested route\r\n        /// Not-required or called for this node type\r\n        /// </summary>\r\n        /// <param name=\"segment\">Segment string</param>\r\n        /// <returns>A <see cref=\"SegmentMatch\"/> instance representing the result of the match</returns>\r\n        public override SegmentMatch Match(string segment)\r\n        {\r\n            throw new NotSupportedException();\r\n        }\r\n\r\n        private IEnumerable<MatchResult> GetFullGreedy(string[] segments, int currentIndex, IDictionary<string, object> capturedParameters)\r\n        {\r\n            if (!this.NodeData.Any())\r\n            {\r\n                return ArrayCache.Empty<MatchResult>();\r\n            }\r\n\r\n            var value = segments.Skip(currentIndex).Aggregate((seg1, seg2) => seg1 + \"/\" + seg2);\r\n            capturedParameters[this.parameterName] = value;\r\n\r\n            return this.NodeData.Select(nd => nd.ToResult(capturedParameters));\r\n        }\r\n\r\n        private void GetParameterName()\r\n        {\r\n            this.parameterName = this.RouteDefinitionSegment.Trim('{', '}').TrimEnd('*');\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Trie/Nodes/GreedyRegExCaptureNode.cs",
    "content": "﻿namespace Nancy.Routing.Trie.Nodes\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Text.RegularExpressions;\r\n\r\n    /// <summary>\r\n    /// A greedy regular expression capture node e.g. ^(?&lt;id>\\d{0,100})$\r\n    /// For use on an entire route path, regular expression must be surrounded by ^( )$\r\n    /// e.g. @\"^(?:(?&lt;id>videos/\\d{1,10})(?:/{0,1}(?&lt;slug>.*)))$\"\r\n    /// This will match for a Url like /videos/123/some-random-slug\r\n    /// and capture 'videos/123' and 'some-random-slug'\r\n    /// </summary>\r\n    public class GreedyRegExCaptureNode : TrieNode\r\n    {\r\n        private Regex expression;\r\n        private string[] groupNames;\r\n\r\n        /// <summary>\r\n        /// Score for this node\r\n        /// </summary>\r\n        public override int Score\r\n        {\r\n            get { return 100; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"GreedyRegExCaptureNode\"/> class with\r\n        /// the provided <paramref name=\"parent\"/>, <paramref name=\"segment\"/> and <paramref name=\"nodeFactory\"/>.\r\n        /// </summary>\r\n        /// <param name=\"parent\">Parent node</param>\r\n        /// <param name=\"segment\">Segment of the route definition</param>\r\n        /// <param name=\"nodeFactory\">Factory for creating new nodes</param>\r\n        public GreedyRegExCaptureNode(TrieNode parent, string segment, ITrieNodeFactory nodeFactory)\r\n            : base(parent, segment, nodeFactory)\r\n        {\r\n            this.BuildRegEx();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all matches for a given requested route\r\n        /// Overridden to handle greedy capturing\r\n        /// </summary>\r\n        /// <param name=\"segments\">Requested route segments</param>\r\n        /// <param name=\"currentIndex\">Current index in the route segments</param>\r\n        /// <param name=\"capturedParameters\">Currently captured parameters</param>\r\n        /// <param name=\"context\">Current Nancy context</param>\r\n        /// <returns>A collection of <see cref=\"MatchResult\"/> objects</returns>\r\n        public override IEnumerable<MatchResult> GetMatches(string[] segments, int currentIndex, IDictionary<string, object> capturedParameters, NancyContext context)\r\n        {\r\n            var value = segments.Skip(currentIndex).Aggregate((seg1, seg2) => seg1 + \"/\" + seg2);\r\n            var match = this.expression.Match(value);\r\n\r\n            if (!match.Success)\r\n            {\r\n                return ArrayCache.Empty<MatchResult>();\r\n            }\r\n\r\n            foreach (var groupName in this.groupNames)\r\n            {\r\n                var group = match.Groups[groupName];\r\n\r\n                if (group.Success)\r\n                {\r\n                    capturedParameters.Add(groupName, group.Value);\r\n                }\r\n            }\r\n\r\n            return this.NodeData.Select(nd => nd.ToResult(capturedParameters));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Matches the segment for a requested route\r\n        /// Not-required or called for this node type\r\n        /// </summary>\r\n        /// <param name=\"segment\">Segment string</param>\r\n        /// <returns>A <see cref=\"SegmentMatch\"/> instance representing the result of the match</returns>\r\n        public override SegmentMatch Match(string segment)\r\n        {\r\n            throw new NotSupportedException();\r\n        }\r\n\r\n        private void BuildRegEx()\r\n        {\r\n            this.expression = new Regex(this.RouteDefinitionSegment, RegexOptions.Compiled);\r\n            this.groupNames = this.expression.GetGroupNames();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Trie/Nodes/LiteralNode.cs",
    "content": "namespace Nancy.Routing.Trie.Nodes\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Literal string node e.g. goo\r\n    /// </summary>\r\n    public class LiteralNode : TrieNode\r\n    {\r\n        /// <summary>\r\n        /// Score for this node\r\n        /// </summary>\r\n        public override int Score\r\n        {\r\n            get { return 10000; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"LiteralNode\"/> class with\r\n        /// the provided <paramref name=\"parent\"/>, <paramref name=\"segment\"/> and <paramref name=\"nodeFactory\"/>.\r\n        /// </summary>\r\n        /// <param name=\"parent\">Parent node</param>\r\n        /// <param name=\"segment\">Segment of the route definition</param>\r\n        /// <param name=\"nodeFactory\">Factory for creating new nodes</param>\r\n        public LiteralNode(TrieNode parent, string segment, ITrieNodeFactory nodeFactory)\r\n            : base(parent, segment, nodeFactory)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Matches the segment for a requested route\r\n        /// </summary>\r\n        /// <param name=\"segment\">Segment string</param>\r\n        /// <returns>A <see cref=\"SegmentMatch\"/> instance representing the result of the match</returns>\r\n        public override SegmentMatch Match(string segment)\r\n        {\r\n            var comparisonType = StaticConfiguration.CaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;\r\n\r\n            if (string.Equals(\r\n                    segment,\r\n                    this.RouteDefinitionSegment,\r\n                    comparisonType))\r\n            {\r\n                return new SegmentMatch(true);\r\n            }\r\n\r\n            return SegmentMatch.NoMatch;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Trie/Nodes/OptionalCaptureNode.cs",
    "content": "namespace Nancy.Routing.Trie.Nodes\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// An optional capture node e.g. {foo?}\r\n    /// </summary>\r\n    public class OptionalCaptureNode : TrieNode\r\n    {\r\n        private string parameterName;\r\n\r\n        /// <summary>\r\n        /// Score for this node\r\n        /// </summary>\r\n        public override int Score\r\n        {\r\n            get { return 1000; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"OptionalCaptureNode\"/> class with\r\n        /// the provided <paramref name=\"parent\"/>, <paramref name=\"segment\"/> and <paramref name=\"nodeFactory\"/>.\r\n        /// </summary>\r\n        /// <param name=\"parent\">Parent node</param>\r\n        /// <param name=\"segment\">Segment of the route definition</param>\r\n        /// <param name=\"nodeFactory\">Factory for creating new nodes</param>\r\n        public OptionalCaptureNode(TrieNode parent, string segment, ITrieNodeFactory nodeFactory)\r\n            : base(parent, segment, nodeFactory)\r\n        {\r\n            this.ExtractParameterName();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Add a new route to the trie\r\n        /// Adds itself as a normal capture node, but also adds this node's\r\n        /// children as children of the parent too\r\n        /// (so it can effectively be \"skipped\" during matching)\r\n        /// </summary>\r\n        /// <param name=\"segments\">The segments of the route definition</param>\r\n        /// <param name=\"currentIndex\">Current index in the segments array</param>\r\n        /// <param name=\"currentScore\">Current score for this route</param>\r\n        /// <param name=\"nodeCount\">Number of nodes added for this route</param>\r\n        /// <param name=\"moduleType\">The module key the route comes from</param>\r\n        /// <param name=\"routeIndex\">The route index in the module</param>\r\n        /// <param name=\"routeDescription\">The route description</param>\r\n        public override void Add(string[] segments, int currentIndex, int currentScore, int nodeCount, Type moduleType, int routeIndex, RouteDescription routeDescription)\r\n        {\r\n            base.Add(segments, currentIndex, currentScore, nodeCount, moduleType, routeIndex, routeDescription);\r\n\r\n            // Keep the same index, reduce the node count and the score\r\n            this.Parent.Add(segments, currentIndex, currentScore - this.Parent.Score, nodeCount - 1, moduleType, routeIndex, routeDescription);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Matches the segment for a requested route\r\n        /// </summary>\r\n        /// <param name=\"segment\">Segment string</param>\r\n        /// <returns>A <see cref=\"SegmentMatch\"/> instance representing the result of the match</returns>\r\n        public override SegmentMatch Match(string segment)\r\n        {\r\n            var match = new SegmentMatch(true);\r\n            match.CapturedParameters[this.parameterName] = segment;\r\n            return match;\r\n        }\r\n\r\n        private void ExtractParameterName()\r\n        {\r\n            this.parameterName = this.RouteDefinitionSegment.Trim('{', '}').TrimEnd('?');\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Trie/Nodes/RegExNode.cs",
    "content": "namespace Nancy.Routing.Trie.Nodes\r\n{\r\n    using System.Text.RegularExpressions;\r\n\r\n    /// <summary>\r\n    /// A regular expression capture node e.g. (?&lt;foo>\\d{2,4})\r\n    /// </summary>\r\n    public class RegExNode : TrieNode\r\n    {\r\n        private Regex expression;\r\n\r\n        private string[] groupNames;\r\n\r\n        /// <summary>\r\n        /// Score for this node\r\n        /// </summary>\r\n        public override int Score\r\n        {\r\n            get { return 1000; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"RegExNode\"/>  class with\r\n        /// the provided <paramref name=\"parent\"/>, <paramref name=\"segment\"/> and <paramref name=\"nodeFactory\"/>.\r\n        /// </summary>\r\n        /// <param name=\"parent\">Parent node</param>\r\n        /// <param name=\"segment\">Segment of the route definition</param>\r\n        /// <param name=\"nodeFactory\">Factory for creating new nodes</param>\r\n        public RegExNode(TrieNode parent, string segment, ITrieNodeFactory nodeFactory)\r\n            : base(parent, segment, nodeFactory)\r\n        {\r\n            this.BuildRegEx();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Matches the segment for a requested route\r\n        /// </summary>\r\n        /// <param name=\"segment\">Segment string</param>\r\n        /// <returns>A <see cref=\"SegmentMatch\"/> instance representing the result of the match</returns>\r\n        public override SegmentMatch Match(string segment)\r\n        {\r\n            var match = this.expression.Match(segment);\r\n\r\n            if (!match.Success)\r\n            {\r\n                return SegmentMatch.NoMatch;\r\n            }\r\n\r\n            var result = new SegmentMatch(true);\r\n            foreach (var groupName in this.groupNames)\r\n            {\r\n                var group = match.Groups[groupName];\r\n                if (group.Success)\r\n                {\r\n                    result.CapturedParameters[groupName] = group.Value;\r\n                }\r\n            }\r\n\r\n            return result;\r\n        }\r\n\r\n        private void BuildRegEx()\r\n        {\r\n            this.expression = new Regex(this.RouteDefinitionSegment, RegexOptions.Compiled);\r\n            this.groupNames = this.expression.GetGroupNames();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Trie/Nodes/RootNode.cs",
    "content": "namespace Nancy.Routing.Trie.Nodes\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Root node of a trie\r\n    /// </summary>\r\n    public class RootNode : TrieNode\r\n    {\r\n        private SegmentMatch segmentMatch = new SegmentMatch(true);\r\n\r\n        private readonly Dictionary<string, object> localCaptures = new Dictionary<string, object>();\r\n\r\n        /// <summary>\r\n        /// Score for this node\r\n        /// </summary>\r\n        public override int Score\r\n        {\r\n            get { return 0; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"RootNode\"/> class class with\r\n        /// the provided <paramref name=\"nodeFactory\"/>.\r\n        /// </summary>\r\n        /// <param name=\"nodeFactory\">The node factory.</param>\r\n        public RootNode(ITrieNodeFactory nodeFactory)\r\n            : base(null, null, nodeFactory)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all matches for a given requested route\r\n        /// </summary>\r\n        /// <param name=\"segments\">Requested route segments</param>\r\n        /// <param name=\"currentIndex\">Current index in the route segments</param>\r\n        /// <param name=\"capturedParameters\">Currently captured parameters</param>\r\n        /// <param name=\"context\">Current Nancy context</param>\r\n        /// <returns>A collection of <see cref=\"MatchResult\"/> objects</returns>\r\n        public override IEnumerable<MatchResult> GetMatches(string[] segments, int currentIndex, IDictionary<string, object> capturedParameters, NancyContext context)\r\n        {\r\n            if (segments.Length == 0)\r\n            {\r\n                return this.BuildResults(capturedParameters, this.localCaptures);\r\n            }\r\n\r\n            return this.GetMatchingChildren(segments, currentIndex, capturedParameters, this.localCaptures, context);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Matches the segment for a requested route\r\n        /// </summary>\r\n        /// <param name=\"segment\">Segment string</param>\r\n        /// <returns>A <see cref=\"SegmentMatch\"/> instance representing the result of the match</returns>\r\n        public override SegmentMatch Match(string segment)\r\n        {\r\n            return this.segmentMatch;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Trie/Nodes/TrieNode.cs",
    "content": "namespace Nancy.Routing.Trie.Nodes\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// A base class representing a node in the route trie\r\n    /// </summary>\r\n    public abstract class TrieNode\r\n    {\r\n        private readonly ITrieNodeFactory nodeFactory;\r\n\r\n        /// <summary>\r\n        /// Gets or sets the parent node\r\n        /// </summary>\r\n        public TrieNode Parent { get; protected set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the segment from the route definition that this node represents\r\n        /// </summary>\r\n        public string RouteDefinitionSegment { get; protected set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the children of this node\r\n        /// </summary>\r\n        public IDictionary<string, TrieNode> Children { get; protected set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the node data stored at this node, which will be converted\r\n        /// into the <see cref=\"MatchResult\"/> if a match is found\r\n        /// </summary>\r\n        public IList<NodeData> NodeData { get; protected set; }\r\n\r\n        /// <summary>\r\n        /// Additional parameters to set that can be determined at trie build time\r\n        /// </summary>\r\n        public IDictionary<string, object> AdditionalParameters { get; protected set; }\r\n\r\n        /// <summary>\r\n        /// Score for this node\r\n        /// </summary>\r\n        public abstract int Score { get; }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"TrieNode\"/> class\r\n        /// </summary>\r\n        /// <param name=\"parent\">Parent node</param>\r\n        /// <param name=\"segment\">Segment of the route definition</param>\r\n        /// <param name=\"nodeFactory\">Factory for creating new nodes</param>\r\n        protected TrieNode(TrieNode parent, string segment, ITrieNodeFactory nodeFactory)\r\n        {\r\n            this.nodeFactory = nodeFactory;\r\n            this.Parent = parent;\r\n            this.RouteDefinitionSegment = segment;\r\n\r\n            this.Children = new Dictionary<string, TrieNode>(StaticConfiguration.CaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase);\r\n            this.AdditionalParameters = new Dictionary<string, object>();\r\n            this.NodeData = new List<NodeData>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Add a new route to the trie\r\n        /// </summary>\r\n        /// <param name=\"segments\">The segments of the route definition</param>\r\n        /// <param name=\"moduleType\">The module key the route comes from</param>\r\n        /// <param name=\"routeIndex\">The route index in the module</param>\r\n        /// <param name=\"routeDescription\">The route description</param>\r\n        public void Add(string[] segments, Type moduleType, int routeIndex, RouteDescription routeDescription)\r\n        {\r\n            this.Add(segments, -1, 0, 0, moduleType, routeIndex, routeDescription);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Add a new route to the trie\r\n        /// </summary>\r\n        /// <param name=\"segments\">The segments of the route definition</param>\r\n        /// <param name=\"currentIndex\">Current index in the segments array</param>\r\n        /// <param name=\"currentScore\">Current score for this route</param>\r\n        /// <param name=\"nodeCount\">Number of nodes added for this route</param>\r\n        /// <param name=\"moduleType\">The module key the route comes from</param>\r\n        /// <param name=\"routeIndex\">The route index in the module</param>\r\n        /// <param name=\"routeDescription\">The route description</param>\r\n        public virtual void Add(string[] segments, int currentIndex, int currentScore, int nodeCount, Type moduleType, int routeIndex, RouteDescription routeDescription)\r\n        {\r\n            if (this.NoMoreSegments(segments, currentIndex))\r\n            {\r\n                this.NodeData.Add(this.BuildNodeData(nodeCount, currentScore + this.Score, moduleType, routeIndex, routeDescription));\r\n                return;\r\n            }\r\n\r\n            nodeCount++;\r\n            currentIndex++;\r\n            TrieNode child;\r\n\r\n            if (!this.Children.TryGetValue(segments[currentIndex], out child))\r\n            {\r\n                child = this.nodeFactory.GetNodeForSegment(this, segments[currentIndex]);\r\n                this.Children.Add(segments[currentIndex], child);\r\n            }\r\n\r\n            child.Add(segments, currentIndex, currentScore + this.Score, nodeCount, moduleType, routeIndex, routeDescription);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all matches for a given requested route\r\n        /// </summary>\r\n        /// <param name=\"segments\">Requested route segments</param>\r\n        /// <param name=\"context\">Current Nancy context</param>\r\n        /// <returns>A collection of <see cref=\"MatchResult\"/> objects</returns>\r\n        public virtual IEnumerable<MatchResult> GetMatches(string[] segments, NancyContext context)\r\n        {\r\n            return this.GetMatches(segments, 0, new Dictionary<string, object>(this.AdditionalParameters), context);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all matches for a given requested route\r\n        /// </summary>\r\n        /// <param name=\"segments\">Requested route segments</param>\r\n        /// <param name=\"currentIndex\">Current index in the route segments</param>\r\n        /// <param name=\"capturedParameters\">Currently captured parameters</param>\r\n        /// <param name=\"context\">Current Nancy context</param>\r\n        /// <returns>A collection of <see cref=\"MatchResult\"/> objects</returns>\r\n        public virtual IEnumerable<MatchResult> GetMatches(string[] segments, int currentIndex, IDictionary<string, object> capturedParameters, NancyContext context)\r\n        {\r\n            var segmentMatch = this.Match(segments[currentIndex]);\r\n            if (segmentMatch == SegmentMatch.NoMatch)\r\n            {\r\n                return MatchResult.NoMatches;\r\n            }\r\n\r\n            if (this.NoMoreSegments(segments, currentIndex))\r\n            {\r\n                return this.BuildResults(capturedParameters, segmentMatch.CapturedParameters) ?? MatchResult.NoMatches;\r\n            }\r\n\r\n            currentIndex++;\r\n\r\n            return this.GetMatchingChildren(segments, currentIndex, capturedParameters, segmentMatch.CapturedParameters, context);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a string representation of all routes\r\n        /// </summary>\r\n        /// <returns>Collection of strings, each representing a route</returns>\r\n        public virtual IEnumerable<string> GetRoutes()\r\n        {\r\n            var routeList = new List<string>(this.Children.Values.SelectMany(c => c.GetRoutes())\r\n                             .Select(s => (this.RouteDefinitionSegment ?? string.Empty) + \"/\" + s));\r\n\r\n            if (this.NodeData.Any())\r\n            {\r\n                var node = this.NodeData.First();\r\n                var resultData = string.Format(\"{0} (Segments: {1} Score: {2})\", this.RouteDefinitionSegment ?? \"/\", node.RouteLength, node.Score);\r\n                routeList.Add(resultData);\r\n            }\r\n\r\n            return routeList;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Build the node data that will be used to create the <see cref=\"MatchResult\"/>\r\n        /// We calculate/store as much as possible at build time to reduce match time.\r\n        /// </summary>\r\n        /// <param name=\"nodeCount\">Number of nodes in the route</param>\r\n        /// <param name=\"score\">Score for the route</param>\r\n        /// <param name=\"moduleType\">The module key the route comes from</param>\r\n        /// <param name=\"routeIndex\">The route index in the module</param>\r\n        /// <param name=\"routeDescription\">The route description</param>\r\n        /// <returns>A NodeData instance</returns>\r\n        protected virtual NodeData BuildNodeData(int nodeCount, int score, Type moduleType, int routeIndex, RouteDescription routeDescription)\r\n        {\r\n            return new NodeData\r\n                       {\r\n                           Method = routeDescription.Method,\r\n                           RouteIndex = routeIndex,\r\n                           RouteLength = nodeCount,\r\n                           Score = score,\r\n                           Condition = routeDescription.Condition,\r\n                           ModuleType = moduleType,\r\n                       };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns whether we are at the end of the segments\r\n        /// </summary>\r\n        /// <param name=\"segments\">Route segments</param>\r\n        /// <param name=\"currentIndex\">Current index</param>\r\n        /// <returns>True if no more segments left, false otherwise</returns>\r\n        protected bool NoMoreSegments(string[] segments, int currentIndex)\r\n        {\r\n            return currentIndex >= segments.Length - 1;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Build the results collection from the captured parameters if\r\n        /// this node is the end result\r\n        /// </summary>\r\n        /// <param name=\"capturedParameters\">Currently captured parameters</param>\r\n        /// <param name=\"localCaptures\">Parameters captured by the local matching</param>\r\n        /// <returns>Array of <see cref=\"MatchResult\"/> objects corresponding to each set of <see cref=\"NodeData\"/> stored at this node</returns>\r\n        protected IEnumerable<MatchResult> BuildResults(IDictionary<string, object> capturedParameters, IDictionary<string, object> localCaptures)\r\n        {\r\n            if (!this.NodeData.Any())\r\n            {\r\n                return MatchResult.NoMatches;\r\n            }\r\n\r\n            var parameters = new Dictionary<string, object>(capturedParameters);\r\n\r\n            if (this.AdditionalParameters.Any())\r\n            {\r\n                foreach (var additionalParameter in this.AdditionalParameters)\r\n                {\r\n                    if (!parameters.ContainsKey(additionalParameter.Key))\r\n                    {\r\n                        parameters[additionalParameter.Key] = additionalParameter.Value;\r\n                    }\r\n                }\r\n            }\r\n\r\n            if (localCaptures.Any())\r\n            {\r\n                foreach (var localCapture in localCaptures)\r\n                {\r\n                    parameters[localCapture.Key] = localCapture.Value;\r\n                }\r\n            }\r\n\r\n            return this.NodeData.Select(n => n.ToResult(parameters));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all the matches from this node's children\r\n        /// </summary>\r\n        /// <param name=\"segments\">Requested route segments</param>\r\n        /// <param name=\"currentIndex\">Current index</param>\r\n        /// <param name=\"capturedParameters\">Currently captured parameters</param>\r\n        /// <param name=\"localCaptures\">Parameters captured by the local matching</param>\r\n        /// <param name=\"context\">Current Nancy context</param>\r\n        /// <returns>Collection of <see cref=\"MatchResult\"/> objects</returns>\r\n        protected IEnumerable<MatchResult> GetMatchingChildren(string[] segments, int currentIndex, IDictionary<string, object> capturedParameters, IDictionary<string, object> localCaptures, NancyContext context)\r\n        {\r\n            var parameters = capturedParameters;\r\n            if (localCaptures.Any() || this.AdditionalParameters.Any())\r\n            {\r\n                parameters = new Dictionary<string, object>(parameters);\r\n\r\n                foreach (var localParameter in localCaptures)\r\n                {\r\n                    parameters[localParameter.Key] = localParameter.Value;\r\n                }\r\n\r\n                foreach (var additionalParameter in this.AdditionalParameters)\r\n                {\r\n                    parameters[additionalParameter.Key] = additionalParameter.Value;\r\n                }\r\n            }\r\n\r\n            foreach (var childNode in this.Children.Values)\r\n            {\r\n                foreach (var match in childNode.GetMatches(segments, currentIndex, parameters, context))\r\n                {\r\n                    yield return match;\r\n                }\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Matches the segment for a requested route\r\n        /// </summary>\r\n        /// <param name=\"segment\">Segment string</param>\r\n        /// <returns>A <see cref=\"SegmentMatch\"/> instance representing the result of the match</returns>\r\n        public abstract SegmentMatch Match(string segment);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Trie/RouteResolverTrie.cs",
    "content": "namespace Nancy.Routing.Trie\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Text;\r\n    using Nodes;\r\n\r\n    /// <summary>\r\n    /// The default route resolution trie\r\n    /// </summary>\r\n    public class RouteResolverTrie : IRouteResolverTrie\r\n    {\r\n        private readonly ITrieNodeFactory nodeFactory;\r\n\r\n        private readonly IDictionary<string, TrieNode> routeTries = new Dictionary<string, TrieNode>(StringComparer.OrdinalIgnoreCase);\r\n\r\n        private static char[] splitSeparators = new[] {'/'};\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"RouteResolverTrie\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"nodeFactory\">The node factory.</param>\r\n        public RouteResolverTrie(ITrieNodeFactory nodeFactory)\r\n        {\r\n            this.nodeFactory = nodeFactory;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Build the trie from the route cache\r\n        /// </summary>\r\n        /// <param name=\"cache\">The route cache</param>\r\n        public void BuildTrie(IRouteCache cache)\r\n        {\r\n            foreach (var cacheItem in cache)\r\n            {\r\n                var moduleKey = cacheItem.Key;\r\n                var routeDefinitions = cacheItem.Value;\r\n\r\n                foreach (var routeDefinition in routeDefinitions)\r\n                {\r\n                    var routeIndex = routeDefinition.Item1;\r\n                    var routeDescription = routeDefinition.Item2;\r\n\r\n                    TrieNode trieNode;\r\n                    if (!this.routeTries.TryGetValue(routeDescription.Method, out trieNode))\r\n                    {\r\n                        trieNode = this.nodeFactory.GetNodeForSegment(null, null);\r\n\r\n                        this.routeTries.Add(routeDefinition.Item2.Method, trieNode);\r\n                    }\r\n\r\n                    var segments = routeDefinition.Item2.Segments.ToArray();\r\n\r\n                    trieNode.Add(segments, moduleKey, routeIndex, routeDescription);\r\n                }\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get all matches for the given method and path\r\n        /// </summary>\r\n        /// <param name=\"method\">HTTP method</param>\r\n        /// <param name=\"path\">Requested path</param>\r\n        /// <param name=\"context\">Current Nancy context</param>\r\n        /// <returns>An array of <see cref=\"MatchResult\"/> elements</returns>\r\n        public MatchResult[] GetMatches(string method, string path, NancyContext context)\r\n        {\r\n            TrieNode result;\r\n\r\n            if (!this.routeTries.TryGetValue(method, out result))\r\n            {\r\n                return MatchResult.NoMatches;\r\n            }\r\n\r\n            return result.GetMatches(path.Split(splitSeparators, StringSplitOptions.RemoveEmptyEntries), context)\r\n                         .ToArray();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get all method options for the given path\r\n        /// </summary>\r\n        /// <param name=\"path\">Requested path</param>\r\n        /// <param name=\"context\">Current Nancy context</param>\r\n        /// <returns>A collection of strings, each representing an allowed method</returns>\r\n        public IEnumerable<string> GetOptions(string path, NancyContext context)\r\n        {\r\n            foreach (var method in this.routeTries.Keys)\r\n            {\r\n                if (this.GetMatches(method, path, context).Any())\r\n                {\r\n                    yield return method;\r\n                }\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns a string that represents the current object.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// A string that represents the current object.\r\n        /// </returns>\r\n        /// <filterpriority>2</filterpriority>\r\n        public override string ToString()\r\n        {\r\n            var sb = new StringBuilder();\r\n\r\n            foreach (var kvp in this.routeTries)\r\n            {\r\n                var method = kvp.Key;\r\n                sb.Append(\r\n                    kvp.Value.GetRoutes().Select(s => method + \" \" + s)\r\n                             .Aggregate((r1, r2) => r1 + \"\\n\" + r2));\r\n            }\r\n\r\n            return sb.ToString();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Routing/Trie/SegmentMatch.cs",
    "content": "namespace Nancy.Routing.Trie\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// A segment match result\r\n    /// </summary>\r\n    public class SegmentMatch\r\n    {\r\n        private static SegmentMatch noMatch = new SegmentMatch(false);\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether the match was successful or not\r\n        /// </summary>\r\n        public bool Matches { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets a <see cref=\"SegmentMatch\"/> representing \"no match\"\r\n        /// </summary>\r\n        public static SegmentMatch NoMatch { get { return noMatch; } }\r\n\r\n        /// <summary>\r\n        /// Gets the captured parameters from the match, if the match was successful\r\n        /// </summary>\r\n        public IDictionary<string, object> CapturedParameters { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"SegmentMatch\"/> class, with\r\n        /// the provided <paramref name=\"matches\"/>.\r\n        /// </summary>\r\n        /// <param name=\"matches\"><see langword=\"true\"/> if match was successful.</param>\r\n        public SegmentMatch(bool matches)\r\n        {\r\n            this.Matches = matches;\r\n\r\n            if (matches)\r\n            {\r\n                this.CapturedParameters = new Dictionary<string, object>();\r\n            }\r\n        }\r\n\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Routing/Trie/TrieNodeFactory.cs",
    "content": "namespace Nancy.Routing.Trie\r\n{\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    using Nancy.Routing.Constraints;\r\n    using Nancy.Routing.Trie.Nodes;\r\n\r\n    /// <summary>\r\n    /// Factory for creating the correct type of TrieNode\r\n    /// </summary>\r\n    public class TrieNodeFactory : ITrieNodeFactory\r\n    {\r\n        private readonly IEnumerable<IRouteSegmentConstraint> routeSegmentConstraints;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"TrieNodeFactory\"/> class with\r\n        /// the provided <paramref name=\"routeSegmentConstraints\"/>.\r\n        /// </summary>\r\n        /// <param name=\"routeSegmentConstraints\">The route segment constraints.</param>\r\n        public TrieNodeFactory(IEnumerable<IRouteSegmentConstraint> routeSegmentConstraints)\r\n        {\r\n            this.routeSegmentConstraints = routeSegmentConstraints;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the correct Trie node type for the given segment\r\n        /// </summary>\r\n        /// <param name=\"parent\">Parent node</param>\r\n        /// <param name=\"segment\">Segment</param>\r\n        /// <returns>TrieNode instance</returns>\r\n        public virtual TrieNode GetNodeForSegment(TrieNode parent, string segment)\r\n        {\r\n            if (parent == null)\r\n            {\r\n                return new RootNode(this);\r\n            }\r\n\r\n            var chars = segment.ToCharArray();\r\n            var start = chars[0];\r\n            var end = chars[chars.Length - 1];\r\n\r\n            if (start == '(' && end == ')')\r\n            {\r\n                return new RegExNode(parent, segment, this);\r\n            }\r\n\r\n            if (start == '{' && end == '}' && chars.Count(c => c == '{' || c == '}') == 2)\r\n            {\r\n                return this.GetCaptureNode(parent, segment);\r\n            }\r\n\r\n            if (segment.StartsWith(\"^(\") && (segment.EndsWith(\")\") || segment.EndsWith(\")$\")))\r\n            {\r\n                return new GreedyRegExCaptureNode(parent, segment, this);\r\n            }\r\n\r\n            if (CaptureNodeWithMultipleParameters.IsMatch(segment))\r\n            {\r\n                return new CaptureNodeWithMultipleParameters(parent, segment, this, routeSegmentConstraints);\r\n            }\r\n\r\n            return new LiteralNode(parent, segment, this);\r\n        }\r\n\r\n        private TrieNode GetCaptureNode(TrieNode parent, string segment)\r\n        {\r\n            if (segment.Contains(\":\"))\r\n            {\r\n                return new CaptureNodeWithConstraint(parent, segment, this, routeSegmentConstraints);\r\n            }\r\n\r\n            if (segment.EndsWith(\"?}\"))\r\n            {\r\n                return new OptionalCaptureNode(parent, segment, this);\r\n            }\r\n\r\n            if (segment.EndsWith(\"*}\"))\r\n            {\r\n                return new GreedyCaptureNode(parent, segment, this);\r\n            }\r\n\r\n            if (segment.Contains(\"?\"))\r\n            {\r\n                return new CaptureNodeWithDefaultValue(parent, segment, this);\r\n            }\r\n\r\n            return new CaptureNode(parent, segment, this);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Security/ClaimsPrincipalExtensions.cs",
    "content": "﻿namespace Nancy.Security\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Security.Claims;\r\n\r\n    /// <summary>\r\n    /// Extension methods for working with IUserIdentity.\r\n    /// </summary>\r\n    public static class ClaimsPrincipalExtensions\r\n    {\r\n        /// <summary>\r\n        /// Tests if the user is authenticated.\r\n        /// </summary>\r\n        /// <param name=\"user\">User to be verified</param>\r\n        /// <returns>True if the user is authenticated, false otherwise</returns>\r\n        public static bool IsAuthenticated(this ClaimsPrincipal user)\r\n        {\r\n            return user != null && user.Identity != null && user.Identity.IsAuthenticated;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tests if the user has all of the required claims.\r\n        /// </summary>\r\n        /// <param name=\"user\">User to be verified</param>\r\n        /// <param name=\"requiredClaims\">Claims the user needs to have</param>\r\n        /// <returns>True if the user has all of the required claims, false otherwise</returns>\r\n        public static bool HasClaims(this ClaimsPrincipal user, params Predicate<Claim>[] requiredClaims)\r\n        {\r\n            return user != null && requiredClaims.All(user.HasClaim);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tests if the user has at least one of the required claims.\r\n        /// </summary>\r\n        /// <param name=\"user\">User to be verified</param>\r\n        /// <param name=\"requiredClaims\">Claims the user needs to have at least one of</param>\r\n        /// <returns>True if the user has at least one of the required claims, false otherwise</returns>\r\n        public static bool HasAnyClaim(this ClaimsPrincipal user, params Predicate<Claim>[] requiredClaims)\r\n        {\r\n            return user != null && requiredClaims.Any(user.HasClaim);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tests if the user has claims that satisfy the supplied validation function.\r\n        /// </summary>\r\n        /// <param name=\"user\">User to be verified</param>\r\n        /// <param name=\"isValid\">Validation function to be called with the authenticated\r\n        /// users claims</param>\r\n        /// <returns>True if the user does pass the supplied validation function, false otherwise</returns>\r\n        public static bool HasValidClaims(this ClaimsPrincipal user, Func<IEnumerable<Claim>, bool> isValid)\r\n        {\r\n            return\r\n                user != null\r\n                && user.Claims != null\r\n                && isValid(user.Claims);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tests if the user is in all of the required roles.\r\n        /// </summary>\r\n        /// <param name=\"user\">User to be verified</param>\r\n        /// <param name=\"requiredRoles\">Roles the user needs to be in</param>\r\n        /// <returns>True if the user is in all of the required roles, false otherwise</returns>\r\n        public static bool IsInRoles(this ClaimsPrincipal user, params string[] requiredRoles)\r\n        {\r\n            return user != null && requiredRoles != null && requiredRoles.All(user.IsInRole);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tests if the user is in at least one of the required roles.\r\n        /// </summary>\r\n        /// <param name=\"user\">User to be verified</param>\r\n        /// <param name=\"requiredRoles\">Roles the user needs to be in at least one of</param>\r\n        /// <returns>True if the user is in at least one of the required roles, false otherwise</returns>\r\n        public static bool IsInAnyRole(this ClaimsPrincipal user, params string[] requiredRoles)\r\n        {\r\n            return user != null && requiredRoles != null && requiredRoles.Any(user.IsInRole);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Security/Csrf.cs",
    "content": "﻿namespace Nancy.Security\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Globalization;\r\n    using System.Linq;\r\n    using System.Text;\r\n\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Cookies;\r\n    using Nancy.Cryptography;\r\n\r\n    /// <summary>\r\n    /// Csrf protection methods\r\n    /// </summary>\r\n    public static class Csrf\r\n    {\r\n        private const string CsrfHookName = \"CsrfPostHook\";\r\n        private const char ValueDelimiter = '#';\r\n        private const char PairDelimiter = '|';\r\n\r\n        /// <summary>\r\n        /// Enables Csrf token generation.\r\n        /// </summary>\r\n        /// <remarks>This is disabled by default.</remarks>\r\n        /// <param name=\"pipelines\">The application pipelines.</param>\r\n        /// <param name=\"cryptographyConfiguration\">The cryptography configuration. This is <see langword=\"null\" /> by default.</param>\r\n        /// <param name=\"useSecureCookie\">Set the CSRF cookie secure flag. This is <see langword=\"false\"/> by default</param>\r\n        public static void Enable(IPipelines pipelines, CryptographyConfiguration cryptographyConfiguration = null, bool useSecureCookie = false)\r\n        {\r\n            cryptographyConfiguration = cryptographyConfiguration ?? CsrfApplicationStartup.CryptographyConfiguration;\r\n\r\n            var postHook = new PipelineItem<Action<NancyContext>>(\r\n                CsrfHookName,\r\n                context =>\r\n                {\r\n                    if (context.Response == null || context.Response.Cookies == null || context.Request.Method.Equals(\"OPTIONS\", StringComparison.OrdinalIgnoreCase))\r\n                    {\r\n                        return;\r\n                    }\r\n\r\n                    object value;\r\n                    if (context.Items.TryGetValue(CsrfToken.DEFAULT_CSRF_KEY, out value))\r\n                    {\r\n                        context.Response.Cookies.Add(new NancyCookie(\r\n                            CsrfToken.DEFAULT_CSRF_KEY,\r\n                            (string)value,\r\n                            true, useSecureCookie));\r\n\r\n                        return;\r\n                    }\r\n\r\n                    string cookieValue;\r\n                    if (context.Request.Cookies.TryGetValue(CsrfToken.DEFAULT_CSRF_KEY, out cookieValue))\r\n                    {\r\n                        var cookieToken = ParseToCsrfToken(cookieValue);\r\n\r\n                        if (CsrfApplicationStartup.TokenValidator.CookieTokenStillValid(cookieToken))\r\n                        {\r\n                            context.Items[CsrfToken.DEFAULT_CSRF_KEY] = cookieValue;\r\n                            return;\r\n                        }\r\n                    }\r\n\r\n                    var tokenString = GenerateTokenString(cryptographyConfiguration);\r\n\r\n                    context.Items[CsrfToken.DEFAULT_CSRF_KEY] = tokenString;\r\n                    context.Response.Cookies.Add(new NancyCookie(CsrfToken.DEFAULT_CSRF_KEY, tokenString, true, useSecureCookie));\r\n                });\r\n\r\n            pipelines.AfterRequest.AddItemToEndOfPipeline(postHook);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Disable csrf token generation\r\n        /// </summary>\r\n        /// <param name=\"pipelines\">Application pipelines</param>\r\n        public static void Disable(IPipelines pipelines)\r\n        {\r\n            pipelines.AfterRequest.RemoveByName(CsrfHookName);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a new csrf token for this response with an optional salt.\r\n        /// Only necessary if a particular route requires a new token for each request.\r\n        /// </summary>\r\n        /// <param name=\"module\">Nancy module</param>\r\n        /// <param name=\"cryptographyConfiguration\">The cryptography configuration. This is <c>null</c> by default.</param>\r\n        public static void CreateNewCsrfToken(this INancyModule module, CryptographyConfiguration cryptographyConfiguration = null)\r\n        {\r\n            var tokenString = GenerateTokenString(cryptographyConfiguration);\r\n            module.Context.Items[CsrfToken.DEFAULT_CSRF_KEY] = tokenString;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a new csrf token with an optional salt.\r\n        /// Does not store the token in context.\r\n        /// </summary>\r\n        /// <returns>The generated token</returns>\r\n        internal static string GenerateTokenString(CryptographyConfiguration cryptographyConfiguration = null)\r\n        {\r\n            cryptographyConfiguration = cryptographyConfiguration ?? CsrfApplicationStartup.CryptographyConfiguration;\r\n            var token = new CsrfToken\r\n            {\r\n                CreatedDate = DateTimeOffset.Now\r\n            };\r\n\r\n            token.CreateRandomBytes();\r\n            token.CreateHmac(cryptographyConfiguration.HmacProvider);\r\n\r\n            var builder = new StringBuilder();\r\n\r\n            builder.AppendFormat(\"RandomBytes{0}{1}\", ValueDelimiter, Convert.ToBase64String(token.RandomBytes));\r\n            builder.Append(PairDelimiter);\r\n            builder.AppendFormat(\"Hmac{0}{1}\", ValueDelimiter, Convert.ToBase64String(token.Hmac));\r\n            builder.Append(PairDelimiter);\r\n            builder.AppendFormat(\"CreatedDate{0}{1}\", ValueDelimiter, token.CreatedDate.ToString(\"o\", CultureInfo.InvariantCulture));\r\n\r\n            return builder.ToString();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Validate that the incoming request has valid CSRF tokens.\r\n        /// Throws <see cref=\"CsrfValidationException\"/> if validation fails.\r\n        /// </summary>\r\n        /// <param name=\"module\">Module object</param>\r\n        /// <param name=\"validityPeriod\">Optional validity period before it times out</param>\r\n        /// <exception cref=\"CsrfValidationException\">If validation fails</exception>\r\n        public static void ValidateCsrfToken(this INancyModule module, TimeSpan? validityPeriod = null)\r\n        {\r\n            var request = module.Request;\r\n\r\n            if (request == null)\r\n            {\r\n                return;\r\n            }\r\n\r\n            var cookieToken = GetCookieToken(request);\r\n            var providedToken = GetProvidedToken(request);\r\n\r\n            var result = CsrfApplicationStartup.TokenValidator.Validate(cookieToken, providedToken, validityPeriod);\r\n\r\n            if (result != CsrfTokenValidationResult.Ok)\r\n            {\r\n                throw new CsrfValidationException(result);\r\n            }\r\n        }\r\n\r\n        private static CsrfToken GetProvidedToken(Request request)\r\n        {\r\n            CsrfToken providedToken = null;\r\n\r\n            var providedTokenString = request.Form[CsrfToken.DEFAULT_CSRF_KEY].Value ?? request.Headers[CsrfToken.DEFAULT_CSRF_KEY].FirstOrDefault();\r\n            if (providedTokenString != null)\r\n            {\r\n                providedToken = ParseToCsrfToken(providedTokenString);\r\n            }\r\n\r\n            return providedToken;\r\n        }\r\n\r\n        private static CsrfToken GetCookieToken(Request request)\r\n        {\r\n            CsrfToken cookieToken = null;\r\n\r\n            string cookieTokenString;\r\n            if (request.Cookies.TryGetValue(CsrfToken.DEFAULT_CSRF_KEY, out cookieTokenString))\r\n            {\r\n                cookieToken = ParseToCsrfToken(cookieTokenString);\r\n            }\r\n\r\n            return cookieToken;\r\n        }\r\n\r\n        private static void AddTokenValue(Dictionary<string, string> dictionary, string key, string value)\r\n        {\r\n            if (!string.IsNullOrEmpty(key))\r\n            {\r\n                dictionary.Add(key, value);\r\n            }\r\n        }\r\n\r\n        private static CsrfToken ParseToCsrfToken(string cookieTokenString)\r\n        {\r\n            var parsed = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);\r\n\r\n            var currentKey = string.Empty;\r\n            var buffer = new StringBuilder();\r\n\r\n            for (var index = 0; index < cookieTokenString.Length; index++)\r\n            {\r\n                var currentCharacter = cookieTokenString[index];\r\n\r\n                switch (currentCharacter)\r\n                {\r\n                    case ValueDelimiter:\r\n                        currentKey = buffer.ToString();\r\n                        buffer.Clear();\r\n                        break;\r\n                    case PairDelimiter:\r\n                        AddTokenValue(parsed, currentKey, buffer.ToString());\r\n                        buffer.Clear();\r\n                        break;\r\n                    default:\r\n                        buffer.Append(currentCharacter);\r\n                        break;\r\n                }\r\n            }\r\n\r\n            AddTokenValue(parsed, currentKey, buffer.ToString());\r\n\r\n            if (parsed.Keys.Count() != 3)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            try\r\n            {\r\n                return new CsrfToken\r\n                {\r\n                    CreatedDate = DateTimeOffset.ParseExact(parsed[\"CreatedDate\"], \"o\", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal),\r\n                    Hmac = Convert.FromBase64String(parsed[\"Hmac\"]),\r\n                    RandomBytes = Convert.FromBase64String(parsed[\"RandomBytes\"])\r\n                };\r\n            }\r\n            catch\r\n            {\r\n                return null;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Security/CsrfApplicationStartup.cs",
    "content": "﻿namespace Nancy.Security\r\n{\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Cryptography;\r\n\r\n    /// <summary>\r\n    /// Wires up the CSRF (anti-forgery token) support at application startup.\r\n    /// </summary>\r\n    public class CsrfApplicationStartup : IApplicationStartup\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"CsrfApplicationStartup\"/> class, using the\r\n        /// provided <paramref name=\"cryptographyConfiguration\"/> and <paramref name=\"tokenValidator\"/>.\r\n        /// </summary>\r\n        /// <param name=\"cryptographyConfiguration\">The cryptographic configuration to use.</param>\r\n        /// <param name=\"tokenValidator\">The token validator that should be used.</param>\r\n        public CsrfApplicationStartup(CryptographyConfiguration cryptographyConfiguration, ICsrfTokenValidator tokenValidator)\r\n        {\r\n            CryptographyConfiguration = cryptographyConfiguration;\r\n            TokenValidator = tokenValidator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the configured crypto config\r\n        /// </summary>\r\n        internal static CryptographyConfiguration CryptographyConfiguration { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the configured token validator\r\n        /// </summary>\r\n        internal static ICsrfTokenValidator TokenValidator { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Perform any initialisation tasks\r\n        /// </summary>\r\n        /// <param name=\"pipelines\">Application pipelines</param>\r\n        public void Initialize(IPipelines pipelines)\r\n        {\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Security/CsrfToken.cs",
    "content": "﻿namespace Nancy.Security\r\n{\r\n    using System;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Represents a Csrf protection token\r\n    /// </summary>\r\n#if !NETSTANDARD1_6\r\n    [Serializable]\r\n#endif\r\n    public sealed class CsrfToken\r\n    {\r\n        /// <summary>\r\n        /// The default key for the csrf cookie/form value/querystring value\r\n        /// </summary>\r\n        public const string DEFAULT_CSRF_KEY = \"NCSRF\";\r\n\r\n        /// <summary>\r\n        /// Randomly generated bytes\r\n        /// </summary>\r\n        public byte[] RandomBytes { get; set; }\r\n\r\n        /// <summary>\r\n        /// Date and time the token was created\r\n        /// </summary>\r\n        public DateTimeOffset CreatedDate { get; set; }\r\n\r\n        /// <summary>\r\n        /// Tamper prevention hmac\r\n        /// </summary>\r\n        public byte[] Hmac { get; set; }\r\n\r\n        /// <summary>\r\n        /// Compares two <see cref=\"CsrfToken\"/> instances.\r\n        /// </summary>\r\n        /// <param name=\"other\">The <see cref=\"CsrfToken\"/> to compare.</param>\r\n        /// <returns>\r\n        /// <see langword=\"true\"/> if two <see cref=\"CsrfToken\"/> instances are equal, <see langword=\"false\"/> otherwise.\r\n        /// </returns>\r\n        public bool Equals(CsrfToken other)\r\n        {\r\n            if (ReferenceEquals(null, other)) return false;\r\n            if (ReferenceEquals(this, other)) return true;\r\n\r\n            return this.RandomBytes.SequenceEqual(other.RandomBytes)\r\n                && other.CreatedDate.Equals(this.CreatedDate)\r\n                && this.Hmac.SequenceEqual(other.Hmac);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determines whether the specified <see cref=\"T:System.Object\"/> is equal to the current <see cref=\"T:System.Object\"/>.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// true if the specified <see cref=\"T:System.Object\"/> is equal to the current <see cref=\"T:System.Object\"/>; otherwise, false.\r\n        /// </returns>\r\n        /// <param name=\"obj\">The <see cref=\"T:System.Object\"/> to compare with the current <see cref=\"T:System.Object\"/>. </param><filterpriority>2</filterpriority>\r\n        public override bool Equals(object obj)\r\n        {\r\n            if (ReferenceEquals(null, obj)) return false;\r\n            if (ReferenceEquals(this, obj)) return true;\r\n            if (obj.GetType() != typeof(CsrfToken)) return false;\r\n            return Equals((CsrfToken)obj);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Serves as a hash function for a particular type.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// A hash code for the current <see cref=\"T:System.Object\"/>.\r\n        /// </returns>\r\n        /// <filterpriority>2</filterpriority>\r\n        public override int GetHashCode()\r\n        {\r\n            unchecked\r\n            {\r\n                int result = (this.RandomBytes != null ? this.RandomBytes.GetHashCode() : 0);\r\n                result = (result*397) ^ this.CreatedDate.GetHashCode();\r\n                result = (result*397) ^ (this.Hmac != null ? this.Hmac.GetHashCode() : 0);\r\n                return result;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Implements the operator == for <see cref=\"CsrfToken\"/> instances.\r\n        /// </summary>\r\n        /// <param name=\"left\">The left <see cref=\"CsrfToken\"/>.</param>\r\n        /// <param name=\"right\">The right <see cref=\"CsrfToken\"/>.</param>\r\n        /// <returns>\r\n        /// <c>true</c> if left and right <see cref=\"CsrfToken\"/> instances are equal.\r\n        /// </returns>\r\n        public static bool operator ==(CsrfToken left, CsrfToken right)\r\n        {\r\n            return Equals(left, right);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Implements the operator != for <see cref=\"CsrfToken\"/> instances.\r\n        /// </summary>\r\n        /// <param name=\"left\">The left <see cref=\"CsrfToken\"/>.</param>\r\n        /// <param name=\"right\">The right <see cref=\"CsrfToken\"/>.</param>\r\n        /// <returns>\r\n        /// <c>true</c> if left and right <see cref=\"CsrfToken\"/> instances are not equal.\r\n        /// </returns>\r\n        public static bool operator !=(CsrfToken left, CsrfToken right)\r\n        {\r\n            return !Equals(left, right);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Security/CsrfTokenExtensions.cs",
    "content": "﻿namespace Nancy.Security\r\n{\r\n    using System;\r\n    using System.Linq;\r\n    using System.Security.Cryptography;\r\n\r\n    using Nancy.Cryptography;\r\n\r\n    /// <summary>\r\n    /// Extension methods for CSRF token related tasks.\r\n    /// </summary>\r\n    public static class CsrfTokenExtensions\r\n    {\r\n        private static readonly RandomNumberGenerator randomGenerator = RandomNumberGenerator.Create();\r\n\r\n        /// <summary>\r\n        /// Gets a byte array representation of the csrf token for generating\r\n        /// hmacs\r\n        /// </summary>\r\n        /// <param name=\"token\">Token</param>\r\n        /// <returns>Byte array representing the token</returns>\r\n        public static byte[] GetCsrfTokenBytes(this CsrfToken token)\r\n        {\r\n            return token.RandomBytes\r\n                        .Concat(BitConverter.GetBytes(token.CreatedDate.UtcTicks))\r\n                        .ToArray();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Calculates and sets the Hmac property on a given token\r\n        /// </summary>\r\n        /// <param name=\"token\">Token</param>\r\n        /// <param name=\"hmacProvider\">Hmac provider to use</param>\r\n        /// <returns>Hmac bytes</returns>\r\n        public static void CreateHmac(this CsrfToken token, IHmacProvider hmacProvider)\r\n        {\r\n            token.Hmac = hmacProvider.GenerateHmac(token.GetCsrfTokenBytes());\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates random bytes for the csrf token\r\n        /// </summary>\r\n        /// <returns>Random byte array</returns>\r\n        public static void CreateRandomBytes(this CsrfToken token)\r\n        {\r\n            var randomBytes = new byte[10];\r\n\r\n            randomGenerator.GetBytes(randomBytes);\r\n\r\n            token.RandomBytes = randomBytes;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Security/CsrfTokenValidationResult.cs",
    "content": "﻿namespace Nancy.Security\r\n{\r\n    /// <summary>\r\n    /// Result of Csrf Token validation\r\n    /// </summary>\r\n    public enum CsrfTokenValidationResult\r\n    {\r\n        /// <summary>\r\n        /// Validated ok\r\n        /// </summary>\r\n        Ok,\r\n\r\n        /// <summary>\r\n        /// One or both of the tokens appears to have been tampered with\r\n        /// </summary>\r\n        TokenTamperedWith,\r\n\r\n        /// <summary>\r\n        /// One or both of the tokens are missing\r\n        /// </summary>\r\n        TokenMissing,\r\n\r\n        /// <summary>\r\n        /// Tokens to not match\r\n        /// </summary>\r\n        TokenMismatch,\r\n\r\n        /// <summary>\r\n        /// Token is valid, but has expired\r\n        /// </summary>\r\n        TokenExpired,\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Security/CsrfValidationException.cs",
    "content": "namespace Nancy.Security\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Contains the exception information about a CSRF token validation.\r\n    /// </summary>\r\n    /// <seealso cref=\"System.Exception\" />\r\n    public class CsrfValidationException : Exception\r\n    {\r\n        /// <summary>\r\n        /// Gets the result for the CSRF token validation.\r\n        /// </summary>\r\n        /// <value>\r\n        /// The result.\r\n        /// </value>\r\n        public CsrfTokenValidationResult Result { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"CsrfValidationException\"/> class, with\r\n        /// the provided <paramref name=\"result\"/>.\r\n        /// </summary>\r\n        /// <param name=\"result\">The CSRF token validation result.</param>\r\n        public CsrfValidationException(CsrfTokenValidationResult result)\r\n            : base(result.ToString())\r\n        {\r\n            Result = result;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Security/DefaultCsrfTokenValidator.cs",
    "content": "namespace Nancy.Security\r\n{\r\n    using System;\r\n    using System.Linq;\r\n\r\n    using Nancy.Cryptography;\r\n\r\n    /// <summary>\r\n    /// The default implementation of the <see cref=\"ICsrfTokenValidator\"/> interface.\r\n    /// </summary>\r\n    public class DefaultCsrfTokenValidator : ICsrfTokenValidator\r\n    {\r\n        private readonly IHmacProvider hmacProvider;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultCsrfTokenValidator\"/> class,\r\n        /// using the provided <paramref name=\"cryptoConfig\"/>.\r\n        /// </summary>\r\n        /// <param name=\"cryptoConfig\">The <see cref=\"CryptographyConfiguration\"/> that should be used.</param>\r\n        public DefaultCsrfTokenValidator(CryptographyConfiguration cryptoConfig)\r\n        {\r\n            this.hmacProvider = cryptoConfig.HmacProvider;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Validates a pair of tokens\r\n        /// </summary>\r\n        /// <param name=\"tokenOne\">First token (usually from either a form post or querystring)</param>\r\n        /// <param name=\"tokenTwo\">Second token (usually from a cookie)</param>\r\n        /// <param name=\"validityPeriod\">Optional period that the tokens are valid for</param>\r\n        /// <returns>Token validation result</returns>\r\n        public CsrfTokenValidationResult Validate(CsrfToken tokenOne, CsrfToken tokenTwo, TimeSpan? validityPeriod = new TimeSpan?())\r\n        {\r\n            if (tokenOne == null || tokenTwo == null)\r\n            {\r\n                return CsrfTokenValidationResult.TokenMissing;\r\n            }\r\n\r\n            if (!tokenOne.Equals(tokenTwo))\r\n            {\r\n                return CsrfTokenValidationResult.TokenMismatch;\r\n            }\r\n\r\n            if (tokenOne.RandomBytes == null || tokenOne.RandomBytes.Length == 0)\r\n            {\r\n                return CsrfTokenValidationResult.TokenTamperedWith;\r\n            }\r\n\r\n            var newToken = new CsrfToken\r\n                               {\r\n                                   CreatedDate = tokenOne.CreatedDate,\r\n                                   RandomBytes = tokenOne.RandomBytes,\r\n                               };\r\n            newToken.CreateHmac(this.hmacProvider);\r\n            if (!newToken.Hmac.SequenceEqual(tokenOne.Hmac))\r\n            {\r\n                return CsrfTokenValidationResult.TokenTamperedWith;\r\n            }\r\n\r\n            if (validityPeriod.HasValue)\r\n            {\r\n                var expiryDate = tokenOne.CreatedDate.Add(validityPeriod.Value);\r\n\r\n                if (DateTimeOffset.Now > expiryDate)\r\n                {\r\n                    return CsrfTokenValidationResult.TokenExpired;\r\n                }\r\n            }\r\n\r\n            return CsrfTokenValidationResult.Ok;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Validates that a cookie token is still valid with the current configuration / keys\r\n        /// </summary>\r\n        /// <param name=\"cookieToken\">Token to validate</param>\r\n        /// <returns>True if valid, false otherwise</returns>\r\n        public bool CookieTokenStillValid(CsrfToken cookieToken)\r\n        {\r\n            if (cookieToken == null || cookieToken.RandomBytes == null || cookieToken.RandomBytes.Length == 0)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            var newToken = new CsrfToken\r\n            {\r\n                CreatedDate = cookieToken.CreatedDate,\r\n                RandomBytes = cookieToken.RandomBytes,\r\n            };\r\n            newToken.CreateHmac(this.hmacProvider);\r\n\r\n            if (!newToken.Hmac.SequenceEqual(cookieToken.Hmac))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            return true;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Security/ICsrfTokenValidator.cs",
    "content": "﻿namespace Nancy.Security\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Validates Csrf tokens\r\n    /// </summary>\r\n    public interface ICsrfTokenValidator\r\n    {\r\n        /// <summary>\r\n        /// Validates a pair of tokens\r\n        /// </summary>\r\n        /// <param name=\"tokenOne\">First token (usually from either a form post or querystring)</param>\r\n        /// <param name=\"tokenTwo\">Second token (usually from a cookie)</param>\r\n        /// <param name=\"validityPeriod\">Optional period that the tokens are valid for</param>\r\n        /// <returns>Token validation result</returns>\r\n        CsrfTokenValidationResult Validate(CsrfToken tokenOne, CsrfToken tokenTwo, TimeSpan? validityPeriod = null);\r\n\r\n        /// <summary>\r\n        /// Validates that a cookie token is still valid with the current configuration / keys\r\n        /// </summary>\r\n        /// <param name=\"cookieToken\">Token to validate</param>\r\n        /// <returns>True if valid, false otherwise</returns>\r\n        bool CookieTokenStillValid(CsrfToken cookieToken);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Security/ModuleSecurity.cs",
    "content": "namespace Nancy.Security\r\n{\r\n    using System;\r\n    using System.Linq;\r\n    using System.Security.Claims;\r\n\r\n    using Nancy.Extensions;\r\n    using Nancy.Responses;\r\n\r\n    /// <summary>\r\n    /// Some simple helpers give some nice authentication syntax in the modules.\r\n    /// </summary>\r\n    public static class ModuleSecurity\r\n    {\r\n        /// <summary>\r\n        /// This module requires authentication\r\n        /// </summary>\r\n        /// <param name=\"module\">Module to enable</param>\r\n        public static void RequiresAuthentication(this INancyModule module)\r\n        {\r\n            module.AddBeforeHookOrExecute(SecurityHooks.RequiresAuthentication(), \"Requires Authentication\");\r\n        }\r\n\r\n        /// <summary>\r\n        /// This module requires authentication and certain claims to be present.\r\n        /// </summary>\r\n        /// <param name=\"module\">Module to enable</param>\r\n        /// <param name=\"requiredClaims\">Claim(s) required</param>\r\n        public static void RequiresClaims(this INancyModule module, params Predicate<Claim>[] requiredClaims)\r\n        {\r\n            module.AddBeforeHookOrExecute(SecurityHooks.RequiresAuthentication(), \"Requires Authentication\");\r\n            module.AddBeforeHookOrExecute(SecurityHooks.RequiresClaims(requiredClaims), \"Requires Claims\");\r\n        }\r\n\r\n        /// <summary>\r\n        /// This module requires authentication and any one of certain claims to be present.\r\n        /// </summary>\r\n        /// <param name=\"module\">Module to enable</param>\r\n        /// <param name=\"requiredClaims\">Claim(s) required</param>\r\n        public static void RequiresAnyClaim(this INancyModule module, params Predicate<Claim>[] requiredClaims)\r\n        {\r\n            module.AddBeforeHookOrExecute(SecurityHooks.RequiresAuthentication(), \"Requires Authentication\");\r\n            module.AddBeforeHookOrExecute(SecurityHooks.RequiresAnyClaim(requiredClaims), \"Requires Any Claim\");\r\n        }\r\n\r\n        /// <summary>\r\n        /// This module requires authentication and certain roles to be present.\r\n        /// </summary>\r\n        /// <param name=\"module\">Module to enable</param>\r\n        /// <param name=\"requiredRoles\">Role(s) required</param>\r\n        public static void RequiresRoles(this INancyModule module, params string[] requiredRoles)\r\n        {\r\n            module.AddBeforeHookOrExecute(SecurityHooks.RequiresAuthentication(), \"Requires Authentication\");\r\n            module.AddBeforeHookOrExecute(SecurityHooks.RequiresRoles(requiredRoles), \"Requires Roles\");\r\n        }\r\n\r\n        /// <summary>\r\n        /// This module requires authentication and any one of certain roles to be present.\r\n        /// </summary>\r\n        /// <param name=\"module\">Module to enable</param>\r\n        /// <param name=\"requiredRoles\">Role(s) at least one of which is required</param>\r\n        public static void RequiresAnyRole(this INancyModule module, params string[] requiredRoles)\r\n        {\r\n            module.AddBeforeHookOrExecute(SecurityHooks.RequiresAuthentication(), \"Requires Authentication\");\r\n            module.AddBeforeHookOrExecute(SecurityHooks.RequiresAnyRole(requiredRoles), \"Requires Any Role\");\r\n        }\r\n        \r\n        /// <summary>\r\n        /// This module requires https.\r\n        /// </summary>\r\n        /// <param name=\"module\">The <see cref=\"INancyModule\"/> that requires HTTPS.</param>\r\n        public static void RequiresHttps(this INancyModule module)\r\n        {\r\n            module.RequiresHttps(true);\r\n        }\r\n\r\n        /// <summary>\r\n        /// This module requires https.\r\n        /// </summary>\r\n        /// <param name=\"module\">The <see cref=\"INancyModule\"/> that requires HTTPS.</param>\r\n        /// <param name=\"redirect\"><see langword=\"true\"/> if the user should be redirected to HTTPS (no port number) if the incoming request was made using HTTP, otherwise <see langword=\"false\"/> if <see cref=\"HttpStatusCode.Forbidden\"/> should be returned.</param>\r\n        public static void RequiresHttps(this INancyModule module, bool redirect)\r\n        {\r\n            module.Before.AddItemToEndOfPipeline(SecurityHooks.RequiresHttps(redirect, null));\r\n        }\r\n\r\n        /// <summary>\r\n        /// This module requires https.\r\n        /// </summary>\r\n        /// <param name=\"module\">The <see cref=\"INancyModule\"/> that requires HTTPS.</param>\r\n        /// <param name=\"redirect\"><see langword=\"true\"/> if the user should be redirected to HTTPS if the incoming request was made using HTTP, otherwise <see langword=\"false\"/> if <see cref=\"HttpStatusCode.Forbidden\"/> should be returned.</param>\r\n        /// <param name=\"httpsPort\">The HTTPS port number to use</param>\r\n        public static void RequiresHttps(this INancyModule module, bool redirect, int httpsPort)\r\n        {\r\n            module.Before.AddItemToEndOfPipeline(SecurityHooks.RequiresHttps(redirect, httpsPort));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Security/SSLProxy.cs",
    "content": "﻿namespace Nancy.Security\r\n{\r\n    using System;\r\n    using System.Linq;\r\n\r\n    using Nancy.Bootstrapper;\r\n\r\n    /// <summary>\r\n    /// Allows a BeforeRequest hook to change Url to HTTPS if X-Forwarded-Proto header present\r\n    /// </summary>\r\n    public static class SSLProxy\r\n    {\r\n        /// <summary>\r\n        /// Checks for Forwarded or X-Forwarded-Proto header and if so makes current url scheme https\r\n        /// </summary>\r\n        /// <param name=\"pipelines\">Application pipelines</param>\r\n        public static void RewriteSchemeUsingForwardedHeaders(IPipelines pipelines)\r\n        {\r\n            pipelines.BeforeRequest += ctx =>\r\n            {\r\n                //X-Forwarded-Proto: https\r\n                if (ctx.Request.Headers.Keys.Any(x => x.Equals(\"X-Forwarded-Proto\", StringComparison.OrdinalIgnoreCase)))\r\n                {\r\n                    if (ctx.Request.Headers[\"X-Forwarded-Proto\"].Contains(\"https\", StringComparer.OrdinalIgnoreCase))\r\n                    {\r\n                        ctx.Request.Url.Scheme = \"https\";\r\n                    }\r\n                }\r\n\r\n                //RFC7239\r\n                if (ctx.Request.Headers.Keys.Any(x => x.Equals(\"Forwarded\", StringComparison.OrdinalIgnoreCase)))\r\n                {\r\n                    var forwardedHeader = ctx.Request.Headers[\"Forwarded\"];\r\n                    var protoValue = forwardedHeader.FirstOrDefault(x => x.StartsWith(\"proto\", StringComparison.OrdinalIgnoreCase));\r\n                    if (protoValue != null && protoValue.Equals(\"proto=https\", StringComparison.OrdinalIgnoreCase))\r\n                    {\r\n                        ctx.Request.Url.Scheme = \"https\";\r\n                    }\r\n                }\r\n\r\n                return null;\r\n            };\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Security/SecurityHooks.cs",
    "content": "﻿namespace Nancy.Security\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Security.Claims;\r\n\r\n    using Nancy.Responses;\r\n\r\n    /// <summary>\r\n    /// Hooks to be used in a request pipeline.\r\n    /// </summary>\r\n    public static class SecurityHooks\r\n    {\r\n        /// <summary>\r\n        /// Creates a hook to be used in a pipeline before a route handler to ensure that\r\n        /// the request was made by an authenticated user.\r\n        /// </summary>\r\n        /// <returns>Hook that returns an Unauthorized response if not authenticated in,\r\n        /// null otherwise</returns>\r\n        public static Func<NancyContext, Response> RequiresAuthentication()\r\n        {\r\n            return UnauthorizedIfNot(ctx => ctx.CurrentUser.IsAuthenticated());\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a hook to be used in a pipeline before a route handler to ensure\r\n        /// that the request was made by an authenticated user having the required claims.\r\n        /// </summary>\r\n        /// <param name=\"claims\">Claims the authenticated user needs to have</param>\r\n        /// <returns>Hook that returns an Unauthorized response if the user is not\r\n        /// authenticated or does not have the required claims, null otherwise</returns>\r\n        public static Func<NancyContext, Response> RequiresClaims(params Predicate<Claim>[] claims)\r\n        {\r\n            return ForbiddenIfNot(ctx => ctx.CurrentUser.HasClaims(claims));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a hook to be used in a pipeline before a route handler to ensure\r\n        /// that the request was made by an authenticated user having at least one of\r\n        /// the required claims.\r\n        /// </summary>\r\n        /// <param name=\"claims\">Claims the authenticated user needs to have at least one of</param>\r\n        /// <returns>Hook that returns an Unauthorized response if the user is not\r\n        /// authenticated or does not have at least one of the required claims, null\r\n        /// otherwise</returns>\r\n        public static Func<NancyContext, Response> RequiresAnyClaim(params Predicate<Claim>[] claims)\r\n        {\r\n            return ForbiddenIfNot(ctx => ctx.CurrentUser.HasAnyClaim(claims));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a hook to be used in a pipeline before a route handler to ensure\r\n        /// that the request was made by an authenticated user whose claims satisfy the\r\n        /// supplied validation function.\r\n        /// </summary>\r\n        /// <param name=\"isValid\">Validation function to be called with the authenticated\r\n        /// users claims</param>\r\n        /// <returns>Hook that returns an Unauthorized response if the user is not\r\n        /// authenticated or does not pass the supplied validation function, null\r\n        /// otherwise</returns>\r\n        public static Func<NancyContext, Response> RequiresValidatedClaims(Func<IEnumerable<Claim>, bool> isValid)\r\n        {\r\n            return ForbiddenIfNot(ctx => ctx.CurrentUser.HasValidClaims(isValid));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a hook to be used in a pipeline before a route handler to ensure\r\n        /// that the request was made by an authenticated user being in all of\r\n        /// the required roles.\r\n        /// </summary>\r\n        /// <param name=\"roles\">Roles the authenticated user needs to be in</param>\r\n        /// <returns>Hook that returns an Unauthorized response if the user is not\r\n        /// authenticated or is not in all of the required roles, null\r\n        /// otherwise</returns>\r\n        public static Func<NancyContext, Response> RequiresRoles(params string[] roles)\r\n        {\r\n            return ForbiddenIfNot(ctx => ctx.CurrentUser.IsInRoles(roles));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a hook to be used in a pipeline before a route handler to ensure\r\n        /// that the request was made by an authenticated user being in at least one of\r\n        /// the required roles.\r\n        /// </summary>\r\n        /// <param name=\"roles\">Roles the authenticated user needs to be in at least one of</param>\r\n        /// <returns>Hook that returns an Unauthorized response if the user is not\r\n        /// authenticated or is not in at least one of the required roles, null\r\n        /// otherwise</returns>\r\n        public static Func<NancyContext, Response> RequiresAnyRole(params string[] roles)\r\n        {\r\n            return ForbiddenIfNot(ctx => ctx.CurrentUser.IsInAnyRole(roles));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a hook to be used in a pipeline before a route handler to ensure that\r\n        /// the request satisfies a specific test.\r\n        /// </summary>\r\n        /// <param name=\"test\">Test that must return true for the request to continue</param>\r\n        /// <returns>Hook that returns an Unauthorized response if the test fails, null otherwise</returns>\r\n        private static Func<NancyContext, Response> UnauthorizedIfNot(Func<NancyContext, bool> test)\r\n        {\r\n            return HttpStatusCodeIfNot(HttpStatusCode.Unauthorized, test);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a hook to be used in a pipeline before a route handler to ensure that\r\n        /// the request satisfies a specific test.\r\n        /// </summary>\r\n        /// <param name=\"test\">Test that must return true for the request to continue</param>\r\n        /// <returns>Hook that returns an Forbidden response if the test fails, null otherwise</returns>\r\n        private static Func<NancyContext, Response> ForbiddenIfNot(Func<NancyContext, bool> test)\r\n        {\r\n            return HttpStatusCodeIfNot(HttpStatusCode.Forbidden, test);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a hook to be used in a pipeline before a route handler to ensure that\r\n        /// the request satisfies a specific test.\r\n        /// </summary>\r\n        /// <param name=\"statusCode\">HttpStatusCode to use for the response</param>\r\n        /// <param name=\"test\">Test that must return true for the request to continue</param>\r\n        /// <returns>Hook that returns a response with a specific HttpStatusCode if the test fails, null otherwise</returns>\r\n        private static Func<NancyContext, Response> HttpStatusCodeIfNot(HttpStatusCode statusCode, Func<NancyContext, bool> test)\r\n        {\r\n            return (ctx) =>\r\n            {\r\n                Response response = null;\r\n                if (!test(ctx))\r\n                {\r\n                    response = new Response { StatusCode = statusCode };\r\n                }\r\n\r\n                return response;\r\n            };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a hook to be used in a pipeline before a route handler to ensure that\r\n        /// the resource is served over HTTPS\r\n        /// </summary>\r\n        /// <param name=\"redirect\"><see langword=\"true\"/> if the user should be redirected to HTTPS (no port number) if the incoming request was made using HTTP, otherwise <see langword=\"false\"/> if <see cref=\"HttpStatusCode.Forbidden\"/> should be returned.</param>\r\n        /// <param name=\"httpsPort\">The HTTPS port number to use</param>\r\n        /// <returns>Hook that returns a <see cref=\"RedirectResponse\"/> with the Url scheme set to HTTPS,\r\n        /// or a <see cref=\"Response\"/> with a <see cref=\"HttpStatusCode.Forbidden\"/> status code if <c>redirect</c> is false or the method is not GET,\r\n        /// null otherwise</returns>\r\n        public static Func<NancyContext, Response> RequiresHttps(bool redirect, int? httpsPort = null)\r\n        {\r\n            return (ctx) =>\r\n            {\r\n                Response response = null;\r\n                var request = ctx.Request;\r\n                if (!request.Url.IsSecure)\r\n                {\r\n                    if (redirect && request.Method.Equals(\"GET\", StringComparison.OrdinalIgnoreCase))\r\n                    {\r\n                        var redirectUrl = request.Url.Clone();\r\n                        redirectUrl.Port = httpsPort;\r\n                        redirectUrl.Scheme = \"https\";\r\n                        response = new RedirectResponse(redirectUrl.ToString());\r\n                    }\r\n                    else\r\n                    {\r\n                        response = new Response { StatusCode = HttpStatusCode.Forbidden };\r\n                    }\r\n                }\r\n\r\n                return response;\r\n            };\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Session/CookieBasedSessions.cs",
    "content": "namespace Nancy.Session\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Text;\r\n\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Cookies;\r\n    using Nancy.Cryptography;\r\n    using Nancy.Helpers;\r\n\r\n    /// <summary>\r\n    /// Cookie based session storage\r\n    /// </summary>\r\n    public class CookieBasedSessions : IObjectSerializerSelector\r\n    {\r\n        private readonly CookieBasedSessionsConfiguration currentConfiguration;\r\n\r\n        /// <summary>\r\n        /// Gets the cookie name that the session is stored in\r\n        /// </summary>\r\n        /// <value>Cookie name</value>\r\n        public string CookieName\r\n        {\r\n            get { return this.currentConfiguration.CookieName; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"CookieBasedSessions\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"encryptionProvider\">The encryption provider.</param>\r\n        /// <param name=\"hmacProvider\">The hmac provider</param>\r\n        /// <param name=\"objectSerializer\">Session object serializer to use</param>\r\n        public CookieBasedSessions(IEncryptionProvider encryptionProvider, IHmacProvider hmacProvider, IObjectSerializer objectSerializer)\r\n        {\r\n            this.currentConfiguration = new CookieBasedSessionsConfiguration\r\n            {\r\n                Serializer = objectSerializer,\r\n                CryptographyConfiguration = new CryptographyConfiguration(encryptionProvider, hmacProvider)\r\n            };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"CookieBasedSessions\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"configuration\">Cookie based sessions configuration.</param>\r\n        public CookieBasedSessions(CookieBasedSessionsConfiguration configuration)\r\n        {\r\n            if (configuration == null)\r\n            {\r\n                throw new ArgumentNullException(\"configuration\");\r\n            }\r\n\r\n            if (!configuration.IsValid)\r\n            {\r\n                throw new ArgumentException(\"Configuration is invalid\", \"configuration\");\r\n            }\r\n            this.currentConfiguration = configuration;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initialise and add cookie based session hooks to the application pipeline\r\n        /// </summary>\r\n        /// <param name=\"pipelines\">Application pipelines</param>\r\n        /// <param name=\"configuration\">Cookie based sessions configuration.</param>\r\n        /// <returns>Formatter selector for choosing a non-default serializer</returns>\r\n        public static IObjectSerializerSelector Enable(IPipelines pipelines, CookieBasedSessionsConfiguration configuration)\r\n        {\r\n            if (pipelines == null)\r\n            {\r\n                throw new ArgumentNullException(\"pipelines\");\r\n            }\r\n\r\n            var sessionStore = new CookieBasedSessions(configuration);\r\n\r\n            pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx => LoadSession(ctx, sessionStore));\r\n            pipelines.AfterRequest.AddItemToEndOfPipeline(ctx => SaveSession(ctx, sessionStore));\r\n\r\n            return sessionStore;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initialise and add cookie based session hooks to the application pipeline\r\n        /// </summary>\r\n        /// <param name=\"pipelines\">Application pipelines</param>\r\n        /// <param name=\"cryptographyConfiguration\">Cryptography configuration</param>\r\n        /// <returns>Formatter selector for choosing a non-default serializer</returns>\r\n        public static IObjectSerializerSelector Enable(IPipelines pipelines, CryptographyConfiguration cryptographyConfiguration)\r\n        {\r\n            var cookieBasedSessionsConfiguration = new CookieBasedSessionsConfiguration(cryptographyConfiguration)\r\n            {\r\n                Serializer = new DefaultObjectSerializer()\r\n            };\r\n            return Enable(pipelines, cookieBasedSessionsConfiguration);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initialise and add cookie based session hooks to the application pipeline with the default encryption provider.\r\n        /// </summary>\r\n        /// <param name=\"pipelines\">Application pipelines</param>\r\n        /// <returns>Formatter selector for choosing a non-default serializer</returns>\r\n        public static IObjectSerializerSelector Enable(IPipelines pipelines)\r\n        {\r\n            return Enable(pipelines, new CookieBasedSessionsConfiguration\r\n            {\r\n                Serializer = new DefaultObjectSerializer()\r\n            });\r\n        }\r\n\r\n        /// <summary>\r\n        /// Using the specified serializer\r\n        /// </summary>\r\n        /// <param name=\"newSerializer\">Formatter to use</param>\r\n        public void WithSerializer(IObjectSerializer newSerializer)\r\n        {\r\n            this.currentConfiguration.Serializer = newSerializer;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Save the session into the response\r\n        /// </summary>\r\n        /// <param name=\"session\">Session to save</param>\r\n        /// <param name=\"response\">Response to save into</param>\r\n        public void Save(ISession session, Response response)\r\n        {\r\n            if (session == null || !session.HasChanged)\r\n            {\r\n                return;\r\n            }\r\n\r\n            var sb = new StringBuilder();\r\n            foreach (var kvp in session)\r\n            {\r\n                sb.Append(HttpUtility.UrlEncode(kvp.Key));\r\n                sb.Append(\"=\");\r\n\r\n                var objectString = this.currentConfiguration.Serializer.Serialize(kvp.Value);\r\n\r\n                sb.Append(HttpUtility.UrlEncode(objectString));\r\n                sb.Append(\";\");\r\n            }\r\n\r\n            var cryptographyConfiguration = this.currentConfiguration.CryptographyConfiguration;\r\n            var encryptedData = cryptographyConfiguration.EncryptionProvider.Encrypt(sb.ToString());\r\n            var hmacBytes = cryptographyConfiguration.HmacProvider.GenerateHmac(encryptedData);\r\n            var cookieData = HttpUtility.UrlEncode(String.Format(\"{0}{1}\", Convert.ToBase64String(hmacBytes), encryptedData));\r\n\r\n            var cookie = new NancyCookie(this.currentConfiguration.CookieName, cookieData, true)\r\n            {\r\n                Domain = this.currentConfiguration.Domain,\r\n                Path = this.currentConfiguration.Path\r\n            };\r\n            response.WithCookie(cookie);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Loads the session from the request\r\n        /// </summary>\r\n        /// <param name=\"request\">Request to load from</param>\r\n        /// <returns>ISession containing the load session values</returns>\r\n        public ISession Load(Request request)\r\n        {\r\n            var dictionary = new Dictionary<string, object>();\r\n\r\n            var cookieName = this.currentConfiguration.CookieName;\r\n            var hmacProvider = this.currentConfiguration.CryptographyConfiguration.HmacProvider;\r\n            var encryptionProvider = this.currentConfiguration.CryptographyConfiguration.EncryptionProvider;\r\n            string cookieValue;\r\n            if (request.Cookies.TryGetValue(cookieName, out cookieValue))\r\n            {\r\n                var cookieData = HttpUtility.UrlDecode(cookieValue);\r\n                var hmacLength = Base64Helpers.GetBase64Length(hmacProvider.HmacLength);\r\n                if (cookieData.Length < hmacLength)\r\n                {\r\n                  return new Session(dictionary);\r\n                }\r\n\r\n                var hmacString = cookieData.Substring(0, hmacLength);\r\n                var encryptedCookie = cookieData.Substring(hmacLength);\r\n\r\n                var hmacBytes = Convert.FromBase64String(hmacString);\r\n                var newHmac = hmacProvider.GenerateHmac(encryptedCookie);\r\n                var hmacValid = HmacComparer.Compare(newHmac, hmacBytes, hmacProvider.HmacLength);\r\n\r\n                var data = encryptionProvider.Decrypt(encryptedCookie);\r\n                var parts = data.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);\r\n                foreach (var part in parts.Select(part => part.Split('=')).Where(part => part.Length == 2))\r\n                {\r\n                    var valueObject = this.currentConfiguration.Serializer.Deserialize(HttpUtility.UrlDecode(part[1]));\r\n\r\n                    dictionary[HttpUtility.UrlDecode(part[0])] = valueObject;\r\n                }\r\n\r\n                if (!hmacValid)\r\n                {\r\n                    dictionary.Clear();\r\n                }\r\n            }\r\n\r\n            return new Session(dictionary);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Saves the request session into the response\r\n        /// </summary>\r\n        /// <param name=\"context\">Nancy context</param>\r\n        /// <param name=\"sessionStore\">Session store</param>\r\n        private static void SaveSession(NancyContext context, CookieBasedSessions sessionStore)\r\n        {\r\n            sessionStore.Save(context.Request.Session, context.Response);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Loads the request session\r\n        /// </summary>\r\n        /// <param name=\"context\">Nancy context</param>\r\n        /// <param name=\"sessionStore\">Session store</param>\r\n        /// <returns>Always returns null</returns>\r\n        private static Response LoadSession(NancyContext context, CookieBasedSessions sessionStore)\r\n        {\r\n            if (context.Request == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            context.Request.Session = sessionStore.Load(context.Request);\r\n\r\n            return null;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Session/CookieBasedSessionsConfiguration.cs",
    "content": "namespace Nancy.Session\r\n{\r\n    using Nancy.Cryptography;\r\n\r\n    /// <summary>\r\n    /// Configuration options for cookie based sessions\r\n    /// </summary>\r\n    public class CookieBasedSessionsConfiguration\r\n    {\r\n        internal const string DefaultCookieName = \"_nc\";\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"CookieBasedSessionsConfiguration\"/> class.\r\n        /// </summary>\r\n        public CookieBasedSessionsConfiguration() : this(CryptographyConfiguration.Default)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"CookieBasedSessionsConfiguration\"/> class.\r\n        /// </summary>\r\n        public CookieBasedSessionsConfiguration(CryptographyConfiguration cryptographyConfiguration)\r\n        {\r\n            CryptographyConfiguration = cryptographyConfiguration;\r\n            CookieName = DefaultCookieName;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the cryptography configuration\r\n        /// </summary>\r\n        public CryptographyConfiguration CryptographyConfiguration { get; set; }\r\n\r\n        /// <summary>\r\n        /// Formatter for de/serializing the session objects\r\n        /// </summary>\r\n        public IObjectSerializer Serializer { get; set; }\r\n\r\n        /// <summary>\r\n        /// Cookie name for storing session information\r\n        /// </summary>\r\n        public string CookieName { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the domain of the session cookie\r\n        /// </summary>\r\n        public string Domain { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the path of the session cookie\r\n        /// </summary>\r\n        public string Path { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether the configuration is valid or not.\r\n        /// </summary>\r\n        public virtual bool IsValid\r\n        {\r\n            get\r\n            {\r\n                if (string.IsNullOrEmpty(this.CookieName))\r\n                {\r\n                    return false;\r\n                }\r\n\r\n                if (this.Serializer == null)\r\n                {\r\n                    return false;\r\n                }\r\n\r\n                if (this.CryptographyConfiguration == null)\r\n                {\r\n                    return false;\r\n                }\r\n\r\n                if (this.CryptographyConfiguration.EncryptionProvider == null)\r\n                {\r\n                    return false;\r\n                }\r\n\r\n                if (this.CryptographyConfiguration.HmacProvider == null)\r\n                {\r\n                    return false;\r\n                }\r\n\r\n                return true;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Session/ISession.cs",
    "content": "namespace Nancy.Session\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Defines the interface for a session\r\n    /// </summary>\r\n    public interface ISession : IEnumerable<KeyValuePair<string, object>>\r\n    {\r\n        /// <summary>\r\n        /// The number of session values\r\n        /// </summary>\r\n        /// <returns>The count of sessions</returns>\r\n        int Count { get; }\r\n\r\n        /// <summary>\r\n        /// Deletes the session and all associated information\r\n        /// </summary>\r\n        void DeleteAll();\r\n\r\n        /// <summary>\r\n        /// Deletes the specific key from the session\r\n        /// </summary>\r\n        void Delete(string key);\r\n\r\n        /// <summary>\r\n        /// Retrieves the value from the session\r\n        /// </summary>\r\n        object this[string key] { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether this instance has changed.\r\n        /// </summary>\r\n        /// <value>\r\n        /// <see langword=\"true\"/> if this instance has changed; otherwise, <see langword=\"false\"/>.\r\n        /// </value>\r\n        bool HasChanged { get; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Session/NullSessionProvider.cs",
    "content": "namespace Nancy.Session\r\n{\r\n    using System;\r\n    using System.Collections;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Provides a dummy session instance with no functionality.\r\n    /// </summary>\r\n    /// <seealso cref=\"Nancy.Session.ISession\" />\r\n    public class NullSessionProvider : ISession\r\n    {\r\n        /// <summary>\r\n        /// Returns an enumerator that iterates through the collection.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// A <see cref=\"T:System.Collections.Generic.IEnumerator`1\"/> that can be used to iterate through the collection.\r\n        /// </returns>\r\n        /// <filterpriority>1</filterpriority>\r\n        public IEnumerator<KeyValuePair<string, object>> GetEnumerator()\r\n        {\r\n            throw new InvalidOperationException(\"Session support is not enabled.\");\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an enumerator that iterates through a collection.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// An <see cref=\"T:System.Collections.IEnumerator\"/> object that can be used to iterate through the collection.\r\n        /// </returns>\r\n        /// <filterpriority>2</filterpriority>\r\n        IEnumerator IEnumerable.GetEnumerator()\r\n        {\r\n            return GetEnumerator();\r\n        }\r\n\r\n        /// <summary>\r\n        /// The number of session values\r\n        /// </summary>\r\n        /// <returns></returns>\r\n        public int Count\r\n        {\r\n            get\r\n            {\r\n                throw new InvalidOperationException(\"Session support is not enabled.\");\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Deletes the session and all associated information\r\n        /// </summary>\r\n        public void DeleteAll()\r\n        {\r\n            throw new InvalidOperationException(\"Session support is not enabled.\");\r\n        }\r\n\r\n        /// <summary>\r\n        /// Deletes the specific key from the session\r\n        /// </summary>\r\n        public void Delete(string key)\r\n        {\r\n            throw new InvalidOperationException(\"Session support is not enabled.\");\r\n        }\r\n\r\n        /// <summary>\r\n        /// Retrieves the value from the session\r\n        /// </summary>\r\n        public object this[string key]\r\n        {\r\n            get\r\n            {\r\n                throw new InvalidOperationException(\"Session support is not enabled.\");\r\n            }\r\n\r\n            set\r\n            {\r\n                throw new InvalidOperationException(\"Session support is not enabled.\");\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether this instance has changed.\r\n        /// </summary>\r\n        /// <value>\r\n        /// <see langword=\"true\"/> if this instance has changed; otherwise, <see langword=\"false\"/>.\r\n        /// </value>\r\n        public bool HasChanged\r\n        {\r\n            get\r\n            {\r\n                return false;\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Session/Session.cs",
    "content": "namespace Nancy.Session\r\n{\r\n    using System;\r\n    using System.Collections;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Session implementation\r\n    /// </summary>\r\n    public class Session : ISession\r\n    {\r\n        private readonly IDictionary<string, object> dictionary;\r\n        private bool hasChanged;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"Session\"/> class.\r\n        /// </summary>\r\n        public Session() : this(new Dictionary<string, object>(0)){}\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"Session\"/> class, with\r\n        /// the provided <paramref name=\"dictionary\"/>.\r\n        /// </summary>\r\n        /// <param name=\"dictionary\">The dictionary.</param>\r\n        public Session(IDictionary<string, object> dictionary)\r\n        {\r\n            this.dictionary = dictionary;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the number of items stored\r\n        /// </summary>\r\n        public int Count\r\n        {\r\n            get { return dictionary.Count; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Deletes all items\r\n        /// </summary>\r\n        public void DeleteAll()\r\n        {\r\n            if (Count > 0)\r\n            {\r\n                MarkAsChanged();\r\n            }\r\n\r\n            dictionary.Clear();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Delete an item with the given key\r\n        /// </summary>\r\n        /// <param name=\"key\">Key to delete</param>\r\n        public void Delete(string key)\r\n        {\r\n            if (dictionary.Remove(key)) { MarkAsChanged(); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets values\r\n        /// </summary>\r\n        /// <param name=\"key\">The key whos value to get or set</param>\r\n        /// <returns>The value, or null or the key didn't exist</returns>\r\n        public object this[string key]\r\n        {\r\n            get\r\n            {\r\n                object value;\r\n                return dictionary.TryGetValue(key, out value) ? value : null;\r\n            }\r\n            set\r\n            {\r\n                var existingValue = this[key] ?? new Object();\r\n\r\n                if (existingValue.Equals(value))\r\n                {\r\n                    return;\r\n                }\r\n\r\n                dictionary[key] = value;\r\n                MarkAsChanged();\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets whether the session has changed\r\n        /// </summary>\r\n        public bool HasChanged\r\n        {\r\n            get { return this.hasChanged; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an enumerator that iterates through a collection.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// An <see cref=\"T:System.Collections.IEnumerator\"/> object that can be used to iterate through the collection.\r\n        /// </returns>\r\n        /// <filterpriority>2</filterpriority>\r\n        IEnumerator IEnumerable.GetEnumerator()\r\n        {\r\n            return this.GetEnumerator();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an enumerator that iterates through the collection.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// A <see cref=\"T:System.Collections.Generic.IEnumerator`1\"/> that can be used to iterate through the collection.\r\n        /// </returns>\r\n        /// <filterpriority>1</filterpriority>\r\n        public IEnumerator<KeyValuePair<string, object>> GetEnumerator()\r\n        {\r\n            return dictionary.GetEnumerator();\r\n        }\r\n\r\n        private void MarkAsChanged()\r\n        {\r\n            hasChanged = true;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/StaticConfiguration.cs",
    "content": "namespace Nancy\r\n{\r\n    using System;\r\n    using System.Diagnostics;\r\n    using System.Linq;\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Diagnostics;\r\n\r\n    /// <summary>\r\n    /// Static configurations.\r\n    /// </summary>\r\n    public static class StaticConfiguration\r\n    {\r\n        static StaticConfiguration()\r\n        {\r\n            CaseSensitive = false;\r\n            RequestQueryFormMultipartLimit = 1000;\r\n            AllowFileStreamUploadAsync = true;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets a value indicating whether or not to enable case sensitivity in query, parameters (DynamicDictionary) and model binding. Enable this to conform with RFC3986.\r\n        /// </summary>\r\n        [Description(\"Enable case sensitivity in query, parameters (DynamicDictionary) and model binding. Enable this to conform with RFC3986.\")]\r\n        public static bool CaseSensitive { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the limit on the number of query string variables, form fields,\r\n        /// or multipart sections in a request.\r\n        /// </summary>\r\n        public static int RequestQueryFormMultipartLimit { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets a value indicating whether or not to disable request stream switching\r\n        /// </summary>\r\n        public static bool? DisableRequestStreamSwitching { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets a value indicating whether this <see cref=\"Nancy.StaticConfiguration\"/> allow file stream\r\n        /// upload async due to mono issues before v4.  Uploads of over 80mb would result in extra padded chars to the filestream corrupting the file.\r\n        /// </summary>\r\n        /// <value><c>true</c> if allow file stream upload async; otherwise, <c>false</c>.</value>\r\n        public static bool AllowFileStreamUploadAsync { get; set; }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/StaticContent.cs",
    "content": "namespace Nancy\r\n{\r\n    using System;\r\n    using System.Linq;\r\n\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Conventions;\r\n\r\n    /// <summary>\r\n    /// Registers the static contents hook in the application pipeline at startup.\r\n    /// </summary>\r\n    public class StaticContent : IApplicationStartup\r\n    {\r\n        private static IRootPathProvider rootPathProvider;\r\n        private static StaticContentsConventions conventions;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"StaticContent\"/> class, using the\r\n        /// provided <paramref name=\"rootPathProvider\"/> and <paramref name=\"conventions\"/>.\r\n        /// </summary>\r\n        /// <param name=\"rootPathProvider\">The current root path provider.</param>\r\n        /// <param name=\"conventions\">The static content conventions.</param>\r\n        public StaticContent(IRootPathProvider rootPathProvider, StaticContentsConventions conventions)\r\n        {\r\n            StaticContent.rootPathProvider = rootPathProvider;\r\n            StaticContent.conventions = conventions;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Perform any initialisation tasks\r\n        /// </summary>\r\n        public void Initialize(IPipelines pipelines)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Enable \"manual\" static content.\r\n        /// Only use this if you want to manually configure a pipeline hook to have static\r\n        /// content server, for example, after authentication.\r\n        /// </summary>\r\n        /// <param name=\"pipelines\">The pipelines to hook into</param>\r\n        public static void Enable(IPipelines pipelines)\r\n        {\r\n            var item = new PipelineItem<Func<NancyContext, Response>>(\"Static content\", ctx =>\r\n            {\r\n                return conventions\r\n                    .Select(convention => convention.Invoke(ctx, rootPathProvider.GetRootPath()))\r\n                    .FirstOrDefault(response => response != null);\r\n            });\r\n\r\n            pipelines.BeforeRequest.AddItemToStartOfPipeline(item);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/StaticContentConfiguration.cs",
    "content": "namespace Nancy\n{\n    using System.Collections.Generic;\n\n    /// <summary>\n    /// Static content configuration.\n    /// </summary>\n    public class StaticContentConfiguration\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"StaticContentConfiguration\"/> class.\n        /// </summary>\n        /// <param name=\"safePaths\">A set of safe paths to retrieve static content from</param>\n        public StaticContentConfiguration(IEnumerable<string> safePaths)\n        {\n            this.SafePaths = safePaths;\n        }\n\n        /// <summary>\n        /// Gets the safe paths to retrieve static content from.\n        /// </summary>\n        /// <value>Safe paths to retrieve static content from</value>\n        public IEnumerable<string> SafePaths { get; private set; }\n    }\n}"
  },
  {
    "path": "src/Nancy/StaticContentConfigurationExtensions.cs",
    "content": "﻿namespace Nancy\n{\n    using System.Collections.Generic;\n    using Nancy.Configuration;\n\n    /// <summary>\n    /// Contains <see cref=\"StaticContentConfiguration\"/> configuration extensions for <see cref=\"INancyEnvironment\"/>.  \n    /// </summary>\n    public static class StaticContentConfigurationExtensions\n    {\n        /// <summary>\n        /// Configures <see cref=\"StaticContentConfiguration\"/> \n        /// </summary>\n        /// <param name=\"environment\">An <see cref=\"INancyEnvironment\"/> that should be configured.</param>\n        /// <param name=\"safepaths\">Paths that the application consider safe to return static content from</param>\n        public static void StaticContent(this INancyEnvironment environment, params string[] safepaths)\n        {\n            environment.AddValue(new StaticContentConfiguration(\n               safePaths: safepaths));\n        }\n    }\n}\n\n"
  },
  {
    "path": "src/Nancy/TinyIoc/TinyIoC.cs",
    "content": "﻿#pragma warning disable CS1591, CS1574, CS1711, CS1712 //  Disable XML comment related warnings\r\n\r\n\r\n//===============================================================================\r\n// TinyIoC\r\n//\r\n// An easy to use, hassle free, Inversion of Control Container for small projects\r\n// and beginners alike.\r\n//\r\n// https://github.com/grumpydev/TinyIoC\r\n//===============================================================================\r\n// Copyright © Steven Robbins.  All rights reserved.\r\n// THIS CODE AND INFORMATION IS PROVIDED \"AS IS\" WITHOUT WARRANTY\r\n// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT\r\n// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\r\n// FITNESS FOR A PARTICULAR PURPOSE.\r\n//===============================================================================\r\n\r\n\r\n#region Preprocessor Directives\r\n// Uncomment this line if you want the container to automatically\r\n// register the TinyMessenger messenger/event aggregator\r\n//#define TINYMESSENGER\r\n\r\n// Uncomment this line if you want to internalize this library\r\n//#define TINYIOC_INTERNAL\r\n\r\n// Uncomment this line if you want to target PCL.\r\n//#define PORTABLE\r\n\r\n// Preprocessor directives for enabling/disabling functionality\r\n// depending on platform features. If the platform has an appropriate\r\n// #DEFINE then these should be set automatically below.\r\n#define EXPRESSIONS\r\n\r\n// Platform supports System.Linq.Expressions\r\n#define COMPILED_EXPRESSIONS                // Platform supports compiling expressions\r\n#define APPDOMAIN_GETASSEMBLIES             // Platform supports getting all assemblies from the AppDomain object\r\n#define UNBOUND_GENERICS_GETCONSTRUCTORS    // Platform supports GetConstructors on unbound generic types\r\n#define GETPARAMETERS_OPEN_GENERICS         // Platform supports GetParameters on open generics\r\n#define RESOLVE_OPEN_GENERICS               // Platform supports resolving open generics\r\n#define READER_WRITER_LOCK_SLIM             // Platform supports ReaderWriterLockSlim\r\n#define SERIALIZABLE                        // Platform supports SerializableAttribute/SerializationInfo/StreamingContext\r\n\r\n#if PORTABLE\r\n#undef APPDOMAIN_GETASSEMBLIES\r\n#undef COMPILED_EXPRESSIONS\r\n#undef READER_WRITER_LOCK_SLIM\r\n#endif\r\n\r\n// CompactFramework / Windows Phone 7\r\n// By default does not support System.Linq.Expressions.\r\n// AppDomain object does not support enumerating all assemblies in the app domain.\r\n#if PocketPC || WINDOWS_PHONE\r\n#undef EXPRESSIONS\r\n#undef COMPILED_EXPRESSIONS\r\n#undef APPDOMAIN_GETASSEMBLIES\r\n#undef UNBOUND_GENERICS_GETCONSTRUCTORS\r\n#endif\r\n\r\n// PocketPC has a bizarre limitation on enumerating parameters on unbound generic methods.\r\n// We need to use a slower workaround in that case.\r\n#if PocketPC\r\n#undef GETPARAMETERS_OPEN_GENERICS\r\n#undef RESOLVE_OPEN_GENERICS\r\n#undef READER_WRITER_LOCK_SLIM\r\n#endif\r\n\r\n#if SILVERLIGHT\r\n#undef APPDOMAIN_GETASSEMBLIES\r\n#endif\r\n\r\n#if NETFX_CORE\r\n#undef APPDOMAIN_GETASSEMBLIES\r\n#undef RESOLVE_OPEN_GENERICS\r\n#endif\r\n\r\n#if COMPILED_EXPRESSIONS\r\n#define USE_OBJECT_CONSTRUCTOR\r\n#endif\r\n\r\n\r\n#if NETSTANDARD2_0\r\n#undef SERIALIZABLE\r\n#undef APPDOMAIN_GETASSEMBLIES\r\n#endif\r\n\r\n#endregion\r\n#if SERIALIZABLE\r\nusing System.Runtime.Serialization;\r\n#endif\r\n\r\nnamespace Nancy.TinyIoc\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Collections.ObjectModel;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n\r\n#if EXPRESSIONS\r\n    using System.Linq.Expressions;\r\n    using System.Threading;\r\n\r\n#endif\r\n\r\n#if NETFX_CORE\r\n\tusing System.Threading.Tasks;\r\n\tusing Windows.Storage.Search;\r\n    using Windows.Storage;\r\n\tusing Windows.UI.Xaml.Shapes;\r\n#endif\r\n\r\n    #region SafeDictionary\r\n#if READER_WRITER_LOCK_SLIM\r\n#if TINYIOC_INTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n    class SafeDictionary<TKey, TValue> : IDisposable\r\n    {\r\n        private readonly ReaderWriterLockSlim _padlock = new ReaderWriterLockSlim();\r\n        private readonly Dictionary<TKey, TValue> _Dictionary = new Dictionary<TKey, TValue>();\r\n\r\n        public TValue this[TKey key]\r\n        {\r\n            set\r\n            {\r\n                _padlock.EnterWriteLock();\r\n\r\n                try\r\n                {\r\n                    TValue current;\r\n                    if (_Dictionary.TryGetValue(key, out current))\r\n                    {\r\n                        var disposable = current as IDisposable;\r\n\r\n                        if (disposable != null)\r\n                            disposable.Dispose();\r\n                    }\r\n\r\n                    _Dictionary[key] = value;\r\n                }\r\n                finally\r\n                {\r\n                    _padlock.ExitWriteLock();\r\n                }\r\n            }\r\n        }\r\n\r\n        public bool TryGetValue(TKey key, out TValue value)\r\n        {\r\n            _padlock.EnterReadLock();\r\n            try\r\n            {\r\n                return _Dictionary.TryGetValue(key, out value);\r\n            }\r\n            finally\r\n            {\r\n                _padlock.ExitReadLock();\r\n            }\r\n        }\r\n\r\n        public bool Remove(TKey key)\r\n        {\r\n            _padlock.EnterWriteLock();\r\n            try\r\n            {\r\n                return _Dictionary.Remove(key);\r\n            }\r\n            finally\r\n            {\r\n                _padlock.ExitWriteLock();\r\n            }\r\n        }\r\n\r\n        public void Clear()\r\n        {\r\n            _padlock.EnterWriteLock();\r\n            try\r\n            {\r\n                _Dictionary.Clear();\r\n            }\r\n            finally\r\n            {\r\n                _padlock.ExitWriteLock();\r\n            }\r\n        }\r\n\r\n        public IEnumerable<TKey> Keys\r\n        {\r\n            get\r\n            {\r\n                _padlock.EnterReadLock();\r\n                try\r\n                {\r\n                    return new List<TKey>(_Dictionary.Keys);\r\n                }\r\n                finally\r\n                {\r\n                    _padlock.ExitReadLock();\r\n                }\r\n            }\r\n        }\r\n\r\n        #region IDisposable Members\r\n\r\n        public void Dispose()\r\n        {\r\n            _padlock.EnterWriteLock();\r\n\r\n            try\r\n            {\r\n                var disposableItems = from item in _Dictionary.Values\r\n                                      where item is IDisposable\r\n                                      select item as IDisposable;\r\n\r\n                foreach (var item in disposableItems)\r\n                {\r\n                    item.Dispose();\r\n                }\r\n            }\r\n            finally\r\n            {\r\n                _padlock.ExitWriteLock();\r\n            }\r\n\r\n            GC.SuppressFinalize(this);\r\n        }\r\n\r\n        #endregion\r\n    }\r\n#else\r\n#if TINYIOC_INTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n    class SafeDictionary<TKey, TValue> : IDisposable\r\n    {\r\n        private readonly object _Padlock = new object();\r\n        private readonly Dictionary<TKey, TValue> _Dictionary = new Dictionary<TKey, TValue>();\r\n\r\n        public TValue this[TKey key]\r\n        {\r\n            set\r\n            {\r\n                lock (_Padlock)\r\n                {\r\n                    TValue current;\r\n                    if (_Dictionary.TryGetValue(key, out current))\r\n                    {\r\n                        var disposable = current as IDisposable;\r\n\r\n                        if (disposable != null)\r\n                            disposable.Dispose();\r\n                    }\r\n\r\n                    _Dictionary[key] = value;\r\n                }\r\n            }\r\n        }\r\n\r\n        public bool TryGetValue(TKey key, out TValue value)\r\n        {\r\n            lock (_Padlock)\r\n            {\r\n                return _Dictionary.TryGetValue(key, out value);\r\n            }\r\n        }\r\n\r\n        public bool Remove(TKey key)\r\n        {\r\n            lock (_Padlock)\r\n            {\r\n                return _Dictionary.Remove(key);\r\n            }\r\n        }\r\n\r\n        public void Clear()\r\n        {\r\n            lock (_Padlock)\r\n            {\r\n                _Dictionary.Clear();\r\n            }\r\n        }\r\n\r\n        public IEnumerable<TKey> Keys\r\n        {\r\n            get\r\n            {\r\n                return _Dictionary.Keys;\r\n            }\r\n        }\r\n    #region IDisposable Members\r\n\r\n        public void Dispose()\r\n        {\r\n            lock (_Padlock)\r\n            {\r\n                var disposableItems = from item in _Dictionary.Values\r\n                                      where item is IDisposable\r\n                                      select item as IDisposable;\r\n\r\n                foreach (var item in disposableItems)\r\n                {\r\n                    item.Dispose();\r\n                }\r\n            }\r\n\r\n            GC.SuppressFinalize(this);\r\n        }\r\n\r\n    #endregion\r\n    }\r\n#endif\r\n    #endregion\r\n\r\n    #region Extensions\r\n#if TINYIOC_INTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n    static class AssemblyExtensions\r\n    {\r\n        public static Type[] SafeGetTypes(this Assembly assembly)\r\n        {\r\n            Type[] assemblies;\r\n\r\n            try\r\n            {\r\n                assemblies = assembly.GetTypes();\r\n            }\r\n            catch (System.IO.FileNotFoundException)\r\n            {\r\n                assemblies = ArrayCache.Empty<Type>();\r\n            }\r\n            catch (NotSupportedException)\r\n            {\r\n                assemblies = ArrayCache.Empty<Type>();\r\n            }\r\n#if !NETFX_CORE\r\n            catch (ReflectionTypeLoadException e)\r\n            {\r\n                assemblies = e.Types.Where(t => t != null).ToArray();\r\n            }\r\n#endif\r\n            return assemblies;\r\n        }\r\n    }\r\n\r\n#if TINYIOC_INTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n    static class TypeExtensions\r\n    {\r\n        private static SafeDictionary<GenericMethodCacheKey, MethodInfo> _genericMethodCache;\r\n\r\n        static TypeExtensions()\r\n        {\r\n            _genericMethodCache = new SafeDictionary<GenericMethodCacheKey, MethodInfo>();\r\n        }\r\n\r\n        //#if NETFX_CORE\r\n        //\t\t/// <summary>\r\n        //\t\t/// Gets a generic method from a type given the method name, generic types and parameter types\r\n        //\t\t/// </summary>\r\n        //\t\t/// <param name=\"sourceType\">Source type</param>\r\n        //\t\t/// <param name=\"methodName\">Name of the method</param>\r\n        //\t\t/// <param name=\"genericTypes\">Generic types to use to make the method generic</param>\r\n        //\t\t/// <param name=\"parameterTypes\">Method parameters</param>\r\n        //\t\t/// <returns>MethodInfo or null if no matches found</returns>\r\n        //\t\t/// <exception cref=\"System.Reflection.AmbiguousMatchException\"/>\r\n        //\t\t/// <exception cref=\"System.ArgumentException\"/>\r\n        //\t\tpublic static MethodInfo GetGenericMethod(this Type sourceType, string methodName, Type[] genericTypes, Type[] parameterTypes)\r\n        //\t\t{\r\n        //\t\t\tMethodInfo method;\r\n        //\t\t\tvar cacheKey = new GenericMethodCacheKey(sourceType, methodName, genericTypes, parameterTypes);\r\n\r\n        //\t\t\t// Shouldn't need any additional locking\r\n        //\t\t\t// we don't care if we do the method info generation\r\n        //\t\t\t// more than once before it gets cached.\r\n        //\t\t\tif (!_genericMethodCache.TryGetValue(cacheKey, out method))\r\n        //\t\t\t{\r\n        //\t\t\t\tmethod = GetMethod(sourceType, methodName, genericTypes, parameterTypes);\r\n        //\t\t\t\t_genericMethodCache[cacheKey] = method;\r\n        //\t\t\t}\r\n\r\n        //\t\t\treturn method;\r\n        //\t\t}\r\n        //#else\r\n        /// <summary>\r\n        /// Gets a generic method from a type given the method name, binding flags, generic types and parameter types\r\n        /// </summary>\r\n        /// <param name=\"sourceType\">Source type</param>\r\n        /// <param name=\"bindingFlags\">Binding flags</param>\r\n        /// <param name=\"methodName\">Name of the method</param>\r\n        /// <param name=\"genericTypes\">Generic types to use to make the method generic</param>\r\n        /// <param name=\"parameterTypes\">Method parameters</param>\r\n        /// <returns>MethodInfo or null if no matches found</returns>\r\n        /// <exception cref=\"System.Reflection.AmbiguousMatchException\"/>\r\n        /// <exception cref=\"System.ArgumentException\"/>\r\n        public static MethodInfo GetGenericMethod(this Type sourceType, BindingFlags bindingFlags, string methodName, Type[] genericTypes, Type[] parameterTypes)\r\n        {\r\n            MethodInfo method;\r\n            var cacheKey = new GenericMethodCacheKey(sourceType, methodName, genericTypes, parameterTypes);\r\n\r\n            // Shouldn't need any additional locking\r\n            // we don't care if we do the method info generation\r\n            // more than once before it gets cached.\r\n            if (!_genericMethodCache.TryGetValue(cacheKey, out method))\r\n            {\r\n                method = GetMethod(sourceType, bindingFlags, methodName, genericTypes, parameterTypes);\r\n                _genericMethodCache[cacheKey] = method;\r\n            }\r\n\r\n            return method;\r\n        }\r\n        //#endif\r\n\r\n#if NETFX_CORE\r\n        private static MethodInfo GetMethod(Type sourceType, BindingFlags flags, string methodName, Type[] genericTypes, Type[] parameterTypes)\r\n        {\r\n            var methods =\r\n                sourceType.GetMethods(flags).Where(\r\n                    mi => string.Equals(methodName, mi.Name, StringComparison.Ordinal)).Where(\r\n                        mi => mi.ContainsGenericParameters).Where(mi => mi.GetGenericArguments().Length == genericTypes.Length).\r\n                    Where(mi => mi.GetParameters().Length == parameterTypes.Length).Select(\r\n                        mi => mi.MakeGenericMethod(genericTypes)).Where(\r\n                            mi => mi.GetParameters().Select(pi => pi.ParameterType).SequenceEqual(parameterTypes)).ToList();\r\n\r\n            if (methods.Count > 1)\r\n            {\r\n                throw new AmbiguousMatchException();\r\n            }\r\n\r\n            return methods.FirstOrDefault();\r\n        }\r\n#else\r\n        private static MethodInfo GetMethod(Type sourceType, BindingFlags bindingFlags, string methodName, Type[] genericTypes, Type[] parameterTypes)\r\n        {\r\n#if GETPARAMETERS_OPEN_GENERICS\r\n            var methods =\r\n                sourceType.GetMethods(bindingFlags).Where(\r\n                    mi => string.Equals(methodName, mi.Name, StringComparison.Ordinal)).Where(\r\n                        mi => mi.ContainsGenericParameters).Where(mi => mi.GetGenericArguments().Length == genericTypes.Length).\r\n                    Where(mi => mi.GetParameters().Length == parameterTypes.Length).Select(\r\n                        mi => mi.MakeGenericMethod(genericTypes)).Where(\r\n                            mi => mi.GetParameters().Select(pi => pi.ParameterType).SequenceEqual(parameterTypes)).ToList();\r\n#else\r\n            var validMethods =  from method in sourceType.GetMethods(bindingFlags)\r\n                                where method.Name == methodName\r\n                                where method.IsGenericMethod\r\n                                where method.GetGenericArguments().Length == genericTypes.Length\r\n                                let genericMethod = method.MakeGenericMethod(genericTypes)\r\n                                where genericMethod.GetParameters().Count() == parameterTypes.Length\r\n                                where genericMethod.GetParameters().Select(pi => pi.ParameterType).SequenceEqual(parameterTypes)\r\n                                select genericMethod;\r\n\r\n            var methods = validMethods.ToList();\r\n#endif\r\n            if (methods.Count > 1)\r\n            {\r\n                throw new AmbiguousMatchException();\r\n            }\r\n\r\n            return methods.FirstOrDefault();\r\n        }\r\n#endif\r\n\r\n        private sealed class GenericMethodCacheKey\r\n        {\r\n            private readonly Type _sourceType;\r\n\r\n            private readonly string _methodName;\r\n\r\n            private readonly Type[] _genericTypes;\r\n\r\n            private readonly Type[] _parameterTypes;\r\n\r\n            private readonly int _hashCode;\r\n\r\n            public GenericMethodCacheKey(Type sourceType, string methodName, Type[] genericTypes, Type[] parameterTypes)\r\n            {\r\n                _sourceType = sourceType;\r\n                _methodName = methodName;\r\n                _genericTypes = genericTypes;\r\n                _parameterTypes = parameterTypes;\r\n                _hashCode = GenerateHashCode();\r\n            }\r\n\r\n            public override bool Equals(object obj)\r\n            {\r\n                var cacheKey = obj as GenericMethodCacheKey;\r\n                if (cacheKey == null)\r\n                    return false;\r\n\r\n                if (_sourceType != cacheKey._sourceType)\r\n                    return false;\r\n\r\n                if (!String.Equals(_methodName, cacheKey._methodName, StringComparison.Ordinal))\r\n                    return false;\r\n\r\n                if (_genericTypes.Length != cacheKey._genericTypes.Length)\r\n                    return false;\r\n\r\n                if (_parameterTypes.Length != cacheKey._parameterTypes.Length)\r\n                    return false;\r\n\r\n                for (int i = 0; i < _genericTypes.Length; ++i)\r\n                {\r\n                    if (_genericTypes[i] != cacheKey._genericTypes[i])\r\n                        return false;\r\n                }\r\n\r\n                for (int i = 0; i < _parameterTypes.Length; ++i)\r\n                {\r\n                    if (_parameterTypes[i] != cacheKey._parameterTypes[i])\r\n                        return false;\r\n                }\r\n\r\n                return true;\r\n            }\r\n\r\n            public override int GetHashCode()\r\n            {\r\n                return _hashCode;\r\n            }\r\n\r\n            private int GenerateHashCode()\r\n            {\r\n                unchecked\r\n                {\r\n                    var result = _sourceType.GetHashCode();\r\n\r\n                    result = (result * 397) ^ _methodName.GetHashCode();\r\n\r\n                    for (int i = 0; i < _genericTypes.Length; ++i)\r\n                    {\r\n                        result = (result * 397) ^ _genericTypes[i].GetHashCode();\r\n                    }\r\n\r\n                    for (int i = 0; i < _parameterTypes.Length; ++i)\r\n                    {\r\n                        result = (result * 397) ^ _parameterTypes[i].GetHashCode();\r\n                    }\r\n\r\n                    return result;\r\n                }\r\n            }\r\n        }\r\n\r\n    }\r\n\r\n    // @mbrit - 2012-05-22 - shim for ForEach call on List<T>...\r\n#if NETFX_CORE\r\n\tinternal static class ListExtender\r\n\t{\r\n\t\tinternal static void ForEach<T>(this List<T> list, Action<T> callback)\r\n\t\t{\r\n\t\t\tforeach (T obj in list)\r\n\t\t\t\tcallback(obj);\r\n\t\t}\r\n\t}\r\n#endif\r\n\r\n    #endregion\r\n\r\n    #region TinyIoC Exception Types\r\n#if SERIALIZABLE\r\n    [Serializable]\r\n#endif\r\n#if TINYIOC_INTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n    class TinyIoCResolutionException : Exception\r\n    {\r\n        private const string ERROR_TEXT = \"Unable to resolve type: {0}\";\r\n\r\n        public TinyIoCResolutionException(Type type)\r\n            : base(String.Format(ERROR_TEXT, type.FullName))\r\n        {\r\n        }\r\n\r\n        public TinyIoCResolutionException(Type type, Exception innerException)\r\n            : base(String.Format(ERROR_TEXT, type.FullName), innerException)\r\n        {\r\n        }\r\n#if SERIALIZABLE\r\n        protected TinyIoCResolutionException(SerializationInfo info, StreamingContext context)\r\n            : base(info, context)\r\n        {\r\n        }\r\n#endif\r\n    }\r\n#if SERIALIZABLE\r\n    [Serializable]\r\n#endif\r\n#if TINYIOC_INTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n    class TinyIoCRegistrationTypeException : Exception\r\n    {\r\n        private const string REGISTER_ERROR_TEXT = \"Cannot register type {0} - abstract classes or interfaces are not valid implementation types for {1}.\";\r\n\r\n        public TinyIoCRegistrationTypeException(Type type, string factory)\r\n            : base(String.Format(REGISTER_ERROR_TEXT, type.FullName, factory))\r\n        {\r\n        }\r\n\r\n        public TinyIoCRegistrationTypeException(Type type, string factory, Exception innerException)\r\n            : base(String.Format(REGISTER_ERROR_TEXT, type.FullName, factory), innerException)\r\n        {\r\n        }\r\n#if SERIALIZABLE\r\n        protected TinyIoCRegistrationTypeException(SerializationInfo info, StreamingContext context)\r\n            : base(info, context)\r\n        {\r\n        }\r\n#endif\r\n    }\r\n#if SERIALIZABLE\r\n    [Serializable]\r\n#endif\r\n#if TINYIOC_INTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n    class TinyIoCRegistrationException : Exception\r\n    {\r\n        private const string CONVERT_ERROR_TEXT = \"Cannot convert current registration of {0} to {1}\";\r\n        private const string GENERIC_CONSTRAINT_ERROR_TEXT = \"Type {1} is not valid for a registration of type {0}\";\r\n\r\n        public TinyIoCRegistrationException(Type type, string method)\r\n            : base(String.Format(CONVERT_ERROR_TEXT, type.FullName, method))\r\n        {\r\n        }\r\n\r\n        public TinyIoCRegistrationException(Type type, string method, Exception innerException)\r\n            : base(String.Format(CONVERT_ERROR_TEXT, type.FullName, method), innerException)\r\n        {\r\n        }\r\n\r\n        public TinyIoCRegistrationException(Type registerType, Type implementationType)\r\n            : base(String.Format(GENERIC_CONSTRAINT_ERROR_TEXT, registerType.FullName, implementationType.FullName))\r\n        {\r\n        }\r\n\r\n        public TinyIoCRegistrationException(Type registerType, Type implementationType, Exception innerException)\r\n            : base(String.Format(GENERIC_CONSTRAINT_ERROR_TEXT, registerType.FullName, implementationType.FullName), innerException)\r\n        {\r\n        }\r\n#if SERIALIZABLE\r\n        protected TinyIoCRegistrationException(SerializationInfo info, StreamingContext context)\r\n            : base(info, context)\r\n        {\r\n        }\r\n#endif\r\n    }\r\n#if SERIALIZABLE\r\n    [Serializable]\r\n#endif\r\n#if TINYIOC_INTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n    class TinyIoCWeakReferenceException : Exception\r\n    {\r\n        private const string ERROR_TEXT = \"Unable to instantiate {0} - referenced object has been reclaimed\";\r\n\r\n        public TinyIoCWeakReferenceException(Type type)\r\n            : base(String.Format(ERROR_TEXT, type.FullName))\r\n        {\r\n        }\r\n\r\n        public TinyIoCWeakReferenceException(Type type, Exception innerException)\r\n            : base(String.Format(ERROR_TEXT, type.FullName), innerException)\r\n        {\r\n        }\r\n#if SERIALIZABLE\r\n        protected TinyIoCWeakReferenceException(SerializationInfo info, StreamingContext context)\r\n            : base(info, context)\r\n        {\r\n        }\r\n#endif\r\n    }\r\n#if SERIALIZABLE\r\n    [Serializable]\r\n#endif\r\n#if TINYIOC_INTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n    class TinyIoCConstructorResolutionException : Exception\r\n    {\r\n        private const string ERROR_TEXT = \"Unable to resolve constructor for {0} using provided Expression.\";\r\n\r\n        public TinyIoCConstructorResolutionException(Type type)\r\n            : base(String.Format(ERROR_TEXT, type.FullName))\r\n        {\r\n        }\r\n\r\n        public TinyIoCConstructorResolutionException(Type type, Exception innerException)\r\n            : base(String.Format(ERROR_TEXT, type.FullName), innerException)\r\n        {\r\n        }\r\n\r\n        public TinyIoCConstructorResolutionException(string message, Exception innerException)\r\n            : base(message, innerException)\r\n        {\r\n        }\r\n\r\n        public TinyIoCConstructorResolutionException(string message)\r\n            : base(message)\r\n        {\r\n        }\r\n#if SERIALIZABLE\r\n        protected TinyIoCConstructorResolutionException(SerializationInfo info, StreamingContext context)\r\n            : base(info, context)\r\n        {\r\n        }\r\n#endif\r\n    }\r\n#if SERIALIZABLE\r\n    [Serializable]\r\n#endif\r\n#if TINYIOC_INTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n    class TinyIoCAutoRegistrationException : Exception\r\n    {\r\n        private const string ERROR_TEXT = \"Duplicate implementation of type {0} found ({1}).\";\r\n\r\n        public TinyIoCAutoRegistrationException(Type registerType, IEnumerable<Type> types)\r\n            : base(String.Format(ERROR_TEXT, registerType, GetTypesString(types)))\r\n        {\r\n        }\r\n\r\n        public TinyIoCAutoRegistrationException(Type registerType, IEnumerable<Type> types, Exception innerException)\r\n            : base(String.Format(ERROR_TEXT, registerType, GetTypesString(types)), innerException)\r\n        {\r\n        }\r\n#if SERIALIZABLE\r\n        protected TinyIoCAutoRegistrationException(SerializationInfo info, StreamingContext context)\r\n            : base(info, context)\r\n        {\r\n        }\r\n#endif\r\n\r\n        private static string GetTypesString(IEnumerable<Type> types)\r\n        {\r\n            var typeNames = from type in types\r\n                            select type.FullName;\r\n\r\n            return string.Join(\",\", typeNames.ToArray());\r\n        }\r\n    }\r\n    #endregion\r\n\r\n    #region Public Setup / Settings Classes\r\n    /// <summary>\r\n    /// Name/Value pairs for specifying \"user\" parameters when resolving\r\n    /// </summary>\r\n#if TINYIOC_INTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n    sealed class NamedParameterOverloads : Dictionary<string, object>\r\n    {\r\n        public static NamedParameterOverloads FromIDictionary(IDictionary<string, object> data)\r\n        {\r\n            return data as NamedParameterOverloads ?? new NamedParameterOverloads(data);\r\n        }\r\n\r\n        public NamedParameterOverloads()\r\n        {\r\n        }\r\n\r\n        public NamedParameterOverloads(IDictionary<string, object> data)\r\n            : base(data)\r\n        {\r\n        }\r\n\r\n        private static readonly NamedParameterOverloads _Default = new NamedParameterOverloads();\r\n\r\n        public static NamedParameterOverloads Default\r\n        {\r\n            get\r\n            {\r\n                return _Default;\r\n            }\r\n        }\r\n    }\r\n\r\n#if TINYIOC_INTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n    enum UnregisteredResolutionActions\r\n    {\r\n        /// <summary>\r\n        /// Attempt to resolve type, even if the type isn't registered.\r\n        /// \r\n        /// Registered types/options will always take precedence.\r\n        /// </summary>\r\n        AttemptResolve,\r\n\r\n        /// <summary>\r\n        /// Fail resolution if type not explicitly registered\r\n        /// </summary>\r\n        Fail,\r\n\r\n        /// <summary>\r\n        /// Attempt to resolve unregistered type if requested type is generic\r\n        /// and no registration exists for the specific generic parameters used.\r\n        /// \r\n        /// Registered types/options will always take precedence.\r\n        /// </summary>\r\n        GenericsOnly\r\n    }\r\n\r\n#if TINYIOC_INTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n    enum NamedResolutionFailureActions\r\n    {\r\n        AttemptUnnamedResolution,\r\n        Fail\r\n    }\r\n\r\n#if TINYIOC_INTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n    enum DuplicateImplementationActions\r\n    {\r\n        RegisterSingle,\r\n        RegisterMultiple,\r\n        Fail\r\n    }\r\n\r\n    /// <summary>\r\n    /// Resolution settings\r\n    /// </summary>\r\n#if TINYIOC_INTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n    sealed class ResolveOptions\r\n    {\r\n        private static readonly ResolveOptions _Default = new ResolveOptions();\r\n        private static readonly ResolveOptions _FailUnregisteredAndNameNotFound = new ResolveOptions() { NamedResolutionFailureAction = NamedResolutionFailureActions.Fail, UnregisteredResolutionAction = UnregisteredResolutionActions.Fail };\r\n        private static readonly ResolveOptions _FailUnregisteredOnly = new ResolveOptions() { NamedResolutionFailureAction = NamedResolutionFailureActions.AttemptUnnamedResolution, UnregisteredResolutionAction = UnregisteredResolutionActions.Fail };\r\n        private static readonly ResolveOptions _FailNameNotFoundOnly = new ResolveOptions() { NamedResolutionFailureAction = NamedResolutionFailureActions.Fail, UnregisteredResolutionAction = UnregisteredResolutionActions.AttemptResolve };\r\n\r\n        private UnregisteredResolutionActions _UnregisteredResolutionAction = UnregisteredResolutionActions.AttemptResolve;\r\n        public UnregisteredResolutionActions UnregisteredResolutionAction\r\n        {\r\n            get { return _UnregisteredResolutionAction; }\r\n            set { _UnregisteredResolutionAction = value; }\r\n        }\r\n\r\n        private NamedResolutionFailureActions _NamedResolutionFailureAction = NamedResolutionFailureActions.Fail;\r\n        public NamedResolutionFailureActions NamedResolutionFailureAction\r\n        {\r\n            get { return _NamedResolutionFailureAction; }\r\n            set { _NamedResolutionFailureAction = value; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the default options (attempt resolution of unregistered types, fail on named resolution if name not found)\r\n        /// </summary>\r\n        public static ResolveOptions Default\r\n        {\r\n            get\r\n            {\r\n                return _Default;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Preconfigured option for attempting resolution of unregistered types and failing on named resolution if name not found\r\n        /// </summary>\r\n        public static ResolveOptions FailNameNotFoundOnly\r\n        {\r\n            get\r\n            {\r\n                return _FailNameNotFoundOnly;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Preconfigured option for failing on resolving unregistered types and on named resolution if name not found\r\n        /// </summary>\r\n        public static ResolveOptions FailUnregisteredAndNameNotFound\r\n        {\r\n            get\r\n            {\r\n                return _FailUnregisteredAndNameNotFound;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Preconfigured option for failing on resolving unregistered types, but attempting unnamed resolution if name not found\r\n        /// </summary>\r\n        public static ResolveOptions FailUnregisteredOnly\r\n        {\r\n            get\r\n            {\r\n                return _FailUnregisteredOnly;\r\n            }\r\n        }\r\n    }\r\n    #endregion\r\n\r\n#if TINYIOC_INTERNAL\r\n    internal\r\n#else\r\n    public\r\n#endif\r\n    sealed partial class TinyIoCContainer : IDisposable\r\n    {\r\n        #region Fake NETFX_CORE Classes\r\n#if NETFX_CORE\r\n        private sealed class MethodAccessException : Exception\r\n        {\r\n        }\r\n\r\n        private sealed class AppDomain\r\n        {\r\n            public static AppDomain CurrentDomain { get; private set; }\r\n\r\n            static AppDomain()\r\n            {\r\n                CurrentDomain = new AppDomain();\r\n            }\r\n\r\n\t\t\t// @mbrit - 2012-05-30 - in WinRT, this should be done async...\r\n            public async Task<List<Assembly>> GetAssembliesAsync()\r\n            {\r\n                var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;\r\n\r\n                List<Assembly> assemblies = new List<Assembly>();\r\n\r\n\t\t\t\tvar files = await folder.GetFilesAsync();\r\n\r\n                foreach (StorageFile file in files)\r\n                {\r\n                    if (file.FileType == \".dll\" || file.FileType == \".exe\")\r\n                    {\r\n                        AssemblyName name = new AssemblyName() { Name = System.IO.Path.GetFileNameWithoutExtension(file.Name) };\r\n\t\t\t\t\t\ttry\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tvar asm = Assembly.Load(name);\r\n\t\t\t\t\t\t\tassemblies.Add(asm);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tcatch\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t// ignore exceptions here...\r\n\t\t\t\t\t\t}\r\n                    }\r\n                }\r\n\r\n\t\t\t\treturn assemblies;\r\n            }\r\n        }\r\n#endif\r\n        #endregion\r\n\r\n        #region \"Fluent\" API\r\n        /// <summary>\r\n        /// Registration options for \"fluent\" API\r\n        /// </summary>\r\n        public sealed class RegisterOptions\r\n        {\r\n            private TinyIoCContainer _Container;\r\n            private TypeRegistration _Registration;\r\n\r\n            public RegisterOptions(TinyIoCContainer container, TypeRegistration registration)\r\n            {\r\n                _Container = container;\r\n                _Registration = registration;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Make registration a singleton (single instance) if possible\r\n            /// </summary>\r\n            /// <returns>RegisterOptions</returns>\r\n            /// <exception cref=\"TinyIoCInstantiationTypeException\"></exception>\r\n            public RegisterOptions AsSingleton()\r\n            {\r\n                var currentFactory = _Container.GetCurrentFactory(_Registration);\r\n\r\n                if (currentFactory == null)\r\n                    throw new TinyIoCRegistrationException(_Registration.Type, \"singleton\");\r\n\r\n                return _Container.AddUpdateRegistration(_Registration, currentFactory.SingletonVariant);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Make registration multi-instance if possible\r\n            /// </summary>\r\n            /// <returns>RegisterOptions</returns>\r\n            /// <exception cref=\"TinyIoCInstantiationTypeException\"></exception>\r\n            public RegisterOptions AsMultiInstance()\r\n            {\r\n                var currentFactory = _Container.GetCurrentFactory(_Registration);\r\n\r\n                if (currentFactory == null)\r\n                    throw new TinyIoCRegistrationException(_Registration.Type, \"multi-instance\");\r\n\r\n                return _Container.AddUpdateRegistration(_Registration, currentFactory.MultiInstanceVariant);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Make registration hold a weak reference if possible\r\n            /// </summary>\r\n            /// <returns>RegisterOptions</returns>\r\n            /// <exception cref=\"TinyIoCInstantiationTypeException\"></exception>\r\n            public RegisterOptions WithWeakReference()\r\n            {\r\n                var currentFactory = _Container.GetCurrentFactory(_Registration);\r\n\r\n                if (currentFactory == null)\r\n                    throw new TinyIoCRegistrationException(_Registration.Type, \"weak reference\");\r\n\r\n                return _Container.AddUpdateRegistration(_Registration, currentFactory.WeakReferenceVariant);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Make registration hold a strong reference if possible\r\n            /// </summary>\r\n            /// <returns>RegisterOptions</returns>\r\n            /// <exception cref=\"TinyIoCInstantiationTypeException\"></exception>\r\n            public RegisterOptions WithStrongReference()\r\n            {\r\n                var currentFactory = _Container.GetCurrentFactory(_Registration);\r\n\r\n                if (currentFactory == null)\r\n                    throw new TinyIoCRegistrationException(_Registration.Type, \"strong reference\");\r\n\r\n                return _Container.AddUpdateRegistration(_Registration, currentFactory.StrongReferenceVariant);\r\n            }\r\n\r\n#if EXPRESSIONS\r\n            public RegisterOptions UsingConstructor<RegisterType>(Expression<Func<RegisterType>> constructor)\r\n            {\r\n                var lambda = constructor as LambdaExpression;\r\n                if (lambda == null)\r\n                    throw new TinyIoCConstructorResolutionException(typeof(RegisterType));\r\n\r\n                var newExpression = lambda.Body as NewExpression;\r\n                if (newExpression == null)\r\n                    throw new TinyIoCConstructorResolutionException(typeof(RegisterType));\r\n\r\n                var constructorInfo = newExpression.Constructor;\r\n                if (constructorInfo == null)\r\n                    throw new TinyIoCConstructorResolutionException(typeof(RegisterType));\r\n\r\n                var currentFactory = _Container.GetCurrentFactory(_Registration);\r\n                if (currentFactory == null)\r\n                    throw new TinyIoCConstructorResolutionException(typeof(RegisterType));\r\n\r\n                currentFactory.SetConstructor(constructorInfo);\r\n\r\n                return this;\r\n            }\r\n#endif\r\n            /// <summary>\r\n            /// Switches to a custom lifetime manager factory if possible.\r\n            /// \r\n            /// Usually used for RegisterOptions \"To*\" extension methods such as the ASP.Net per-request one.\r\n            /// </summary>\r\n            /// <param name=\"instance\">RegisterOptions instance</param>\r\n            /// <param name=\"lifetimeProvider\">Custom lifetime manager</param>\r\n            /// <param name=\"errorString\">Error string to display if switch fails</param>\r\n            /// <returns>RegisterOptions</returns>\r\n            public static RegisterOptions ToCustomLifetimeManager(RegisterOptions instance, ITinyIoCObjectLifetimeProvider lifetimeProvider, string errorString)\r\n            {\r\n                if (instance == null)\r\n                    throw new ArgumentNullException(\"instance\", \"instance is null.\");\r\n\r\n                if (lifetimeProvider == null)\r\n                    throw new ArgumentNullException(\"lifetimeProvider\", \"lifetimeProvider is null.\");\r\n\r\n                if (string.IsNullOrEmpty(errorString))\r\n                    throw new ArgumentException(\"errorString is null or empty.\", \"errorString\");\r\n\r\n                var currentFactory = instance._Container.GetCurrentFactory(instance._Registration);\r\n\r\n                if (currentFactory == null)\r\n                    throw new TinyIoCRegistrationException(instance._Registration.Type, errorString);\r\n\r\n                return instance._Container.AddUpdateRegistration(instance._Registration, currentFactory.GetCustomObjectLifetimeVariant(lifetimeProvider, errorString));\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Registration options for \"fluent\" API when registering multiple implementations\r\n        /// </summary>\r\n        public sealed class MultiRegisterOptions\r\n        {\r\n            private IEnumerable<RegisterOptions> _RegisterOptions;\r\n\r\n            /// <summary>\r\n            /// Initializes a new instance of the MultiRegisterOptions class.\r\n            /// </summary>\r\n            /// <param name=\"registerOptions\">Registration options</param>\r\n            public MultiRegisterOptions(IEnumerable<RegisterOptions> registerOptions)\r\n            {\r\n                _RegisterOptions = registerOptions;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Make registration a singleton (single instance) if possible\r\n            /// </summary>\r\n            /// <returns>RegisterOptions</returns>\r\n            /// <exception cref=\"TinyIoCInstantiationTypeException\"></exception>\r\n            public MultiRegisterOptions AsSingleton()\r\n            {\r\n                _RegisterOptions = ExecuteOnAllRegisterOptions(ro => ro.AsSingleton());\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Make registration multi-instance if possible\r\n            /// </summary>\r\n            /// <returns>MultiRegisterOptions</returns>\r\n            /// <exception cref=\"TinyIoCInstantiationTypeException\"></exception>\r\n            public MultiRegisterOptions AsMultiInstance()\r\n            {\r\n                _RegisterOptions = ExecuteOnAllRegisterOptions(ro => ro.AsMultiInstance());\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Switches to a custom lifetime manager factory if possible.\r\n            /// \r\n            /// Usually used for RegisterOptions \"To*\" extension methods such as the ASP.Net per-request one.\r\n            /// </summary>\r\n            /// <param name=\"instance\">MultiRegisterOptions instance</param>\r\n            /// <param name=\"lifetimeProvider\">Custom lifetime manager</param>\r\n            /// <param name=\"errorString\">Error string to display if switch fails</param>\r\n            /// <returns>MultiRegisterOptions</returns>\r\n            public static MultiRegisterOptions ToCustomLifetimeManager(\r\n                MultiRegisterOptions instance,\r\n                ITinyIoCObjectLifetimeProvider lifetimeProvider,\r\n                string errorString)\r\n            {\r\n                if (instance == null)\r\n                    throw new ArgumentNullException(\"instance\", \"instance is null.\");\r\n\r\n                if (lifetimeProvider == null)\r\n                    throw new ArgumentNullException(\"lifetimeProvider\", \"lifetimeProvider is null.\");\r\n\r\n                if (string.IsNullOrEmpty(errorString))\r\n                    throw new ArgumentException(\"errorString is null or empty.\", \"errorString\");\r\n\r\n                instance._RegisterOptions = instance.ExecuteOnAllRegisterOptions(ro => RegisterOptions.ToCustomLifetimeManager(ro, lifetimeProvider, errorString));\r\n\r\n                return instance;\r\n            }\r\n\r\n            private IEnumerable<RegisterOptions> ExecuteOnAllRegisterOptions(Func<RegisterOptions, RegisterOptions> action)\r\n            {\r\n                var newRegisterOptions = new List<RegisterOptions>();\r\n\r\n                foreach (var registerOption in _RegisterOptions)\r\n                {\r\n                    newRegisterOptions.Add(action(registerOption));\r\n                }\r\n\r\n                return newRegisterOptions;\r\n            }\r\n        }\r\n        #endregion\r\n\r\n        #region Public API\r\n        #region Child Containers\r\n        public TinyIoCContainer GetChildContainer()\r\n        {\r\n            return new TinyIoCContainer(this);\r\n        }\r\n        #endregion\r\n\r\n        #region Registration\r\n        /// <summary>\r\n        /// Attempt to automatically register all non-generic classes and interfaces in the current app domain.\r\n        /// \r\n        /// If more than one class implements an interface then only one implementation will be registered\r\n        /// although no error will be thrown.\r\n        /// </summary>\r\n        public void AutoRegister()\r\n        {\r\n#if APPDOMAIN_GETASSEMBLIES\r\n            AutoRegisterInternal(AppDomain.CurrentDomain.GetAssemblies().Where(a => !IsIgnoredAssembly(a)), DuplicateImplementationActions.RegisterSingle, null);\r\n#else\r\n            AutoRegisterInternal(new Assembly[] { this.GetType().Assembly() }, DuplicateImplementationActions.RegisterSingle, null);\r\n#endif\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempt to automatically register all non-generic classes and interfaces in the current app domain.\r\n        /// Types will only be registered if they pass the supplied registration predicate.\r\n        /// \r\n        /// If more than one class implements an interface then only one implementation will be registered\r\n        /// although no error will be thrown.\r\n        /// </summary>\r\n        /// <param name=\"registrationPredicate\">Predicate to determine if a particular type should be registered</param>\r\n        public void AutoRegister(Func<Type, bool> registrationPredicate)\r\n        {\r\n#if APPDOMAIN_GETASSEMBLIES\r\n            AutoRegisterInternal(AppDomain.CurrentDomain.GetAssemblies().Where(a => !IsIgnoredAssembly(a)), DuplicateImplementationActions.RegisterSingle, registrationPredicate);\r\n#else\r\n            AutoRegisterInternal(new Assembly[] { this.GetType().Assembly() }, DuplicateImplementationActions.RegisterSingle, registrationPredicate);\r\n#endif\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempt to automatically register all non-generic classes and interfaces in the current app domain.\r\n        /// </summary>\r\n        /// <param name=\"duplicateAction\">What action to take when encountering duplicate implementations of an interface/base class.</param>\r\n        /// <exception cref=\"TinyIoCAutoRegistrationException\"/>\r\n        public void AutoRegister(DuplicateImplementationActions duplicateAction)\r\n        {\r\n#if APPDOMAIN_GETASSEMBLIES\r\n            AutoRegisterInternal(AppDomain.CurrentDomain.GetAssemblies().Where(a => !IsIgnoredAssembly(a)), duplicateAction, null);\r\n#else\r\n            AutoRegisterInternal(new Assembly[] { this.GetType().Assembly() }, duplicateAction, null);\r\n#endif\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempt to automatically register all non-generic classes and interfaces in the current app domain.\r\n        /// Types will only be registered if they pass the supplied registration predicate.\r\n        /// </summary>\r\n        /// <param name=\"duplicateAction\">What action to take when encountering duplicate implementations of an interface/base class.</param>\r\n        /// <param name=\"registrationPredicate\">Predicate to determine if a particular type should be registered</param>\r\n        /// <exception cref=\"TinyIoCAutoRegistrationException\"/>\r\n        public void AutoRegister(DuplicateImplementationActions duplicateAction, Func<Type, bool> registrationPredicate)\r\n        {\r\n#if APPDOMAIN_GETASSEMBLIES\r\n            AutoRegisterInternal(AppDomain.CurrentDomain.GetAssemblies().Where(a => !IsIgnoredAssembly(a)), duplicateAction, registrationPredicate);\r\n#else\r\n            AutoRegisterInternal(new Assembly[] { this.GetType().Assembly() }, duplicateAction, registrationPredicate);\r\n#endif\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempt to automatically register all non-generic classes and interfaces in the specified assemblies\r\n        /// \r\n        /// If more than one class implements an interface then only one implementation will be registered\r\n        /// although no error will be thrown.\r\n        /// </summary>\r\n        /// <param name=\"assemblies\">Assemblies to process</param>\r\n        public void AutoRegister(IEnumerable<Assembly> assemblies)\r\n        {\r\n            AutoRegisterInternal(assemblies, DuplicateImplementationActions.RegisterSingle, null);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempt to automatically register all non-generic classes and interfaces in the specified assemblies\r\n        /// Types will only be registered if they pass the supplied registration predicate.\r\n        /// \r\n        /// If more than one class implements an interface then only one implementation will be registered\r\n        /// although no error will be thrown.\r\n        /// </summary>\r\n        /// <param name=\"assemblies\">Assemblies to process</param>\r\n        /// <param name=\"registrationPredicate\">Predicate to determine if a particular type should be registered</param>\r\n        public void AutoRegister(IEnumerable<Assembly> assemblies, Func<Type, bool> registrationPredicate)\r\n        {\r\n            AutoRegisterInternal(assemblies, DuplicateImplementationActions.RegisterSingle, registrationPredicate);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempt to automatically register all non-generic classes and interfaces in the specified assemblies\r\n        /// </summary>\r\n        /// <param name=\"assemblies\">Assemblies to process</param>\r\n        /// <param name=\"duplicateAction\">What action to take when encountering duplicate implementations of an interface/base class.</param>\r\n        /// <exception cref=\"TinyIoCAutoRegistrationException\"/>\r\n        public void AutoRegister(IEnumerable<Assembly> assemblies, DuplicateImplementationActions duplicateAction)\r\n        {\r\n            AutoRegisterInternal(assemblies, duplicateAction, null);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempt to automatically register all non-generic classes and interfaces in the specified assemblies\r\n        /// Types will only be registered if they pass the supplied registration predicate.\r\n        /// </summary>\r\n        /// <param name=\"assemblies\">Assemblies to process</param>\r\n        /// <param name=\"duplicateAction\">What action to take when encountering duplicate implementations of an interface/base class.</param>\r\n        /// <param name=\"registrationPredicate\">Predicate to determine if a particular type should be registered</param>\r\n        /// <exception cref=\"TinyIoCAutoRegistrationException\"/>\r\n        public void AutoRegister(IEnumerable<Assembly> assemblies, DuplicateImplementationActions duplicateAction, Func<Type, bool> registrationPredicate)\r\n        {\r\n            AutoRegisterInternal(assemblies, duplicateAction, registrationPredicate);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates/replaces a container class registration with default options.\r\n        /// </summary>\r\n        /// <param name=\"registerType\">Type to register</param>\r\n        /// <returns>RegisterOptions for fluent API</returns>\r\n        public RegisterOptions Register(Type registerType)\r\n        {\r\n            return RegisterInternal(registerType, string.Empty, GetDefaultObjectFactory(registerType, registerType));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates/replaces a named container class registration with default options.\r\n        /// </summary>\r\n        /// <param name=\"registerType\">Type to register</param>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <returns>RegisterOptions for fluent API</returns>\r\n        public RegisterOptions Register(Type registerType, string name)\r\n        {\r\n            return RegisterInternal(registerType, name, GetDefaultObjectFactory(registerType, registerType));\r\n\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates/replaces a container class registration with a given implementation and default options.\r\n        /// </summary>\r\n        /// <param name=\"registerType\">Type to register</param>\r\n        /// <param name=\"registerImplementation\">Type to instantiate that implements RegisterType</param>\r\n        /// <returns>RegisterOptions for fluent API</returns>\r\n        public RegisterOptions Register(Type registerType, Type registerImplementation)\r\n        {\r\n            return this.RegisterInternal(registerType, string.Empty, GetDefaultObjectFactory(registerType, registerImplementation));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates/replaces a named container class registration with a given implementation and default options.\r\n        /// </summary>\r\n        /// <param name=\"registerType\">Type to register</param>\r\n        /// <param name=\"registerImplementation\">Type to instantiate that implements RegisterType</param>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <returns>RegisterOptions for fluent API</returns>\r\n        public RegisterOptions Register(Type registerType, Type registerImplementation, string name)\r\n        {\r\n            return this.RegisterInternal(registerType, name, GetDefaultObjectFactory(registerType, registerImplementation));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates/replaces a container class registration with a specific, strong referenced, instance.\r\n        /// </summary>\r\n        /// <param name=\"registerType\">Type to register</param>\r\n        /// <param name=\"instance\">Instance of RegisterType to register</param>\r\n        /// <returns>RegisterOptions for fluent API</returns>\r\n        public RegisterOptions Register(Type registerType, object instance)\r\n        {\r\n            return RegisterInternal(registerType, string.Empty, new InstanceFactory(registerType, registerType, instance));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates/replaces a named container class registration with a specific, strong referenced, instance.\r\n        /// </summary>\r\n        /// <param name=\"registerType\">Type to register</param>\r\n        /// <param name=\"instance\">Instance of RegisterType to register</param>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <returns>RegisterOptions for fluent API</returns>\r\n        public RegisterOptions Register(Type registerType, object instance, string name)\r\n        {\r\n            return RegisterInternal(registerType, name, new InstanceFactory(registerType, registerType, instance));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates/replaces a container class registration with a specific, strong referenced, instance.\r\n        /// </summary>\r\n        /// <param name=\"registerType\">Type to register</param>\r\n        /// <param name=\"registerImplementation\">Type of instance to register that implements RegisterType</param>\r\n        /// <param name=\"instance\">Instance of RegisterImplementation to register</param>\r\n        /// <returns>RegisterOptions for fluent API</returns>\r\n        public RegisterOptions Register(Type registerType, Type registerImplementation, object instance)\r\n        {\r\n            return RegisterInternal(registerType, string.Empty, new InstanceFactory(registerType, registerImplementation, instance));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates/replaces a named container class registration with a specific, strong referenced, instance.\r\n        /// </summary>\r\n        /// <param name=\"registerType\">Type to register</param>\r\n        /// <param name=\"registerImplementation\">Type of instance to register that implements RegisterType</param>\r\n        /// <param name=\"instance\">Instance of RegisterImplementation to register</param>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <returns>RegisterOptions for fluent API</returns>\r\n        public RegisterOptions Register(Type registerType, Type registerImplementation, object instance, string name)\r\n        {\r\n            return RegisterInternal(registerType, name, new InstanceFactory(registerType, registerImplementation, instance));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates/replaces a container class registration with a user specified factory\r\n        /// </summary>\r\n        /// <param name=\"registerType\">Type to register</param>\r\n        /// <param name=\"factory\">Factory/lambda that returns an instance of RegisterType</param>\r\n        /// <returns>RegisterOptions for fluent API</returns>\r\n        public RegisterOptions Register(Type registerType, Func<TinyIoCContainer, NamedParameterOverloads, object> factory)\r\n        {\r\n            return RegisterInternal(registerType, string.Empty, new DelegateFactory(registerType, factory));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates/replaces a container class registration with a user specified factory\r\n        /// </summary>\r\n        /// <param name=\"registerType\">Type to register</param>\r\n        /// <param name=\"factory\">Factory/lambda that returns an instance of RegisterType</param>\r\n        /// <param name=\"name\">Name of registation</param>\r\n        /// <returns>RegisterOptions for fluent API</returns>\r\n        public RegisterOptions Register(Type registerType, Func<TinyIoCContainer, NamedParameterOverloads, object> factory, string name)\r\n        {\r\n            return RegisterInternal(registerType, name, new DelegateFactory(registerType, factory));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates/replaces a container class registration with default options.\r\n        /// </summary>\r\n        /// <typeparam name=\"RegisterImplementation\">Type to register</typeparam>\r\n        /// <returns>RegisterOptions for fluent API</returns>\r\n        public RegisterOptions Register<RegisterType>()\r\n            where RegisterType : class\r\n        {\r\n            return this.Register(typeof(RegisterType));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates/replaces a named container class registration with default options.\r\n        /// </summary>\r\n        /// <typeparam name=\"RegisterImplementation\">Type to register</typeparam>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <returns>RegisterOptions for fluent API</returns>\r\n        public RegisterOptions Register<RegisterType>(string name)\r\n            where RegisterType : class\r\n        {\r\n            return this.Register(typeof(RegisterType), name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates/replaces a container class registration with a given implementation and default options.\r\n        /// </summary>\r\n        /// <typeparam name=\"RegisterType\">Type to register</typeparam>\r\n        /// <typeparam name=\"RegisterImplementation\">Type to instantiate that implements RegisterType</typeparam>\r\n        /// <returns>RegisterOptions for fluent API</returns>\r\n        public RegisterOptions Register<RegisterType, RegisterImplementation>()\r\n            where RegisterType : class\r\n            where RegisterImplementation : class, RegisterType\r\n        {\r\n            return this.Register(typeof(RegisterType), typeof(RegisterImplementation));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates/replaces a named container class registration with a given implementation and default options.\r\n        /// </summary>\r\n        /// <typeparam name=\"RegisterType\">Type to register</typeparam>\r\n        /// <typeparam name=\"RegisterImplementation\">Type to instantiate that implements RegisterType</typeparam>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <returns>RegisterOptions for fluent API</returns>\r\n        public RegisterOptions Register<RegisterType, RegisterImplementation>(string name)\r\n            where RegisterType : class\r\n            where RegisterImplementation : class, RegisterType\r\n        {\r\n            return this.Register(typeof(RegisterType), typeof(RegisterImplementation), name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates/replaces a container class registration with a specific, strong referenced, instance.\r\n        /// </summary>\r\n        /// <typeparam name=\"RegisterType\">Type to register</typeparam>\r\n        /// <param name=\"instance\">Instance of RegisterType to register</param>\r\n        /// <returns>RegisterOptions for fluent API</returns>\r\n        public RegisterOptions Register<RegisterType>(RegisterType instance)\r\n           where RegisterType : class\r\n        {\r\n            return this.Register(typeof(RegisterType), instance);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates/replaces a named container class registration with a specific, strong referenced, instance.\r\n        /// </summary>\r\n        /// <typeparam name=\"RegisterType\">Type to register</typeparam>\r\n        /// <param name=\"instance\">Instance of RegisterType to register</param>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <returns>RegisterOptions for fluent API</returns>\r\n        public RegisterOptions Register<RegisterType>(RegisterType instance, string name)\r\n            where RegisterType : class\r\n        {\r\n            return this.Register(typeof(RegisterType), instance, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates/replaces a container class registration with a specific, strong referenced, instance.\r\n        /// </summary>\r\n        /// <typeparam name=\"RegisterType\">Type to register</typeparam>\r\n        /// <typeparam name=\"RegisterImplementation\">Type of instance to register that implements RegisterType</typeparam>\r\n        /// <param name=\"instance\">Instance of RegisterImplementation to register</param>\r\n        /// <returns>RegisterOptions for fluent API</returns>\r\n        public RegisterOptions Register<RegisterType, RegisterImplementation>(RegisterImplementation instance)\r\n            where RegisterType : class\r\n            where RegisterImplementation : class, RegisterType\r\n        {\r\n            return this.Register(typeof(RegisterType), typeof(RegisterImplementation), instance);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates/replaces a named container class registration with a specific, strong referenced, instance.\r\n        /// </summary>\r\n        /// <typeparam name=\"RegisterType\">Type to register</typeparam>\r\n        /// <typeparam name=\"RegisterImplementation\">Type of instance to register that implements RegisterType</typeparam>\r\n        /// <param name=\"instance\">Instance of RegisterImplementation to register</param>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <returns>RegisterOptions for fluent API</returns>\r\n        public RegisterOptions Register<RegisterType, RegisterImplementation>(RegisterImplementation instance, string name)\r\n            where RegisterType : class\r\n            where RegisterImplementation : class, RegisterType\r\n        {\r\n            return this.Register(typeof(RegisterType), typeof(RegisterImplementation), instance, name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates/replaces a container class registration with a user specified factory\r\n        /// </summary>\r\n        /// <typeparam name=\"RegisterType\">Type to register</typeparam>\r\n        /// <param name=\"factory\">Factory/lambda that returns an instance of RegisterType</param>\r\n        /// <returns>RegisterOptions for fluent API</returns>\r\n        public RegisterOptions Register<RegisterType>(Func<TinyIoCContainer, NamedParameterOverloads, RegisterType> factory)\r\n            where RegisterType : class\r\n        {\r\n            if (factory == null)\r\n            {\r\n                throw new ArgumentNullException(\"factory\");\r\n            }\r\n\r\n            return this.Register(typeof(RegisterType), (c, o) => factory(c, o));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates/replaces a named container class registration with a user specified factory\r\n        /// </summary>\r\n        /// <typeparam name=\"RegisterType\">Type to register</typeparam>\r\n        /// <param name=\"factory\">Factory/lambda that returns an instance of RegisterType</param>\r\n        /// <param name=\"name\">Name of registation</param>\r\n        /// <returns>RegisterOptions for fluent API</returns>\r\n        public RegisterOptions Register<RegisterType>(Func<TinyIoCContainer, NamedParameterOverloads, RegisterType> factory, string name)\r\n            where RegisterType : class\r\n        {\r\n            if (factory == null)\r\n            {\r\n                throw new ArgumentNullException(\"factory\");\r\n            }\r\n\r\n            return this.Register(typeof(RegisterType), (c, o) => factory(c, o), name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Register multiple implementations of a type.\r\n        /// \r\n        /// Internally this registers each implementation using the full name of the class as its registration name.\r\n        /// </summary>\r\n        /// <typeparam name=\"RegisterType\">Type that each implementation implements</typeparam>\r\n        /// <param name=\"implementationTypes\">Types that implement RegisterType</param>\r\n        /// <returns>MultiRegisterOptions for the fluent API</returns>\r\n        public MultiRegisterOptions RegisterMultiple<RegisterType>(IEnumerable<Type> implementationTypes)\r\n        {\r\n            return RegisterMultiple(typeof(RegisterType), implementationTypes);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Register multiple implementations of a type.\r\n        /// \r\n        /// Internally this registers each implementation using the full name of the class as its registration name.\r\n        /// </summary>\r\n        /// <param name=\"registrationType\">Type that each implementation implements</param>\r\n        /// <param name=\"implementationTypes\">Types that implement RegisterType</param>\r\n        /// <returns>MultiRegisterOptions for the fluent API</returns>\r\n        public MultiRegisterOptions RegisterMultiple(Type registrationType, IEnumerable<Type> implementationTypes)\r\n        {\r\n            if (implementationTypes == null)\r\n                throw new ArgumentNullException(\"types\", \"types is null.\");\r\n\r\n            foreach (var type in implementationTypes)\r\n                //#if NETFX_CORE\r\n                //\t\t\t\tif (!registrationType.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()))\r\n                //#else\r\n                if (!registrationType.IsAssignableFrom(type))\r\n                    //#endif\r\n                    throw new ArgumentException(String.Format(\"types: The type {0} is not assignable from {1}\", registrationType.FullName, type.FullName));\r\n\r\n            if (implementationTypes.Count() != implementationTypes.Distinct().Count())\r\n            {\r\n                var queryForDuplicatedTypes = from i in implementationTypes\r\n                                              group i by i\r\n                                                  into j\r\n                                              where j.Count() > 1\r\n                                              select j.Key.FullName;\r\n\r\n                var fullNamesOfDuplicatedTypes = string.Join(\",\\n\", queryForDuplicatedTypes.ToArray());\r\n                var multipleRegMessage = string.Format(\"types: The same implementation type cannot be specified multiple times for {0}\\n\\n{1}\", registrationType.FullName, fullNamesOfDuplicatedTypes);\r\n                throw new ArgumentException(multipleRegMessage);\r\n            }\r\n\r\n            var registerOptions = new List<RegisterOptions>();\r\n\r\n            foreach (var type in implementationTypes)\r\n            {\r\n                registerOptions.Add(Register(registrationType, type, type.FullName));\r\n            }\r\n\r\n            return new MultiRegisterOptions(registerOptions);\r\n        }\r\n        #endregion\r\n\r\n        #region Unregistration\r\n\r\n        /// <summary>\r\n        /// Remove a container class registration.\r\n        /// </summary>\r\n        /// <typeparam name=\"RegisterType\">Type to unregister</typeparam>\r\n        /// <returns>true if the registration is successfully found and removed; otherwise, false.</returns>\r\n        public bool Unregister<RegisterType>()\r\n        {\r\n            return Unregister(typeof(RegisterType), string.Empty);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Remove a named container class registration.\r\n        /// </summary>\r\n        /// <typeparam name=\"RegisterType\">Type to unregister</typeparam>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <returns>true if the registration is successfully found and removed; otherwise, false.</returns>\r\n        public bool Unregister<RegisterType>(string name)\r\n        {\r\n            return Unregister(typeof(RegisterType), name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Remove a container class registration.\r\n        /// </summary>\r\n        /// <param name=\"registerType\">Type to unregister</param>\r\n        /// <returns>true if the registration is successfully found and removed; otherwise, false.</returns>\r\n        public bool Unregister(Type registerType)\r\n        {\r\n            return Unregister(registerType, string.Empty);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Remove a named container class registration.\r\n        /// </summary>\r\n        /// <param name=\"registerType\">Type to unregister</param>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <returns>true if the registration is successfully found and removed; otherwise, false.</returns>\r\n        public bool Unregister(Type registerType, string name)\r\n        {\r\n            var typeRegistration = new TypeRegistration(registerType, name);\r\n\r\n            return RemoveRegistration(typeRegistration);\r\n        }\r\n\r\n        #endregion\r\n\r\n        #region Resolution\r\n        /// <summary>\r\n        /// Attempts to resolve a type using default options.\r\n        /// </summary>\r\n        /// <param name=\"resolveType\">Type to resolve</param>\r\n        /// <returns>Instance of type</returns>\r\n        /// <exception cref=\"TinyIoCResolutionException\">Unable to resolve the type.</exception>\r\n        public object Resolve(Type resolveType)\r\n        {\r\n            return ResolveInternal(new TypeRegistration(resolveType), NamedParameterOverloads.Default, ResolveOptions.Default);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to resolve a type using specified options.\r\n        /// </summary>\r\n        /// <param name=\"resolveType\">Type to resolve</param>\r\n        /// <param name=\"options\">Resolution options</param>\r\n        /// <returns>Instance of type</returns>\r\n        /// <exception cref=\"TinyIoCResolutionException\">Unable to resolve the type.</exception>\r\n        public object Resolve(Type resolveType, ResolveOptions options)\r\n        {\r\n            return ResolveInternal(new TypeRegistration(resolveType), NamedParameterOverloads.Default, options);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to resolve a type using default options and the supplied name.\r\n        ///\r\n        /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).\r\n        /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.\r\n        /// </summary>\r\n        /// <param name=\"resolveType\">Type to resolve</param>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <returns>Instance of type</returns>\r\n        /// <exception cref=\"TinyIoCResolutionException\">Unable to resolve the type.</exception>\r\n        public object Resolve(Type resolveType, string name)\r\n        {\r\n            return ResolveInternal(new TypeRegistration(resolveType, name), NamedParameterOverloads.Default, ResolveOptions.Default);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to resolve a type using supplied options and  name.\r\n        ///\r\n        /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).\r\n        /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.\r\n        /// </summary>\r\n        /// <param name=\"resolveType\">Type to resolve</param>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <param name=\"options\">Resolution options</param>\r\n        /// <returns>Instance of type</returns>\r\n        /// <exception cref=\"TinyIoCResolutionException\">Unable to resolve the type.</exception>\r\n        public object Resolve(Type resolveType, string name, ResolveOptions options)\r\n        {\r\n            return ResolveInternal(new TypeRegistration(resolveType, name), NamedParameterOverloads.Default, options);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to resolve a type using default options and the supplied constructor parameters.\r\n        ///\r\n        /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).\r\n        /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.\r\n        /// </summary>\r\n        /// <param name=\"resolveType\">Type to resolve</param>\r\n        /// <param name=\"parameters\">User specified constructor parameters</param>\r\n        /// <returns>Instance of type</returns>\r\n        /// <exception cref=\"TinyIoCResolutionException\">Unable to resolve the type.</exception>\r\n        public object Resolve(Type resolveType, NamedParameterOverloads parameters)\r\n        {\r\n            return ResolveInternal(new TypeRegistration(resolveType), parameters, ResolveOptions.Default);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to resolve a type using specified options and the supplied constructor parameters.\r\n        ///\r\n        /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).\r\n        /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.\r\n        /// </summary>\r\n        /// <param name=\"resolveType\">Type to resolve</param>\r\n        /// <param name=\"parameters\">User specified constructor parameters</param>\r\n        /// <param name=\"options\">Resolution options</param>\r\n        /// <returns>Instance of type</returns>\r\n        /// <exception cref=\"TinyIoCResolutionException\">Unable to resolve the type.</exception>\r\n        public object Resolve(Type resolveType, NamedParameterOverloads parameters, ResolveOptions options)\r\n        {\r\n            return ResolveInternal(new TypeRegistration(resolveType), parameters, options);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to resolve a type using default options and the supplied constructor parameters and name.\r\n        ///\r\n        /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).\r\n        /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.\r\n        /// </summary>\r\n        /// <param name=\"resolveType\">Type to resolve</param>\r\n        /// <param name=\"parameters\">User specified constructor parameters</param>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <returns>Instance of type</returns>\r\n        /// <exception cref=\"TinyIoCResolutionException\">Unable to resolve the type.</exception>\r\n        public object Resolve(Type resolveType, string name, NamedParameterOverloads parameters)\r\n        {\r\n            return ResolveInternal(new TypeRegistration(resolveType, name), parameters, ResolveOptions.Default);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to resolve a named type using specified options and the supplied constructor parameters.\r\n        ///\r\n        /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).\r\n        /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.\r\n        /// </summary>\r\n        /// <param name=\"resolveType\">Type to resolve</param>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <param name=\"parameters\">User specified constructor parameters</param>\r\n        /// <param name=\"options\">Resolution options</param>\r\n        /// <returns>Instance of type</returns>\r\n        /// <exception cref=\"TinyIoCResolutionException\">Unable to resolve the type.</exception>\r\n        public object Resolve(Type resolveType, string name, NamedParameterOverloads parameters, ResolveOptions options)\r\n        {\r\n            return ResolveInternal(new TypeRegistration(resolveType, name), parameters, options);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to resolve a type using default options.\r\n        /// </summary>\r\n        /// <typeparam name=\"ResolveType\">Type to resolve</typeparam>\r\n        /// <returns>Instance of type</returns>\r\n        /// <exception cref=\"TinyIoCResolutionException\">Unable to resolve the type.</exception>\r\n        public ResolveType Resolve<ResolveType>()\r\n            where ResolveType : class\r\n        {\r\n            return (ResolveType)Resolve(typeof(ResolveType));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to resolve a type using specified options.\r\n        /// </summary>\r\n        /// <typeparam name=\"ResolveType\">Type to resolve</typeparam>\r\n        /// <param name=\"options\">Resolution options</param>\r\n        /// <returns>Instance of type</returns>\r\n        /// <exception cref=\"TinyIoCResolutionException\">Unable to resolve the type.</exception>\r\n        public ResolveType Resolve<ResolveType>(ResolveOptions options)\r\n            where ResolveType : class\r\n        {\r\n            return (ResolveType)Resolve(typeof(ResolveType), options);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to resolve a type using default options and the supplied name.\r\n        ///\r\n        /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).\r\n        /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.\r\n        /// </summary>\r\n        /// <typeparam name=\"ResolveType\">Type to resolve</typeparam>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <returns>Instance of type</returns>\r\n        /// <exception cref=\"TinyIoCResolutionException\">Unable to resolve the type.</exception>\r\n        public ResolveType Resolve<ResolveType>(string name)\r\n            where ResolveType : class\r\n        {\r\n            return (ResolveType)Resolve(typeof(ResolveType), name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to resolve a type using supplied options and  name.\r\n        ///\r\n        /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).\r\n        /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.\r\n        /// </summary>\r\n        /// <typeparam name=\"ResolveType\">Type to resolve</typeparam>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <param name=\"options\">Resolution options</param>\r\n        /// <returns>Instance of type</returns>\r\n        /// <exception cref=\"TinyIoCResolutionException\">Unable to resolve the type.</exception>\r\n        public ResolveType Resolve<ResolveType>(string name, ResolveOptions options)\r\n            where ResolveType : class\r\n        {\r\n            return (ResolveType)Resolve(typeof(ResolveType), name, options);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to resolve a type using default options and the supplied constructor parameters.\r\n        ///\r\n        /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).\r\n        /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.\r\n        /// </summary>\r\n        /// <typeparam name=\"ResolveType\">Type to resolve</typeparam>\r\n        /// <param name=\"parameters\">User specified constructor parameters</param>\r\n        /// <returns>Instance of type</returns>\r\n        /// <exception cref=\"TinyIoCResolutionException\">Unable to resolve the type.</exception>\r\n        public ResolveType Resolve<ResolveType>(NamedParameterOverloads parameters)\r\n            where ResolveType : class\r\n        {\r\n            return (ResolveType)Resolve(typeof(ResolveType), parameters);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to resolve a type using specified options and the supplied constructor parameters.\r\n        ///\r\n        /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).\r\n        /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.\r\n        /// </summary>\r\n        /// <typeparam name=\"ResolveType\">Type to resolve</typeparam>\r\n        /// <param name=\"parameters\">User specified constructor parameters</param>\r\n        /// <param name=\"options\">Resolution options</param>\r\n        /// <returns>Instance of type</returns>\r\n        /// <exception cref=\"TinyIoCResolutionException\">Unable to resolve the type.</exception>\r\n        public ResolveType Resolve<ResolveType>(NamedParameterOverloads parameters, ResolveOptions options)\r\n            where ResolveType : class\r\n        {\r\n            return (ResolveType)Resolve(typeof(ResolveType), parameters, options);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to resolve a type using default options and the supplied constructor parameters and name.\r\n        ///\r\n        /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).\r\n        /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.\r\n        /// </summary>\r\n        /// <typeparam name=\"ResolveType\">Type to resolve</typeparam>\r\n        /// <param name=\"parameters\">User specified constructor parameters</param>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <returns>Instance of type</returns>\r\n        /// <exception cref=\"TinyIoCResolutionException\">Unable to resolve the type.</exception>\r\n        public ResolveType Resolve<ResolveType>(string name, NamedParameterOverloads parameters)\r\n            where ResolveType : class\r\n        {\r\n            return (ResolveType)Resolve(typeof(ResolveType), name, parameters);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to resolve a named type using specified options and the supplied constructor parameters.\r\n        ///\r\n        /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).\r\n        /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.\r\n        /// </summary>\r\n        /// <typeparam name=\"ResolveType\">Type to resolve</typeparam>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <param name=\"parameters\">User specified constructor parameters</param>\r\n        /// <param name=\"options\">Resolution options</param>\r\n        /// <returns>Instance of type</returns>\r\n        /// <exception cref=\"TinyIoCResolutionException\">Unable to resolve the type.</exception>\r\n        public ResolveType Resolve<ResolveType>(string name, NamedParameterOverloads parameters, ResolveOptions options)\r\n            where ResolveType : class\r\n        {\r\n            return (ResolveType)Resolve(typeof(ResolveType), name, parameters, options);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to predict whether a given type can be resolved with default options.\r\n        ///\r\n        /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.\r\n        /// </summary>\r\n        /// <param name=\"resolveType\">Type to resolve</param>\r\n        /// <returns>Bool indicating whether the type can be resolved</returns>\r\n        public bool CanResolve(Type resolveType)\r\n        {\r\n            return CanResolveInternal(new TypeRegistration(resolveType), NamedParameterOverloads.Default, ResolveOptions.Default);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to predict whether a given named type can be resolved with default options.\r\n        ///\r\n        /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.\r\n        /// </summary>\r\n        /// <param name=\"resolveType\">Type to resolve</param>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <returns>Bool indicating whether the type can be resolved</returns>\r\n        private bool CanResolve(Type resolveType, string name)\r\n        {\r\n            return CanResolveInternal(new TypeRegistration(resolveType, name), NamedParameterOverloads.Default, ResolveOptions.Default);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to predict whether a given type can be resolved with the specified options.\r\n        ///\r\n        /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.\r\n        /// </summary>\r\n        /// <param name=\"resolveType\">Type to resolve</param>\r\n        /// <param name=\"options\">Resolution options</param>\r\n        /// <returns>Bool indicating whether the type can be resolved</returns>\r\n        public bool CanResolve(Type resolveType, ResolveOptions options)\r\n        {\r\n            return CanResolveInternal(new TypeRegistration(resolveType), NamedParameterOverloads.Default, options);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to predict whether a given named type can be resolved with the specified options.\r\n        ///\r\n        /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.\r\n        /// </summary>\r\n        /// <param name=\"resolveType\">Type to resolve</param>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <param name=\"options\">Resolution options</param>\r\n        /// <returns>Bool indicating whether the type can be resolved</returns>\r\n        public bool CanResolve(Type resolveType, string name, ResolveOptions options)\r\n        {\r\n            return CanResolveInternal(new TypeRegistration(resolveType, name), NamedParameterOverloads.Default, options);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to predict whether a given type can be resolved with the supplied constructor parameters and default options.\r\n        ///\r\n        /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).\r\n        /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.\r\n        /// \r\n        /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.\r\n        /// </summary>\r\n        /// <param name=\"resolveType\">Type to resolve</param>\r\n        /// <param name=\"parameters\">User supplied named parameter overloads</param>\r\n        /// <returns>Bool indicating whether the type can be resolved</returns>\r\n        public bool CanResolve(Type resolveType, NamedParameterOverloads parameters)\r\n        {\r\n            return CanResolveInternal(new TypeRegistration(resolveType), parameters, ResolveOptions.Default);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to predict whether a given named type can be resolved with the supplied constructor parameters and default options.\r\n        ///\r\n        /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).\r\n        /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.\r\n        /// \r\n        /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.\r\n        /// </summary>\r\n        /// <param name=\"resolveType\">Type to resolve</param>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <param name=\"parameters\">User supplied named parameter overloads</param>\r\n        /// <returns>Bool indicating whether the type can be resolved</returns>\r\n        public bool CanResolve(Type resolveType, string name, NamedParameterOverloads parameters)\r\n        {\r\n            return CanResolveInternal(new TypeRegistration(resolveType, name), parameters, ResolveOptions.Default);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to predict whether a given type can be resolved with the supplied constructor parameters options.\r\n        ///\r\n        /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).\r\n        /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.\r\n        /// \r\n        /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.\r\n        /// </summary>\r\n        /// <param name=\"resolveType\">Type to resolve</param>\r\n        /// <param name=\"parameters\">User supplied named parameter overloads</param>\r\n        /// <param name=\"options\">Resolution options</param>\r\n        /// <returns>Bool indicating whether the type can be resolved</returns>\r\n        public bool CanResolve(Type resolveType, NamedParameterOverloads parameters, ResolveOptions options)\r\n        {\r\n            return CanResolveInternal(new TypeRegistration(resolveType), parameters, options);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to predict whether a given named type can be resolved with the supplied constructor parameters options.\r\n        ///\r\n        /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).\r\n        /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.\r\n        /// \r\n        /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.\r\n        /// </summary>\r\n        /// <param name=\"resolveType\">Type to resolve</param>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <param name=\"parameters\">User supplied named parameter overloads</param>\r\n        /// <param name=\"options\">Resolution options</param>\r\n        /// <returns>Bool indicating whether the type can be resolved</returns>\r\n        public bool CanResolve(Type resolveType, string name, NamedParameterOverloads parameters, ResolveOptions options)\r\n        {\r\n            return CanResolveInternal(new TypeRegistration(resolveType, name), parameters, options);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to predict whether a given type can be resolved with default options.\r\n        ///\r\n        /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.\r\n        /// </summary>\r\n        /// <typeparam name=\"ResolveType\">Type to resolve</typeparam>\r\n        /// <returns>Bool indicating whether the type can be resolved</returns>\r\n        public bool CanResolve<ResolveType>()\r\n            where ResolveType : class\r\n        {\r\n            return CanResolve(typeof(ResolveType));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to predict whether a given named type can be resolved with default options.\r\n        ///\r\n        /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.\r\n        /// </summary>\r\n        /// <typeparam name=\"ResolveType\">Type to resolve</typeparam>\r\n        /// <returns>Bool indicating whether the type can be resolved</returns>\r\n        public bool CanResolve<ResolveType>(string name)\r\n            where ResolveType : class\r\n        {\r\n            return CanResolve(typeof(ResolveType), name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to predict whether a given type can be resolved with the specified options.\r\n        ///\r\n        /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.\r\n        /// </summary>\r\n        /// <typeparam name=\"ResolveType\">Type to resolve</typeparam>\r\n        /// <param name=\"options\">Resolution options</param>\r\n        /// <returns>Bool indicating whether the type can be resolved</returns>\r\n        public bool CanResolve<ResolveType>(ResolveOptions options)\r\n            where ResolveType : class\r\n        {\r\n            return CanResolve(typeof(ResolveType), options);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to predict whether a given named type can be resolved with the specified options.\r\n        ///\r\n        /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.\r\n        /// </summary>\r\n        /// <typeparam name=\"ResolveType\">Type to resolve</typeparam>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <param name=\"options\">Resolution options</param>\r\n        /// <returns>Bool indicating whether the type can be resolved</returns>\r\n        public bool CanResolve<ResolveType>(string name, ResolveOptions options)\r\n            where ResolveType : class\r\n        {\r\n            return CanResolve(typeof(ResolveType), name, options);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to predict whether a given type can be resolved with the supplied constructor parameters and default options.\r\n        ///\r\n        /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).\r\n        /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.\r\n        /// \r\n        /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.\r\n        /// </summary>\r\n        /// <typeparam name=\"ResolveType\">Type to resolve</typeparam>\r\n        /// <param name=\"parameters\">User supplied named parameter overloads</param>\r\n        /// <returns>Bool indicating whether the type can be resolved</returns>\r\n        public bool CanResolve<ResolveType>(NamedParameterOverloads parameters)\r\n            where ResolveType : class\r\n        {\r\n            return CanResolve(typeof(ResolveType), parameters);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to predict whether a given named type can be resolved with the supplied constructor parameters and default options.\r\n        ///\r\n        /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).\r\n        /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.\r\n        /// \r\n        /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.\r\n        /// </summary>\r\n        /// <typeparam name=\"ResolveType\">Type to resolve</typeparam>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <param name=\"parameters\">User supplied named parameter overloads</param>\r\n        /// <returns>Bool indicating whether the type can be resolved</returns>\r\n        public bool CanResolve<ResolveType>(string name, NamedParameterOverloads parameters)\r\n            where ResolveType : class\r\n        {\r\n            return CanResolve(typeof(ResolveType), name, parameters);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to predict whether a given type can be resolved with the supplied constructor parameters options.\r\n        ///\r\n        /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).\r\n        /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.\r\n        /// \r\n        /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.\r\n        /// </summary>\r\n        /// <typeparam name=\"ResolveType\">Type to resolve</typeparam>\r\n        /// <param name=\"parameters\">User supplied named parameter overloads</param>\r\n        /// <param name=\"options\">Resolution options</param>\r\n        /// <returns>Bool indicating whether the type can be resolved</returns>\r\n        public bool CanResolve<ResolveType>(NamedParameterOverloads parameters, ResolveOptions options)\r\n            where ResolveType : class\r\n        {\r\n            return CanResolve(typeof(ResolveType), parameters, options);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to predict whether a given named type can be resolved with the supplied constructor parameters options.\r\n        ///\r\n        /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists).\r\n        /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail.\r\n        /// \r\n        /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called.\r\n        /// </summary>\r\n        /// <typeparam name=\"ResolveType\">Type to resolve</typeparam>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <param name=\"parameters\">User supplied named parameter overloads</param>\r\n        /// <param name=\"options\">Resolution options</param>\r\n        /// <returns>Bool indicating whether the type can be resolved</returns>\r\n        public bool CanResolve<ResolveType>(string name, NamedParameterOverloads parameters, ResolveOptions options)\r\n            where ResolveType : class\r\n        {\r\n            return CanResolve(typeof(ResolveType), name, parameters, options);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attemps to resolve a type using the default options\r\n        /// </summary>\r\n        /// <param name=\"resolveType\">Type to resolve</param>\r\n        /// <param name=\"resolvedType\">Resolved type or default if resolve fails</param>\r\n        /// <returns>True if resolved sucessfully, false otherwise</returns>\r\n        public bool TryResolve(Type resolveType, out object resolvedType)\r\n        {\r\n            try\r\n            {\r\n                resolvedType = Resolve(resolveType);\r\n                return true;\r\n            }\r\n            catch (TinyIoCResolutionException)\r\n            {\r\n                resolvedType = null;\r\n                return false;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attemps to resolve a type using the given options\r\n        /// </summary>\r\n        /// <param name=\"resolveType\">Type to resolve</param>\r\n        /// <param name=\"options\">Resolution options</param>\r\n        /// <param name=\"resolvedType\">Resolved type or default if resolve fails</param>\r\n        /// <returns>True if resolved sucessfully, false otherwise</returns>\r\n        public bool TryResolve(Type resolveType, ResolveOptions options, out object resolvedType)\r\n        {\r\n            try\r\n            {\r\n                resolvedType = Resolve(resolveType, options);\r\n                return true;\r\n            }\r\n            catch (TinyIoCResolutionException)\r\n            {\r\n                resolvedType = null;\r\n                return false;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attemps to resolve a type using the default options and given name\r\n        /// </summary>\r\n        /// <param name=\"resolveType\">Type to resolve</param>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <param name=\"resolvedType\">Resolved type or default if resolve fails</param>\r\n        /// <returns>True if resolved sucessfully, false otherwise</returns>\r\n        public bool TryResolve(Type resolveType, string name, out object resolvedType)\r\n        {\r\n            try\r\n            {\r\n                resolvedType = Resolve(resolveType, name);\r\n                return true;\r\n            }\r\n            catch (TinyIoCResolutionException)\r\n            {\r\n                resolvedType = null;\r\n                return false;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attemps to resolve a type using the given options and name\r\n        /// </summary>\r\n        /// <param name=\"resolveType\">Type to resolve</param>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <param name=\"options\">Resolution options</param>\r\n        /// <param name=\"resolvedType\">Resolved type or default if resolve fails</param>\r\n        /// <returns>True if resolved sucessfully, false otherwise</returns>\r\n        public bool TryResolve(Type resolveType, string name, ResolveOptions options, out object resolvedType)\r\n        {\r\n            try\r\n            {\r\n                resolvedType = Resolve(resolveType, name, options);\r\n                return true;\r\n            }\r\n            catch (TinyIoCResolutionException)\r\n            {\r\n                resolvedType = null;\r\n                return false;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attemps to resolve a type using the default options and supplied constructor parameters\r\n        /// </summary>\r\n        /// <param name=\"resolveType\">Type to resolve</param>\r\n        /// <param name=\"parameters\">User specified constructor parameters</param>\r\n        /// <param name=\"resolvedType\">Resolved type or default if resolve fails</param>\r\n        /// <returns>True if resolved sucessfully, false otherwise</returns>\r\n        public bool TryResolve(Type resolveType, NamedParameterOverloads parameters, out object resolvedType)\r\n        {\r\n            try\r\n            {\r\n                resolvedType = Resolve(resolveType, parameters);\r\n                return true;\r\n            }\r\n            catch (TinyIoCResolutionException)\r\n            {\r\n                resolvedType = null;\r\n                return false;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attemps to resolve a type using the default options and supplied name and constructor parameters\r\n        /// </summary>\r\n        /// <param name=\"resolveType\">Type to resolve</param>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <param name=\"parameters\">User specified constructor parameters</param>\r\n        /// <param name=\"resolvedType\">Resolved type or default if resolve fails</param>\r\n        /// <returns>True if resolved sucessfully, false otherwise</returns>\r\n        public bool TryResolve(Type resolveType, string name, NamedParameterOverloads parameters, out object resolvedType)\r\n        {\r\n            try\r\n            {\r\n                resolvedType = Resolve(resolveType, name, parameters);\r\n                return true;\r\n            }\r\n            catch (TinyIoCResolutionException)\r\n            {\r\n                resolvedType = null;\r\n                return false;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attemps to resolve a type using the supplied options and constructor parameters\r\n        /// </summary>\r\n        /// <param name=\"resolveType\">Type to resolve</param>\r\n        /// <param name=\"parameters\">User specified constructor parameters</param>\r\n        /// <param name=\"options\">Resolution options</param>\r\n        /// <param name=\"resolvedType\">Resolved type or default if resolve fails</param>\r\n        /// <returns>True if resolved sucessfully, false otherwise</returns>\r\n        public bool TryResolve(Type resolveType, NamedParameterOverloads parameters, ResolveOptions options, out object resolvedType)\r\n        {\r\n            try\r\n            {\r\n                resolvedType = Resolve(resolveType, parameters, options);\r\n                return true;\r\n            }\r\n            catch (TinyIoCResolutionException)\r\n            {\r\n                resolvedType = null;\r\n                return false;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attemps to resolve a type using the supplied name, options and constructor parameters\r\n        /// </summary>\r\n        /// <param name=\"resolveType\">Type to resolve</param>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <param name=\"parameters\">User specified constructor parameters</param>\r\n        /// <param name=\"options\">Resolution options</param>\r\n        /// <param name=\"resolvedType\">Resolved type or default if resolve fails</param>\r\n        /// <returns>True if resolved sucessfully, false otherwise</returns>\r\n        public bool TryResolve(Type resolveType, string name, NamedParameterOverloads parameters, ResolveOptions options, out object resolvedType)\r\n        {\r\n            try\r\n            {\r\n                resolvedType = Resolve(resolveType, name, parameters, options);\r\n                return true;\r\n            }\r\n            catch (TinyIoCResolutionException)\r\n            {\r\n                resolvedType = null;\r\n                return false;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attemps to resolve a type using the default options\r\n        /// </summary>\r\n        /// <typeparam name=\"ResolveType\">Type to resolve</typeparam>\r\n        /// <param name=\"resolvedType\">Resolved type or default if resolve fails</param>\r\n        /// <returns>True if resolved sucessfully, false otherwise</returns>\r\n        public bool TryResolve<ResolveType>(out ResolveType resolvedType)\r\n            where ResolveType : class\r\n        {\r\n            try\r\n            {\r\n                resolvedType = Resolve<ResolveType>();\r\n                return true;\r\n            }\r\n            catch (TinyIoCResolutionException)\r\n            {\r\n                resolvedType = default(ResolveType);\r\n                return false;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attemps to resolve a type using the given options\r\n        /// </summary>\r\n        /// <typeparam name=\"ResolveType\">Type to resolve</typeparam>\r\n        /// <param name=\"options\">Resolution options</param>\r\n        /// <param name=\"resolvedType\">Resolved type or default if resolve fails</param>\r\n        /// <returns>True if resolved sucessfully, false otherwise</returns>\r\n        public bool TryResolve<ResolveType>(ResolveOptions options, out ResolveType resolvedType)\r\n            where ResolveType : class\r\n        {\r\n            try\r\n            {\r\n                resolvedType = Resolve<ResolveType>(options);\r\n                return true;\r\n            }\r\n            catch (TinyIoCResolutionException)\r\n            {\r\n                resolvedType = default(ResolveType);\r\n                return false;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attemps to resolve a type using the default options and given name\r\n        /// </summary>\r\n        /// <typeparam name=\"ResolveType\">Type to resolve</typeparam>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <param name=\"resolvedType\">Resolved type or default if resolve fails</param>\r\n        /// <returns>True if resolved sucessfully, false otherwise</returns>\r\n        public bool TryResolve<ResolveType>(string name, out ResolveType resolvedType)\r\n            where ResolveType : class\r\n        {\r\n            try\r\n            {\r\n                resolvedType = Resolve<ResolveType>(name);\r\n                return true;\r\n            }\r\n            catch (TinyIoCResolutionException)\r\n            {\r\n                resolvedType = default(ResolveType);\r\n                return false;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attemps to resolve a type using the given options and name\r\n        /// </summary>\r\n        /// <typeparam name=\"ResolveType\">Type to resolve</typeparam>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <param name=\"options\">Resolution options</param>\r\n        /// <param name=\"resolvedType\">Resolved type or default if resolve fails</param>\r\n        /// <returns>True if resolved sucessfully, false otherwise</returns>\r\n        public bool TryResolve<ResolveType>(string name, ResolveOptions options, out ResolveType resolvedType)\r\n            where ResolveType : class\r\n        {\r\n            try\r\n            {\r\n                resolvedType = Resolve<ResolveType>(name, options);\r\n                return true;\r\n            }\r\n            catch (TinyIoCResolutionException)\r\n            {\r\n                resolvedType = default(ResolveType);\r\n                return false;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attemps to resolve a type using the default options and supplied constructor parameters\r\n        /// </summary>\r\n        /// <typeparam name=\"ResolveType\">Type to resolve</typeparam>\r\n        /// <param name=\"parameters\">User specified constructor parameters</param>\r\n        /// <param name=\"resolvedType\">Resolved type or default if resolve fails</param>\r\n        /// <returns>True if resolved sucessfully, false otherwise</returns>\r\n        public bool TryResolve<ResolveType>(NamedParameterOverloads parameters, out ResolveType resolvedType)\r\n            where ResolveType : class\r\n        {\r\n            try\r\n            {\r\n                resolvedType = Resolve<ResolveType>(parameters);\r\n                return true;\r\n            }\r\n            catch (TinyIoCResolutionException)\r\n            {\r\n                resolvedType = default(ResolveType);\r\n                return false;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attemps to resolve a type using the default options and supplied name and constructor parameters\r\n        /// </summary>\r\n        /// <typeparam name=\"ResolveType\">Type to resolve</typeparam>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <param name=\"parameters\">User specified constructor parameters</param>\r\n        /// <param name=\"resolvedType\">Resolved type or default if resolve fails</param>\r\n        /// <returns>True if resolved sucessfully, false otherwise</returns>\r\n        public bool TryResolve<ResolveType>(string name, NamedParameterOverloads parameters, out ResolveType resolvedType)\r\n            where ResolveType : class\r\n        {\r\n            try\r\n            {\r\n                resolvedType = Resolve<ResolveType>(name, parameters);\r\n                return true;\r\n            }\r\n            catch (TinyIoCResolutionException)\r\n            {\r\n                resolvedType = default(ResolveType);\r\n                return false;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attemps to resolve a type using the supplied options and constructor parameters\r\n        /// </summary>\r\n        /// <typeparam name=\"ResolveType\">Type to resolve</typeparam>\r\n        /// <param name=\"parameters\">User specified constructor parameters</param>\r\n        /// <param name=\"options\">Resolution options</param>\r\n        /// <param name=\"resolvedType\">Resolved type or default if resolve fails</param>\r\n        /// <returns>True if resolved sucessfully, false otherwise</returns>\r\n        public bool TryResolve<ResolveType>(NamedParameterOverloads parameters, ResolveOptions options, out ResolveType resolvedType)\r\n            where ResolveType : class\r\n        {\r\n            try\r\n            {\r\n                resolvedType = Resolve<ResolveType>(parameters, options);\r\n                return true;\r\n            }\r\n            catch (TinyIoCResolutionException)\r\n            {\r\n                resolvedType = default(ResolveType);\r\n                return false;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attemps to resolve a type using the supplied name, options and constructor parameters\r\n        /// </summary>\r\n        /// <typeparam name=\"ResolveType\">Type to resolve</typeparam>\r\n        /// <param name=\"name\">Name of registration</param>\r\n        /// <param name=\"parameters\">User specified constructor parameters</param>\r\n        /// <param name=\"options\">Resolution options</param>\r\n        /// <param name=\"resolvedType\">Resolved type or default if resolve fails</param>\r\n        /// <returns>True if resolved sucessfully, false otherwise</returns>\r\n        public bool TryResolve<ResolveType>(string name, NamedParameterOverloads parameters, ResolveOptions options, out ResolveType resolvedType)\r\n            where ResolveType : class\r\n        {\r\n            try\r\n            {\r\n                resolvedType = Resolve<ResolveType>(name, parameters, options);\r\n                return true;\r\n            }\r\n            catch (TinyIoCResolutionException)\r\n            {\r\n                resolvedType = default(ResolveType);\r\n                return false;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns all registrations of a type\r\n        /// </summary>\r\n        /// <param name=\"resolveType\">Type to resolveAll</param>\r\n        /// <param name=\"includeUnnamed\">Whether to include un-named (default) registrations</param>\r\n        /// <returns>IEnumerable</returns>\r\n        public IEnumerable<object> ResolveAll(Type resolveType, bool includeUnnamed)\r\n        {\r\n            return ResolveAllInternal(resolveType, includeUnnamed);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns all registrations of a type, both named and unnamed\r\n        /// </summary>\r\n        /// <param name=\"resolveType\">Type to resolveAll</param>\r\n        /// <returns>IEnumerable</returns>\r\n        public IEnumerable<object> ResolveAll(Type resolveType)\r\n        {\r\n            return ResolveAll(resolveType, false);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns all registrations of a type\r\n        /// </summary>\r\n        /// <typeparam name=\"ResolveType\">Type to resolveAll</typeparam>\r\n        /// <param name=\"includeUnnamed\">Whether to include un-named (default) registrations</param>\r\n        /// <returns>IEnumerable</returns>\r\n        public IEnumerable<ResolveType> ResolveAll<ResolveType>(bool includeUnnamed)\r\n            where ResolveType : class\r\n        {\r\n            return this.ResolveAll(typeof(ResolveType), includeUnnamed).Cast<ResolveType>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns all registrations of a type, both named and unnamed\r\n        /// </summary>\r\n        /// <typeparam name=\"ResolveType\">Type to resolveAll</typeparam>\r\n        /// <returns>IEnumerable</returns>\r\n        public IEnumerable<ResolveType> ResolveAll<ResolveType>()\r\n            where ResolveType : class\r\n        {\r\n            return ResolveAll<ResolveType>(true);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to resolve all public property dependencies on the given object.\r\n        /// </summary>\r\n        /// <param name=\"input\">Object to \"build up\"</param>\r\n        public void BuildUp(object input)\r\n        {\r\n            BuildUpInternal(input, ResolveOptions.Default);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Attempts to resolve all public property dependencies on the given object using the given resolve options.\r\n        /// </summary>\r\n        /// <param name=\"input\">Object to \"build up\"</param>\r\n        /// <param name=\"resolveOptions\">Resolve options to use</param>\r\n        public void BuildUp(object input, ResolveOptions resolveOptions)\r\n        {\r\n            BuildUpInternal(input, resolveOptions);\r\n        }\r\n        #endregion\r\n        #endregion\r\n\r\n        #region Object Factories\r\n        /// <summary>\r\n        /// Provides custom lifetime management for ASP.Net per-request lifetimes etc.\r\n        /// </summary>\r\n        public interface ITinyIoCObjectLifetimeProvider\r\n        {\r\n            /// <summary>\r\n            /// Gets the stored object if it exists, or null if not\r\n            /// </summary>\r\n            /// <returns>Object instance or null</returns>\r\n            object GetObject();\r\n\r\n            /// <summary>\r\n            /// Store the object\r\n            /// </summary>\r\n            /// <param name=\"value\">Object to store</param>\r\n            void SetObject(object value);\r\n\r\n            /// <summary>\r\n            /// Release the object\r\n            /// </summary>\r\n            void ReleaseObject();\r\n        }\r\n\r\n        private abstract class ObjectFactoryBase\r\n        {\r\n            /// <summary>\r\n            /// Whether to assume this factory sucessfully constructs its objects\r\n            /// \r\n            /// Generally set to true for delegate style factories as CanResolve cannot delve\r\n            /// into the delegates they contain.\r\n            /// </summary>\r\n            public virtual bool AssumeConstruction { get { return false; } }\r\n\r\n            /// <summary>\r\n            /// The type the factory instantiates\r\n            /// </summary>\r\n            public abstract Type CreatesType { get; }\r\n\r\n            /// <summary>\r\n            /// Constructor to use, if specified\r\n            /// </summary>\r\n            public ConstructorInfo Constructor { get; protected set; }\r\n\r\n            /// <summary>\r\n            /// Create the type\r\n            /// </summary>\r\n            /// <param name=\"requestedType\">Type user requested to be resolved</param>\r\n            /// <param name=\"container\">Container that requested the creation</param>\r\n            /// <param name=\"parameters\">Any user parameters passed</param>\r\n            /// <param name=\"options\"></param>\r\n            /// <returns></returns>\r\n            public abstract object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options);\r\n\r\n            public virtual ObjectFactoryBase SingletonVariant\r\n            {\r\n                get\r\n                {\r\n                    throw new TinyIoCRegistrationException(this.GetType(), \"singleton\");\r\n                }\r\n            }\r\n\r\n            public virtual ObjectFactoryBase MultiInstanceVariant\r\n            {\r\n                get\r\n                {\r\n                    throw new TinyIoCRegistrationException(this.GetType(), \"multi-instance\");\r\n                }\r\n            }\r\n\r\n            public virtual ObjectFactoryBase StrongReferenceVariant\r\n            {\r\n                get\r\n                {\r\n                    throw new TinyIoCRegistrationException(this.GetType(), \"strong reference\");\r\n                }\r\n            }\r\n\r\n            public virtual ObjectFactoryBase WeakReferenceVariant\r\n            {\r\n                get\r\n                {\r\n                    throw new TinyIoCRegistrationException(this.GetType(), \"weak reference\");\r\n                }\r\n            }\r\n\r\n            public virtual ObjectFactoryBase GetCustomObjectLifetimeVariant(ITinyIoCObjectLifetimeProvider lifetimeProvider, string errorString)\r\n            {\r\n                throw new TinyIoCRegistrationException(this.GetType(), errorString);\r\n            }\r\n\r\n            public virtual void SetConstructor(ConstructorInfo constructor)\r\n            {\r\n                Constructor = constructor;\r\n            }\r\n\r\n            public virtual ObjectFactoryBase GetFactoryForChildContainer(Type type, TinyIoCContainer parent, TinyIoCContainer child)\r\n            {\r\n                return this;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// IObjectFactory that creates new instances of types for each resolution\r\n        /// </summary>\r\n        private class MultiInstanceFactory : ObjectFactoryBase\r\n        {\r\n            private readonly Type registerType;\r\n            private readonly Type registerImplementation;\r\n            public override Type CreatesType { get { return this.registerImplementation; } }\r\n\r\n            public MultiInstanceFactory(Type registerType, Type registerImplementation)\r\n            {\r\n                //#if NETFX_CORE\r\n                //\t\t\t\tif (registerImplementation.GetTypeInfo().IsAbstract() || registerImplementation.GetTypeInfo().IsInterface())\r\n                //\t\t\t\t\tthrow new TinyIoCRegistrationTypeException(registerImplementation, \"MultiInstanceFactory\");\r\n                //#else\r\n                if (registerImplementation.IsAbstract() || registerImplementation.IsInterface())\r\n                    throw new TinyIoCRegistrationTypeException(registerImplementation, \"MultiInstanceFactory\");\r\n                //#endif\r\n                if (!IsValidAssignment(registerType, registerImplementation))\r\n                    throw new TinyIoCRegistrationTypeException(registerImplementation, \"MultiInstanceFactory\");\r\n\r\n                this.registerType = registerType;\r\n                this.registerImplementation = registerImplementation;\r\n            }\r\n\r\n            public override object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options)\r\n            {\r\n                try\r\n                {\r\n                    return container.ConstructType(requestedType, this.registerImplementation, Constructor, parameters, options);\r\n                }\r\n                catch (TinyIoCResolutionException ex)\r\n                {\r\n                    throw new TinyIoCResolutionException(this.registerType, ex);\r\n                }\r\n            }\r\n\r\n            public override ObjectFactoryBase SingletonVariant\r\n            {\r\n                get\r\n                {\r\n                    return new SingletonFactory(this.registerType, this.registerImplementation);\r\n                }\r\n            }\r\n\r\n            public override ObjectFactoryBase GetCustomObjectLifetimeVariant(ITinyIoCObjectLifetimeProvider lifetimeProvider, string errorString)\r\n            {\r\n                return new CustomObjectLifetimeFactory(this.registerType, this.registerImplementation, lifetimeProvider, errorString);\r\n            }\r\n\r\n            public override ObjectFactoryBase MultiInstanceVariant\r\n            {\r\n                get\r\n                {\r\n                    return this;\r\n                }\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// IObjectFactory that invokes a specified delegate to construct the object\r\n        /// </summary>\r\n        private class DelegateFactory : ObjectFactoryBase\r\n        {\r\n            private readonly Type registerType;\r\n\r\n            private Func<TinyIoCContainer, NamedParameterOverloads, object> _factory;\r\n\r\n            public override bool AssumeConstruction { get { return true; } }\r\n\r\n            public override Type CreatesType { get { return this.registerType; } }\r\n\r\n            public override object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options)\r\n            {\r\n                try\r\n                {\r\n                    return _factory.Invoke(container, parameters);\r\n                }\r\n                catch (Exception ex)\r\n                {\r\n                    throw new TinyIoCResolutionException(this.registerType, ex);\r\n                }\r\n            }\r\n\r\n            public DelegateFactory(Type registerType, Func<TinyIoCContainer, NamedParameterOverloads, object> factory)\r\n            {\r\n                if (factory == null)\r\n                    throw new ArgumentNullException(\"factory\");\r\n\r\n                _factory = factory;\r\n\r\n                this.registerType = registerType;\r\n            }\r\n\r\n            public override ObjectFactoryBase WeakReferenceVariant\r\n            {\r\n                get\r\n                {\r\n                    return new WeakDelegateFactory(this.registerType, _factory);\r\n                }\r\n            }\r\n\r\n            public override ObjectFactoryBase StrongReferenceVariant\r\n            {\r\n                get\r\n                {\r\n                    return this;\r\n                }\r\n            }\r\n\r\n            public override void SetConstructor(ConstructorInfo constructor)\r\n            {\r\n                throw new TinyIoCConstructorResolutionException(\"Constructor selection is not possible for delegate factory registrations\");\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// IObjectFactory that invokes a specified delegate to construct the object\r\n        /// Holds the delegate using a weak reference\r\n        /// </summary>\r\n        private class WeakDelegateFactory : ObjectFactoryBase\r\n        {\r\n            private readonly Type registerType;\r\n\r\n            private WeakReference _factory;\r\n\r\n            public override bool AssumeConstruction { get { return true; } }\r\n\r\n            public override Type CreatesType { get { return this.registerType; } }\r\n\r\n            public override object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options)\r\n            {\r\n                var factory = _factory.Target as Func<TinyIoCContainer, NamedParameterOverloads, object>;\r\n\r\n                if (factory == null)\r\n                    throw new TinyIoCWeakReferenceException(this.registerType);\r\n\r\n                try\r\n                {\r\n                    return factory.Invoke(container, parameters);\r\n                }\r\n                catch (Exception ex)\r\n                {\r\n                    throw new TinyIoCResolutionException(this.registerType, ex);\r\n                }\r\n            }\r\n\r\n            public WeakDelegateFactory(Type registerType, Func<TinyIoCContainer, NamedParameterOverloads, object> factory)\r\n            {\r\n                if (factory == null)\r\n                    throw new ArgumentNullException(\"factory\");\r\n\r\n                _factory = new WeakReference(factory);\r\n\r\n                this.registerType = registerType;\r\n            }\r\n\r\n            public override ObjectFactoryBase StrongReferenceVariant\r\n            {\r\n                get\r\n                {\r\n                    var factory = _factory.Target as Func<TinyIoCContainer, NamedParameterOverloads, object>;\r\n\r\n                    if (factory == null)\r\n                        throw new TinyIoCWeakReferenceException(this.registerType);\r\n\r\n                    return new DelegateFactory(this.registerType, factory);\r\n                }\r\n            }\r\n\r\n            public override ObjectFactoryBase WeakReferenceVariant\r\n            {\r\n                get\r\n                {\r\n                    return this;\r\n                }\r\n            }\r\n\r\n            public override void SetConstructor(ConstructorInfo constructor)\r\n            {\r\n                throw new TinyIoCConstructorResolutionException(\"Constructor selection is not possible for delegate factory registrations\");\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Stores an particular instance to return for a type\r\n        /// </summary>\r\n        private class InstanceFactory : ObjectFactoryBase, IDisposable\r\n        {\r\n            private readonly Type registerType;\r\n            private readonly Type registerImplementation;\r\n            private object _instance;\r\n\r\n            public override bool AssumeConstruction { get { return true; } }\r\n\r\n            public InstanceFactory(Type registerType, Type registerImplementation, object instance)\r\n            {\r\n                if (!IsValidAssignment(registerType, registerImplementation))\r\n                    throw new TinyIoCRegistrationTypeException(registerImplementation, \"InstanceFactory\");\r\n\r\n                this.registerType = registerType;\r\n                this.registerImplementation = registerImplementation;\r\n                _instance = instance;\r\n            }\r\n\r\n            public override Type CreatesType\r\n            {\r\n                get { return this.registerImplementation; }\r\n            }\r\n\r\n            public override object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options)\r\n            {\r\n                return _instance;\r\n            }\r\n\r\n            public override ObjectFactoryBase MultiInstanceVariant\r\n            {\r\n                get { return new MultiInstanceFactory(this.registerType, this.registerImplementation); }\r\n            }\r\n\r\n            public override ObjectFactoryBase WeakReferenceVariant\r\n            {\r\n                get\r\n                {\r\n                    return new WeakInstanceFactory(this.registerType, this.registerImplementation, this._instance);\r\n                }\r\n            }\r\n\r\n            public override ObjectFactoryBase StrongReferenceVariant\r\n            {\r\n                get\r\n                {\r\n                    return this;\r\n                }\r\n            }\r\n\r\n            public override void SetConstructor(ConstructorInfo constructor)\r\n            {\r\n                throw new TinyIoCConstructorResolutionException(\"Constructor selection is not possible for instance factory registrations\");\r\n            }\r\n\r\n            public void Dispose()\r\n            {\r\n                var disposable = _instance as IDisposable;\r\n\r\n                if (disposable != null)\r\n                    disposable.Dispose();\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Stores an particular instance to return for a type\r\n        /// \r\n        /// Stores the instance with a weak reference\r\n        /// </summary>\r\n        private class WeakInstanceFactory : ObjectFactoryBase, IDisposable\r\n        {\r\n            private readonly Type registerType;\r\n            private readonly Type registerImplementation;\r\n            private readonly WeakReference _instance;\r\n\r\n            public WeakInstanceFactory(Type registerType, Type registerImplementation, object instance)\r\n            {\r\n                if (!IsValidAssignment(registerType, registerImplementation))\r\n                    throw new TinyIoCRegistrationTypeException(registerImplementation, \"WeakInstanceFactory\");\r\n\r\n                this.registerType = registerType;\r\n                this.registerImplementation = registerImplementation;\r\n                _instance = new WeakReference(instance);\r\n            }\r\n\r\n            public override Type CreatesType\r\n            {\r\n                get { return this.registerImplementation; }\r\n            }\r\n\r\n            public override object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options)\r\n            {\r\n                var instance = _instance.Target;\r\n\r\n                if (instance == null)\r\n                    throw new TinyIoCWeakReferenceException(this.registerType);\r\n\r\n                return instance;\r\n            }\r\n\r\n            public override ObjectFactoryBase MultiInstanceVariant\r\n            {\r\n                get\r\n                {\r\n                    return new MultiInstanceFactory(this.registerType, this.registerImplementation);\r\n                }\r\n            }\r\n\r\n            public override ObjectFactoryBase WeakReferenceVariant\r\n            {\r\n                get\r\n                {\r\n                    return this;\r\n                }\r\n            }\r\n\r\n            public override ObjectFactoryBase StrongReferenceVariant\r\n            {\r\n                get\r\n                {\r\n                    var instance = _instance.Target;\r\n\r\n                    if (instance == null)\r\n                        throw new TinyIoCWeakReferenceException(this.registerType);\r\n\r\n                    return new InstanceFactory(this.registerType, this.registerImplementation, instance);\r\n                }\r\n            }\r\n\r\n            public override void SetConstructor(ConstructorInfo constructor)\r\n            {\r\n                throw new TinyIoCConstructorResolutionException(\"Constructor selection is not possible for instance factory registrations\");\r\n            }\r\n\r\n            public void Dispose()\r\n            {\r\n                var disposable = _instance.Target as IDisposable;\r\n\r\n                if (disposable != null)\r\n                    disposable.Dispose();\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// A factory that lazy instantiates a type and always returns the same instance\r\n        /// </summary>\r\n        private class SingletonFactory : ObjectFactoryBase, IDisposable\r\n        {\r\n            private readonly Type registerType;\r\n            private readonly Type registerImplementation;\r\n            private readonly object SingletonLock = new object();\r\n            private object _Current;\r\n\r\n            public SingletonFactory(Type registerType, Type registerImplementation)\r\n            {\r\n                //#if NETFX_CORE\r\n                //\t\t\t\tif (registerImplementation.GetTypeInfo().IsAbstract() || registerImplementation.GetTypeInfo().IsInterface())\r\n                //#else\r\n                if (registerImplementation.IsAbstract() || registerImplementation.IsInterface())\r\n                    //#endif\r\n                    throw new TinyIoCRegistrationTypeException(registerImplementation, \"SingletonFactory\");\r\n\r\n                if (!IsValidAssignment(registerType, registerImplementation))\r\n                    throw new TinyIoCRegistrationTypeException(registerImplementation, \"SingletonFactory\");\r\n\r\n                this.registerType = registerType;\r\n                this.registerImplementation = registerImplementation;\r\n            }\r\n\r\n            public override Type CreatesType\r\n            {\r\n                get { return this.registerImplementation; }\r\n            }\r\n\r\n            public override object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options)\r\n            {\r\n                if (parameters.Count != 0)\r\n                    throw new ArgumentException(\"Cannot specify parameters for singleton types\");\r\n\r\n                lock (SingletonLock)\r\n                    if (_Current == null)\r\n                        _Current = container.ConstructType(requestedType, this.registerImplementation, Constructor, options);\r\n\r\n                return _Current;\r\n            }\r\n\r\n            public override ObjectFactoryBase SingletonVariant\r\n            {\r\n                get\r\n                {\r\n                    return this;\r\n                }\r\n            }\r\n\r\n            public override ObjectFactoryBase GetCustomObjectLifetimeVariant(ITinyIoCObjectLifetimeProvider lifetimeProvider, string errorString)\r\n            {\r\n                return new CustomObjectLifetimeFactory(this.registerType, this.registerImplementation, lifetimeProvider, errorString);\r\n            }\r\n\r\n            public override ObjectFactoryBase MultiInstanceVariant\r\n            {\r\n                get\r\n                {\r\n                    return new MultiInstanceFactory(this.registerType, this.registerImplementation);\r\n                }\r\n            }\r\n\r\n            public override ObjectFactoryBase GetFactoryForChildContainer(Type type, TinyIoCContainer parent, TinyIoCContainer child)\r\n            {\r\n                // We make sure that the singleton is constructed before the child container takes the factory.\r\n                // Otherwise the results would vary depending on whether or not the parent container had resolved\r\n                // the type before the child container does.\r\n                GetObject(type, parent, NamedParameterOverloads.Default, ResolveOptions.Default);\r\n                return this;\r\n            }\r\n\r\n            public void Dispose()\r\n            {\r\n                if (this._Current == null)\r\n                    return;\r\n\r\n                var disposable = this._Current as IDisposable;\r\n\r\n                if (disposable != null)\r\n                    disposable.Dispose();\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// A factory that offloads lifetime to an external lifetime provider\r\n        /// </summary>\r\n        private class CustomObjectLifetimeFactory : ObjectFactoryBase, IDisposable\r\n        {\r\n            private readonly object SingletonLock = new object();\r\n            private readonly Type registerType;\r\n            private readonly Type registerImplementation;\r\n            private readonly ITinyIoCObjectLifetimeProvider _LifetimeProvider;\r\n\r\n            public CustomObjectLifetimeFactory(Type registerType, Type registerImplementation, ITinyIoCObjectLifetimeProvider lifetimeProvider, string errorMessage)\r\n            {\r\n                if (lifetimeProvider == null)\r\n                    throw new ArgumentNullException(\"lifetimeProvider\", \"lifetimeProvider is null.\");\r\n\r\n                if (!IsValidAssignment(registerType, registerImplementation))\r\n                    throw new TinyIoCRegistrationTypeException(registerImplementation, \"SingletonFactory\");\r\n\r\n                //#if NETFX_CORE\r\n                //\t\t\t\tif (registerImplementation.GetTypeInfo().IsAbstract() || registerImplementation.GetTypeInfo().IsInterface())\r\n                //#else\r\n                if (registerImplementation.IsAbstract() || registerImplementation.IsInterface())\r\n                    //#endif\r\n                    throw new TinyIoCRegistrationTypeException(registerImplementation, errorMessage);\r\n\r\n                this.registerType = registerType;\r\n                this.registerImplementation = registerImplementation;\r\n                _LifetimeProvider = lifetimeProvider;\r\n            }\r\n\r\n            public override Type CreatesType\r\n            {\r\n                get { return this.registerImplementation; }\r\n            }\r\n\r\n            public override object GetObject(Type requestedType, TinyIoCContainer container, NamedParameterOverloads parameters, ResolveOptions options)\r\n            {\r\n                object current;\r\n\r\n                lock (SingletonLock)\r\n                {\r\n                    current = _LifetimeProvider.GetObject();\r\n                    if (current == null)\r\n                    {\r\n                        current = container.ConstructType(requestedType, this.registerImplementation, Constructor, options);\r\n                        _LifetimeProvider.SetObject(current);\r\n                    }\r\n                }\r\n\r\n                return current;\r\n            }\r\n\r\n            public override ObjectFactoryBase SingletonVariant\r\n            {\r\n                get\r\n                {\r\n                    _LifetimeProvider.ReleaseObject();\r\n                    return new SingletonFactory(this.registerType, this.registerImplementation);\r\n                }\r\n            }\r\n\r\n            public override ObjectFactoryBase MultiInstanceVariant\r\n            {\r\n                get\r\n                {\r\n                    _LifetimeProvider.ReleaseObject();\r\n                    return new MultiInstanceFactory(this.registerType, this.registerImplementation);\r\n                }\r\n            }\r\n\r\n            public override ObjectFactoryBase GetCustomObjectLifetimeVariant(ITinyIoCObjectLifetimeProvider lifetimeProvider, string errorString)\r\n            {\r\n                _LifetimeProvider.ReleaseObject();\r\n                return new CustomObjectLifetimeFactory(this.registerType, this.registerImplementation, lifetimeProvider, errorString);\r\n            }\r\n\r\n            public override ObjectFactoryBase GetFactoryForChildContainer(Type type, TinyIoCContainer parent, TinyIoCContainer child)\r\n            {\r\n                // We make sure that the singleton is constructed before the child container takes the factory.\r\n                // Otherwise the results would vary depending on whether or not the parent container had resolved\r\n                // the type before the child container does.\r\n                GetObject(type, parent, NamedParameterOverloads.Default, ResolveOptions.Default);\r\n                return this;\r\n            }\r\n\r\n            public void Dispose()\r\n            {\r\n                _LifetimeProvider.ReleaseObject();\r\n            }\r\n        }\r\n        #endregion\r\n\r\n        #region Singleton Container\r\n        private static readonly TinyIoCContainer _Current = new TinyIoCContainer();\r\n\r\n        static TinyIoCContainer()\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Lazy created Singleton instance of the container for simple scenarios\r\n        /// </summary>\r\n        public static TinyIoCContainer Current\r\n        {\r\n            get\r\n            {\r\n                return _Current;\r\n            }\r\n        }\r\n        #endregion\r\n\r\n        #region Type Registrations\r\n        public sealed class TypeRegistration\r\n        {\r\n            private int _hashCode;\r\n\r\n            public Type Type { get; private set; }\r\n            public string Name { get; private set; }\r\n\r\n            public TypeRegistration(Type type)\r\n                : this(type, string.Empty)\r\n            {\r\n            }\r\n\r\n            public TypeRegistration(Type type, string name)\r\n            {\r\n                Type = type;\r\n                Name = name;\r\n\r\n                _hashCode = String.Concat(Type.FullName, \"|\", Name).GetHashCode();\r\n            }\r\n\r\n            public override bool Equals(object obj)\r\n            {\r\n                var typeRegistration = obj as TypeRegistration;\r\n\r\n                if (typeRegistration == null)\r\n                    return false;\r\n\r\n                if (Type != typeRegistration.Type)\r\n                    return false;\r\n\r\n                if (String.Compare(Name, typeRegistration.Name, StringComparison.Ordinal) != 0)\r\n                    return false;\r\n\r\n                return true;\r\n            }\r\n\r\n            public override int GetHashCode()\r\n            {\r\n                return _hashCode;\r\n            }\r\n        }\r\n        private readonly SafeDictionary<TypeRegistration, ObjectFactoryBase> _RegisteredTypes;\r\n#if USE_OBJECT_CONSTRUCTOR\r\n        private delegate object ObjectConstructor(params object[] parameters);\r\n        private static readonly SafeDictionary<ConstructorInfo, ObjectConstructor> _ObjectConstructorCache = new SafeDictionary<ConstructorInfo, ObjectConstructor>();\r\n#endif\r\n        #endregion\r\n\r\n        #region Constructors\r\n        public TinyIoCContainer()\r\n        {\r\n            _RegisteredTypes = new SafeDictionary<TypeRegistration, ObjectFactoryBase>();\r\n\r\n            RegisterDefaultTypes();\r\n        }\r\n\r\n        TinyIoCContainer _Parent;\r\n        private TinyIoCContainer(TinyIoCContainer parent)\r\n            : this()\r\n        {\r\n            _Parent = parent;\r\n        }\r\n        #endregion\r\n\r\n        #region Internal Methods\r\n        private readonly object _AutoRegisterLock = new object();\r\n        private void AutoRegisterInternal(IEnumerable<Assembly> assemblies, DuplicateImplementationActions duplicateAction, Func<Type, bool> registrationPredicate)\r\n        {\r\n            lock (_AutoRegisterLock)\r\n            {\r\n                var types = assemblies.SelectMany(a => a.SafeGetTypes()).Where(t => !IsIgnoredType(t, registrationPredicate)).ToList();\r\n\r\n                var concreteTypes = types\r\n                    .Where(type => type.IsClass() && (type.IsAbstract() == false) && (type != this.GetType() && (type.DeclaringType != this.GetType()) && (!type.IsGenericTypeDefinition())))\r\n                    .ToList();\r\n\r\n                foreach (var type in concreteTypes)\r\n                {\r\n                    try\r\n                    {\r\n                        RegisterInternal(type, string.Empty, GetDefaultObjectFactory(type, type));\r\n                    }\r\n#if PORTABLE\r\n                    catch (MemberAccessException)\r\n#else\r\n                    catch (MethodAccessException)\r\n#endif\r\n                    {\r\n                        // Ignore methods we can't access - added for Silverlight\r\n                    }\r\n                }\r\n\r\n                var abstractInterfaceTypes = from type in types\r\n                                             where ((type.IsInterface() || type.IsAbstract()) && (type.DeclaringType != this.GetType()) && (!type.IsGenericTypeDefinition()))\r\n                                             select type;\r\n\r\n                foreach (var type in abstractInterfaceTypes)\r\n                {\r\n                    var localType = type;\r\n                    var implementations = from implementationType in concreteTypes\r\n                                          where localType.IsAssignableFrom(implementationType)\r\n                                          select implementationType;\r\n\r\n                    if (implementations.Skip(1).Any())\r\n                    {\r\n                        if (duplicateAction == DuplicateImplementationActions.Fail)\r\n                            throw new TinyIoCAutoRegistrationException(type, implementations);\r\n\r\n                        if (duplicateAction == DuplicateImplementationActions.RegisterMultiple)\r\n                        {\r\n                            RegisterMultiple(type, implementations);\r\n                        }\r\n                    }\r\n\r\n                    var firstImplementation = implementations.FirstOrDefault();\r\n                    if (firstImplementation != null)\r\n                    {\r\n                        try\r\n                        {\r\n                            RegisterInternal(type, string.Empty, GetDefaultObjectFactory(type, firstImplementation));\r\n                        }\r\n#if PORTABLE\r\n                        catch (MemberAccessException)\r\n#else\r\n                        catch (MethodAccessException)\r\n#endif\r\n                        {\r\n                            // Ignore methods we can't access - added for Silverlight\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        private bool IsIgnoredAssembly(Assembly assembly)\r\n        {\r\n            // TODO - find a better way to remove \"system\" assemblies from the auto registration\r\n            var ignoreChecks = new List<Func<Assembly, bool>>()\r\n            {\r\n                asm => asm.FullName.StartsWith(\"Microsoft.\", StringComparison.Ordinal),\r\n                asm => asm.FullName.StartsWith(\"System.\", StringComparison.Ordinal),\r\n                asm => asm.FullName.StartsWith(\"System,\", StringComparison.Ordinal),\r\n                asm => asm.FullName.StartsWith(\"CR_ExtUnitTest\", StringComparison.Ordinal),\r\n                asm => asm.FullName.StartsWith(\"mscorlib,\", StringComparison.Ordinal),\r\n                asm => asm.FullName.StartsWith(\"CR_VSTest\", StringComparison.Ordinal),\r\n                asm => asm.FullName.StartsWith(\"DevExpress.CodeRush\", StringComparison.Ordinal),\r\n                asm => asm.FullName.StartsWith(\"xunit.\", StringComparison.Ordinal),\r\n            };\r\n\r\n            foreach (var check in ignoreChecks)\r\n            {\r\n                if (check(assembly))\r\n                    return true;\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        private bool IsIgnoredType(Type type, Func<Type, bool> registrationPredicate)\r\n        {\r\n            // TODO - find a better way to remove \"system\" types from the auto registration\r\n            var ignoreChecks = new List<Func<Type, bool>>()\r\n            {\r\n                t => t.FullName.StartsWith(\"System.\", StringComparison.Ordinal),\r\n                t => t.FullName.StartsWith(\"Microsoft.\", StringComparison.Ordinal),\r\n                t => t.IsPrimitive(),\r\n#if !UNBOUND_GENERICS_GETCONSTRUCTORS\r\n                t => t.IsGenericTypeDefinition(),\r\n#endif\r\n                t => (t.GetConstructors(BindingFlags.Instance | BindingFlags.Public).Length == 0) && !(t.IsInterface() || t.IsAbstract()),\r\n            };\r\n\r\n            if (registrationPredicate != null)\r\n            {\r\n                ignoreChecks.Add(t => !registrationPredicate(t));\r\n            }\r\n\r\n            foreach (var check in ignoreChecks)\r\n            {\r\n                if (check(type))\r\n                    return true;\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        private void RegisterDefaultTypes()\r\n        {\r\n            Register<TinyIoCContainer>(this);\r\n\r\n#if TINYMESSENGER\r\n            // Only register the TinyMessenger singleton if we are the root container\r\n            if (_Parent == null)\r\n                Register<TinyMessenger.ITinyMessengerHub, TinyMessenger.TinyMessengerHub>();\r\n#endif\r\n        }\r\n\r\n        private ObjectFactoryBase GetCurrentFactory(TypeRegistration registration)\r\n        {\r\n            ObjectFactoryBase current = null;\r\n\r\n            _RegisteredTypes.TryGetValue(registration, out current);\r\n\r\n            return current;\r\n        }\r\n\r\n        private RegisterOptions RegisterInternal(Type registerType, string name, ObjectFactoryBase factory)\r\n        {\r\n            var typeRegistration = new TypeRegistration(registerType, name);\r\n\r\n            return AddUpdateRegistration(typeRegistration, factory);\r\n        }\r\n\r\n        private RegisterOptions AddUpdateRegistration(TypeRegistration typeRegistration, ObjectFactoryBase factory)\r\n        {\r\n            _RegisteredTypes[typeRegistration] = factory;\r\n\r\n            return new RegisterOptions(this, typeRegistration);\r\n        }\r\n\r\n        private bool RemoveRegistration(TypeRegistration typeRegistration)\r\n        {\r\n            return _RegisteredTypes.Remove(typeRegistration);\r\n        }\r\n\r\n        private ObjectFactoryBase GetDefaultObjectFactory(Type registerType, Type registerImplementation)\r\n        {\r\n            //#if NETFX_CORE\r\n            //\t\t\tif (registerType.GetTypeInfo().IsInterface() || registerType.GetTypeInfo().IsAbstract())\r\n            //#else\r\n            if (registerType.IsInterface() || registerType.IsAbstract())\r\n                //#endif\r\n                return new SingletonFactory(registerType, registerImplementation);\r\n\r\n            return new MultiInstanceFactory(registerType, registerImplementation);\r\n        }\r\n\r\n        private bool CanResolveInternal(TypeRegistration registration, NamedParameterOverloads parameters, ResolveOptions options)\r\n        {\r\n            if (parameters == null)\r\n                throw new ArgumentNullException(\"parameters\");\r\n\r\n            Type checkType = registration.Type;\r\n            string name = registration.Name;\r\n\r\n            ObjectFactoryBase factory;\r\n            if (_RegisteredTypes.TryGetValue(new TypeRegistration(checkType, name), out factory))\r\n            {\r\n                if (factory.AssumeConstruction)\r\n                    return true;\r\n\r\n                if (factory.Constructor == null)\r\n                    return (GetBestConstructor(factory.CreatesType, parameters, options) != null) ? true : false;\r\n                else\r\n                    return CanConstruct(factory.Constructor, parameters, options);\r\n            }\r\n\r\n#if RESOLVE_OPEN_GENERICS\r\n            if (checkType.IsInterface() && checkType.IsGenericType())\r\n            {\r\n                // if the type is registered as an open generic, then see if the open generic is registered\r\n                if (_RegisteredTypes.TryGetValue(new TypeRegistration(checkType.GetGenericTypeDefinition(), name), out factory))\r\n                {\r\n                    if (factory.AssumeConstruction)\r\n                        return true;\r\n\r\n                    if (factory.Constructor == null)\r\n                        return (GetBestConstructor(factory.CreatesType, parameters, options) != null) ? true : false;\r\n                    else\r\n                        return CanConstruct(factory.Constructor, parameters, options);\r\n                }\r\n            }\r\n#endif\r\n\r\n            // Fail if requesting named resolution and settings set to fail if unresolved\r\n            // Or bubble up if we have a parent\r\n            if (!string.IsNullOrEmpty(name) && options.NamedResolutionFailureAction == NamedResolutionFailureActions.Fail)\r\n                return (_Parent != null) ? _Parent.CanResolveInternal(registration, parameters, options) : false;\r\n\r\n            // Attemped unnamed fallback container resolution if relevant and requested\r\n            if (!string.IsNullOrEmpty(name) && options.NamedResolutionFailureAction == NamedResolutionFailureActions.AttemptUnnamedResolution)\r\n            {\r\n                if (_RegisteredTypes.TryGetValue(new TypeRegistration(checkType), out factory))\r\n                {\r\n                    if (factory.AssumeConstruction)\r\n                        return true;\r\n\r\n                    return (GetBestConstructor(factory.CreatesType, parameters, options) != null) ? true : false;\r\n                }\r\n            }\r\n\r\n            // Check if type is an automatic lazy factory request\r\n            if (IsAutomaticLazyFactoryRequest(checkType))\r\n                return true;\r\n\r\n            // Check if type is an IEnumerable<ResolveType>\r\n            if (IsIEnumerableRequest(registration.Type))\r\n                return true;\r\n\r\n            // Attempt unregistered construction if possible and requested\r\n            // If we cant', bubble if we have a parent\r\n            if ((options.UnregisteredResolutionAction == UnregisteredResolutionActions.AttemptResolve) || (checkType.IsGenericType() && options.UnregisteredResolutionAction == UnregisteredResolutionActions.GenericsOnly))\r\n                return (GetBestConstructor(checkType, parameters, options) != null) ? true : (_Parent != null) ? _Parent.CanResolveInternal(registration, parameters, options) : false;\r\n\r\n            // Bubble resolution up the container tree if we have a parent\r\n            if (_Parent != null)\r\n                return _Parent.CanResolveInternal(registration, parameters, options);\r\n\r\n            return false;\r\n        }\r\n\r\n        private bool IsIEnumerableRequest(Type type)\r\n        {\r\n            if (!type.IsGenericType())\r\n                return false;\r\n\r\n            Type genericType = type.GetGenericTypeDefinition();\r\n\r\n            if (genericType == typeof(IEnumerable<>))\r\n                return true;\r\n\r\n            return false;\r\n        }\r\n\r\n        private bool IsAutomaticLazyFactoryRequest(Type type)\r\n        {\r\n            if (!type.IsGenericType())\r\n                return false;\r\n\r\n            Type genericType = type.GetGenericTypeDefinition();\r\n\r\n            // Just a func\r\n            if (genericType == typeof(Func<>))\r\n                return true;\r\n\r\n            // 2 parameter func with string as first parameter (name)\r\n            //#if NETFX_CORE\r\n            //\t\t\tif ((genericType == typeof(Func<,>) && type.GetTypeInfo().GenericTypeArguments[0] == typeof(string)))\r\n            //#else\r\n            if ((genericType == typeof(Func<,>) && type.GetGenericArguments()[0] == typeof(string)))\r\n                //#endif\r\n                return true;\r\n\r\n            // 3 parameter func with string as first parameter (name) and IDictionary<string, object> as second (parameters)\r\n            //#if NETFX_CORE\r\n            //\t\t\tif ((genericType == typeof(Func<,,>) && type.GetTypeInfo().GenericTypeArguments[0] == typeof(string) && type.GetTypeInfo().GenericTypeArguments[1] == typeof(IDictionary<String, object>)))\r\n            //#else\r\n            if ((genericType == typeof(Func<,,>) && type.GetGenericArguments()[0] == typeof(string) && type.GetGenericArguments()[1] == typeof(IDictionary<String, object>)))\r\n                //#endif\r\n                return true;\r\n\r\n            return false;\r\n        }\r\n\r\n        private ObjectFactoryBase GetParentObjectFactory(TypeRegistration registration)\r\n        {\r\n            if (_Parent == null)\r\n                return null;\r\n\r\n            ObjectFactoryBase factory;\r\n            if (_Parent._RegisteredTypes.TryGetValue(registration, out factory))\r\n            {\r\n                return factory.GetFactoryForChildContainer(registration.Type, _Parent, this);\r\n            }\r\n\r\n            return _Parent.GetParentObjectFactory(registration);\r\n        }\r\n\r\n        private object ResolveInternal(TypeRegistration registration, NamedParameterOverloads parameters, ResolveOptions options)\r\n        {\r\n            ObjectFactoryBase factory;\r\n\r\n            // Attempt container resolution\r\n            if (_RegisteredTypes.TryGetValue(registration, out factory))\r\n            {\r\n                try\r\n                {\r\n                    return factory.GetObject(registration.Type, this, parameters, options);\r\n                }\r\n                catch (TinyIoCResolutionException)\r\n                {\r\n                    throw;\r\n                }\r\n                catch (Exception ex)\r\n                {\r\n                    throw new TinyIoCResolutionException(registration.Type, ex);\r\n                }\r\n            }\r\n\r\n#if RESOLVE_OPEN_GENERICS\r\n            // Attempt container resolution of open generic\r\n            if (registration.Type.IsGenericType())\r\n            {\r\n                var openTypeRegistration = new TypeRegistration(registration.Type.GetGenericTypeDefinition(),\r\n                                                                registration.Name);\r\n\r\n                if (_RegisteredTypes.TryGetValue(openTypeRegistration, out factory))\r\n                {\r\n                    try\r\n                    {\r\n                        return factory.GetObject(registration.Type, this, parameters, options);\r\n                    }\r\n                    catch (TinyIoCResolutionException)\r\n                    {\r\n                        throw;\r\n                    }\r\n                    catch (Exception ex)\r\n                    {\r\n                        throw new TinyIoCResolutionException(registration.Type, ex);\r\n                    }\r\n                }\r\n            }\r\n#endif\r\n\r\n            // Attempt to get a factory from parent if we can\r\n            var bubbledObjectFactory = GetParentObjectFactory(registration);\r\n            if (bubbledObjectFactory != null)\r\n            {\r\n                try\r\n                {\r\n                    return bubbledObjectFactory.GetObject(registration.Type, this, parameters, options);\r\n                }\r\n                catch (TinyIoCResolutionException)\r\n                {\r\n                    throw;\r\n                }\r\n                catch (Exception ex)\r\n                {\r\n                    throw new TinyIoCResolutionException(registration.Type, ex);\r\n                }\r\n            }\r\n\r\n            // Fail if requesting named resolution and settings set to fail if unresolved\r\n            if (!string.IsNullOrEmpty(registration.Name) && options.NamedResolutionFailureAction == NamedResolutionFailureActions.Fail)\r\n                throw new TinyIoCResolutionException(registration.Type);\r\n\r\n            // Attemped unnamed fallback container resolution if relevant and requested\r\n            if (!string.IsNullOrEmpty(registration.Name) && options.NamedResolutionFailureAction == NamedResolutionFailureActions.AttemptUnnamedResolution)\r\n            {\r\n                if (_RegisteredTypes.TryGetValue(new TypeRegistration(registration.Type, string.Empty), out factory))\r\n                {\r\n                    try\r\n                    {\r\n                        return factory.GetObject(registration.Type, this, parameters, options);\r\n                    }\r\n                    catch (TinyIoCResolutionException)\r\n                    {\r\n                        throw;\r\n                    }\r\n                    catch (Exception ex)\r\n                    {\r\n                        throw new TinyIoCResolutionException(registration.Type, ex);\r\n                    }\r\n                }\r\n            }\r\n\r\n#if EXPRESSIONS\r\n            // Attempt to construct an automatic lazy factory if possible\r\n            if (IsAutomaticLazyFactoryRequest(registration.Type))\r\n                return GetLazyAutomaticFactoryRequest(registration.Type);\r\n#endif\r\n            if (IsIEnumerableRequest(registration.Type))\r\n                return GetIEnumerableRequest(registration.Type);\r\n\r\n            // Attempt unregistered construction if possible and requested\r\n            if ((options.UnregisteredResolutionAction == UnregisteredResolutionActions.AttemptResolve) || (registration.Type.IsGenericType() && options.UnregisteredResolutionAction == UnregisteredResolutionActions.GenericsOnly))\r\n            {\r\n                if (!registration.Type.IsAbstract() && !registration.Type.IsInterface())\r\n                    return ConstructType(null, registration.Type, parameters, options);\r\n            }\r\n\r\n            // Unable to resolve - throw\r\n            throw new TinyIoCResolutionException(registration.Type);\r\n        }\r\n\r\n#if EXPRESSIONS\r\n        private object GetLazyAutomaticFactoryRequest(Type type)\r\n        {\r\n            if (!type.IsGenericType())\r\n                return null;\r\n\r\n            Type genericType = type.GetGenericTypeDefinition();\r\n            //#if NETFX_CORE\r\n            //\t\t\tType[] genericArguments = type.GetTypeInfo().GenericTypeArguments.ToArray();\r\n            //#else\r\n            Type[] genericArguments = type.GetGenericArguments();\r\n            //#endif\r\n\r\n            // Just a func\r\n            if (genericType == typeof(Func<>))\r\n            {\r\n                Type returnType = genericArguments[0];\r\n\r\n                //#if NETFX_CORE\r\n                //\t\t\t\tMethodInfo resolveMethod = typeof(TinyIoCContainer).GetTypeInfo().GetDeclaredMethods(\"Resolve\").First(mi => !mi.GetParameters().Any());\r\n                //#else\r\n                MethodInfo resolveMethod = typeof(TinyIoCContainer).GetMethod(\"Resolve\", ArrayCache.Empty<Type>());\r\n                //#endif\r\n                resolveMethod = resolveMethod.MakeGenericMethod(returnType);\r\n\r\n                var resolveCall = Expression.Call(Expression.Constant(this), resolveMethod);\r\n\r\n                var resolveLambda = Expression.Lambda(resolveCall).Compile();\r\n\r\n                return resolveLambda;\r\n            }\r\n\r\n            // 2 parameter func with string as first parameter (name)\r\n            if ((genericType == typeof(Func<,>)) && (genericArguments[0] == typeof(string)))\r\n            {\r\n                Type returnType = genericArguments[1];\r\n\r\n                //#if NETFX_CORE\r\n                //\t\t\t\tMethodInfo resolveMethod = typeof(TinyIoCContainer).GetTypeInfo().GetDeclaredMethods(\"Resolve\").First(mi => mi.GetParameters().Length == 1 && mi.GetParameters()[0].GetType() == typeof(String));\r\n                //#else\r\n                MethodInfo resolveMethod = typeof(TinyIoCContainer).GetMethod(\"Resolve\", new Type[] { typeof(String) });\r\n                //#endif\r\n                resolveMethod = resolveMethod.MakeGenericMethod(returnType);\r\n\r\n                ParameterExpression[] resolveParameters = new ParameterExpression[] { Expression.Parameter(typeof(String), \"name\") };\r\n                var resolveCall = Expression.Call(Expression.Constant(this), resolveMethod, resolveParameters);\r\n\r\n                var resolveLambda = Expression.Lambda(resolveCall, resolveParameters).Compile();\r\n\r\n                return resolveLambda;\r\n            }\r\n\r\n            // 3 parameter func with string as first parameter (name) and IDictionary<string, object> as second (parameters)\r\n            //#if NETFX_CORE\r\n            //\t\t\tif ((genericType == typeof(Func<,,>) && type.GenericTypeArguments[0] == typeof(string) && type.GenericTypeArguments[1] == typeof(IDictionary<string, object>)))\r\n            //#else\r\n            if ((genericType == typeof(Func<,,>) && type.GetGenericArguments()[0] == typeof(string) && type.GetGenericArguments()[1] == typeof(IDictionary<string, object>)))\r\n            //#endif\r\n            {\r\n                Type returnType = genericArguments[2];\r\n\r\n                var name = Expression.Parameter(typeof(string), \"name\");\r\n                var parameters = Expression.Parameter(typeof(IDictionary<string, object>), \"parameters\");\r\n\r\n                //#if NETFX_CORE\r\n                //\t\t\t\tMethodInfo resolveMethod = typeof(TinyIoCContainer).GetTypeInfo().GetDeclaredMethods(\"Resolve\").First(mi => mi.GetParameters().Length == 2 && mi.GetParameters()[0].GetType() == typeof(String) && mi.GetParameters()[1].GetType() == typeof(NamedParameterOverloads));\r\n                //#else\r\n                MethodInfo resolveMethod = typeof(TinyIoCContainer).GetMethod(\"Resolve\", new Type[] { typeof(String), typeof(NamedParameterOverloads) });\r\n                //#endif\r\n                resolveMethod = resolveMethod.MakeGenericMethod(returnType);\r\n\r\n                var resolveCall = Expression.Call(Expression.Constant(this), resolveMethod, name, Expression.Call(typeof(NamedParameterOverloads), \"FromIDictionary\", null, parameters));\r\n\r\n                var resolveLambda = Expression.Lambda(resolveCall, name, parameters).Compile();\r\n\r\n                return resolveLambda;\r\n            }\r\n\r\n            throw new TinyIoCResolutionException(type);\r\n        }\r\n#endif\r\n        private object GetIEnumerableRequest(Type type)\r\n        {\r\n            //#if NETFX_CORE\r\n            //\t\t\tvar genericResolveAllMethod = this.GetType().GetGenericMethod(\"ResolveAll\", type.GenericTypeArguments, new[] { typeof(bool) });\r\n            //#else\r\n            var genericResolveAllMethod = this.GetType().GetGenericMethod(BindingFlags.Public | BindingFlags.Instance, \"ResolveAll\", type.GetGenericArguments(), new[] { typeof(bool) });\r\n            //#endif\r\n\r\n            return genericResolveAllMethod.Invoke(this, new object[] { false });\r\n        }\r\n\r\n        private bool CanConstruct(ConstructorInfo ctor, NamedParameterOverloads parameters, ResolveOptions options)\r\n        {\r\n            if (parameters == null)\r\n                throw new ArgumentNullException(\"parameters\");\r\n\r\n            foreach (var parameter in ctor.GetParameters())\r\n            {\r\n                if (string.IsNullOrEmpty(parameter.Name))\r\n                    return false;\r\n\r\n                var isParameterOverload = parameters.ContainsKey(parameter.Name);\r\n\r\n                //#if NETFX_CORE                \r\n                //\t\t\t\tif (parameter.ParameterType.GetTypeInfo().IsPrimitive && !isParameterOverload)\r\n                //#else\r\n                if (parameter.ParameterType.IsPrimitive() && !isParameterOverload)\r\n                    //#endif\r\n                    return false;\r\n\r\n                if (!isParameterOverload && !CanResolveInternal(new TypeRegistration(parameter.ParameterType), NamedParameterOverloads.Default, options))\r\n                    return false;\r\n            }\r\n\r\n            return true;\r\n        }\r\n\r\n        private ConstructorInfo GetBestConstructor(Type type, NamedParameterOverloads parameters, ResolveOptions options)\r\n        {\r\n            if (parameters == null)\r\n                throw new ArgumentNullException(\"parameters\");\r\n\r\n            //#if NETFX_CORE\r\n            //\t\t\tif (type.GetTypeInfo().IsValueType)\r\n            //#else\r\n            if (type.IsValueType())\r\n                //#endif\r\n                return null;\r\n\r\n            // Get constructors in reverse order based on the number of parameters\r\n            // i.e. be as \"greedy\" as possible so we satify the most amount of dependencies possible\r\n            var ctors = this.GetTypeConstructors(type);\r\n\r\n            foreach (var ctor in ctors)\r\n            {\r\n                if (this.CanConstruct(ctor, parameters, options))\r\n                    return ctor;\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        private IEnumerable<ConstructorInfo> GetTypeConstructors(Type type)\r\n        {\r\n            //#if NETFX_CORE\r\n            //\t\t\treturn type.GetTypeInfo().DeclaredConstructors.OrderByDescending(ctor => ctor.GetParameters().Count());\r\n            //#else\r\n            return type.GetConstructors().OrderByDescending(ctor => ctor.GetParameters().Count());\r\n            //#endif\r\n        }\r\n\r\n        private object ConstructType(Type requestedType, Type implementationType, ResolveOptions options)\r\n        {\r\n            return ConstructType(requestedType, implementationType, null, NamedParameterOverloads.Default, options);\r\n        }\r\n\r\n        private object ConstructType(Type requestedType, Type implementationType, ConstructorInfo constructor, ResolveOptions options)\r\n        {\r\n            return ConstructType(requestedType, implementationType, constructor, NamedParameterOverloads.Default, options);\r\n        }\r\n\r\n        private object ConstructType(Type requestedType, Type implementationType, NamedParameterOverloads parameters, ResolveOptions options)\r\n        {\r\n            return ConstructType(requestedType, implementationType, null, parameters, options);\r\n        }\r\n\r\n        private object ConstructType(Type requestedType, Type implementationType, ConstructorInfo constructor, NamedParameterOverloads parameters, ResolveOptions options)\r\n        {\r\n            var typeToConstruct = implementationType;\r\n\r\n#if RESOLVE_OPEN_GENERICS\r\n            if (implementationType.IsGenericTypeDefinition())\r\n            {\r\n                if (requestedType == null || !requestedType.IsGenericType() || !requestedType.GetGenericArguments().Any())\r\n                    throw new TinyIoCResolutionException(typeToConstruct);\r\n\r\n                typeToConstruct = typeToConstruct.MakeGenericType(requestedType.GetGenericArguments());\r\n            }\r\n#endif\r\n            if (constructor == null)\r\n            {\r\n                // Try and get the best constructor that we can construct\r\n                // if we can't construct any then get the constructor\r\n                // with the least number of parameters so we can throw a meaningful\r\n                // resolve exception\r\n                constructor = GetBestConstructor(typeToConstruct, parameters, options) ?? GetTypeConstructors(typeToConstruct).LastOrDefault();\r\n            }\r\n\r\n            if (constructor == null)\r\n                throw new TinyIoCResolutionException(typeToConstruct);\r\n\r\n            var ctorParams = constructor.GetParameters();\r\n            object[] args = new object[ctorParams.Count()];\r\n\r\n            for (int parameterIndex = 0; parameterIndex < ctorParams.Count(); parameterIndex++)\r\n            {\r\n                var currentParam = ctorParams[parameterIndex];\r\n\r\n                try\r\n                {\r\n                    object value;\r\n                    args[parameterIndex] = parameters.TryGetValue(currentParam.Name, out value) ?\r\n                                            value :\r\n                                            ResolveInternal(\r\n                                                new TypeRegistration(currentParam.ParameterType),\r\n                                                NamedParameterOverloads.Default,\r\n                                                options);\r\n                }\r\n                catch (TinyIoCResolutionException ex)\r\n                {\r\n                    // If a constructor parameter can't be resolved\r\n                    // it will throw, so wrap it and throw that this can't\r\n                    // be resolved.\r\n                    throw new TinyIoCResolutionException(typeToConstruct, ex);\r\n                }\r\n                catch (Exception ex)\r\n                {\r\n                    throw new TinyIoCResolutionException(typeToConstruct, ex);\r\n                }\r\n            }\r\n\r\n            try\r\n            {\r\n#if USE_OBJECT_CONSTRUCTOR\r\n                var constructionDelegate = CreateObjectConstructionDelegateWithCache(constructor);\r\n                return constructionDelegate.Invoke(args);\r\n#else\r\n                return constructor.Invoke(args);\r\n#endif\r\n            }\r\n            catch (Exception ex)\r\n            {\r\n                throw new TinyIoCResolutionException(typeToConstruct, ex);\r\n            }\r\n        }\r\n\r\n#if USE_OBJECT_CONSTRUCTOR\r\n        private static ObjectConstructor CreateObjectConstructionDelegateWithCache(ConstructorInfo constructor)\r\n        {\r\n            ObjectConstructor objectConstructor;\r\n            if (_ObjectConstructorCache.TryGetValue(constructor, out objectConstructor))\r\n                return objectConstructor;\r\n\r\n            // We could lock the cache here, but there's no real side\r\n            // effect to two threads creating the same ObjectConstructor\r\n            // at the same time, compared to the cost of a lock for \r\n            // every creation.\r\n            var constructorParams = constructor.GetParameters();\r\n            var lambdaParams = Expression.Parameter(typeof(object[]), \"parameters\");\r\n            var newParams = new Expression[constructorParams.Length];\r\n\r\n            for (int i = 0; i < constructorParams.Length; i++)\r\n            {\r\n                var paramsParameter = Expression.ArrayIndex(lambdaParams, Expression.Constant(i));\r\n\r\n                newParams[i] = Expression.Convert(paramsParameter, constructorParams[i].ParameterType);\r\n            }\r\n\r\n            var newExpression = Expression.New(constructor, newParams);\r\n\r\n            var constructionLambda = Expression.Lambda(typeof(ObjectConstructor), newExpression, lambdaParams);\r\n\r\n            objectConstructor = (ObjectConstructor)constructionLambda.Compile();\r\n\r\n            _ObjectConstructorCache[constructor] = objectConstructor;\r\n            return objectConstructor;\r\n        }\r\n#endif\r\n\r\n        private void BuildUpInternal(object input, ResolveOptions resolveOptions)\r\n        {\r\n            //#if NETFX_CORE\r\n            //\t\t\tvar properties = from property in input.GetType().GetTypeInfo().DeclaredProperties\r\n            //\t\t\t\t\t\t\t where (property.GetMethod != null) && (property.SetMethod != null) && !property.PropertyType.GetTypeInfo().IsValueType\r\n            //\t\t\t\t\t\t\t select property;\r\n            //#else\r\n            var properties = from property in input.GetType().GetProperties()\r\n                             where (property.GetGetMethod() != null) && (property.GetSetMethod() != null) && !property.PropertyType.IsValueType()\r\n                             select property;\r\n            //#endif\r\n\r\n            foreach (var property in properties)\r\n            {\r\n                if (property.GetValue(input, null) == null)\r\n                {\r\n                    try\r\n                    {\r\n                        property.SetValue(input, ResolveInternal(new TypeRegistration(property.PropertyType), NamedParameterOverloads.Default, resolveOptions), null);\r\n                    }\r\n                    catch (TinyIoCResolutionException)\r\n                    {\r\n                        // Catch any resolution errors and ignore them\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        private IEnumerable<TypeRegistration> GetParentRegistrationsForType(Type resolveType)\r\n        {\r\n            if (_Parent == null)\r\n                return ArrayCache.Empty<TypeRegistration>();\r\n\r\n            var registrations = _Parent._RegisteredTypes.Keys.Where(tr => tr.Type == resolveType);\r\n\r\n            return registrations.Concat(_Parent.GetParentRegistrationsForType(resolveType));\r\n        }\r\n\r\n        private IEnumerable<object> ResolveAllInternal(Type resolveType, bool includeUnnamed)\r\n        {\r\n            var registrations = _RegisteredTypes.Keys.Where(tr => tr.Type == resolveType).Concat(GetParentRegistrationsForType(resolveType)).Distinct();\r\n\r\n            if (!includeUnnamed)\r\n                registrations = registrations.Where(tr => tr.Name != string.Empty);\r\n\r\n            return registrations.Select(registration => this.ResolveInternal(registration, NamedParameterOverloads.Default, ResolveOptions.Default));\r\n        }\r\n\r\n        private static bool IsValidAssignment(Type registerType, Type registerImplementation)\r\n        {\r\n            //#if NETFX_CORE\r\n            //\t\t\tvar registerTypeDef = registerType.GetTypeInfo();\r\n            //\t\t\tvar registerImplementationDef = registerImplementation.GetTypeInfo();\r\n\r\n            //\t\t\tif (!registerTypeDef.IsGenericTypeDefinition)\r\n            //\t\t\t{\r\n            //\t\t\t\tif (!registerTypeDef.IsAssignableFrom(registerImplementationDef))\r\n            //\t\t\t\t\treturn false;\r\n            //\t\t\t}\r\n            //\t\t\telse\r\n            //\t\t\t{\r\n            //\t\t\t\tif (registerTypeDef.IsInterface())\r\n            //\t\t\t\t{\r\n            //\t\t\t\t\tif (!registerImplementationDef.ImplementedInterfaces.Any(t => t.GetTypeInfo().Name == registerTypeDef.Name))\r\n            //\t\t\t\t\t\treturn false;\r\n            //\t\t\t\t}\r\n            //\t\t\t\telse if (registerTypeDef.IsAbstract() && registerImplementationDef.BaseType() != registerType)\r\n            //\t\t\t\t{\r\n            //\t\t\t\t\treturn false;\r\n            //\t\t\t\t}\r\n            //\t\t\t}\r\n            //#else\r\n            if (!registerType.IsGenericTypeDefinition())\r\n            {\r\n                if (!registerType.IsAssignableFrom(registerImplementation))\r\n                    return false;\r\n            }\r\n            else\r\n            {\r\n                if (registerType.IsInterface())\r\n                {\r\n#if (PORTABLE || NETSTANDARD1_6)\r\n                    if (!registerImplementation.GetInterfaces().Any(t => t.Name == registerType.Name))\r\n                        return false;\r\n#else\r\n                    if (!registerImplementation.FindInterfaces((t, o) => t.Name == registerType.Name, null).Any())\r\n                        return false;\r\n#endif\r\n                }\r\n                else if (registerType.IsAbstract() && registerImplementation.BaseType() != registerType)\r\n                {\r\n                    return false;\r\n                }\r\n            }\r\n            //#endif\r\n            return true;\r\n        }\r\n\r\n        #endregion\r\n\r\n        #region IDisposable Members\r\n        bool disposed = false;\r\n        public void Dispose()\r\n        {\r\n            if (!disposed)\r\n            {\r\n                disposed = true;\r\n\r\n                _RegisteredTypes.Dispose();\r\n\r\n                GC.SuppressFinalize(this);\r\n            }\r\n        }\r\n\r\n        #endregion\r\n    }\r\n\r\n#if NETSTANDARD2_0\r\n    static class ReverseTypeExtender\r\n    {\r\n        public static bool IsClass(this Type type)\r\n        {\r\n            return type.GetTypeInfo().IsClass;\r\n        }\r\n\r\n        public static bool IsAbstract(this Type type)\r\n        {\r\n            return type.GetTypeInfo().IsAbstract;\r\n        }\r\n\r\n        public static bool IsInterface(this Type type)\r\n        {\r\n            return type.GetTypeInfo().IsInterface;\r\n        }\r\n\r\n        public static bool IsPrimitive(this Type type)\r\n        {\r\n            return type.GetTypeInfo().IsPrimitive;\r\n        }\r\n\r\n        public static bool IsValueType(this Type type)\r\n        {\r\n            return type.GetTypeInfo().IsValueType;\r\n        }\r\n\r\n        public static bool IsGenericType(this Type type)\r\n        {\r\n            return type.GetTypeInfo().IsGenericType;\r\n        }\r\n\r\n        public static bool IsGenericParameter(this Type type)\r\n        {\r\n            return type.IsGenericParameter;\r\n        }\r\n\r\n        public static bool IsGenericTypeDefinition(this Type type)\r\n        {\r\n            return type.GetTypeInfo().IsGenericTypeDefinition;\r\n        }\r\n\r\n        public static Type BaseType(this Type type)\r\n        {\r\n            return type.GetTypeInfo().BaseType;\r\n        }\r\n\r\n        public static Assembly Assembly(this Type type)\r\n        {\r\n            return type.GetTypeInfo().Assembly;\r\n        }\r\n    }\r\n#endif\r\n    // reverse shim for WinRT SR changes...\r\n#if (!NETFX_CORE && !NETSTANDARD2_0)\r\n    static class ReverseTypeExtender\r\n    {\r\n        public static bool IsClass(this Type type)\r\n        {\r\n            return type.IsClass;\r\n        }\r\n\r\n        public static bool IsAbstract(this Type type)\r\n        {\r\n            return type.IsAbstract;\r\n        }\r\n\r\n        public static bool IsInterface(this Type type)\r\n        {\r\n            return type.IsInterface;\r\n        }\r\n\r\n        public static bool IsPrimitive(this Type type)\r\n        {\r\n            return type.IsPrimitive;\r\n        }\r\n\r\n        public static bool IsValueType(this Type type)\r\n        {\r\n            return type.IsValueType;\r\n        }\r\n\r\n        public static bool IsGenericType(this Type type)\r\n        {\r\n            return type.IsGenericType;\r\n        }\r\n\r\n        public static bool IsGenericParameter(this Type type)\r\n        {\r\n            return type.IsGenericParameter;\r\n        }\r\n\r\n        public static bool IsGenericTypeDefinition(this Type type)\r\n        {\r\n            return type.IsGenericTypeDefinition;\r\n        }\r\n\r\n        public static Type BaseType(this Type type)\r\n        {\r\n            return type.BaseType;\r\n        }\r\n\r\n        public static Assembly Assembly(this Type type)\r\n        {\r\n            return type.Assembly;\r\n        }\r\n    }\r\n#endif\r\n}\r\n"
  },
  {
    "path": "src/Nancy/TraceConfiguration.cs",
    "content": "namespace Nancy\r\n{\r\n    /// <summary>\r\n    /// Configuration for tracing.\r\n    /// </summary>\r\n    public class TraceConfiguration\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"TraceConfiguration\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"enabled\">Determines if tracing should be enabled.</param>\r\n        /// <param name=\"displayErrorTraces\">Determines if traces should be displayed in error messages.</param>\r\n        public TraceConfiguration(bool enabled, bool displayErrorTraces)\r\n        {\r\n            this.Enabled = enabled;\r\n            this.DisplayErrorTraces = displayErrorTraces;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether or not to enable request tracing.\r\n        /// </summary>\r\n        /// <value><see langword=\"true\"/> if tracing should be enabled, otherwise <see langword=\"false\"/>.</value>\r\n        public bool Enabled { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether or not to display traces in error messages.\r\n        /// </summary>\r\n        /// <value><see langword=\"true\"/> traces should be displayed in error messages, otherwise <see langword=\"false\"/>.</value>\r\n        public bool DisplayErrorTraces { get; private set; }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/TraceConfigurationExtensions.cs",
    "content": "namespace Nancy\r\n{\r\n    using Nancy.Configuration;\r\n\r\n    /// <summary>\r\n    /// Contains <see cref=\"TraceConfiguration\"/> configuration extensions for <see cref=\"INancyEnvironment\"/>.\r\n    /// </summary>\r\n    public static class TraceConfigurationExtensions\r\n    {\r\n        /// <summary>\r\n        /// Configures <see cref=\"TraceConfiguration\"/>.\r\n        /// </summary>\r\n        /// <param name=\"environment\">An <see cref=\"INancyEnvironment\"/> that should be configured.</param>\r\n        /// <param name=\"enabled\"><see langword=\"true\"/> if tracing should be enabled, otherwise <see langword=\"false\"/>.</param>\r\n        /// <param name=\"displayErrorTraces\"><see langword=\"true\"/> traces should be displayed in error messages, otherwise <see langword=\"false\"/>.</param>\r\n        public static void Tracing(this INancyEnvironment environment, bool enabled, bool displayErrorTraces)\r\n        {\r\n            environment.AddValue(new TraceConfiguration(\r\n                enabled: enabled,\r\n                displayErrorTraces: displayErrorTraces));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/TypeCatalogExtensions.cs",
    "content": "namespace Nancy\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Contains extension methods for <see cref=\"ITypeCatalog\"/> implementations.\r\n    /// </summary>\r\n    public static class TypeCatalogExtensions\r\n    {\r\n        /// <summary>\r\n        /// Gets all <see cref=\"Type\"/> instances that are assignable to <paramref name=\"type\"/>, using <see cref=\"TypeResolveStrategies.All\"/>.\r\n        /// </summary>\r\n        /// <param name=\"typeCatalog\">The <see cref=\"ITypeCatalog\"/> instance where the types should be retrieved from.</param>\r\n        /// <param name=\"type\">The <see cref=\"Type\"/> that all returned types should be assingable to.</param>\r\n        /// <returns>An <see cref=\"IReadOnlyCollection{T}\"/> of <see cref=\"Type\"/> instances.</returns>\r\n        public static IReadOnlyCollection<Type> GetTypesAssignableTo(this ITypeCatalog typeCatalog, Type type)\r\n        {\r\n            return typeCatalog.GetTypesAssignableTo(type, TypeResolveStrategies.All);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all <see cref=\"Type\"/> instances that are assignable to <typeparamref name=\"TType\"/>, using <see cref=\"TypeResolveStrategies.All\"/>.\r\n        /// </summary>\r\n        /// <param name=\"typeCatalog\">The <see cref=\"ITypeCatalog\"/> instance where the types should be retrieved from.</param>\r\n        /// <typeparam name=\"TType\">The <see cref=\"Type\"/> that all returned types should be assingable to.</typeparam>\r\n        /// <returns>An <see cref=\"IReadOnlyCollection{T}\"/> of <see cref=\"Type\"/> instances.</returns>\r\n        public static IReadOnlyCollection<Type> GetTypesAssignableTo<TType>(this ITypeCatalog typeCatalog)\r\n        {\r\n            return typeCatalog.GetTypesAssignableTo(typeof(TType), TypeResolveStrategies.All);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all types that are assignable to the provided <typeparamref name=\"TType\"/>.\r\n        /// </summary>\r\n        /// <param name=\"typeCatalog\">The <see cref=\"ITypeCatalog\"/> instance where the types should be retrieved from.</param>\r\n        /// <param name=\"strategy\">A <see cref=\"TypeResolveStrategy\"/> that should be used then retrieving types.</param>\r\n        /// <typeparam name=\"TType\">The <see cref=\"Type\"/> that returned types should be assignable to.</typeparam>\r\n        /// <returns>An <see cref=\"IReadOnlyCollection{T}\"/> of <see cref=\"Type\"/> instances.</returns>\r\n        public static IReadOnlyCollection<Type> GetTypesAssignableTo<TType>(this ITypeCatalog typeCatalog, TypeResolveStrategy strategy)\r\n        {\r\n            return typeCatalog.GetTypesAssignableTo(typeof(TType), strategy);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/TypeResolveStrategies.cs",
    "content": "namespace Nancy\r\n{\r\n    using System;\r\n    using System.Reflection;\r\n    using Nancy.Extensions;\r\n    \r\n    /// <summary>\r\n    /// Default <see cref=\"TypeResolveStrategy\"/> implementations.\r\n    /// </summary>\r\n    public class TypeResolveStrategies\r\n    {\r\n        /// <summary>\r\n        /// Resolve types from all available locations.\r\n        /// </summary>\r\n        public static readonly TypeResolveStrategy All = type =>\r\n        {\r\n            return true;\r\n        };\r\n\r\n        /// <summary>\r\n        /// Resolve types that are not located in the Nancy assembly.\r\n        /// </summary>\r\n        public static readonly TypeResolveStrategy ExcludeNancy = type =>\r\n        {\r\n            return !OnlyNancy.Invoke(type);\r\n        };\r\n\r\n        /// <summary>\r\n        /// Resolve types that are not located in the Nancy namespace.\r\n        /// </summary>\r\n        public static readonly TypeResolveStrategy ExcludeNancyNamespace = type =>\r\n        {\r\n            return !OnlyNancyNamespace.Invoke(type);\r\n        };\r\n\r\n        /// <summary>\r\n        /// Resolve types that are located in the Nancy assembly.\r\n        /// </summary>\r\n        public static readonly TypeResolveStrategy OnlyNancy = type =>\r\n        {\r\n            return type.GetAssembly().Equals(typeof(INancyEngine).GetTypeInfo().Assembly);\r\n        };\r\n\r\n        /// <summary>\r\n        /// Resolve types that are located in the Nancy namespace.\r\n        /// </summary>\r\n        public static readonly TypeResolveStrategy OnlyNancyNamespace = type =>\r\n        {\r\n            return (type.Namespace ?? string.Empty).StartsWith(\"Nancy\", StringComparison.OrdinalIgnoreCase);\r\n        };\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/TypeResolveStrategy.cs",
    "content": "﻿namespace Nancy\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Predicate used to decide if a <see cref=\"Type\"/> should be included when resolving types.\r\n    /// </summary>\r\n    /// <param name=\"type\">The <see cref=\"Type\"/> that is being inspected.</param>\r\n    /// <value><see langword=\"true\"/> if the type should be included in the result, otherwise <see langword=\"false\"/>.</value>\r\n    public delegate bool TypeResolveStrategy(Type type);\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Url.cs",
    "content": "namespace Nancy\r\n{\r\n    using System;\r\n    using System.Net;\r\n    using System.Net.Sockets;\r\n    using System.Text;\r\n\r\n    /// <summary>\r\n    /// Represents a full Url of the form scheme://hostname:port/basepath/path?query\r\n    /// </summary>\r\n    /// <remarks>Since this is for  internal use, and fragments are not passed to the server, fragments are not supported.</remarks>\r\n    public sealed class Url\r\n    {\r\n        private string basePath;\r\n\r\n        private string query;\r\n\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"Url\"/> class.\r\n        /// </summary>\r\n        public Url()\r\n        {\r\n            this.Scheme = \"http\";\r\n            this.HostName = string.Empty;\r\n            this.Port = null;\r\n            this.BasePath = string.Empty;\r\n            this.Path = string.Empty;\r\n            this.Query = string.Empty;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"Url\" /> class, with\r\n        /// the provided <paramref name=\"url\"/>.\r\n        /// </summary>\r\n        /// <param name=\"url\">A <see cref=\"string\" /> containing a URL.</param>\r\n        public Url(string url)\r\n        {\r\n            var uri = new Uri(url);\r\n            this.HostName = uri.Host;\r\n            this.Path = uri.LocalPath;\r\n            this.Port = uri.Port;\r\n            this.Query = uri.Query;\r\n            this.Scheme = uri.Scheme;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the HTTP protocol used by the client.\r\n        /// </summary>\r\n        /// <value>The protocol.</value>\r\n        public string Scheme { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets the hostname of the request\r\n        /// </summary>\r\n        public string HostName { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets the port name of the request\r\n        /// </summary>\r\n        public int? Port { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets the base path of the request i.e. the \"Nancy root\"\r\n        /// </summary>\r\n        public string BasePath\r\n        {\r\n            get { return this.basePath; }\r\n            set { this.basePath = (value ?? string.Empty).TrimEnd('/'); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the path of the request, relative to the base path\r\n        /// This property drives the route matching\r\n        /// </summary>\r\n        public string Path { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets the querystring data of the requested resource.\r\n        /// </summary>\r\n        public string Query\r\n        {\r\n            get { return this.query; }\r\n            set { this.query = GetQuery(value); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the domain part of the request\r\n        /// </summary>\r\n        public string SiteBase\r\n        {\r\n            get\r\n            {\r\n                return new StringBuilder()\r\n                    .Append(this.Scheme)\r\n                    .Append(\"://\")\r\n                    .Append(GetHostName(this.HostName))\r\n                    .Append(GetPort(this.Port))\r\n                    .ToString();\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets whether the url is secure or not.\r\n        /// </summary>\r\n        public bool IsSecure\r\n        {\r\n            get\r\n            {\r\n                return \"https\".Equals(this.Scheme, StringComparison.OrdinalIgnoreCase);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns a <see cref=\"System.String\" /> that represents this instance.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// A <see cref=\"System.String\" /> that represents this instance.\r\n        /// </returns>\r\n        public override string ToString()\r\n        {\r\n            return new StringBuilder()\r\n                .Append(this.Scheme)\r\n                .Append(\"://\")\r\n                .Append(GetHostName(this.HostName))\r\n                .Append(GetPort(this.Port))\r\n                .Append(GetCorrectPath(this.BasePath))\r\n                .Append(GetCorrectPath(this.Path))\r\n                .Append(this.Query)\r\n                .ToString();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Clones the url.\r\n        /// </summary>\r\n        /// <returns>Returns a new cloned instance of the url.</returns>\r\n        public Url Clone()\r\n        {\r\n            return new Url\r\n            {\r\n                BasePath = this.BasePath,\r\n                HostName = this.HostName,\r\n                Port = this.Port,\r\n                Query = this.Query,\r\n                Path = this.Path,\r\n                Scheme = this.Scheme\r\n            };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Casts the current <see cref=\"Url\"/> instance to a <see cref=\"string\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"url\">The instance that should be cast.</param>\r\n        /// <returns>A <see cref=\"string\"/> representation of the <paramref name=\"url\"/>.</returns>\r\n        public static implicit operator string(Url url)\r\n        {\r\n            return url.ToString();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Casts the current <see cref=\"string\"/> instance to a <see cref=\"Url\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"url\">The instance that should be cast.</param>\r\n        /// <returns>An <see cref=\"Url\"/> representation of the <paramref name=\"url\"/>.</returns>\r\n        public static implicit operator Url(string url)\r\n        {\r\n            return new Uri(url);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Casts the current <see cref=\"Url\"/> instance to a <see cref=\"Uri\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"url\">The instance that should be cast.</param>\r\n        /// <returns>An <see cref=\"Uri\"/> representation of the <paramref name=\"url\"/>.</returns>\r\n        public static implicit operator Uri(Url url)\r\n        {\r\n            return new Uri(url.ToString(), UriKind.Absolute);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Casts a <see cref=\"Uri\"/> instance to a <see cref=\"Url\"/> instance\r\n        /// </summary>\r\n        /// <param name=\"uri\">The instance that should be cast.</param>\r\n        /// <returns>An <see cref=\"Url\"/> representation of the <paramref name=\"uri\"/>.</returns>\r\n        public static implicit operator Url(Uri uri)\r\n        {\r\n            if (uri.IsAbsoluteUri)\r\n            {\r\n                return new Url\r\n                {\r\n                    HostName = uri.Host,\r\n                    Path = uri.LocalPath,\r\n                    Port = uri.Port,\r\n                    Query = uri.Query,\r\n                    Scheme = uri.Scheme\r\n                };\r\n            }\r\n\r\n            return new Url { Path = uri.OriginalString };\r\n        }\r\n\r\n        private static string GetQuery(string query)\r\n        {\r\n            return string.IsNullOrEmpty(query) ? string.Empty : (query[0] == '?' ? query : '?' + query);\r\n        }\r\n\r\n        private static string GetCorrectPath(string path)\r\n        {\r\n            return (string.IsNullOrEmpty(path) || path.Equals(\"/\")) ? string.Empty : path;\r\n        }\r\n\r\n        private static string GetPort(int? port)\r\n        {\r\n            return port.HasValue ? string.Concat(\":\", port.Value) :  string.Empty;\r\n        }\r\n\r\n        private static string GetHostName(string hostName)\r\n        {\r\n            IPAddress address;\r\n\r\n            if (IPAddress.TryParse(hostName, out address))\r\n            {\r\n                var addressString = address.ToString();\r\n\r\n                return address.AddressFamily == AddressFamily.InterNetworkV6\r\n                    ? string.Format(\"[{0}]\", addressString)\r\n                    : addressString;\r\n            }\r\n\r\n            return hostName;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Validation/CompositeValidator.cs",
    "content": "﻿namespace Nancy.Validation\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// A composite validator to combine other validators.\r\n    /// </summary>\r\n    public class CompositeValidator : IModelValidator\r\n    {\r\n        private readonly IEnumerable<IModelValidator> validators;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"CompositeValidator\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"validators\">The validators.</param>\r\n        /// <param name=\"modelType\">The type of the model that is being validated.</param>\r\n        public CompositeValidator(IEnumerable<IModelValidator> validators, Type modelType)\r\n        {\r\n            var modelValidators =\r\n                validators.ToArray();\r\n\r\n            this.ModelType = modelType;\r\n            this.Description = CreateCompositeDescription(modelValidators, modelType);\r\n            this.validators = modelValidators;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the description of the validator.\r\n        /// </summary>\r\n        public ModelValidationDescriptor Description { get; private set; }\r\n\r\n        /// <summary>\r\n        /// The type of the model that is being validated by the validator.\r\n        /// </summary>\r\n        public Type ModelType { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Validates the specified instance.\r\n        /// </summary>\r\n        /// <param name=\"instance\">The instance that should be validated.</param>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> of the current request.</param>\r\n        /// <returns>A <see cref=\"ModelValidationResult\"/> with the result of the validation.</returns>\r\n        public ModelValidationResult Validate(object instance, NancyContext context)\r\n        {\r\n            var errors = validators\r\n                .Select(v => v.Validate(instance, context))\r\n                .Where(r => r != null)\r\n                .SelectMany(r => r.Errors)\r\n                .ToDictionary(x => x.Key, x => x.Value);\r\n\r\n            return (!errors.Any()) ?\r\n                new ModelValidationResult() :\r\n                new ModelValidationResult(errors);\r\n        }\r\n\r\n        private static ModelValidationDescriptor CreateCompositeDescription(IEnumerable<IModelValidator> validators, Type modelType)\r\n        {\r\n            var rules = validators\r\n                .SelectMany(v => v.Description.Rules)\r\n                .ToDictionary(x => x.Key, x => x.Value);\r\n\r\n            return new ModelValidationDescriptor(rules, modelType);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Validation/DefaultValidatorLocator.cs",
    "content": "﻿namespace Nancy.Validation\r\n{\r\n    using System;\r\n    using System.Collections.Concurrent;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// The default Nancy implementation of IValidatorLocator.\r\n    /// </summary>\r\n    public class DefaultValidatorLocator : IModelValidatorLocator\r\n    {\r\n        private readonly ConcurrentDictionary<Type, IModelValidator> cachedValidators;\r\n        private readonly IEnumerable<IModelValidatorFactory> factories;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultValidatorLocator\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"factories\">The factories.</param>\r\n        public DefaultValidatorLocator(IEnumerable<IModelValidatorFactory> factories)\r\n        {\r\n            this.cachedValidators =\r\n                new ConcurrentDictionary<Type, IModelValidator>();\r\n\r\n            this.factories = factories ?? Enumerable.Empty<IModelValidatorFactory>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a validator for a given type.\r\n        /// </summary>\r\n        /// <param name=\"type\">The type to validate.</param>\r\n        /// <returns>An <see cref=\"IModelValidator\"/> instance or <see langword=\"null\"/> if none found.</returns>\r\n        public IModelValidator GetValidatorForType(Type type)\r\n        {\r\n            if (!this.factories.Any())\r\n            {\r\n                throw new ModelValidationException(\"No model validator factory could be located. Please ensure that you have an appropriate validation package installed, such as one of the Nancy.Validation packages.\");\r\n            }\r\n\r\n            return cachedValidators.GetOrAdd(type, CreateValidator);\r\n        }\r\n\r\n        private IModelValidator CreateValidator(Type type)\r\n        {\r\n            var validators = this.factories\r\n                .Select(factory => factory.Create(type))\r\n                .Where(validator => validator != null)\r\n                .ToArray();\r\n\r\n            if(!validators.Any())\r\n            {\r\n                return null;\r\n            }\r\n\r\n            return (validators.Length == 1) ?\r\n                validators[0] :\r\n                new CompositeValidator(validators, type);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Validation/IModelValidator.cs",
    "content": "﻿namespace Nancy.Validation\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Provides a way to validate a type as well as a description to use for client-side validation.\r\n    /// </summary>\r\n    public interface IModelValidator\r\n    {\r\n        /// <summary>\r\n        /// Gets the description of the validator.\r\n        /// </summary>\r\n        ModelValidationDescriptor Description { get; }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"Type\"/> of the model that is being validated by the validator.\r\n        /// </summary>\r\n        Type ModelType { get; }\r\n\r\n        /// <summary>\r\n        /// Validates the specified instance.\r\n        /// </summary>\r\n        /// <param name=\"instance\">The instance that should be validated.</param>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> of the current request.</param>\r\n        /// <returns>A <see cref=\"ModelValidationResult\"/> with the result of the validation.</returns>\r\n        ModelValidationResult Validate(object instance, NancyContext context);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Validation/IModelValidatorFactory.cs",
    "content": "﻿namespace Nancy.Validation\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Creates instances of IValidator.\r\n    /// </summary>\r\n    public interface IModelValidatorFactory\r\n    {\r\n        /// <summary>\r\n        /// Creates a validator for the given type.\r\n        /// </summary>\r\n        /// <param name=\"type\">The type.</param>\r\n        /// <returns>A validator for the given type or null if none exists.</returns>\r\n        IModelValidator Create(Type type);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Validation/IModelValidatorLocator.cs",
    "content": "﻿namespace Nancy.Validation\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Locates a validator for a given type.\r\n    /// </summary>\r\n    public interface IModelValidatorLocator\r\n    {\r\n        /// <summary>\r\n        /// Gets a validator for a given type.\r\n        /// </summary>\r\n        /// <param name=\"type\">The type to validate.</param>\r\n        /// <returns>An <see cref=\"IModelValidator\"/> instance or <see langword=\"null\"/> if none found.</returns>\r\n        IModelValidator GetValidatorForType(Type type);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Validation/ModelValidationDescriptor.cs",
    "content": "﻿namespace Nancy.Validation\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// A description of the rules a validator provides.\r\n    /// </summary>\r\n    public class ModelValidationDescriptor\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ModelValidationDescriptor\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"rules\">The rules that describes the model.</param>\r\n        /// <param name=\"modelType\">The type of the model that the rules are defined for.</param>\r\n        public ModelValidationDescriptor(IEnumerable<ModelValidationRule> rules, Type modelType)\r\n            : this(GetModelValidationRuleDictionary(rules), modelType)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ModelValidationDescriptor\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"rules\">The rules that describes the model, grouped by member name.</param>\r\n        /// <param name=\"modelType\">The type of the model that the rules are defined for.</param>\r\n        public ModelValidationDescriptor(IDictionary<string, IList<ModelValidationRule>> rules, Type modelType)\r\n        {\r\n            this.Rules = rules;\r\n            this.ModelType = modelType;\r\n        }\r\n\r\n        /// <summary>\r\n        /// The type of the model that is being described.\r\n        /// </summary>\r\n        public Type ModelType { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the rules.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IDictionary{TKey,TValue}\"/> instance that contains <see cref=\"ModelValidationRule\"/> instances grouped by property name.</value>\r\n        public IDictionary<string, IList<ModelValidationRule>> Rules { get; private set; }\r\n\r\n        private static IDictionary<string, IList<ModelValidationRule>> GetModelValidationRuleDictionary(IEnumerable<ModelValidationRule> rules)\r\n        {\r\n            var results =\r\n                new Dictionary<string, IList<ModelValidationRule>>(StringComparer.OrdinalIgnoreCase);\r\n\r\n            if (rules == null)\r\n            {\r\n                return results;\r\n            }\r\n\r\n            foreach (var rule in rules)\r\n            {\r\n                foreach (var name in rule.MemberNames)\r\n                {\r\n                    IList<ModelValidationRule> list;\r\n                    if (!results.TryGetValue(name, out list))\r\n                    {\r\n                        list = new List<ModelValidationRule>();\r\n                        results.Add(name, list);\r\n                    }\r\n\r\n                    list.Add(rule);\r\n                }\r\n            }\r\n\r\n            return results;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Validation/ModelValidationError.cs",
    "content": "﻿namespace Nancy.Validation\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Represents a model validation error.\r\n    /// </summary>\r\n    public class ModelValidationError\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ModelValidationError\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"memberName\">Name of the member that the error describes.</param>\r\n        /// <param name=\"errorMessage\"></param>\r\n        public ModelValidationError(string memberName, string errorMessage)\r\n            : this(new[] { memberName }, errorMessage)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ModelValidationError\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"memberNames\">The member names that the error describes.</param>\r\n        /// <param name=\"errorMessage\"></param>\r\n        public ModelValidationError(IEnumerable<string> memberNames, string errorMessage)\r\n        {\r\n            this.MemberNames = memberNames;\r\n            this.ErrorMessage = errorMessage;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the member names that are a part of the error.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> that contains the name of the members.</value>\r\n        public IEnumerable<string> MemberNames { get; private set; }\r\n\r\n        /// <summary>\r\n        /// \r\n        /// </summary>\r\n        public string ErrorMessage { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Implicitly cast a validation error to a string.\r\n        /// </summary>\r\n        /// <param name=\"error\">The <see cref=\"ModelValidationError\"/> that should be cast.</param>\r\n        /// <returns>A <see cref=\"string\"/> containing the validation error description.</returns>\r\n        public static implicit operator string(ModelValidationError error)\r\n        {\r\n            return error.ErrorMessage;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns the <see cref=\"ErrorMessage\"/>.\r\n        /// </summary>\r\n        /// <returns>A string containing the error message.</returns>\r\n        public override string ToString()\r\n        {\r\n            return this.ErrorMessage;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Validation/ModelValidationException.cs",
    "content": "﻿namespace Nancy.Validation\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Exception that is thrown during problems with model validation.\r\n    /// </summary>\r\n    public class ModelValidationException : Exception\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ModelValidationException\"/> class.\r\n        /// </summary>\r\n        public ModelValidationException()\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ModelValidationException\"/> class,\r\n        /// with the provided <paramref name=\"message\"/>.\r\n        /// </summary>\r\n        /// <param name=\"message\">The error message that explains the reason for the exception.</param>\r\n        public ModelValidationException(string message) : base(message)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ModelValidationException\"/> class,\r\n        /// with the provided <paramref name=\"message\"/> and <paramref name=\"innerException\"/>\r\n        /// </summary>\r\n        /// <param name=\"message\">The error message that explains the reason for the exception.</param>\r\n        /// <param name=\"innerException\">The exception that is the cause of the current exception, or a null reference if no inner exception is specified.</param>\r\n        public ModelValidationException(string message, Exception innerException) : base(message, innerException)\r\n        {\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Validation/ModelValidationResult.cs",
    "content": "﻿namespace Nancy.Validation\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Diagnostics;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Represents the result of a model validation.\r\n    /// </summary>\r\n    [DebuggerDisplay(\"IsValid = {IsValid}\")]\r\n    public class ModelValidationResult\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ModelValidationResult\"/> class.\r\n        /// </summary>\r\n        public ModelValidationResult()\r\n            : this(Enumerable.Empty<ModelValidationError>())\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ModelValidationResult\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"errors\">The <see cref=\"ModelValidationError\"/> instances that makes up the result.</param>\r\n        public ModelValidationResult(IEnumerable<ModelValidationError> errors)\r\n            : this(GetModelValidationErrorDictionary((errors ?? Enumerable.Empty<ModelValidationError>()).ToArray()))\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ModelValidationResult\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"errors\">The <see cref=\"ModelValidationError\"/> instances that makes up the result, grouped by member name.</param>\r\n        public ModelValidationResult(IDictionary<string, IList<ModelValidationError>> errors)\r\n        {\r\n            this.Errors = errors;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the errors.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IDictionary{TKey,TValue}\"/> instance that contains <see cref=\"ModelValidationError\"/> instances grouped by property name.</value>\r\n        public IDictionary<string, IList<ModelValidationError>> Errors { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets a clean representation of the errors.\r\n        /// </summary>\r\n        /// <returns></returns>\r\n        public IEnumerable<dynamic> FormattedErrors\r\n        {\r\n            get\r\n            {\r\n                var result = this.Errors.Select(x => new {Key = x.Key, Errors = x.Value.Select(y => y.ErrorMessage).ToArray()}); \r\n                return result;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether the validated instance is valid or not.\r\n        /// </summary>\r\n        /// <value><see langword=\"true\"/> if the validated instance is valid; otherwise, <see langword=\"false\"/>.</value>\r\n        public bool IsValid\r\n        {\r\n            get { return !Errors.Keys.Any(); }\r\n        }\r\n\r\n        private static IDictionary<string, IList<ModelValidationError>> GetModelValidationErrorDictionary(ModelValidationError[] results)\r\n        {\r\n            var output =\r\n                new Dictionary<string, IList<ModelValidationError>>(StringComparer.OrdinalIgnoreCase);\r\n\r\n            if (results == null || !results.Any())\r\n            {\r\n                return output;\r\n            }\r\n\r\n            foreach (var result in results)\r\n            {\r\n                IList<ModelValidationError> value;\r\n                foreach (var name in result.MemberNames)\r\n                {\r\n                    if (!output.TryGetValue(name, out value))\r\n                    {\r\n                        value = new List<ModelValidationError>();\r\n                        output.Add(name, value);\r\n                    }\r\n\r\n                    value.Add(result);\r\n                }\r\n                \r\n                if (!result.MemberNames.Any() && !string.IsNullOrEmpty(result.ErrorMessage))\r\n                {\r\n                    if (!output.TryGetValue(string.Empty, out value))\r\n                    {\r\n                        value = new List<ModelValidationError>();\r\n                        output.Add(string.Empty, value);\r\n                    }\r\n\r\n                    value.Add(result);\r\n                }\r\n            }\r\n\r\n            return output;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Validation/ModelValidationRule.cs",
    "content": "﻿namespace Nancy.Validation\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// A description of a validation rule.\r\n    /// </summary>\r\n    public class ModelValidationRule\r\n    {\r\n        private readonly Func<string, string> errorMessageFormatter;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ModelValidationRule\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"ruleType\">Type of the rule.</param>\r\n        /// <param name=\"errorMessageFormatter\">The error message formatter.</param>\r\n        public ModelValidationRule(string ruleType, Func<string, string> errorMessageFormatter)\r\n        {\r\n            if (ruleType == null)\r\n            {\r\n                throw new ArgumentNullException(\"ruleType\");\r\n            }\r\n\r\n            if (errorMessageFormatter == null)\r\n            {\r\n                throw new ArgumentNullException(\"errorMessageFormatter\");\r\n            }\r\n\r\n            this.RuleType = ruleType;\r\n            this.errorMessageFormatter = errorMessageFormatter;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ModelValidationRule\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"ruleType\">Type of the rule.</param>\r\n        /// <param name=\"errorMessageFormatter\">The error message formatter.</param>\r\n        /// <param name=\"memberNames\">Name of the member.</param>\r\n        public ModelValidationRule(string ruleType, Func<string, string> errorMessageFormatter, IEnumerable<string> memberNames)\r\n            : this(ruleType, errorMessageFormatter)\r\n        {\r\n            this.MemberNames = memberNames;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the names of the members this rule validates.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> that contains the name of the member.</value>\r\n        public IEnumerable<string> MemberNames { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the type of the rule.\r\n        /// </summary>\r\n        /// <value>The type of the rule.</value>\r\n        public string RuleType { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the error message that this rule will provide upon error.\r\n        /// </summary>\r\n        /// <param name=\"name\">The name.</param>\r\n        /// <returns>The error message.</returns>\r\n        public string GetErrorMessage(string name)\r\n        {\r\n            return errorMessageFormatter(name);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Validation/ModuleExtensions.cs",
    "content": "﻿namespace Nancy.Validation\r\n{\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Extensions to <see cref=\"INancyModule\"/> for validation.\r\n    /// </summary>\r\n    public static class ModuleExtensions\r\n    {\r\n        /// <summary>\r\n        /// Performs validation on the specified <paramref name=\"instance\"/>.\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The type of the <paramref name=\"instance\"/> that is being validated.</typeparam>\r\n        /// <param name=\"module\">The module that the validation is performed from.</param>\r\n        /// <param name=\"instance\">The instance that is being validated.</param>\r\n        /// <returns>A <see cref=\"ModelValidationResult\"/> instance.</returns>\r\n        public static ModelValidationResult Validate<T>(this INancyModule module, T instance)\r\n        {\r\n            var validator =\r\n                module.ValidatorLocator.GetValidatorForType(typeof(T));\r\n\r\n            var result = (validator == null) ?\r\n                new ModelValidationResult() :\r\n                validator.Validate(instance, module.Context);\r\n\r\n            if (module.ModelValidationResult.Errors.Any())\r\n            {\r\n                module.ModelValidationResult.Errors =\r\n                    module.ModelValidationResult.Errors.Concat(result.Errors).ToDictionary(key => key.Key, val => val.Value);\r\n            }\r\n\r\n            module.ModelValidationResult = module.ModelValidationResult.Errors.Any()\r\n                                               ? module.ModelValidationResult\r\n                                               : result;\r\n\r\n            return module.ModelValidationResult;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Validation/Rules/ComparisonOperator.cs",
    "content": "﻿namespace Nancy.Validation.Rules\r\n{\r\n    /// <summary>\r\n    /// Specifies the validation comparison operators used by the <see cref=\"ComparisonValidationRule\"/> type.\r\n    /// </summary>\r\n    public enum ComparisonOperator\r\n    {\r\n        /// <summary>\r\n        /// A comparison for greater than.\r\n        /// </summary>\r\n        GreaterThan,\r\n\r\n        /// <summary>\r\n        /// A comparison for greater than or equal to.\r\n        /// </summary>\r\n        GreaterThanOrEqual,\r\n\r\n        /// <summary>\r\n        /// A comparison for less than.\r\n        /// </summary>\r\n        LessThan,\r\n\r\n        /// <summary>\r\n        /// A comparison for less than or equal to.\r\n        /// </summary>\r\n        LessThanOrEqual,\r\n\r\n        /// <summary>\r\n        /// A comparison for equality.\r\n        /// </summary>\r\n        Equal,\r\n\r\n        /// <summary>\r\n        /// A comparison for inequality.\r\n        /// </summary>\r\n        NotEqual\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Validation/Rules/ComparisonValidationRule.cs",
    "content": "﻿namespace Nancy.Validation.Rules\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Implementation of <see cref=\"ModelValidationRule\"/> for comparing two values using a\r\n    /// provided <see cref=\"ComparisonOperator\"/>.\r\n    /// </summary>\r\n    public class ComparisonValidationRule : ModelValidationRule\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ComparisonValidationRule\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"errorMessageFormatter\">The error message formatter.</param>\r\n        /// <param name=\"memberNames\">The member names.</param>\r\n        /// <param name=\"operator\">The <see cref=\"ComparisonOperator\"/> that should be used when comparing values.</param>\r\n        /// <param name=\"value\">Gets the value to compare against.</param>\r\n        public ComparisonValidationRule(Func<string, string> errorMessageFormatter, IEnumerable<string> memberNames, ComparisonOperator @operator, object value)\r\n            : base(\"Comparison\", errorMessageFormatter, memberNames)\r\n        {\r\n            this.Operator = @operator;\r\n            this.Value = value;\r\n        }\r\n\r\n        /// <summary>\r\n        /// The <see cref=\"ComparisonOperator\"/> that should be used when comparing values.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"ComparisonOperator\"/> value.</value>\r\n        public ComparisonOperator Operator { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the value to compare against.\r\n        /// </summary>\r\n        public object Value { get; private set; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Validation/Rules/NotEmptyValidationRule.cs",
    "content": "﻿namespace Nancy.Validation.Rules\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Implementation of <see cref=\"ModelValidationRule\"/> for ensuring a string does not\r\n    /// contain an empty value.\r\n    /// </summary>\r\n    public class NotEmptyValidationRule : ModelValidationRule\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NotEmptyValidationRule\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"errorMessageFormatter\">The error message formatter.</param>\r\n        /// <param name=\"memberNames\">The member names.</param>\r\n        public NotEmptyValidationRule(Func<string, string> errorMessageFormatter, IEnumerable<string> memberNames)\r\n            : base(\"NotEmpty\", errorMessageFormatter, memberNames)\r\n        {\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Validation/Rules/NotNullValidationRule.cs",
    "content": "﻿namespace Nancy.Validation.Rules\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Implementation of <see cref=\"ModelValidationRule\"/> for ensuring a string is not null.\r\n    /// </summary>\r\n    public class NotNullValidationRule : ModelValidationRule\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NotNullValidationRule\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"errorMessageFormatter\">The error message formatter.</param>\r\n        /// <param name=\"memberNames\">The member names.</param>\r\n        public NotNullValidationRule(Func<string, string> errorMessageFormatter, IEnumerable<string> memberNames)\r\n            : base(\"NotNull\", errorMessageFormatter, memberNames)\r\n        {\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Validation/Rules/RegexValidationRule.cs",
    "content": "﻿namespace Nancy.Validation.Rules\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Implementation of <see cref=\"ModelValidationRule\"/> for ensuring a string matches the\r\n    /// pattern which is defined by a regex.\r\n    /// </summary>\r\n    public class RegexValidationRule : ModelValidationRule\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"RegexValidationRule\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"errorMessageFormatter\">The error message formatter.</param>\r\n        /// <param name=\"memberNames\">The member names.</param>\r\n        /// <param name=\"pattern\">The regex pattern that should be used to check for a match.</param>\r\n        public RegexValidationRule(Func<string, string> errorMessageFormatter, IEnumerable<string> memberNames, string pattern)\r\n            : base(\"Regex\", errorMessageFormatter, memberNames)\r\n        {\r\n            this.Pattern = pattern;\r\n        }\r\n\r\n        /// <summary>\r\n        /// The regex pattern that should be used to check for a match.\r\n        /// </summary>\r\n        public string Pattern { get; private set; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Validation/Rules/StringLengthValidationRule.cs",
    "content": "﻿namespace Nancy.Validation.Rules\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Implementation of <see cref=\"ModelValidationRule\"/> for ensuring that the length of a string\r\n    /// is withing the specified range.\r\n    /// </summary>\r\n    public class StringLengthValidationRule : ModelValidationRule\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"StringLengthValidationRule\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"errorMessageFormatter\">The error message formatter.</param>\r\n        /// <param name=\"memberNames\">The member names.</param>\r\n        /// <param name=\"minLength\">Minimum allowed length of the string</param>\r\n        /// <param name=\"maxLength\">Maximum allowed length of the string</param>\r\n        public StringLengthValidationRule(Func<string, string> errorMessageFormatter, IEnumerable<string> memberNames, int minLength, int maxLength)\r\n            : base(\"StringLength\", errorMessageFormatter, memberNames)\r\n        {\r\n            this.MinLength = minLength;\r\n            this.MaxLength = maxLength;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the length of the min.\r\n        /// </summary>\r\n        /// <value>The length of the min.</value>\r\n        public int MinLength { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the length of the max.\r\n        /// </summary>\r\n        /// <value>The length of the max.</value>\r\n        public int MaxLength { get; private set; }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/ViewConfiguration.cs",
    "content": "namespace Nancy\r\n{\r\n    /// <summary>\r\n    /// Configuration for view rendering.\r\n    /// </summary>\r\n    public class ViewConfiguration\r\n    {\r\n        /// <summary>\r\n        /// A default instance of the <see cref=\"ViewConfiguration\"/> class.\r\n        /// </summary>\r\n        public static readonly ViewConfiguration Default = new ViewConfiguration(\r\n            runtimeViewDiscovery: false,\r\n            runtimeViewUpdates: false);\r\n\r\n        private ViewConfiguration()\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ViewConfiguration\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"runtimeViewDiscovery\">Determines if views can be discovered during runtime.</param>\r\n        /// <param name=\"runtimeViewUpdates\">Determines if views can be updated during runtime.</param>\r\n        public ViewConfiguration(bool runtimeViewDiscovery = false, bool runtimeViewUpdates = false)\r\n        {\r\n            this.RuntimeViewDiscovery = runtimeViewDiscovery;\r\n            this.RuntimeViewUpdates = runtimeViewUpdates;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets a value indicating whether or not to enable runtime view discovery\r\n        /// </summary>\r\n        /// <value><see langword=\"true\"/> if views can be discovered during runtime, otherwise <see langword=\"false\"/>.</value>\r\n        public bool RuntimeViewDiscovery { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether or not to allow runtime changes of views.\r\n        /// </summary>\r\n        /// <value><see langword=\"true\"/> if views can be updated during runtime, otherwise <see langword=\"false\"/>.</value>\r\n        public bool RuntimeViewUpdates { get; private set; }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/ViewConfigurationExtensions.cs",
    "content": "namespace Nancy\r\n{\r\n    using Configuration;\r\n\r\n    /// <summary>\r\n    /// Contains <see cref=\"ViewConfiguration\"/> configuration extensions for <see cref=\"INancyEnvironment\"/>.\r\n    /// </summary>\r\n    public static class ViewConfigurationExtensions\r\n    {\r\n        /// <summary>\r\n        /// Configures <see cref=\"ViewConfiguration\"/>.\r\n        /// </summary>\r\n        /// <param name=\"environment\">An <see cref=\"INancyEnvironment\"/> that should be configured.</param>\r\n        /// <param name=\"runtimeViewDiscovery\"><see langword=\"true\"/> if views can be discovered during runtime, otherwise <see langword=\"false\"/>.</param>\r\n        /// <param name=\"runtimeViewUpdates\"><see langword=\"true\"/> if views can be updated during runtime, otherwise <see langword=\"false\"/>.</param>\r\n        public static void Views(this INancyEnvironment environment, bool? runtimeViewDiscovery = false, bool? runtimeViewUpdates = false)\r\n        {\r\n            environment.AddValue(new ViewConfiguration(\r\n                runtimeViewDiscovery: runtimeViewDiscovery ?? ViewConfiguration.Default.RuntimeViewDiscovery,\r\n                runtimeViewUpdates: runtimeViewUpdates ?? ViewConfiguration.Default.RuntimeViewUpdates));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/ViewEngines/AmbiguousViewsException.cs",
    "content": "﻿namespace Nancy.ViewEngines\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Thrown when multiple <see cref=\"ViewLocationResult\"/> instances describe the exact same view.\r\n    /// </summary>\r\n    public class AmbiguousViewsException : Exception\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"AmbiguousViewsException\"/> class.\r\n        /// </summary>\r\n        public AmbiguousViewsException()\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"AmbiguousViewsException\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"message\">The message that should be displayed with the exception.</param>\r\n        public AmbiguousViewsException(string message)\r\n            : base(message)\r\n        {\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/DefaultFileSystemReader.cs",
    "content": "﻿namespace Nancy.ViewEngines\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Default implementation for retrieving information about views that are stored on the file system.\r\n    /// </summary>\r\n    public class DefaultFileSystemReader : IFileSystemReader\r\n    {\r\n        /// <summary>\r\n        /// Gets information about view that are stored in folders below the applications root path.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path of the folder where the views should be looked for.</param>\r\n        /// <param name=\"supportedViewExtensions\">A list of view extensions to look for.</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> containing view locations and contents readers.</returns>\r\n        public IEnumerable<Tuple<string, Func<StreamReader>>> GetViewsWithSupportedExtensions(string path, IEnumerable<string> supportedViewExtensions)\r\n        {\r\n            return supportedViewExtensions\r\n                .SelectMany(extension => GetFilenames(path, extension))\r\n                .Distinct()\r\n                .Select(file => new Tuple<string, Func<StreamReader>>(file, () => new StreamReader(new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))))\r\n                .ToList();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the last modified time for the file specified\r\n        /// </summary>\r\n        /// <param name=\"filename\">Filename</param>\r\n        /// <returns>Time the file was last modified</returns>\r\n        public DateTime GetLastModified(string filename)\r\n        {\r\n            return File.GetLastWriteTimeUtc(filename);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets information about specific views that are stored in folders below the applications root path.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path of the folder where the views should be looked for.</param>\r\n        /// <param name=\"viewName\">Name of the view to search for</param>\r\n        /// <param name=\"supportedViewExtensions\">A list of view extensions to look for.</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> containing view locations and contents readers.</returns>\r\n        public IEnumerable<Tuple<string, Func<StreamReader>>> GetViewsWithSupportedExtensions(string path, string viewName, IEnumerable<string> supportedViewExtensions)\r\n        {\r\n            return GetFilenames(path, viewName, supportedViewExtensions)\r\n                       .Select(file => new Tuple<string, Func<StreamReader>>(file, () => new StreamReader(new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))))\r\n                       .ToList();\r\n        }\r\n\r\n        private static IEnumerable<string> GetFilenames(string path, string viewName, IEnumerable<string> supportedViewExtensions)\r\n        {\r\n            return Directory.GetFiles(path, viewName + \".*\", SearchOption.TopDirectoryOnly)\r\n                            .Where(f => IsValidExtention(f, supportedViewExtensions));\r\n        }\r\n\r\n        private static bool IsValidExtention(string filename, IEnumerable<string> supportedViewExtensions)\r\n        {\r\n            var extension = Path.GetExtension(filename);\r\n\r\n            if (string.IsNullOrEmpty(extension))\r\n            {\r\n                return false;\r\n            }\r\n\r\n            return supportedViewExtensions.Contains(extension.Substring(1));\r\n        }\r\n\r\n        private static IEnumerable<string> GetFilenames(string path, string extension)\r\n        {\r\n            return !Directory.Exists(path) \r\n                ? Enumerable.Empty<string>()\r\n                : Directory.GetFiles(path, string.Concat(\"*.\", extension), SearchOption.AllDirectories);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/DefaultRenderContext.cs",
    "content": "﻿namespace Nancy.ViewEngines\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    using Nancy.Extensions;\r\n    using Nancy.Helpers;\r\n    using Nancy.Localization;\r\n    using Nancy.Security;\r\n\r\n    /// <summary>\r\n    /// Default render context implementation.\r\n    /// </summary>\r\n    public class DefaultRenderContext : IRenderContext\r\n    {\r\n        private readonly IViewResolver viewResolver;\r\n        private readonly IViewCache viewCache;\r\n\r\n        private readonly ITextResource textResource;\r\n\r\n        private readonly ViewLocationContext viewLocationContext;\r\n\r\n        private TextResourceFinder textResourceFinder;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultRenderContext\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"viewResolver\"></param>\r\n        /// <param name=\"viewCache\"></param>\r\n        /// <param name=\"textResource\"></param>\r\n        /// <param name=\"viewLocationContext\"></param>\r\n        public DefaultRenderContext(IViewResolver viewResolver, IViewCache viewCache, ITextResource textResource, ViewLocationContext viewLocationContext)\r\n        {\r\n            this.viewResolver = viewResolver;\r\n            this.viewCache = viewCache;\r\n            this.textResource = textResource;\r\n            this.viewLocationContext = viewLocationContext;\r\n            this.textResourceFinder = new TextResourceFinder(textResource, viewLocationContext.Context);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the context of the current request.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"NancyContext\"/> instance.</value>\r\n        public NancyContext Context\r\n        {\r\n            get { return this.viewLocationContext.Context; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the view cache that is used by Nancy.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IViewCache\"/> instance.</value>\r\n        public IViewCache ViewCache\r\n        {\r\n            get { return this.viewCache; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the text resource for localisation\r\n        /// </summary>\r\n        public ITextResource TextResource\r\n        {\r\n            get { return this.textResource; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the text resource finder for localisation\r\n        /// </summary>\r\n        public dynamic TextResourceFinder\r\n        {\r\n            get { return this.textResourceFinder; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Parses a path and returns an absolute url path, taking into account\r\n        /// base directory etc.\r\n        /// </summary>\r\n        /// <param name=\"input\">Input url such as ~/styles/main.css</param>\r\n        /// <returns>Parsed absolute url path</returns>\r\n        public string ParsePath(string input)\r\n        {\r\n            return this.viewLocationContext.Context.ToFullPath(input);\r\n        }\r\n\r\n        /// <summary>\r\n        /// HTML encodes a string.\r\n        /// </summary>\r\n        /// <param name=\"input\">The string that should be HTML encoded.</param>\r\n        /// <returns>A HTML encoded <see cref=\"string\"/>.</returns>\r\n        public string HtmlEncode(string input)\r\n        {\r\n            return HttpUtility.HtmlEncode(input);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Locates a view that matches the provided <paramref name=\"viewName\"/> and <paramref name=\"model\"/>.\r\n        /// </summary>\r\n        /// <param name=\"viewName\">The name of the view that should be located.</param>\r\n        /// <param name=\"model\">The model that should be used when locating the view.</param>\r\n        /// <returns>A <see cref=\"ViewLocationResult\"/> instance if the view could be located; otherwise, <see langword=\"null\"/>.</returns>\r\n        public ViewLocationResult LocateView(string viewName, dynamic model)\r\n        {\r\n            return this.viewResolver.GetViewLocation(viewName, model, this.viewLocationContext);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Generates a Csrf token.\r\n        /// The token should be stored in a cookie and the form as a hidden field.\r\n        /// In both cases the name should be the key of the returned key value pair.\r\n        /// </summary>\r\n        /// <returns>A tuple containing the name (cookie name and form/querystring name) and value</returns>\r\n        public KeyValuePair<string, string> GetCsrfToken()\r\n        {\r\n            object tokenObject;\r\n            if (!this.viewLocationContext.Context.Items.TryGetValue(CsrfToken.DEFAULT_CSRF_KEY, out tokenObject))\r\n            {\r\n                throw new InvalidOperationException(\"CSRF is not enabled on this request\");\r\n            }\r\n\r\n            var tokenString = tokenObject as string;\r\n            if (string.IsNullOrEmpty(tokenString))\r\n            {\r\n                throw new InvalidOperationException(\"CSRF object is invalid\");\r\n            }\r\n\r\n            return new KeyValuePair<string, string>(CsrfToken.DEFAULT_CSRF_KEY, tokenString);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/DefaultRenderContextFactory.cs",
    "content": "﻿namespace Nancy.ViewEngines\r\n{\r\n    using Nancy.Localization;\r\n\r\n    /// <summary>\r\n    /// Default render context factory implementation.\r\n    /// </summary>\r\n    public class DefaultRenderContextFactory : IRenderContextFactory\r\n    {\r\n        private readonly IViewCache viewCache;\r\n        private readonly IViewResolver viewResolver;\r\n        private readonly ITextResource textResource;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultRenderContextFactory\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"viewCache\">The view cache that should be used by the created render context.</param>\r\n        /// <param name=\"viewResolver\">The view resolver that should be used by the created render context.</param>\r\n        /// <param name=\"textResource\">The <see cref=\"ITextResource\"/> that should be used by the engine.</param>\r\n        public DefaultRenderContextFactory(IViewCache viewCache, IViewResolver viewResolver, ITextResource textResource)\r\n        {\r\n            this.viewCache = viewCache;\r\n            this.viewResolver = viewResolver;\r\n            this.textResource = textResource;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a <see cref=\"IRenderContext\"/> for the specified <see cref=\"ViewLocationContext\"/>.\r\n        /// </summary>\r\n        /// <param name=\"viewLocationContext\">The <see cref=\"ViewLocationContext\"/> for which the context should be created.</param>\r\n        /// <returns>A <see cref=\"IRenderContext\"/> instance.</returns>\r\n        public IRenderContext GetRenderContext(ViewLocationContext viewLocationContext)\r\n        {\r\n            return new DefaultRenderContext(this.viewResolver, this.viewCache, this.textResource, viewLocationContext);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/DefaultResourceReader.cs",
    "content": "﻿namespace Nancy.ViewEngines\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n\r\n    /// <summary>\r\n    /// Default implementation for extracting view information form an assembly.\r\n    /// </summary>\r\n    public class DefaultResourceReader : IResourceReader\r\n    {\r\n        /// <summary>\r\n        /// Gets information about the resources that are embedded in the assembly.\r\n        /// </summary>\r\n        /// <param name=\"assembly\">The <see cref=\"Assembly\"/> to retrieve view information from.</param>\r\n        /// <param name=\"supportedViewEngineExtensions\">A list of view extensions to look for.</param>\r\n        /// <returns>A <see cref=\"IList{T}\"/> of resource locations and content readers.</returns>\r\n        public IList<Tuple<string, Func<StreamReader>>> GetResourceStreamMatches(Assembly assembly, IEnumerable<string> supportedViewEngineExtensions)\r\n        {\r\n            var resourceStreams =\r\n                from resourceName in assembly.GetManifestResourceNames()\r\n                from viewEngineExtension in supportedViewEngineExtensions\r\n                where GetResourceExtension(resourceName).Equals(viewEngineExtension, StringComparison.OrdinalIgnoreCase)\r\n                select new Tuple<string, Func<StreamReader>>(\r\n                    resourceName,\r\n                    () => new StreamReader(assembly.GetManifestResourceStream(resourceName)));\r\n\r\n            return resourceStreams.ToList();\r\n        }\r\n\r\n        private static string GetResourceExtension(string resourceName)\r\n        {\r\n            var extension = Path.GetExtension(resourceName);\r\n            return string.IsNullOrEmpty(extension) ? string.Empty : extension.Substring(1);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/DefaultViewCache.cs",
    "content": "﻿namespace Nancy.ViewEngines\r\n{\r\n    using System;\r\n    using System.Collections.Concurrent;\r\n    using Configuration;\r\n\r\n    /// <summary>\r\n    /// Default implementation of <see cref=\"IViewCache\"/>.\r\n    /// </summary>\r\n    /// <remarks>Supports expiring content if it is stale, through the <see cref=\"ViewConfiguration.RuntimeViewUpdates\"/> setting.</remarks>\r\n    public class DefaultViewCache : IViewCache\r\n    {\r\n        private readonly ConcurrentDictionary<ViewLocationResult, object> cache;\r\n        private readonly ViewConfiguration configuration;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultViewCache\"/> class.\r\n        /// </summary>\r\n        public DefaultViewCache(INancyEnvironment environment)\r\n        {\r\n            this.cache = new ConcurrentDictionary<ViewLocationResult, object>();\r\n            this.configuration = environment.GetValue<ViewConfiguration>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or adds a view from the cache.\r\n        /// </summary>\r\n        /// <typeparam name=\"TCompiledView\">The type of the cached view instance.</typeparam>\r\n        /// <param name=\"viewLocationResult\">A <see cref=\"ViewLocationResult\"/> instance that describes the view that is being added or retrieved from the cache.</param>\r\n        /// <param name=\"valueFactory\">A function that produces the value that should be added to the cache in case it does not already exist.</param>\r\n        /// <returns>An instance of the type specified by the <typeparamref name=\"TCompiledView\"/> type.</returns>\r\n        public TCompiledView GetOrAdd<TCompiledView>(ViewLocationResult viewLocationResult, Func<ViewLocationResult, TCompiledView> valueFactory)\r\n        {\r\n            if (this.configuration.RuntimeViewUpdates)\r\n            {\r\n                if (viewLocationResult.IsStale())\r\n                {\r\n                    object old;\r\n                    this.cache.TryRemove(viewLocationResult, out old);\r\n                }\r\n            }\r\n\r\n            return (TCompiledView)this.cache.GetOrAdd(viewLocationResult, x => valueFactory(x));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/ViewEngines/DefaultViewFactory.cs",
    "content": "﻿namespace Nancy.ViewEngines\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Dynamic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using System.Text.RegularExpressions;\r\n    using Nancy.Conventions;\r\n\r\n    /// <summary>\r\n    /// The default implementation for how views are resolved and rendered by Nancy.\r\n    /// </summary>\r\n    public class DefaultViewFactory : IViewFactory\r\n    {\r\n        private readonly IViewResolver viewResolver;\r\n        private readonly IEnumerable<IViewEngine> viewEngines;\r\n        private readonly IRenderContextFactory renderContextFactory;\r\n        private readonly ViewLocationConventions conventions;\r\n        private readonly IRootPathProvider rootPathProvider;\r\n        private static readonly Action<Stream> EmptyView = x => { };\r\n        private readonly string[] viewEngineExtensions;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultViewFactory\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"viewResolver\">An <see cref=\"IViewResolver\"/> instance that should be used to resolve the location of a view.</param>\r\n        /// <param name=\"viewEngines\">An <see cref=\"IEnumerable{T}\"/> instance containing the <see cref=\"IViewEngine\"/> instances that should be able to be used to render a view</param>\r\n        /// <param name=\"renderContextFactory\">A <see cref=\"IRenderContextFactory\"/> instance that should be used to create an <see cref=\"IRenderContext\"/> when a view is rendered.</param>\r\n        /// <param name=\"conventions\">An <see cref=\"ViewLocationConventions\"/> instance that should be used to resolve all possible view locations </param>\r\n        /// <param name=\"rootPathProvider\">An <see cref=\"IRootPathProvider\"/> instance.</param>\r\n        public DefaultViewFactory(IViewResolver viewResolver, IEnumerable<IViewEngine> viewEngines, IRenderContextFactory renderContextFactory, ViewLocationConventions conventions, IRootPathProvider rootPathProvider)\r\n        {\r\n            this.viewResolver = viewResolver;\r\n            this.viewEngines = viewEngines;\r\n            this.renderContextFactory = renderContextFactory;\r\n            this.conventions = conventions;\r\n            this.rootPathProvider = rootPathProvider;\r\n\r\n            this.viewEngineExtensions = this.viewEngines.SelectMany(ive => ive.Extensions).ToArray();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Renders the view with the name and model defined by the <paramref name=\"viewName\"/> and <paramref name=\"model\"/> parameters.\r\n        /// </summary>\r\n        /// <param name=\"viewName\">The name of the view to render.</param>\r\n        /// <param name=\"model\">The model that should be passed into the view.</param>\r\n        /// <param name=\"viewLocationContext\">A <see cref=\"ViewLocationContext\"/> instance, containing information about the context for which the view is being rendered.</param>\r\n        /// <returns>A delegate that can be invoked with the <see cref=\"Stream\"/> that the view should be rendered to.</returns>\r\n        public Response RenderView(string viewName, dynamic model, ViewLocationContext viewLocationContext)\r\n        {\r\n            if (viewName == null && model == null)\r\n            {\r\n                throw new ArgumentException(\"View name and model parameters cannot both be null.\");\r\n            }\r\n\r\n            if (model == null && viewName.Length == 0)\r\n            {\r\n                throw new ArgumentException(\"The view name parameter cannot be empty when the model parameters is null.\");\r\n            }\r\n\r\n            if (viewLocationContext == null)\r\n            {\r\n                throw new ArgumentNullException(\"viewLocationContext\", \"The value of the viewLocationContext parameter cannot be null.\");\r\n            }\r\n\r\n            var actualViewName =\r\n                viewName ?? GetViewNameFromModel(model, viewLocationContext.Context);\r\n\r\n            viewLocationContext.Context.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat(\"[DefaultViewFactory] Rendering view with name \", actualViewName)));\r\n\r\n            return this.GetRenderedView(actualViewName, model, viewLocationContext);\r\n        }\r\n\r\n        private Response GetRenderedView(string viewName, dynamic model, ViewLocationContext viewLocationContext)\r\n        {\r\n            var viewLocationResult =\r\n                this.viewResolver.GetViewLocation(viewName, model, viewLocationContext);\r\n\r\n            var resolvedViewEngine =\r\n                GetViewEngine(viewLocationResult, viewLocationContext.Context);\r\n\r\n            if (resolvedViewEngine == null)\r\n            {\r\n                viewLocationContext.Context.Trace.TraceLog.WriteLog(x => x.AppendLine(\"[DefaultViewFactory] Unable to find view engine that could render the view.\"));\r\n                throw new ViewNotFoundException(viewName, this.viewEngineExtensions, this.GetInspectedLocations(viewName, model, viewLocationContext), this.rootPathProvider);\r\n            }\r\n\r\n            viewLocationContext.Context.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat(\"[DefaultViewFactory] Rendering view with view engine \", resolvedViewEngine.GetType().FullName)));\r\n\r\n            return SafeInvokeViewEngine(\r\n                resolvedViewEngine,\r\n                viewLocationResult,\r\n                GetSafeModel(model),\r\n                this.renderContextFactory.GetRenderContext(viewLocationContext)\r\n            );\r\n        }\r\n\r\n        private string[] GetInspectedLocations(string viewName, dynamic model, ViewLocationContext viewLocationContext)\r\n        {\r\n            var inspectedLocations = new List<string>();\r\n\r\n            foreach (var convention in this.conventions)\r\n            {\r\n                try\r\n                {\r\n                    var location =\r\n                        convention.Invoke(viewName, model, viewLocationContext);\r\n\r\n                    if (!string.IsNullOrWhiteSpace(location))\r\n                    {\r\n                        inspectedLocations.Add(location);\r\n                    }\r\n                }\r\n                catch\r\n                {\r\n                    // ignored\r\n                }\r\n            }\r\n\r\n            return inspectedLocations.ToArray();\r\n        }\r\n\r\n        private static object GetSafeModel(object model)\r\n        {\r\n            return (model.IsAnonymousType()) ? GetExpandoObject(model) : model;\r\n        }\r\n\r\n        private static ExpandoObject GetExpandoObject(object source)\r\n        {\r\n            var expandoObject = new ExpandoObject();\r\n            IDictionary<string, object> results = expandoObject;\r\n\r\n            foreach (var propertyInfo in source.GetType().GetProperties())\r\n            {\r\n                results[propertyInfo.Name] = propertyInfo.GetValue(source, null);\r\n            }\r\n\r\n            return expandoObject;\r\n        }\r\n\r\n        private IViewEngine GetViewEngine(ViewLocationResult viewLocationResult, NancyContext context)\r\n        {\r\n            if (viewLocationResult == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            context.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat(\"[DefaultViewFactory] Attempting to resolve view engine for view extension \", viewLocationResult.Extension)));\r\n\r\n            var matchingViewEngines =\r\n                from viewEngine in this.viewEngines\r\n                where viewEngine.Extensions.Any(x => x.Equals(viewLocationResult.Extension, StringComparison.OrdinalIgnoreCase))\r\n                select viewEngine;\r\n\r\n            return matchingViewEngines.FirstOrDefault();\r\n        }\r\n\r\n        private static string GetViewNameFromModel(dynamic model, NancyContext context)\r\n        {\r\n            context.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat(\"[DefaultViewFactory] Extracting view name from model of type \", model.GetType().FullName)));\r\n\r\n            return Regex.Replace(model.GetType().Name, \"Model$\", string.Empty);\r\n        }\r\n\r\n        private static Response SafeInvokeViewEngine(IViewEngine viewEngine, ViewLocationResult locationResult, dynamic model, IRenderContext renderContext)\r\n        {\r\n            try\r\n            {\r\n                return viewEngine.RenderView(locationResult, model, renderContext);\r\n            }\r\n            catch (Exception)\r\n            {\r\n                return EmptyView;\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/DefaultViewLocator.cs",
    "content": "﻿namespace Nancy.ViewEngines\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Threading;\r\n    using Configuration;\r\n\r\n    /// <summary>\r\n    /// The default implementation of <see cref=\"IViewLocator\"/>.\r\n    /// </summary>\r\n    public class DefaultViewLocator : IViewLocator\r\n    {\r\n        private readonly List<ViewLocationResult> viewLocationResults;\r\n        private readonly IViewLocationProvider viewLocationProvider;\r\n        private readonly IEnumerable<IViewEngine> viewEngines;\r\n        private readonly ReaderWriterLockSlim padlock = new ReaderWriterLockSlim();\r\n        private readonly char[] invalidCharacters;\r\n        private readonly ViewConfiguration configuration;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultViewLocator\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"viewLocationProvider\">An <see cref=\"IViewLocationProvider\"/> instance.</param>\r\n        /// <param name=\"viewEngines\">An <see cref=\"IEnumerable{T}\"/> of <see cref=\"IViewEngine\"/> instances.</param>\r\n        /// <param name=\"environment\">An <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        public DefaultViewLocator(IViewLocationProvider viewLocationProvider, IEnumerable<IViewEngine> viewEngines, INancyEnvironment environment)\r\n        {\r\n            this.viewLocationProvider = viewLocationProvider;\r\n            this.viewEngines = viewEngines;\r\n            this.invalidCharacters = Path.GetInvalidFileNameChars().Where(c => c != '/').ToArray();\r\n            this.viewLocationResults = new List<ViewLocationResult>(this.GetInitialViewLocations());\r\n            this.configuration = environment.GetValue<ViewConfiguration>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the location of the view defined by the <paramref name=\"viewName\"/> parameter.\r\n        /// </summary>\r\n        /// <param name=\"viewName\">Name of the view to locate.</param>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> instance for the current request.</param>\r\n        /// <returns>A <see cref=\"ViewLocationResult\"/> instance if the view could be located; otherwise <see langword=\"null\"/>.</returns>\r\n        public ViewLocationResult LocateView(string viewName, NancyContext context)\r\n        {\r\n            if (string.IsNullOrEmpty(viewName))\r\n            {\r\n                return null;\r\n            }\r\n\r\n            if (!this.IsValidViewName(viewName))\r\n            {\r\n                return null;\r\n            }\r\n\r\n            // If we can't do runtime discovery there's no need to lock anything\r\n            // as we can assume our cache is immutable.\r\n            if (!this.configuration.RuntimeViewDiscovery)\r\n            {\r\n                return this.LocateCachedView(viewName);\r\n            }\r\n\r\n            this.padlock.EnterUpgradeableReadLock();\r\n            try\r\n            {\r\n                var cachedResult = this.LocateCachedView(viewName);\r\n\r\n                if (cachedResult != null)\r\n                {\r\n                    return cachedResult;\r\n                }\r\n\r\n                return !this.configuration.RuntimeViewDiscovery\r\n                    ? null\r\n                    : this.LocateAndCacheUncachedView(viewName);\r\n            }\r\n            finally\r\n            {\r\n                this.padlock.ExitUpgradeableReadLock();\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all the views that are currently discovered\r\n        /// Note: this is *not* the recommended way to deal with the view locator\r\n        /// as it doesn't allow for runtime discovery of views with the\r\n        /// <see cref=\"ViewConfiguration\"/>.\r\n        /// </summary>\r\n        /// <returns>A collection of <see cref=\"ViewLocationResult\"/> instances</returns>\r\n        public IEnumerable<ViewLocationResult> GetAllCurrentlyDiscoveredViews()\r\n        {\r\n            this.padlock.EnterReadLock();\r\n\r\n            try\r\n            {\r\n                // Make a copy to avoid any modification issues\r\n                var newList = new List<ViewLocationResult>(this.viewLocationResults.Count);\r\n                this.viewLocationResults.ForEach(newList.Add);\r\n                return newList;\r\n            }\r\n            finally\r\n            {\r\n                this.padlock.ExitReadLock();\r\n            }\r\n        }\r\n\r\n        private ViewLocationResult LocateAndCacheUncachedView(string viewName)\r\n        {\r\n            var uncachedResults = this.GetUncachedMatchingViews(viewName);\r\n            if (!uncachedResults.Any())\r\n            {\r\n                return null;\r\n            }\r\n\r\n            this.padlock.EnterWriteLock();\r\n            try\r\n            {\r\n                this.viewLocationResults.AddRange(uncachedResults);\r\n            }\r\n            finally\r\n            {\r\n                this.padlock.ExitWriteLock();\r\n            }\r\n\r\n            if (uncachedResults.Length > 1)\r\n            {\r\n                throw new AmbiguousViewsException(GetAmbiguousViewExceptionMessage(uncachedResults.Length, uncachedResults));\r\n            }\r\n\r\n            return uncachedResults.First();\r\n        }\r\n\r\n        private ViewLocationResult LocateCachedView(string viewName)\r\n        {\r\n            var cachedResults = this.GetCachedMatchingViews(viewName);\r\n            if (cachedResults.Length == 1)\r\n            {\r\n                return cachedResults.Single();\r\n            }\r\n\r\n            if (cachedResults.Length > 1)\r\n            {\r\n                throw new AmbiguousViewsException(GetAmbiguousViewExceptionMessage(cachedResults.Length, cachedResults));\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        private ViewLocationResult[] GetUncachedMatchingViews(string viewName)\r\n        {\r\n            var viewExtension = GetExtensionFromViewName(viewName);\r\n\r\n            var supportedViewExtensions = string.IsNullOrEmpty(viewExtension)\r\n                ? this.GetSupportedViewExtensions()\r\n                : new[] { viewExtension };\r\n\r\n            var location = GetLocationFromViewName(viewName);\r\n            var nameWithoutExtension = GetFilenameWithoutExtensionFromViewName(viewName);\r\n\r\n            return this.viewLocationProvider.GetLocatedViews(supportedViewExtensions, location, nameWithoutExtension)\r\n                                            .ToArray();\r\n        }\r\n\r\n        private ViewLocationResult[] GetCachedMatchingViews(string viewName)\r\n        {\r\n            return this.viewLocationResults.Where(x => NameMatchesView(viewName, x))\r\n                       .Where(x => ExtensionMatchesView(viewName, x))\r\n                       .Where(x => LocationMatchesView(viewName, x))\r\n                       .ToArray();\r\n        }\r\n\r\n        private IEnumerable<ViewLocationResult> GetInitialViewLocations()\r\n        {\r\n            var supportedViewExtensions =\r\n                this.GetSupportedViewExtensions();\r\n\r\n            var viewsLocatedByProviders =\r\n                this.viewLocationProvider.GetLocatedViews(supportedViewExtensions);\r\n\r\n            return viewsLocatedByProviders.ToArray();\r\n        }\r\n\r\n        private IEnumerable<string> GetSupportedViewExtensions()\r\n        {\r\n            return this.viewEngines\r\n                .SelectMany(engine => engine.Extensions)\r\n                .Distinct();\r\n        }\r\n\r\n        private static string GetAmbiguousViewExceptionMessage(int count, IEnumerable<ViewLocationResult> viewsThatMatchesCriteria)\r\n        {\r\n            return string.Format(\"This exception was thrown because multiple views were found. {0} view(s):\\r\\n\\t{1}\", count, string.Join(\"\\r\\n\\t\", viewsThatMatchesCriteria.Select(GetFullLocationOfView).ToArray()));\r\n        }\r\n\r\n        private static string GetFullLocationOfView(ViewLocationResult viewLocationResult)\r\n        {\r\n            return string.Concat(viewLocationResult.Location, \"/\", viewLocationResult.Name, \".\", viewLocationResult.Extension);\r\n        }\r\n\r\n        private static bool ExtensionMatchesView(string viewName, ViewLocationResult viewLocationResult)\r\n        {\r\n            var extension = GetExtensionFromViewName(viewName);\r\n\r\n            return string.IsNullOrEmpty(extension) ||\r\n                viewLocationResult.Extension.Equals(extension, StringComparison.OrdinalIgnoreCase);\r\n        }\r\n\r\n        private static bool LocationMatchesView(string viewName, ViewLocationResult viewLocationResult)\r\n        {\r\n            var location = GetLocationFromViewName(viewName);\r\n\r\n            return viewLocationResult.Location.Equals(location, StringComparison.OrdinalIgnoreCase);\r\n        }\r\n\r\n        private static bool NameMatchesView(string viewName, ViewLocationResult viewLocationResult)\r\n        {\r\n            var name = GetFilenameWithoutExtensionFromViewName(viewName);\r\n\r\n            return (!string.IsNullOrEmpty(name)) &&\r\n                viewLocationResult.Name.Equals(name, StringComparison.OrdinalIgnoreCase);\r\n        }\r\n\r\n        private static string GetFilenameWithoutExtensionFromViewName(string viewName)\r\n        {\r\n            return Path.GetFileNameWithoutExtension(viewName);\r\n        }\r\n\r\n        private static string GetLocationFromViewName(string viewName)\r\n        {\r\n            var filename = Path.GetFileName(viewName);\r\n            var index = viewName.LastIndexOf(filename, StringComparison.OrdinalIgnoreCase);\r\n            var location = index >= 0 ? viewName.Remove(index, filename.Length) : viewName;\r\n            location = location.TrimEnd('/');\r\n            return location;\r\n        }\r\n\r\n        private static string GetExtensionFromViewName(string viewName)\r\n        {\r\n            var extension = Path.GetExtension(viewName);\r\n\r\n            return !string.IsNullOrEmpty(extension) ? extension.Substring(1) : extension;\r\n        }\r\n\r\n        private bool IsValidViewName(string viewName)\r\n        {\r\n            return !this.invalidCharacters.Any(viewName.Contains);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/ViewEngines/DefaultViewResolver.cs",
    "content": "﻿namespace Nancy.ViewEngines\r\n{\r\n    using System;\r\n\r\n    using Nancy.Conventions;\r\n\r\n    /// <summary>\r\n    /// Default implementation on how views are resolved by Nancy.\r\n    /// </summary>\r\n    public class DefaultViewResolver : IViewResolver\r\n    {\r\n        private readonly ViewLocationConventions conventions;\r\n        private readonly IViewLocator viewLocator;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultViewResolver\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"viewLocator\">The view locator that should be used to locate views.</param>\r\n        /// <param name=\"conventions\">The conventions that the view resolver should use to figure out where to look for views.</param>\r\n        public DefaultViewResolver(IViewLocator viewLocator, ViewLocationConventions conventions)\r\n        {\r\n            if (viewLocator == null)\r\n            {\r\n                throw new InvalidOperationException(\"Cannot create an instance of DefaultViewResolver with view locator parameter having null value.\");\r\n            }\r\n\r\n            if (conventions == null)\r\n            {\r\n                throw new InvalidOperationException(\"Cannot create an instance of DefaultViewResolver with conventions parameter having null value.\");\r\n            }\r\n\r\n            this.viewLocator = viewLocator;\r\n            this.conventions = conventions;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Locates a view based on the provided information.\r\n        /// </summary>\r\n        /// <param name=\"viewName\">The name of the view to locate.</param>\r\n        /// <param name=\"model\">The model that will be used with the view.</param>\r\n        /// <param name=\"viewLocationContext\">A <see cref=\"ViewLocationContext\"/> instance, containing information about the context for which the view is being located.</param>\r\n        /// <returns>A <see cref=\"ViewLocationResult\"/> instance if the view could be found, otherwise <see langword=\"null\"/>.</returns>\r\n        public ViewLocationResult GetViewLocation(string viewName, dynamic model, ViewLocationContext viewLocationContext)\r\n        {\r\n            if (string.IsNullOrEmpty(viewName))\r\n            {\r\n                return null;\r\n            }\r\n\r\n            if (viewLocationContext == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            viewLocationContext.Context.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat(\"[DefaultViewResolver] Resolving view for '\", viewName , \"', using view location conventions.\")));\r\n\r\n            foreach (var convention in conventions)\r\n            {\r\n                var conventionBasedViewName =\r\n                    SafeInvokeConvention(convention, viewName, model, viewLocationContext);\r\n\r\n                if (string.IsNullOrEmpty(conventionBasedViewName))\r\n                {\r\n                    continue;\r\n                }\r\n\r\n                viewLocationContext.Context.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat(\"[DefaultViewResolver] Attempting to locate view using convention '\", conventionBasedViewName, \"'\")));\r\n\r\n                var locatedView =\r\n                    this.viewLocator.LocateView(conventionBasedViewName, viewLocationContext.Context);\r\n\r\n                if (locatedView != null)\r\n                {\r\n                    viewLocationContext.Context.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat(\"[DefaultViewResolver] View resolved at '\", conventionBasedViewName, \"'\")));\r\n                    return locatedView;\r\n                }\r\n            }\r\n\r\n            viewLocationContext.Context.Trace.TraceLog.WriteLog(x => x.AppendLine(\"[DefaultViewResolver] No view could be resolved using the available view location conventions.\"));\r\n\r\n            return null;\r\n        }\r\n\r\n        private static string SafeInvokeConvention(Func<string, object, ViewLocationContext, string> convention, string viewName, dynamic model, ViewLocationContext viewLocationContext)\r\n        {\r\n            try\r\n            {\r\n                return convention.Invoke(viewName, model, viewLocationContext);\r\n            }\r\n            catch\r\n            {\r\n                return null;\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/Extensions.cs",
    "content": "﻿namespace Nancy.ViewEngines\r\n{\r\n    using System;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using System.Runtime.CompilerServices;\r\n\r\n    /// <summary>\r\n    /// Contains miscellaneous extension methods.\r\n    /// </summary>\r\n    public static class Extensions\r\n    {\r\n        /// <summary>\r\n        /// Checks if the evaluated instance is an anonymous\r\n        /// </summary>\r\n        /// <param name=\"source\">The object instance to check.</param>\r\n        /// <returns><see langword=\"true\"/> if the object is an anonymous type; otherwise <see langword=\"false\"/>.</returns>\r\n        public static bool IsAnonymousType(this object source)\r\n        {\r\n            return source != null && source.GetType().IsAnonymousType();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determines whether the given type is anonymous or not.\r\n        /// </summary>\r\n        /// <param name=\"type\">The type.</param>\r\n        /// <returns><see langword=\"true\"/> if type is anonymous, <see langword=\"false\"/> otherwise</returns>\r\n        public static bool IsAnonymousType(this Type type)\r\n        {\r\n            if (type == null)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            return type.GetTypeInfo().IsGenericType\r\n                   && (type.GetTypeInfo().Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic\r\n                   && (type.Name.StartsWith(\"<>\", StringComparison.OrdinalIgnoreCase) || type.Name.StartsWith(\"VB$\", StringComparison.OrdinalIgnoreCase))\r\n                   && (type.Name.Contains(\"AnonymousType\") || type.Name.Contains(\"AnonType\"))\r\n                   && type.GetTypeInfo().GetCustomAttributes(typeof(CompilerGeneratedAttribute)).Any();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/FileSystemViewLocationProvider.cs",
    "content": "﻿namespace Nancy.ViewEngines\r\n{\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Contains the functionality for locating a view that is located on the file system.\r\n    /// </summary>\r\n    public class FileSystemViewLocationProvider : IViewLocationProvider\r\n    {\r\n        private readonly IFileSystemReader fileSystemReader;\r\n        private readonly string rootPath;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"FileSystemViewLocationProvider\"/> class, with\r\n        /// the provided <paramref name=\"rootPathProvider\"/>.\r\n        /// </summary>\r\n        /// <param name=\"rootPathProvider\">A <see cref=\"IRootPathProvider\"/> instance.</param>\r\n        /// <remarks>Creating an instance using this constructor will result in the <see cref=\"DefaultFileSystemReader\"/> being used internally.</remarks>\r\n        public FileSystemViewLocationProvider(IRootPathProvider rootPathProvider)\r\n            : this(rootPathProvider, new DefaultFileSystemReader())\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"FileSystemViewLocationProvider\"/> class, with\r\n        /// the provided <paramref name=\"rootPathProvider\"/> and <paramref name=\"fileSystemReader\"/>.\r\n        /// </summary>\r\n        /// <param name=\"rootPathProvider\">A <see cref=\"IRootPathProvider\"/> instance.</param>\r\n        /// <param name=\"fileSystemReader\">An <see cref=\"IFileSystemReader\"/> instance that should be used when retrieving view information from the file system.</param>\r\n        public FileSystemViewLocationProvider(IRootPathProvider rootPathProvider, IFileSystemReader fileSystemReader)\r\n        {\r\n            this.fileSystemReader = fileSystemReader;\r\n            this.rootPath = rootPathProvider.GetRootPath();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an <see cref=\"ViewLocationResult\"/> instance for all the views that could be located by the provider.\r\n        /// </summary>\r\n        /// <param name=\"supportedViewExtensions\">An <see cref=\"IEnumerable{T}\"/> instance, containing the view engine file extensions that is supported by the running instance of Nancy.</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance, containing <see cref=\"ViewLocationResult\"/> instances for the located views.</returns>\r\n        /// <remarks>If no views could be located, this method should return an empty enumerable, never <see langword=\"null\"/>.</remarks>\r\n        public IEnumerable<ViewLocationResult> GetLocatedViews(IEnumerable<string> supportedViewExtensions)\r\n        {\r\n            if (string.IsNullOrEmpty(this.rootPath))\r\n            {\r\n                return Enumerable.Empty<ViewLocationResult>();\r\n            }\r\n\r\n            return this.GetViewsFromPath(this.rootPath, supportedViewExtensions);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an <see cref=\"ViewLocationResult\"/> instance for all the views matching the viewName that could be located by the provider.\r\n        /// </summary>\r\n        /// <param name=\"supportedViewExtensions\">An <see cref=\"IEnumerable{T}\"/> instance, containing the view engine file extensions that is supported by the running instance of Nancy.</param>\r\n        /// <param name=\"location\">Location of the view</param>\r\n        /// <param name=\"viewName\">The name of the view to try and find</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance, containing <see cref=\"ViewLocationResult\"/> instances for the located views.</returns>\r\n        /// <remarks>If no views could be located, this method should return an empty enumerable, never <see langword=\"null\"/>.</remarks>\r\n        public IEnumerable<ViewLocationResult> GetLocatedViews(IEnumerable<string> supportedViewExtensions, string location, string viewName)\r\n        {\r\n            if (string.IsNullOrEmpty(this.rootPath))\r\n            {\r\n                return Enumerable.Empty<ViewLocationResult>();\r\n            }\r\n\r\n            var path = this.rootPath;\r\n\r\n            if (!string.IsNullOrEmpty(location))\r\n            {\r\n                path = Path.Combine(path, location.Replace('/', Path.DirectorySeparatorChar));\r\n            }\r\n\r\n            if (!Directory.Exists(path))\r\n            {\r\n                return Enumerable.Empty<ViewLocationResult>();\r\n            }\r\n\r\n            var results = this.GetViewsFromPath(path, viewName, supportedViewExtensions);\r\n\r\n            return results;\r\n        }\r\n\r\n        private IEnumerable<ViewLocationResult> GetViewsFromPath(string path, string viewName, IEnumerable<string> supportedViewExtensions)\r\n        {\r\n            var matches = this.fileSystemReader.GetViewsWithSupportedExtensions(path, viewName, supportedViewExtensions);\r\n\r\n            return from match in matches\r\n                   select\r\n                       new FileSystemViewLocationResult(\r\n                       GetViewLocation(match.Item1, this.rootPath),\r\n                       Path.GetFileNameWithoutExtension(match.Item1),\r\n                       Path.GetExtension(match.Item1).Substring(1),\r\n                       match.Item2,\r\n                       match.Item1,\r\n                       this.fileSystemReader);\r\n        }\r\n\r\n        private IEnumerable<ViewLocationResult> GetViewsFromPath(string path, IEnumerable<string> supportedViewExtensions)\r\n        {\r\n            var matches = this.fileSystemReader.GetViewsWithSupportedExtensions(path, supportedViewExtensions);\r\n\r\n            return from match in matches\r\n                   select\r\n                       new FileSystemViewLocationResult(\r\n                       GetViewLocation(match.Item1, this.rootPath),\r\n                       Path.GetFileNameWithoutExtension(match.Item1),\r\n                       Path.GetExtension(match.Item1).Substring(1),\r\n                       match.Item2,\r\n                       match.Item1,\r\n                       this.fileSystemReader);\r\n        }\r\n\r\n        private static string GetViewLocation(string match, string rootPath)\r\n        {\r\n            var location = match\r\n                .Replace(rootPath, string.Empty)\r\n                .TrimStart(new[] { Path.DirectorySeparatorChar })\r\n                .Replace(@\"\\\", \"/\")\r\n                .Replace(Path.GetFileName(match), string.Empty)\r\n                .TrimEnd(new [] { '/' });\r\n\r\n            return location;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/FileSystemViewLocationResult.cs",
    "content": "﻿namespace Nancy.ViewEngines\r\n{\r\n    using System;\r\n    using System.IO;\r\n\r\n    /// <summary>\r\n    /// View location result for file system based views.\r\n    /// Supports detecting if the contents have changed since it\r\n    /// was last read.\r\n    /// </summary>\r\n    public class FileSystemViewLocationResult : ViewLocationResult\r\n    {\r\n        private readonly IFileSystemReader fileSystem;\r\n\r\n        private readonly string fileName;\r\n\r\n        private DateTime lastUpdated;\r\n\r\n        private readonly Func<TextReader> fileContents;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ViewLocationResult\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"location\">The location of where the view was found.</param>\r\n        /// <param name=\"name\">The name of the view.</param>\r\n        /// <param name=\"extension\">The file extension of the located view.</param>\r\n        /// <param name=\"contents\">A <see cref=\"TextReader\"/> that can be used to read the contents of the located view.</param>\r\n        /// <param name=\"fullFilename\">Full filename of the file</param>\r\n        /// <param name=\"fileSystem\">An <see cref=\"IFileSystemReader\"/> instance that should be used when retrieving view information from the file system.</param>\r\n        public FileSystemViewLocationResult(string location, string name, string extension, Func<TextReader> contents, string fullFilename, IFileSystemReader fileSystem)\r\n        {\r\n            this.fileSystem = fileSystem;\r\n            this.Location = location;\r\n            this.Name = name;\r\n            this.Extension = extension;\r\n            this.fileContents = contents;\r\n            this.Contents = this.GetContents;\r\n            this.fileName = fullFilename;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether the current item is stale\r\n        /// </summary>\r\n        /// <returns>True if stale, false otherwise</returns>\r\n        public override bool IsStale()\r\n        {\r\n            return this.lastUpdated != this.fileSystem.GetLastModified(this.fileName);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Wraps the real contents delegate to set the last modified date first\r\n        /// </summary>\r\n        /// <returns>TextReader to read the file</returns>\r\n        private TextReader GetContents()\r\n        {\r\n            this.lastUpdated = this.fileSystem.GetLastModified(this.fileName);\r\n\r\n            return this.fileContents.Invoke();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/IFileSystemReader.cs",
    "content": "namespace Nancy.ViewEngines\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality for retrieving information about views that are stored on the file system.\r\n    /// </summary>\r\n    public interface IFileSystemReader\r\n    {\r\n        /// <summary>\r\n        /// Gets information about view that are stored in folders below the applications root path.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path of the folder where the views should be looked for.</param>\r\n        /// <param name=\"supportedViewExtensions\">A list of view extensions to look for.</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> containing view locations and contents readers.</returns>\r\n        IEnumerable<Tuple<string, Func<StreamReader>>> GetViewsWithSupportedExtensions(string path, IEnumerable<string> supportedViewExtensions);\r\n\r\n        /// <summary>\r\n        /// Gets the last modified time for the file specified\r\n        /// </summary>\r\n        /// <param name=\"filename\">Filename</param>\r\n        /// <returns>Time the file was last modified</returns>\r\n        DateTime GetLastModified(string filename);\r\n\r\n        /// <summary>\r\n        /// Gets information about specific views that are stored in folders below the applications root path.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path of the folder where the views should be looked for.</param>\r\n        /// <param name=\"viewName\">Name of the view to search for</param>\r\n        /// <param name=\"supportedViewExtensions\">A list of view extensions to look for.</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> containing view locations and contents readers.</returns>\r\n        IEnumerable<Tuple<string, Func<StreamReader>>> GetViewsWithSupportedExtensions(string path, string viewName, IEnumerable<string> supportedViewExtensions);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/IRenderContext.cs",
    "content": "namespace Nancy.ViewEngines\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using Nancy.Localization;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality of the context that is passed into a view engine when the view is requested to be rendered.\r\n    /// </summary>\r\n    public interface IRenderContext\r\n    {\r\n        /// <summary>\r\n        /// Gets the context of the current request.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"NancyContext\"/> instance.</value>\r\n        NancyContext Context { get; }\r\n\r\n        /// <summary>\r\n        /// Gets the view cache that is used by Nancy.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IViewCache\"/> instance.</value>\r\n        IViewCache ViewCache { get; }\r\n\r\n        /// <summary>\r\n        /// Gets the text resource for localisation\r\n        /// </summary>\r\n        ITextResource TextResource { get; }\r\n\r\n        /// <summary>\r\n        /// Gets the text resource finder for localisation\r\n        /// </summary>\r\n        dynamic TextResourceFinder { get; }\r\n\r\n        /// <summary>\r\n        /// Parses a path and returns an absolute url path, taking into account\r\n        /// base directory etc.\r\n        /// </summary>\r\n        /// <param name=\"input\">Input url such as ~/styles/main.css</param>\r\n        /// <returns>Parsed absolute url path</returns>\r\n        string ParsePath(string input);\r\n\r\n        /// <summary>\r\n        /// HTML encodes a string.\r\n        /// </summary>\r\n        /// <param name=\"input\">The string that should be HTML encoded.</param>\r\n        /// <returns>A HTML encoded <see cref=\"string\"/>.</returns>\r\n        string HtmlEncode(string input);\r\n\r\n        /// <summary>\r\n        /// Locates a view that matches the provided <paramref name=\"viewName\"/> and <paramref name=\"model\"/>.\r\n        /// </summary>\r\n        /// <param name=\"viewName\">The name of the view that should be located.</param>\r\n        /// <param name=\"model\">The model that should be used when locating the view.</param>\r\n        /// <returns>A <see cref=\"ViewLocationResult\"/> instance if the view could be located; otherwise, <see langword=\"null\"/>.</returns>\r\n        ViewLocationResult LocateView(string viewName, dynamic model);\r\n\r\n        /// <summary>\r\n        /// Gets the current Csrf token.\r\n        /// The token should be stored in a cookie and the form as a hidden field.\r\n        /// In both cases the name should be the key of the returned key value pair.\r\n        /// </summary>\r\n        /// <returns>A tuple containing the name (cookie name and form/querystring name) and value</returns>\r\n        KeyValuePair<string, string> GetCsrfToken();\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/IRenderContextFactory.cs",
    "content": "﻿namespace Nancy.ViewEngines\r\n{\r\n    /// <summary>\r\n    /// Defines the functionality required to manufacture <see cref=\"IRenderContext\"/> instances.\r\n    /// </summary>\r\n    public interface IRenderContextFactory\r\n    {\r\n        /// <summary>\r\n        /// Gets a <see cref=\"IRenderContext\"/> for the specified <see cref=\"ViewLocationContext\"/>.\r\n        /// </summary>\r\n        /// <param name=\"viewLocationContext\">The <see cref=\"ViewLocationContext\"/> for which the context should be created.</param>\r\n        /// <returns>A <see cref=\"IRenderContext\"/> instance.</returns>\r\n        IRenderContext GetRenderContext(ViewLocationContext viewLocationContext);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/IResourceReader.cs",
    "content": "﻿namespace Nancy.ViewEngines\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Reflection;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality of a reader that extracts embedded views from an assembly.\r\n    /// </summary>\r\n    public interface IResourceReader\r\n    {\r\n        /// <summary>\r\n        /// Gets information about the resources that are embedded in the assembly.\r\n        /// </summary>\r\n        /// <param name=\"assembly\">The <see cref=\"Assembly\"/> to retrieve view information from.</param>\r\n        /// <param name=\"supportedViewEngineExtensions\">A list of view extensions to look for.</param>\r\n        /// <returns>A <see cref=\"IList{T}\"/> of resource locations and content readers.</returns>\r\n        IList<Tuple<string, Func<StreamReader>>> GetResourceStreamMatches(Assembly assembly, IEnumerable<string> supportedViewEngineExtensions);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/IViewCache.cs",
    "content": "﻿namespace Nancy.ViewEngines\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality of a Nancy view cache.\r\n    /// </summary>\r\n    public interface IViewCache\r\n    {\r\n        /// <summary>\r\n        /// Gets or adds a view from the cache.\r\n        /// </summary>\r\n        /// <typeparam name=\"TCompiledView\">The type of the cached view instance.</typeparam>\r\n        /// <param name=\"viewLocationResult\">A <see cref=\"ViewLocationResult\"/> instance that describes the view that is being added or retrieved from the cache.</param>\r\n        /// <param name=\"valueFactory\">A function that produces the value that should be added to the cache in case it does not already exist.</param>\r\n        /// <returns>An instance of the type specified by the <typeparamref name=\"TCompiledView\"/> type.</returns>\r\n        TCompiledView GetOrAdd<TCompiledView>(ViewLocationResult viewLocationResult, Func<ViewLocationResult, TCompiledView> valueFactory);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/IViewEngine.cs",
    "content": "﻿namespace Nancy.ViewEngines\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality that a view engine must support to be integrated into Nancy.\r\n    /// </summary>\r\n    public interface IViewEngine\r\n    {\r\n        /// <summary>\r\n        /// Gets the extensions file extensions that are supported by the view engine.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> instance containing the extensions.</value>\r\n        /// <remarks>The extensions should not have a leading dot in the name.</remarks>\r\n        IEnumerable<string> Extensions { get; }\r\n\r\n        /// <summary>\r\n        /// Initialise the view engine (if necessary)\r\n        /// </summary>\r\n        /// <param name=\"viewEngineStartupContext\">Startup context</param>\r\n        void Initialize(ViewEngineStartupContext viewEngineStartupContext);\r\n\r\n        /// <summary>\r\n        /// Renders the view.\r\n        /// </summary>\r\n        /// <param name=\"viewLocationResult\">A <see cref=\"ViewLocationResult\"/> instance, containing information on how to get the view template.</param>\r\n        /// <param name=\"model\">The model that should be passed into the view</param>\r\n        /// <param name=\"renderContext\"></param>\r\n        /// <returns>A response</returns>\r\n        Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/IViewFactory.cs",
    "content": "﻿namespace Nancy.ViewEngines\r\n{\r\n    /// <summary>\r\n    /// Defines the functionality used by a <see cref=\"INancyModule\"/> to render a view to the response.\r\n    /// </summary>\r\n    public interface IViewFactory : IHideObjectMembers\r\n    {\r\n        /// <summary>\r\n        /// Renders the view with the name and model defined by the <paramref name=\"viewName\"/> and <paramref name=\"model\"/> parameters.\r\n        /// </summary>\r\n        /// <param name=\"viewName\">The name of the view to render.</param>\r\n        /// <param name=\"model\">The module path of the module that is rendering the view.</param>\r\n        /// <param name=\"viewLocationContext\">A <see cref=\"ViewLocationContext\"/> instance, containing information about the context for which the view is being rendered.</param>\r\n        /// <returns>A response.</returns>\r\n        Response RenderView(string viewName, dynamic model, ViewLocationContext viewLocationContext);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/IViewLocationProvider.cs",
    "content": "﻿namespace Nancy.ViewEngines\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality used by Nancy to located a view.\r\n    /// </summary>\r\n    public interface IViewLocationProvider\r\n    {\r\n        /// <summary>\r\n        /// Returns an <see cref=\"ViewLocationResult\"/> instance for all the views that could be located by the provider.\r\n        /// </summary>\r\n        /// <param name=\"supportedViewExtensions\">An <see cref=\"IEnumerable{T}\"/> instance, containing the view engine file extensions that is supported by the running instance of Nancy.</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance, containing <see cref=\"ViewLocationResult\"/> instances for the located views.</returns>\r\n        /// <remarks>If no views could be located, this method should return an empty enumerable, never <see langword=\"null\"/>.</remarks>\r\n        IEnumerable<ViewLocationResult> GetLocatedViews(IEnumerable<string> supportedViewExtensions);\r\n\r\n        /// <summary>\r\n        /// Returns an <see cref=\"ViewLocationResult\"/> instance for all the views matching the viewName that could be located by the provider.\r\n        /// </summary>\r\n        /// <param name=\"supportedViewExtensions\">An <see cref=\"IEnumerable{T}\"/> instance, containing the view engine file extensions that is supported by the running instance of Nancy.</param>\r\n        /// <param name=\"location\">Location of the view</param>\r\n        /// <param name=\"viewName\">The name of the view to try and find</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance, containing <see cref=\"ViewLocationResult\"/> instances for the located views.</returns>\r\n        /// <remarks>If no views could be located, this method should return an empty enumerable, never <see langword=\"null\"/>.</remarks>\r\n        IEnumerable<ViewLocationResult> GetLocatedViews(IEnumerable<string> supportedViewExtensions, string location, string viewName);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/IViewLocator.cs",
    "content": "﻿namespace Nancy.ViewEngines\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality for locating the requested view.\r\n    /// </summary>\r\n    public interface IViewLocator : IHideObjectMembers\r\n    {\r\n        /// <summary>\r\n        /// Gets the location of the view defined by the <paramref name=\"viewName\"/> parameter.\r\n        /// </summary>\r\n        /// <param name=\"viewName\">Name of the view to locate.</param>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> instance for the current request.</param>\r\n        /// <returns>A <see cref=\"ViewLocationResult\"/> instance if the view could be located; otherwise <see langword=\"null\"/>.</returns>\r\n        ViewLocationResult LocateView(string viewName, NancyContext context);\r\n\r\n        /// <summary>\r\n        /// Gets all the views that are currently discovered\r\n        /// Note: this is *not* the recommended way to deal with the view locator\r\n        /// as it doesn't allow for runtime discovery of views with the\r\n        /// <see cref=\"ViewConfiguration\"/>.\r\n        /// </summary>\r\n        /// <returns>A collection of <see cref=\"ViewLocationResult\"/> instances</returns>\r\n        IEnumerable<ViewLocationResult> GetAllCurrentlyDiscoveredViews();\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/ViewEngines/IViewResolver.cs",
    "content": "﻿namespace Nancy.ViewEngines\r\n{\r\n    /// <summary>\r\n    /// Defines the functionality for resolving the requested view.\r\n    /// </summary>\r\n    public interface IViewResolver : IHideObjectMembers\r\n    {\r\n        /// <summary>\r\n        /// Locates a view based on the provided information.\r\n        /// </summary>\r\n        /// <param name=\"viewName\">The name of the view to locate.</param>\r\n        /// <param name=\"model\">The model that will be used with the view.</param>\r\n        /// <param name=\"viewLocationContext\">A <see cref=\"ViewLocationContext\"/> instance, containing information about the context for which the view is being located.</param>\r\n        /// <returns>A <see cref=\"ViewLocationResult\"/> instance if the view could be found, otherwise <see langword=\"null\"/>.</returns>\r\n        ViewLocationResult GetViewLocation(string viewName, dynamic model, ViewLocationContext viewLocationContext);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/ResourceViewLocationProvider.cs",
    "content": "﻿namespace Nancy.ViewEngines\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n\r\n    /// <summary>\r\n    /// Contains the functionality for locating a view that has been embedded into an assembly resource.\r\n    /// </summary>\r\n    public class ResourceViewLocationProvider : IViewLocationProvider\r\n    {\r\n        private readonly IResourceReader resourceReader;\r\n        private readonly IResourceAssemblyProvider resourceAssemblyProvider;\r\n\r\n        /// <summary>\r\n        /// User-configured root namespaces for assemblies.\r\n        /// </summary>\r\n        public static readonly IDictionary<Assembly, string> RootNamespaces = new Dictionary<Assembly, string>();\r\n\r\n        /// <summary>\r\n        /// A list of assemblies to ignore when scanning for embedded views.\r\n        /// </summary>\r\n        public static readonly IList<Assembly> Ignore = new List<Assembly>();\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ResourceViewLocationProvider\"/> class, with\r\n        /// the provided <paramref name=\"assemblyCatalog\"/>.\r\n        /// </summary>\r\n        /// <param name=\"assemblyCatalog\">An <see cref=\"IAssemblyCatalog\"/> instance.</param>\r\n        public ResourceViewLocationProvider(IAssemblyCatalog assemblyCatalog)\r\n            : this(new DefaultResourceReader(), new ResourceAssemblyProvider(assemblyCatalog))\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ResourceViewLocationProvider\"/> class, with\r\n        /// the provided <paramref name=\"resourceReader\"/> and <paramref name=\"resourceAssemblyProvider\"/>.\r\n        /// </summary>\r\n        /// <param name=\"resourceReader\">An <see cref=\"IResourceReader\"/> instance that should be used when extracting embedded views.</param>\r\n        /// <param name=\"resourceAssemblyProvider\">An <see cref=\"IResourceAssemblyProvider\"/> instance that should be used to determine which assemblies to scan for embedded views.</param>\r\n        public ResourceViewLocationProvider(IResourceReader resourceReader, IResourceAssemblyProvider resourceAssemblyProvider)\r\n        {\r\n            this.resourceReader = resourceReader;\r\n            this.resourceAssemblyProvider = resourceAssemblyProvider;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an <see cref=\"ViewLocationResult\"/> instance for all the views that could be located by the provider.\r\n        /// </summary>\r\n        /// <param name=\"supportedViewExtensions\">An <see cref=\"IEnumerable{T}\"/> instance, containing the view engine file extensions that is supported by the running instance of Nancy.</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance, containing <see cref=\"ViewLocationResult\"/> instances for the located views.</returns>\r\n        /// <remarks>If no views could be located, this method should return an empty enumerable, never <see langword=\"null\"/>.</remarks>\r\n        public IEnumerable<ViewLocationResult> GetLocatedViews(IEnumerable<string> supportedViewExtensions)\r\n        {\r\n            if (supportedViewExtensions == null || !supportedViewExtensions.Any())\r\n            {\r\n                return Enumerable.Empty<ViewLocationResult>();\r\n            }\r\n\r\n            return this.resourceAssemblyProvider\r\n                .GetAssembliesToScan()\r\n                .Union(RootNamespaces.Keys)\r\n                .Where(x => !Ignore.Contains(x))\r\n                .SelectMany(x => GetViewLocations(x, supportedViewExtensions));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an <see cref=\"ViewLocationResult\"/> instance for all the views matching the viewName that could be located by the provider.\r\n        /// </summary>\r\n        /// <param name=\"supportedViewExtensions\">An <see cref=\"IEnumerable{T}\"/> instance, containing the view engine file extensions that is supported by the running instance of Nancy.</param>\r\n        /// <param name=\"location\">Location of the view</param>\r\n        /// <param name=\"viewName\">The name of the view to try and find</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance, containing <see cref=\"ViewLocationResult\"/> instances for the located views.</returns>\r\n        /// <remarks>If no views could be located, this method should return an empty enumerable, never <see langword=\"null\"/>.</remarks>\r\n        public IEnumerable<ViewLocationResult> GetLocatedViews(IEnumerable<string> supportedViewExtensions, string location, string viewName)\r\n        {\r\n            var allResults = this.GetLocatedViews(supportedViewExtensions);\r\n\r\n            return allResults.Where(vlr => vlr.Location.Equals(location, StringComparison.OrdinalIgnoreCase) &&\r\n                                           vlr.Name.Equals(viewName, StringComparison.OrdinalIgnoreCase));\r\n        }\r\n\r\n        private IEnumerable<ViewLocationResult> GetViewLocations(Assembly assembly, IEnumerable<string> supportedViewExtensions)\r\n        {\r\n            var resourceStreams =\r\n                this.resourceReader.GetResourceStreamMatches(assembly, supportedViewExtensions);\r\n\r\n            if (!resourceStreams.Any())\r\n            {\r\n                return Enumerable.Empty<ViewLocationResult>();\r\n            }\r\n\r\n            if (resourceStreams.Count() == 1 && !RootNamespaces.ContainsKey(assembly))\r\n            {\r\n                var errorMessage =\r\n                    string.Format(\"Only one view was found in assembly {0}, but no rootnamespace had been registered.\", assembly.FullName);\r\n\r\n                throw new InvalidOperationException(errorMessage);\r\n            }\r\n\r\n            string commonNamespace;\r\n            if (!RootNamespaces.TryGetValue(assembly, out commonNamespace))\r\n            {\r\n                commonNamespace = ExtractAssemblyRootNamespace(assembly);\r\n            }\r\n\r\n            if (string.IsNullOrWhiteSpace(commonNamespace))\r\n            {\r\n                return Enumerable.Empty<ViewLocationResult>();\r\n            }\r\n\r\n            return\r\n                from resource in resourceStreams\r\n                let resourceFileName = GetResourceFileName(resource.Item1)\r\n                where !resourceFileName.Equals(string.Empty)\r\n                select new ViewLocationResult(\r\n                    GetResourceLocation(commonNamespace, resource.Item1, resourceFileName),\r\n                    Path.GetFileNameWithoutExtension(resourceFileName),\r\n                    GetResourceExtension(resource.Item1),\r\n                    resource.Item2);\r\n        }\r\n\r\n        private static string GetResourceLocation(string commonNamespace, string resource, string resourceName)\r\n        {\r\n            return resource\r\n                .Replace(commonNamespace, string.Empty)\r\n                .Replace(resourceName, string.Empty)\r\n                .Trim(new[] { '.' })\r\n                .Replace(\".\", \"/\");\r\n        }\r\n\r\n        private static string ExtractCommonResourceNamespace(IEnumerable<string> resources)\r\n        {\r\n            if (resources.Count() == 1)\r\n            {\r\n                var resource = resources.First();\r\n\r\n                return resource\r\n                    .Replace(GetResourceFileName(resource), string.Empty)\r\n                    .TrimEnd(new[] { '.' });\r\n            }\r\n\r\n            var commonPathSegments = resources.Select(s => new { parts = s.Split('.') })\r\n                .Aggregate((previous, current) => new { parts = current.parts.TakeWhile((step, index) => step == previous.parts.ElementAtOrDefault(index)).ToArray() });\r\n\r\n            var commonResourceNamespace =\r\n                string.Join(\".\", commonPathSegments.parts);\r\n\r\n            return commonResourceNamespace;\r\n        }\r\n\r\n        private static string ExtractAssemblyRootNamespace(Assembly assembly)\r\n        {\r\n            var resources = assembly\r\n                .GetTypes()\r\n                .Where(x => !x.IsAnonymousType())\r\n                .Select(x => x.FullName)\r\n                .ToList();\r\n\r\n            return ExtractCommonResourceNamespace(resources);\r\n        }\r\n\r\n        private static string GetResourceFileName(string resourceName)\r\n        {\r\n            var nameSegments =\r\n                resourceName.Split(new[] { \".\" }, StringSplitOptions.RemoveEmptyEntries);\r\n\r\n            var segmentCount =\r\n                nameSegments.Count();\r\n\r\n            return (segmentCount < 2) ?\r\n                string.Empty :\r\n                string.Concat(nameSegments[segmentCount - 2], \".\", nameSegments[segmentCount - 1]);\r\n        }\r\n\r\n        private static string GetResourceExtension(string resourceName)\r\n        {\r\n            var extension = Path.GetExtension(resourceName);\r\n            return extension != null ? extension.Substring(1) : string.Empty;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/SuperSimpleViewEngine/ISuperSimpleViewEngineMatcher.cs",
    "content": "﻿namespace Nancy.ViewEngines.SuperSimpleViewEngine\r\n{\r\n    /// <summary>\r\n    /// Matches and modifies the content of a rendered SuperSimpleViewEngine view.\r\n    /// </summary>\r\n    public interface ISuperSimpleViewEngineMatcher\r\n    {\r\n        /// <summary>\r\n        /// Invokes the matcher on the content of the rendered view.\r\n        /// </summary>\r\n        /// <param name=\"content\">The content of the rendered view.</param>\r\n        /// <param name=\"model\">The model that was passed to the view.</param>\r\n        /// <param name=\"host\">The <see cref=\"IViewEngineHost\"/> host.</param>\r\n        /// <returns>The modified version of the view.</returns>\r\n        string Invoke(string content, dynamic model, IViewEngineHost host);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/SuperSimpleViewEngine/IViewEngineHost.cs",
    "content": "namespace Nancy.ViewEngines.SuperSimpleViewEngine\r\n{\r\n    /// <summary>\r\n    /// Provides the view engine with utility functions for\r\n    /// encoding, locating partial view templates etc.\r\n    /// </summary>\r\n    public interface IViewEngineHost\r\n    {\r\n        /// <summary>\r\n        /// Context object of the host application.\r\n        /// </summary>\r\n        /// <value>An instance of the context object from the host.</value>\r\n        object Context { get; }\r\n\r\n        /// <summary>\r\n        /// Html \"safe\" encode a string\r\n        /// </summary>\r\n        /// <param name=\"input\">Input string</param>\r\n        /// <returns>Encoded string</returns>\r\n        string HtmlEncode(string input);\r\n\r\n        /// <summary>\r\n        /// Get the contents of a template\r\n        /// </summary>\r\n        /// <param name=\"templateName\">Name/location of the template</param>\r\n        /// <param name=\"model\">Model to use to locate the template via conventions</param>\r\n        /// <returns>Contents of the template, or null if not found</returns>\r\n        string GetTemplate(string templateName, object model);\r\n\r\n        /// <summary>\r\n        /// Gets a uri string for a named route\r\n        /// </summary>\r\n        /// <param name=\"name\">Named route name</param>\r\n        /// <param name=\"parameters\">Parameters to use to expand the uri string</param>\r\n        /// <returns>Expanded uri string, or null if not found</returns>\r\n        string GetUriString(string name, params string[] parameters);\r\n\r\n        /// <summary>\r\n        /// Expands a path to include any base paths\r\n        /// </summary>\r\n        /// <param name=\"path\">Path to expand</param>\r\n        /// <returns>Expanded path</returns>\r\n        string ExpandPath(string path);\r\n\r\n        /// <summary>\r\n        /// Get the anti forgery token form element\r\n        /// </summary>\r\n        /// <returns>String containing the form element</returns>\r\n        string AntiForgeryToken();\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/SuperSimpleViewEngine/NancyViewEngineHost.cs",
    "content": "namespace Nancy.ViewEngines.SuperSimpleViewEngine\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Nancy view engine host\r\n    /// </summary>\r\n    /// <seealso cref=\"Nancy.ViewEngines.SuperSimpleViewEngine.IViewEngineHost\" />\r\n    public class NancyViewEngineHost : IViewEngineHost\r\n    {\r\n        private IRenderContext renderContext;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancyViewEngineHost\"/> class, with\r\n        /// the provided <paramref name=\"renderContext\"/>.\r\n        /// </summary>\r\n        /// <param name=\"renderContext\">\r\n        /// The render context.\r\n        /// </param>\r\n        public NancyViewEngineHost(IRenderContext renderContext)\r\n        {\r\n            this.renderContext = renderContext;\r\n            this.Context = this.renderContext.Context;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Context object of the host application.\r\n        /// </summary>\r\n        /// <value>An instance of the context object from the host.</value>\r\n        public object Context { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Html \"safe\" encode a string\r\n        /// </summary>\r\n        /// <param name=\"input\">Input string</param>\r\n        /// <returns>Encoded string</returns>\r\n        public string HtmlEncode(string input)\r\n        {\r\n            return this.renderContext.HtmlEncode(input);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the contents of a template\r\n        /// </summary>\r\n        /// <param name=\"templateName\">Name/location of the template</param>\r\n        /// <param name=\"model\">Model to use to locate the template via conventions</param>\r\n        /// <returns>Contents of the template, or null if not found</returns>\r\n        public string GetTemplate(string templateName, object model)\r\n        {\r\n            var viewLocationResult = this.renderContext.LocateView(templateName, model);\r\n\r\n            if (viewLocationResult == null)\r\n            {\r\n                return \"[ERR!]\";\r\n            }\r\n\r\n            using(var reader = viewLocationResult.Contents.Invoke())\r\n                return reader.ReadToEnd();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a uri string for a named route\r\n        /// </summary>\r\n        /// <param name=\"name\">Named route name</param>\r\n        /// <param name=\"parameters\">Parameters to use to expand the uri string</param>\r\n        /// <returns>Expanded uri string, or null if not found</returns>\r\n        public string GetUriString(string name, params string[] parameters)\r\n        {\r\n            throw new NotImplementedException();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Expands a path to include any base paths\r\n        /// </summary>\r\n        /// <param name=\"path\">Path to expand</param>\r\n        /// <returns>Expanded path</returns>\r\n        public string ExpandPath(string path)\r\n        {\r\n            return this.renderContext.ParsePath(path);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the anti forgery token form element\r\n        /// </summary>\r\n        /// <returns>String containing the form element</returns>\r\n        public string AntiForgeryToken()\r\n        {\r\n            var tokenKeyValue = this.renderContext.GetCsrfToken();\r\n\r\n            return string.Format(\"<input type=\\\"hidden\\\" name=\\\"{0}\\\" value=\\\"{1}\\\" />\", tokenKeyValue.Key, tokenKeyValue.Value);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/SuperSimpleViewEngine/SuperSimpleViewEngine.cs",
    "content": "namespace Nancy.ViewEngines.SuperSimpleViewEngine\r\n{\r\n    using Microsoft.CSharp.RuntimeBinder;\r\n    using System;\r\n    using System.Collections;\r\n    using System.Collections.Generic;\r\n    using System.Dynamic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using System.Runtime.CompilerServices;\r\n    using System.Text.RegularExpressions;\r\n    using System.Text;\r\n\r\n    /// <summary>\r\n    /// A super-simple view engine\r\n    /// </summary>\r\n    public class SuperSimpleViewEngine\r\n    {\r\n        /// <summary>\r\n        /// Compiled Regex for viewbag substitutions\r\n        /// </summary>\r\n        private static readonly Regex ViewBagSubstitutionsRegEx = new Regex(@\"@(?<Encode>!)?ViewBag(?:\\.(?<ParameterName>[a-zA-Z0-9-_]+))*;?\", RegexOptions.Compiled);\r\n\r\n        /// <summary>\r\n        /// Compiled Regex for single substitutions\r\n        /// </summary>\r\n        private static readonly Regex SingleSubstitutionsRegEx = new Regex(@\"@(?<Encode>!)?Model(?:\\.(?<ParameterName>[a-zA-Z0-9-_]+))*;?\", RegexOptions.Compiled);\r\n\r\n        /// <summary>\r\n        /// Compiled Regex for context subsituations\r\n        /// </summary>\r\n        private static readonly Regex ContextSubstitutionsRegEx = new Regex(@\"@(?<Encode>!)?Context(?:\\.(?<ParameterName>[a-zA-Z0-9-_]+))*;?\", RegexOptions.Compiled);\r\n\r\n        /// <summary>\r\n        /// Compiled Regex for each blocks\r\n        /// </summary>\r\n        private static readonly Regex EachSubstitutionRegEx = new Regex(@\"@Each(?:\\.(?<ModelSource>(Model|Context)+))?(?:\\.(?<ParameterName>[a-zA-Z0-9-_]+))*;?(?<Contents>.*?)@EndEach;?\", RegexOptions.Compiled | RegexOptions.Singleline);\r\n\r\n        /// <summary>\r\n        /// Compiled Regex for each block current substitutions\r\n        /// </summary>\r\n        private static readonly Regex EachItemSubstitutionRegEx = new Regex(@\"@(?<Encode>!)?Current(?:\\.(?<ParameterName>[a-zA-Z0-9-_]+))*;?\", RegexOptions.Compiled);\r\n\r\n        /// <summary>\r\n        /// Compiled Regex for if blocks\r\n        /// </summary>\r\n        private const string ConditionalOpenSyntaxPattern = @\"@If(?<Not>Not)?(?<Null>Null)?(?:\\.(?<ModelSource>(Model|Context)+))?(?:\\.(?<ParameterName>[a-zA-Z0-9-_]+))+;?\";\r\n        private const string ConditionalOpenInnerSyntaxPattern = @\"@If(?:Not)?(?:Null)?(?:\\.(?:(Model|Context)+))?(?:\\.(?:[a-zA-Z0-9-_]+))+;?\";\r\n        private const string ConditionalCloseStynaxPattern = @\"@EndIf;?\";\r\n         \r\n        private static readonly string ConditionalSubstituionPattern =\r\n            string.Format(@\"{0}(?<Contents>:[.*]|(?>{2}(?<DEPTH>)|{1}(?<-DEPTH>)|.)*(?(DEPTH)(?!))){1}\", \r\n                            ConditionalOpenSyntaxPattern,\r\n                            ConditionalCloseStynaxPattern,\r\n                            ConditionalOpenInnerSyntaxPattern);\r\n\r\n        private static readonly Regex ConditionalSubstitutionRegEx = new Regex(ConditionalSubstituionPattern, RegexOptions.Compiled | RegexOptions.Singleline);\r\n\r\n        /// <summary>\r\n        /// Compiled regex for partial blocks\r\n        /// </summary>\r\n        private static readonly Regex PartialSubstitutionRegEx = new Regex(@\"@Partial\\['(?<ViewName>[^\\]]+)'(?:.[ ]?@?(?<Model>(Model|Current)(?:\\.(?<ParameterName>[a-zA-Z0-9-_]+))*))?\\];?\", RegexOptions.Compiled);\r\n\r\n        /// <summary>\r\n        /// Compiled RegEx for section block declarations\r\n        /// </summary>\r\n        private static readonly Regex SectionDeclarationRegEx = new Regex(@\"@Section\\[\\'(?<SectionName>.+?)\\'\\];?\", RegexOptions.Compiled);\r\n\r\n        /// <summary>\r\n        /// Compiled RegEx for section block contents\r\n        /// </summary>\r\n        private static readonly Regex SectionContentsRegEx = new Regex(@\"(?:@Section\\[\\'(?<SectionName>.+?)\\'\\];?(?<SectionContents>.*?)@EndSection;?)\", RegexOptions.Compiled | RegexOptions.Singleline);\r\n\r\n        /// <summary>\r\n        /// Compiled RegEx for master page declaration\r\n        /// </summary>\r\n        private static readonly Regex MasterPageHeaderRegEx = new Regex(@\"^(?:@Master\\[\\'(?<MasterPage>.+?)\\'\\]);?\", RegexOptions.Compiled);\r\n\r\n        /// <summary>\r\n        /// Compiled RegEx for path expansion\r\n        /// </summary>\r\n        private static readonly Regex PathExpansionRegEx = new Regex(@\"(?:@Path\\[\\'(?<Path>.+?)\\'\\]);?\", RegexOptions.Compiled);\r\n\r\n        /// <summary>\r\n        /// Compiled RegEx for path expansion in attribute values\r\n        /// </summary>\r\n        private static readonly Regex AttributeValuePathExpansionRegEx = new Regex(@\"(?<Attribute>[a-zA-Z]+)=(?<Quote>[\"\"'])(?<Path>~.+?)\\k<Quote>\", RegexOptions.Compiled);\r\n\r\n        /// <summary>\r\n        /// Compiled RegEx for the CSRF anti forgery token\r\n        /// </summary>\r\n        private static readonly Regex AntiForgeryTokenRegEx = new Regex(@\"@AntiForgeryToken;?\", RegexOptions.Compiled);\r\n\r\n        /// <summary>\r\n        /// View engine transform processors\r\n        /// </summary>\r\n        private readonly List<Func<string, object, IViewEngineHost, string>> processors;\r\n\r\n        /// <summary>\r\n        /// View engine extensions\r\n        /// </summary>\r\n        private readonly IEnumerable<ISuperSimpleViewEngineMatcher> matchers;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"SuperSimpleViewEngine\"/> class.\r\n        /// </summary>\r\n        public SuperSimpleViewEngine()\r\n            : this(Enumerable.Empty<ISuperSimpleViewEngineMatcher>())\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"SuperSimpleViewEngine\"/> class, using\r\n        /// the provided <see cref=\"ISuperSimpleViewEngineMatcher\"/> extensions.\r\n        /// </summary>\r\n        /// <param name=\"matchers\">The matchers to use with the engine.</param>\r\n        public SuperSimpleViewEngine(IEnumerable<ISuperSimpleViewEngineMatcher> matchers)\r\n        {\r\n            this.matchers = matchers ?? Enumerable.Empty<ISuperSimpleViewEngineMatcher>();\r\n\r\n            this.processors = new List<Func<string, object, IViewEngineHost, string>>\r\n            {\r\n                PerformViewBagSubstitutions,\r\n                PerformSingleSubstitutions,\r\n                PerformContextSubstitutions,\r\n                PerformEachSubstitutions,\r\n                PerformConditionalSubstitutions,\r\n                PerformPathSubstitutions,\r\n                PerformAntiForgeryTokenSubstitutions,\r\n                this.PerformPartialSubstitutions,\r\n                this.PerformMasterPageSubstitutions,\r\n            };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Renders a template\r\n        /// </summary>\r\n        /// <param name=\"template\">The template to render.</param>\r\n        /// <param name=\"model\">The model to user for rendering.</param>\r\n        /// <param name=\"host\">The view engine host</param>\r\n        /// <returns>A string containing the expanded template.</returns>\r\n        public string Render(string template, dynamic model, IViewEngineHost host)\r\n        {\r\n            var output =\r\n                this.processors.Aggregate(template, (current, processor) => processor(current, model ?? new object(), host));\r\n\r\n            return this.matchers.Aggregate(output, (current, extension) => extension.Invoke(current, model, host));\r\n        }\r\n\r\n        /// <summary>\r\n        /// <para>\r\n        /// Gets a property value from the given model.\r\n        /// </para>\r\n        /// <para>\r\n        /// Anonymous types, standard types and ExpandoObject are supported.\r\n        /// Arbitrary dynamics (implementing IDynamicMetaObjectProvider) are not, unless\r\n        /// they also implement IDictionary string, object for accessing properties.\r\n        /// </para>\r\n        /// </summary>\r\n        /// <param name=\"model\">The model.</param>\r\n        /// <param name=\"propertyName\">The property name to evaluate.</param>\r\n        /// <returns>Tuple - Item1 being a bool for whether the evaluation was successful, Item2 being the value.</returns>\r\n        /// <exception cref=\"ArgumentException\">Model type is not supported.</exception>\r\n        private static Tuple<bool, object> GetPropertyValue(object model, string propertyName)\r\n        {\r\n            if (model == null || string.IsNullOrEmpty(propertyName))\r\n            {\r\n                return new Tuple<bool, object>(false, null);\r\n            }\r\n\r\n            if (model is IDictionary<string, object>)\r\n            {\r\n                return DynamicDictionaryPropertyEvaluator(model, propertyName);\r\n            }\r\n\r\n            if (!(model is IDynamicMetaObjectProvider))\r\n            {\r\n                return StandardTypePropertyEvaluator(model, propertyName);\r\n            }\r\n\r\n            if (model is DynamicDictionaryValue)\r\n            {\r\n                var dynamicModel = model as DynamicDictionaryValue;\r\n\r\n                return GetPropertyValue(dynamicModel.Value, propertyName);\r\n            }\r\n\r\n            if (model is DynamicObject)\r\n            {\r\n                return GetDynamicMember(model, propertyName);\r\n            }\r\n\r\n            throw new ArgumentException(\"model must be a standard type or implement IDictionary<string, object>\", \"model\");\r\n        }\r\n\r\n        private static Tuple<bool, object> GetDynamicMember(object obj, string memberName)\r\n        {\r\n            var binder = Microsoft.CSharp.RuntimeBinder.Binder.GetMember(CSharpBinderFlags.None, memberName, obj.GetType(),\r\n                new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });\r\n\r\n            var callsite = CallSite<Func<CallSite, object, object>>.Create(binder);\r\n\r\n            var result = callsite.Target(callsite, obj);\r\n\r\n            return result == null ? new Tuple<bool, object>(false, null) : new Tuple<bool, object>(true, result);\r\n        }\r\n\r\n        /// <summary>\r\n        /// A property extractor for standard types.\r\n        /// </summary>\r\n        /// <param name=\"model\">The model.</param>\r\n        /// <param name=\"propertyName\">The property name.</param>\r\n        /// <returns>Tuple - Item1 being a bool for whether the evaluation was successful, Item2 being the value.</returns>\r\n        private static Tuple<bool, object> StandardTypePropertyEvaluator(object model, string propertyName)\r\n        {\r\n            var type = model.GetType();\r\n            var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);\r\n\r\n            var property =\r\n                properties.Where(p => string.Equals(p.Name, propertyName, StringComparison.Ordinal)).\r\n                FirstOrDefault();\r\n\r\n            if (property != null)\r\n            {\r\n                return new Tuple<bool, object>(true, property.GetValue(model, null));\r\n            }\r\n\r\n            var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);\r\n\r\n            var field =\r\n                fields.Where(p => string.Equals(p.Name, propertyName, StringComparison.Ordinal)).\r\n                FirstOrDefault();\r\n\r\n            return field == null ? new Tuple<bool, object>(false, null) : new Tuple<bool, object>(true, field.GetValue(model));\r\n        }\r\n\r\n        /// <summary>\r\n        /// A property extractor designed for ExpandoObject, but also for any\r\n        /// type that implements IDictionary string object for accessing its\r\n        /// properties.\r\n        /// </summary>\r\n        /// <param name=\"model\">The model.</param>\r\n        /// <param name=\"propertyName\">The property name.</param>\r\n        /// <returns>Tuple - Item1 being a bool for whether the evaluation was successful, Item2 being the value.</returns>\r\n        private static Tuple<bool, object> DynamicDictionaryPropertyEvaluator(object model, string propertyName)\r\n        {\r\n            var dictionaryModel = (IDictionary<string, object>)model;\r\n\r\n            object output;\r\n            return !dictionaryModel.TryGetValue(propertyName, out output) ? new Tuple<bool, object>(false, null) : new Tuple<bool, object>(true, output);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets an IEnumerable of capture group values\r\n        /// </summary>\r\n        /// <param name=\"m\">The match to use.</param>\r\n        /// <param name=\"groupName\">Group name containing the capture group.</param>\r\n        /// <returns>IEnumerable of capture group values as strings.</returns>\r\n        private static IEnumerable<string> GetCaptureGroupValues(Match m, string groupName)\r\n        {\r\n            return m.Groups[groupName].Captures.Cast<Capture>().Select(c => c.Value);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a property value from a collection of nested parameter names\r\n        /// </summary>\r\n        /// <param name=\"model\">The model containing properties.</param>\r\n        /// <param name=\"parameters\">A collection of nested parameters (e.g. User, Name</param>\r\n        /// <returns>Tuple - Item1 being a bool for whether the evaluation was successful, Item2 being the value.</returns>\r\n        private static Tuple<bool, object> GetPropertyValueFromParameterCollection(object model, IEnumerable<string> parameters)\r\n        {\r\n            if (parameters == null)\r\n            {\r\n                return new Tuple<bool, object>(true, model);\r\n            }\r\n\r\n            var currentObject = model;\r\n\r\n            foreach (var parameter in parameters)\r\n            {\r\n                var currentResult = GetPropertyValue(currentObject, parameter);\r\n\r\n                if (currentResult.Item1 == false)\r\n                {\r\n                    return new Tuple<bool, object>(false, null);\r\n                }\r\n\r\n                currentObject = currentResult.Item2;\r\n            }\r\n\r\n            return new Tuple<bool, object>(true, currentObject);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the predicate result for an If or IfNot block\r\n        /// </summary>\r\n        /// <param name=\"item\">The item to evaluate</param>\r\n        /// <param name=\"properties\">Property list to evaluate</param>\r\n        /// <param name=\"nullCheck\">Whether to check for null, rather than straight boolean</param>\r\n        /// <returns>Bool representing the predicate result</returns>\r\n        private static bool GetPredicateResult(object item, IEnumerable<string> properties, bool nullCheck)\r\n        {\r\n            var substitutionObject = GetPropertyValueFromParameterCollection(item, properties);\r\n\r\n            if (substitutionObject.Item1 == false && properties.Last().StartsWith(\"Has\"))\r\n            {\r\n                var newProperties =\r\n                    properties.Take(properties.Count() - 1).Concat(new[] { properties.Last().Substring(3) });\r\n\r\n                substitutionObject = GetPropertyValueFromParameterCollection(item, newProperties);\r\n\r\n                return GetHasPredicateResultFromSubstitutionObject(substitutionObject.Item2);\r\n            }\r\n\r\n            return GetPredicateResultFromSubstitutionObject(substitutionObject.Item2, nullCheck);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns the predicate result if the substitionObject is a valid bool\r\n        /// </summary>\r\n        /// <param name=\"substitutionObject\">The substitution object.</param>\r\n        /// <param name=\"nullCheck\"></param>\r\n        /// <returns>Bool value of the substitutionObject, or false if unable to cast.</returns>\r\n        private static bool GetPredicateResultFromSubstitutionObject(object substitutionObject, bool nullCheck)\r\n        {\r\n            if (nullCheck)\r\n            {\r\n                return substitutionObject == null;\r\n            }\r\n\r\n            if (substitutionObject != null && substitutionObject.GetType().GetProperty(\"Value\") != null)\r\n            {\r\n                object value = ((dynamic)substitutionObject).Value;\r\n\r\n                if (value is bool?)\r\n                {\r\n                    substitutionObject = value;\r\n                }\r\n            }\r\n\r\n            var predicateResult = false;\r\n            var substitutionBool = substitutionObject as bool?;\r\n            if (substitutionBool != null)\r\n            {\r\n                predicateResult = substitutionBool.Value;\r\n            }\r\n\r\n            return predicateResult;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns the predicate result if the substitionObject is a valid ICollection\r\n        /// </summary>\r\n        /// <param name=\"substitutionObject\">The substitution object.</param>\r\n        /// <returns>Bool value of the whether the ICollection has items, or false if unable to cast.</returns>\r\n        private static bool GetHasPredicateResultFromSubstitutionObject(object substitutionObject)\r\n        {\r\n            var predicateResult = false;\r\n\r\n            var substitutionCollection = substitutionObject as ICollection;\r\n            if (substitutionCollection != null)\r\n            {\r\n                predicateResult = substitutionCollection.Count != 0;\r\n            }\r\n\r\n            return predicateResult;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs single @ViewBag.PropertyName substitutions.\r\n        /// </summary>\r\n        /// <param name=\"template\">The template.</param>\r\n        /// <param name=\"model\">This parameter is not used, the model is based on the \"host.Context.ViewBag\".</param>\r\n        /// <param name=\"host\">View engine host</param>\r\n        /// <returns>Template with @ViewBag.PropertyName blocks expanded.</returns>\r\n        private static string PerformViewBagSubstitutions(string template, object model, IViewEngineHost host)\r\n        {\r\n            return ViewBagSubstitutionsRegEx.Replace(\r\n                template,\r\n                m =>\r\n                {\r\n                    var properties = GetCaptureGroupValues(m, \"ParameterName\");\r\n\r\n                    var substitution = GetPropertyValueFromParameterCollection(((dynamic)host.Context).ViewBag, properties);\r\n\r\n                    if (!substitution.Item1)\r\n                    {\r\n                        return \"[ERR!]\";\r\n                    }\r\n\r\n                    if (substitution.Item2 == null)\r\n                    {\r\n                        return string.Empty;\r\n                    }\r\n\r\n                    return m.Groups[\"Encode\"].Success ? host.HtmlEncode(substitution.Item2.ToString()) : substitution.Item2.ToString();\r\n                });\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs single @Model.PropertyName substitutions.\r\n        /// </summary>\r\n        /// <param name=\"template\">The template.</param>\r\n        /// <param name=\"model\">The model.</param>\r\n        /// <param name=\"host\">View engine host</param>\r\n        /// <returns>Template with @Model.PropertyName blocks expanded.</returns>\r\n        private static string PerformSingleSubstitutions(string template, object model, IViewEngineHost host)\r\n        {\r\n            return SingleSubstitutionsRegEx.Replace(\r\n                template,\r\n                m =>\r\n                {\r\n                    var properties = GetCaptureGroupValues(m, \"ParameterName\");\r\n\r\n                    var substitution = GetPropertyValueFromParameterCollection(model, properties);\r\n\r\n                    if (!substitution.Item1)\r\n                    {\r\n                        return \"[ERR!]\";\r\n                    }\r\n\r\n                    if (substitution.Item2 == null)\r\n                    {\r\n                        return string.Empty;\r\n                    }\r\n\r\n                    return m.Groups[\"Encode\"].Success ? host.HtmlEncode(substitution.Item2.ToString()) : substitution.Item2.ToString();\r\n                });\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs single @Context.PropertyName substitutions.\r\n        /// </summary>\r\n        /// <param name=\"template\">The template.</param>\r\n        /// <param name=\"model\">The model.</param>\r\n        /// <param name=\"host\">View engine host</param>\r\n        /// <returns>Template with @Context.PropertyName blocks expanded.</returns>\r\n        private static string PerformContextSubstitutions(string template, object model, IViewEngineHost host)\r\n        {\r\n            return ContextSubstitutionsRegEx.Replace(\r\n                template,\r\n                m =>\r\n                {\r\n                    var properties = GetCaptureGroupValues(m, \"ParameterName\");\r\n\r\n                    var substitution = GetPropertyValueFromParameterCollection(host.Context, properties);\r\n\r\n                    if (!substitution.Item1)\r\n                    {\r\n                        return \"[ERR!]\";\r\n                    }\r\n\r\n                    if (substitution.Item2 == null)\r\n                    {\r\n                        return string.Empty;\r\n                    }\r\n\r\n                    return m.Groups[\"Encode\"].Success ? host.HtmlEncode(substitution.Item2.ToString()) : substitution.Item2.ToString();\r\n                });\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs @Each.PropertyName substitutions\r\n        /// </summary>\r\n        /// <param name=\"template\">The template.</param>\r\n        /// <param name=\"model\">The model.</param>\r\n        /// <param name=\"host\">View engine host</param>\r\n        /// <returns>Template with @Each.PropertyName blocks expanded.</returns>\r\n        private string PerformEachSubstitutions(string template, object model, IViewEngineHost host)\r\n        {\r\n            return EachSubstitutionRegEx.Replace(\r\n                template,\r\n                m =>\r\n                {\r\n                    var properties = GetCaptureGroupValues(m, \"ParameterName\");\r\n\r\n                    var modelSource = GetCaptureGroupValues(m, \"ModelSource\").SingleOrDefault();\r\n\r\n                    if (modelSource != null && modelSource.Equals(\"Context\", StringComparison.OrdinalIgnoreCase))\r\n                    {\r\n                        model = host.Context;\r\n                    }\r\n\r\n                    var substitutionObject = GetPropertyValueFromParameterCollection(model, properties);\r\n\r\n                    if (substitutionObject.Item1 == false)\r\n                    {\r\n                        return \"[ERR!]\";\r\n                    }\r\n\r\n                    if (substitutionObject.Item2 == null)\r\n                    {\r\n                        return string.Empty;\r\n                    }\r\n\r\n                    var substitutionEnumerable = substitutionObject.Item2 as IEnumerable;\r\n                    if (substitutionEnumerable == null)\r\n                    {\r\n                        return \"[ERR!]\";\r\n                    }\r\n\r\n                    var contents = m.Groups[\"Contents\"].Value;\r\n\r\n                    var result = new StringBuilder();\r\n                    foreach (var item in substitutionEnumerable)\r\n                    {\r\n                        var modifiedContent = PerformPartialSubstitutions(contents, item, host);\r\n                        modifiedContent = PerformConditionalSubstitutions(modifiedContent, item, host);\r\n                        result.Append(ReplaceCurrentMatch(modifiedContent, item, host));\r\n                    }\r\n\r\n                    return result.ToString();\r\n                });\r\n        }\r\n\r\n        /// <summary>\r\n        /// Expand a @Current match inside an @Each iterator\r\n        /// </summary>\r\n        /// <param name=\"contents\">Contents of the @Each block</param>\r\n        /// <param name=\"item\">Current item from the @Each enumerable</param>\r\n        /// <param name=\"host\">View engine host</param>\r\n        /// <returns>String result of the expansion of the @Each.</returns>\r\n        private static string ReplaceCurrentMatch(string contents, object item, IViewEngineHost host)\r\n        {\r\n            return EachItemSubstitutionRegEx.Replace(\r\n                contents,\r\n                eachMatch =>\r\n                {\r\n                    if (string.IsNullOrEmpty(eachMatch.Groups[\"ParameterName\"].Value))\r\n                    {\r\n                        return eachMatch.Groups[\"Encode\"].Success ? host.HtmlEncode(item.ToString()) : item.ToString();\r\n                    }\r\n\r\n                    var properties = GetCaptureGroupValues(eachMatch, \"ParameterName\");\r\n\r\n                    var substitution = GetPropertyValueFromParameterCollection(item, properties);\r\n\r\n                    if (!substitution.Item1)\r\n                    {\r\n                        return \"[ERR!]\";\r\n                    }\r\n\r\n                    if (substitution.Item2 == null)\r\n                    {\r\n                        return string.Empty;\r\n                    }\r\n\r\n                    return eachMatch.Groups[\"Encode\"].Success ? host.HtmlEncode(substitution.Item2.ToString()) : substitution.Item2.ToString();\r\n                });\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs @If.PropertyName and @IfNot.PropertyName substitutions\r\n        /// </summary>\r\n        /// <param name=\"template\">The template.</param>\r\n        /// <param name=\"model\">The model.</param>\r\n        /// <param name=\"host\">View engine host</param>\r\n        /// <returns>Template with @If.PropertyName @IfNot.PropertyName blocks removed/expanded.</returns>\r\n        private static string PerformConditionalSubstitutions(string template, object model, IViewEngineHost host)\r\n        {\r\n            var result = template;\r\n\r\n            result = ConditionalSubstitutionRegEx.Replace(\r\n                result,\r\n                m =>\r\n                {\r\n                    var properties = GetCaptureGroupValues(m, \"ParameterName\");\r\n\r\n                    var modelSource = GetCaptureGroupValues(m, \"ModelSource\").SingleOrDefault();\r\n\r\n                    if (modelSource != null && modelSource.Equals(\"Context\", StringComparison.OrdinalIgnoreCase))\r\n                    {\r\n                        model = host.Context;\r\n                    }\r\n\r\n                    var predicateResult = GetPredicateResult(model, properties, m.Groups[\"Null\"].Value == \"Null\");\r\n\r\n                    if (m.Groups[\"Not\"].Value == \"Not\")\r\n                    {\r\n                        predicateResult = !predicateResult;\r\n                    }\r\n\r\n                    return predicateResult ? PerformConditionalSubstitutions(m.Groups[\"Contents\"].Value, model, host) : string.Empty;\r\n                });\r\n\r\n            return result;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Perform path expansion substitutions\r\n        /// </summary>\r\n        /// <param name=\"template\">The template.</param>\r\n        /// <param name=\"model\">The model.</param>\r\n        /// <param name=\"host\">View engine host</param>\r\n        /// <returns>Template with paths expanded</returns>\r\n        private static string PerformPathSubstitutions(string template, object model, IViewEngineHost host)\r\n        {\r\n            var result = template;\r\n\r\n            result = PathExpansionRegEx.Replace(\r\n                result,\r\n                m =>\r\n                {\r\n                    var path = m.Groups[\"Path\"].Value;\r\n\r\n                    return host.ExpandPath(path);\r\n                });\r\n\r\n            result = AttributeValuePathExpansionRegEx.Replace(\r\n                result, \r\n                m =>\r\n                {\r\n                    var attribute = m.Groups[\"Attribute\"];\r\n                    var quote = m.Groups[\"Quote\"].Value;\r\n                    var path = m.Groups[\"Path\"].Value;\r\n\r\n                    var expandedPath = host.ExpandPath(path);\r\n                \r\n                    return string.Format(\"{0}={1}{2}{1}\", attribute, quote, expandedPath);\r\n                });\r\n\r\n            return result;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Perform CSRF anti forgery token expansions\r\n        /// </summary>\r\n        /// <param name=\"template\">The template.</param>\r\n        /// <param name=\"model\">The model.</param>\r\n        /// <param name=\"host\">View engine host</param>\r\n        /// <returns>Template with anti forgery tokens expanded</returns>\r\n        private static string PerformAntiForgeryTokenSubstitutions(string template, object model, IViewEngineHost host)\r\n        {\r\n            return AntiForgeryTokenRegEx.Replace(template, x => host.AntiForgeryToken());\r\n        }\r\n\r\n        /// <summary>\r\n        /// Perform @Partial partial view expansion\r\n        /// </summary>\r\n        /// <param name=\"template\">The template.</param>\r\n        /// <param name=\"model\">The model.</param>\r\n        /// <param name=\"host\">View engine host</param>\r\n        /// <returns>Template with partials expanded</returns>\r\n        private string PerformPartialSubstitutions(string template, dynamic model, IViewEngineHost host)\r\n        {\r\n            var result = template;\r\n\r\n            result = PartialSubstitutionRegEx.Replace(\r\n                result,\r\n                m =>\r\n                {\r\n                    var partialViewName = ReplaceCurrentMatch(m.Groups[\"ViewName\"].Value, model, host);\r\n                    var partialModel = model;\r\n                    var properties = GetCaptureGroupValues(m, \"ParameterName\");\r\n\r\n                    if (m.Groups[\"Model\"].Length > 0)\r\n                    {\r\n                        var modelValue = GetPropertyValueFromParameterCollection(partialModel, properties);\r\n\r\n                        if (modelValue.Item1 != true)\r\n                        {\r\n                            return \"[ERR!]\";\r\n                        }\r\n\r\n                        partialModel = modelValue.Item2;\r\n                    }\r\n\r\n                    var partialTemplate = host.GetTemplate(partialViewName, partialModel);\r\n\r\n                    return this.Render(partialTemplate, partialModel, host);\r\n                });\r\n\r\n            return result;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Invokes the master page rendering with current sections if necessary\r\n        /// </summary>\r\n        /// <param name=\"template\">The template.</param>\r\n        /// <param name=\"model\">The model.</param>\r\n        /// <param name=\"host\">View engine host</param>\r\n        /// <returns>Template with master page applied and sections substituted</returns>\r\n        private string PerformMasterPageSubstitutions(string template, object model, IViewEngineHost host)\r\n        {\r\n            var masterPageName = GetMasterPageName(template);\r\n\r\n            if (string.IsNullOrWhiteSpace(masterPageName))\r\n            {\r\n                return template;\r\n            }\r\n\r\n            var masterTemplate = host.GetTemplate(masterPageName, model);\r\n            var sectionMatches = SectionContentsRegEx.Matches(template);\r\n            var sections = sectionMatches.Cast<Match>().ToDictionary(sectionMatch => sectionMatch.Groups[\"SectionName\"].Value, sectionMatch => sectionMatch.Groups[\"SectionContents\"].Value);\r\n\r\n            return this.RenderMasterPage(masterTemplate, sections, model, host);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Renders a master page - does a normal render then replaces any section tags with sections passed in\r\n        /// </summary>\r\n        /// <param name=\"masterTemplate\">The master page template</param>\r\n        /// <param name=\"sections\">Dictionary of section contents</param>\r\n        /// <param name=\"model\">The model.</param>\r\n        /// <param name=\"host\">View engine host</param>\r\n        /// <returns>Template with the master page applied and sections substituted</returns>\r\n        private string RenderMasterPage(string masterTemplate, IDictionary<string, string> sections, object model, IViewEngineHost host)\r\n        {\r\n            var result = this.Render(masterTemplate, model, host);\r\n\r\n            result = SectionDeclarationRegEx.Replace(\r\n                result,\r\n                m =>\r\n                {\r\n                    var sectionName = m.Groups[\"SectionName\"].Value;\r\n                    string sectionValue;\r\n                    return sections.TryGetValue(sectionName, out sectionValue) ? sectionValue : string.Empty;\r\n                });\r\n\r\n            return result;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the master page name, if one is specified\r\n        /// </summary>\r\n        /// <param name=\"template\">The template</param>\r\n        /// <returns>Master page name or String.Empty</returns>\r\n        private static string GetMasterPageName(string template)\r\n        {\r\n            using (var stringReader = new StringReader(template))\r\n            {\r\n                var firstLine = stringReader.ReadLine();\r\n\r\n                if (firstLine == null)\r\n                {\r\n                    return string.Empty;\r\n                }\r\n\r\n                var masterPageMatch = MasterPageHeaderRegEx.Match(firstLine);\r\n\r\n                return masterPageMatch.Success ? masterPageMatch.Groups[\"MasterPage\"].Value : string.Empty;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/ViewEngines/SuperSimpleViewEngine/SuperSimpleViewEngineRegistrations.cs",
    "content": "﻿namespace Nancy.ViewEngines.SuperSimpleViewEngine\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using Nancy.Bootstrapper;\r\n\r\n    /// <summary>\r\n    /// Performs application registrations for the SuperSimpleViewEngine.\r\n    /// </summary>\r\n    public class SuperSimpleViewEngineRegistrations : IRegistrations\r\n    {\r\n        private readonly ITypeCatalog typeCatalog;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the\r\n        /// <see cref=\"Nancy.ViewEngines.SuperSimpleViewEngine.SuperSimpleViewEngineRegistrations\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"typeCatalog\">Type catalog.</param>\r\n        public SuperSimpleViewEngineRegistrations (ITypeCatalog typeCatalog)\r\n        {\r\n            this.typeCatalog = typeCatalog;\r\n        }\r\n    \r\n        /// <summary>\r\n        /// Gets the type registrations to register for this startup task\r\n        /// </summary>\r\n        public IEnumerable<TypeRegistration> TypeRegistrations\r\n        {\r\n            get { return null; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the collection registrations to register for this startup task\r\n        /// </summary>\r\n        public IEnumerable<CollectionTypeRegistration> CollectionTypeRegistrations\r\n        {\r\n            get\r\n            {\r\n                return new[] {\r\n                    new CollectionTypeRegistration(typeof(ISuperSimpleViewEngineMatcher), this.typeCatalog.GetTypesAssignableTo<ISuperSimpleViewEngineMatcher>())\r\n                };\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the instance registrations to register for this startup task\r\n        /// </summary>\r\n        public IEnumerable<InstanceRegistration> InstanceRegistrations\r\n        {\r\n            get { return null; }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/SuperSimpleViewEngine/SuperSimpleViewEngineWrapper.cs",
    "content": "﻿namespace Nancy.ViewEngines.SuperSimpleViewEngine\r\n{\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n\r\n    using Nancy.Responses;\r\n\r\n    /// <summary>\r\n    /// Nancy IViewEngine wrapper for the super simple view engine\r\n    /// </summary>\r\n    public class SuperSimpleViewEngineWrapper : IViewEngine\r\n    {\r\n        /// <summary>\r\n        /// Extensions that the view engine supports\r\n        /// </summary>\r\n        private readonly string[] extensions = new[] { \"sshtml\", \"html\", \"htm\" };\r\n\r\n        /// <summary>\r\n        /// The engine itself\r\n        /// </summary>\r\n        private readonly SuperSimpleViewEngine viewEngine;\r\n\r\n        /// <summary>\r\n        /// Gets the extensions file extensions that are supported by the view engine.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> instance containing the extensions.</value>\r\n        /// <remarks>The extensions should not have a leading dot in the name.</remarks>\r\n        public IEnumerable<string> Extensions\r\n        {\r\n            get { return this.extensions; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"SuperSimpleViewEngineWrapper\"/> class, using\r\n        /// the provided <see cref=\"ISuperSimpleViewEngineMatcher\"/> extensions.\r\n        /// </summary>\r\n        /// <param name=\"matchers\">The matchers to use with the engine.</param>\r\n        public SuperSimpleViewEngineWrapper(IEnumerable<ISuperSimpleViewEngineMatcher> matchers)\r\n        {\r\n            this.viewEngine = new SuperSimpleViewEngine(matchers);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initialise the view engine (if necessary)\r\n        /// </summary>\r\n        /// <param name=\"viewEngineStartupContext\">Startup context</param>\r\n        public void Initialize(ViewEngineStartupContext viewEngineStartupContext)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Renders the view.\r\n        /// </summary>\r\n        /// <param name=\"viewLocationResult\">A <see cref=\"ViewLocationResult\"/> instance, containing information on how to get the view template.</param>\r\n        /// <param name=\"model\">The model that should be passed into the view</param>\r\n        /// <param name=\"renderContext\">An <see cref=\"IRenderContext\"/> instance.</param>\r\n        /// <returns>A response</returns>\r\n        public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)\r\n        {\r\n            return new HtmlResponse(contents: s =>\r\n            {\r\n                var writer = new StreamWriter(s);\r\n                var templateContents = renderContext.ViewCache.GetOrAdd(viewLocationResult, vr =>\r\n                {\r\n                    using (var reader = vr.Contents.Invoke())\r\n                        return reader.ReadToEnd();\r\n                });\r\n\r\n                writer.Write(this.viewEngine.Render(templateContents, model, new NancyViewEngineHost(renderContext)));\r\n                writer.Flush();\r\n            });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/ViewEngineApplicationStartup.cs",
    "content": "namespace Nancy.ViewEngines\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using Nancy.Bootstrapper;\r\n\r\n    /// <summary>\r\n    /// Calls the initialize method on all <see cref=\"IViewEngine\"/> implementations, at application startup.\r\n    /// </summary>\r\n    public class ViewEngineApplicationStartup : IApplicationStartup\r\n    {\r\n        private readonly IEnumerable<IViewEngine> viewEngines;\r\n        private readonly IViewCache viewCache;\r\n        private readonly IViewLocator viewLocator;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ViewEngineApplicationStartup\"/> class, with the\r\n        /// provided <paramref name=\"viewEngines\"/>, <paramref name=\"viewCache\"/> and <paramref name=\"viewLocator\"/>.\r\n        /// </summary>\r\n        /// <param name=\"viewEngines\">The available view engines.</param>\r\n        /// <param name=\"viewCache\">The view cache.</param>\r\n        /// <param name=\"viewLocator\">The view locator.</param>\r\n        public ViewEngineApplicationStartup(IEnumerable<IViewEngine> viewEngines, IViewCache viewCache, IViewLocator viewLocator)\r\n        {\r\n            this.viewEngines = viewEngines;\r\n            this.viewCache = viewCache;\r\n            this.viewLocator = viewLocator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Perform any initialisation tasks\r\n        /// </summary>\r\n        /// <param name=\"pipelines\">Application pipelines</param>\r\n        public void Initialize(IPipelines pipelines)\r\n        {\r\n            foreach (var viewEngine in viewEngines)\r\n            {\r\n                viewEngine.Initialize(CreateViewEngineStartupContext(viewEngine));\r\n            }\r\n        }\r\n\r\n        private ViewEngineStartupContext CreateViewEngineStartupContext(IViewEngine viewEngine)\r\n        {\r\n            return new ViewEngineStartupContext(\r\n                this.viewCache,\r\n                this.viewLocator);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/ViewEngineStartupContext.cs",
    "content": "﻿namespace Nancy.ViewEngines\r\n{\r\n    /// <summary>\r\n    /// Context passed to each view engine on startup\r\n    /// </summary>\r\n    public class ViewEngineStartupContext\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ViewEngineStartupContext\"/> class, with\r\n        /// the provided <paramref name=\"viewCache\"/> and <paramref name=\"viewLocator\"/>.\r\n        /// </summary>\r\n        /// <param name=\"viewCache\">The view cache.</param>\r\n        /// <param name=\"viewLocator\">The view locator.</param>\r\n        public ViewEngineStartupContext(IViewCache viewCache, IViewLocator viewLocator)\r\n        {\r\n            this.ViewLocator = viewLocator;\r\n            this.ViewCache = viewCache;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the Nancy view cache - can be used to precompile views at startup\r\n        /// if necessary.\r\n        /// </summary>\r\n        public IViewCache ViewCache { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the Nancy view locator\r\n        /// </summary>\r\n        public IViewLocator ViewLocator { get; private set; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/ViewLocationContext.cs",
    "content": "namespace Nancy.ViewEngines\r\n{\r\n    /// <summary>\r\n    /// The context for which a view is being located.\r\n    /// </summary>\r\n    public class ViewLocationContext\r\n    {\r\n        /// <summary>\r\n        /// The module path of the <see cref=\"INancyModule\"/> that is locating a view.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the module path.</value>\r\n        public string ModulePath { get; set; }\r\n\r\n        /// <summary>\r\n        /// The name of the <see cref=\"INancyModule\"/> that is locating a view.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the name of the module.</value>\r\n        public string ModuleName { get; set; }\r\n\r\n        /// <summary>\r\n        /// The request/response context\r\n        /// </summary>\r\n        public NancyContext Context{ get; set; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/ViewLocationResult.cs",
    "content": "﻿namespace Nancy.ViewEngines\r\n{\r\n    using System;\r\n    using System.IO;\r\n\r\n    /// <summary>\r\n    /// Contains the result of an attempt to locate a view.\r\n    /// </summary>\r\n    public class ViewLocationResult : IEquatable<ViewLocationResult>\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ViewLocationResult\"/> class.\r\n        /// </summary>\r\n        protected ViewLocationResult()\r\n        {\r\n\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ViewLocationResult\"/> class, with\r\n        /// the provided <paramref name=\"location\"/>, <paramref name=\"name\"/>, \r\n        /// <paramref name=\"extension\"/> and <paramref name=\"contents\"/>.\r\n        /// </summary>\r\n        /// <param name=\"location\">The location of where the view was found.</param>\r\n        /// <param name=\"name\">The name of the view.</param>\r\n        /// <param name=\"extension\">The file extension of the located view.</param>\r\n        /// <param name=\"contents\">A <see cref=\"TextReader\"/> that can be used to read the contents of the located view.</param>\r\n        public ViewLocationResult(string location, string name, string extension, Func<TextReader> contents)\r\n        {\r\n            this.Location = location;\r\n            this.Name = name;\r\n            this.Extension = extension;\r\n            this.Contents = contents;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a function that produces a reader for retrieving the contents of the view.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"Func{T}\"/> instance that can be used to produce a reader for retrieving the contents of the view.</value>\r\n        public Func<TextReader> Contents { get; protected set; }\r\n\r\n        /// <summary>\r\n        /// Gets the extension of the view that was located.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the extension of the view that was located.</value>\r\n        /// <remarks>The extension should not contain a leading dot.</remarks>\r\n        public string Extension { get; protected set; }\r\n\r\n        /// <summary>\r\n        /// Gets the location of where the view was found.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the location of the view.</value>\r\n        public string Location { get; protected set; }\r\n\r\n        /// <summary>\r\n        /// Gets the full name of the view that was found\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the name of the view.</value>\r\n        public string Name { get; protected set; }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether the current item is stale\r\n        /// </summary>\r\n        /// <returns>True if stale, false otherwise</returns>\r\n        public virtual bool IsStale()\r\n        {\r\n            return false;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Indicates whether the current object is equal to another object of the same type.\r\n        /// </summary>\r\n        /// <returns><see langword=\"true\"/> if the current object is equal to the <paramref name=\"other\"/> parameter; otherwise, <see langword=\"false\"/>.</returns>\r\n        /// <param name=\"other\">An <see cref=\"ViewLocationResult\"/> to compare with this instance.</param>\r\n        public bool Equals(ViewLocationResult other)\r\n        {\r\n            if (ReferenceEquals(null, other)) return false;\r\n            if (ReferenceEquals(this, other)) return true;\r\n            return Equals(other.Extension, Extension) && Equals(other.Location, Location) && Equals(other.Name, Name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determines whether the specified <see cref=\"object\"/> is equal to the current <see cref=\"object\"/>.\r\n        /// </summary>\r\n        /// <returns><see langword=\"true\"/> if the specified <see cref=\"object\"/> is equal to the current <see cref=\"object\"/>; otherwise, <see langword=\"false\"/>.</returns>\r\n        /// <param name=\"obj\">The <see cref=\"object\"/> to compare with the current <see cref=\"object\"/>.</param>\r\n        public override bool Equals(object obj)\r\n        {\r\n            if (ReferenceEquals(null, obj)) return false;\r\n            if (ReferenceEquals(this, obj)) return true;\r\n            return obj.GetType() == typeof (ViewLocationResult) && Equals((ViewLocationResult) obj);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Serves as a hash function for a particular type.\r\n        /// </summary>\r\n        /// <returns>A hash code for the current <see cref=\"ViewLocationResult\"/>.</returns>\r\n        public override int GetHashCode()\r\n        {\r\n            unchecked\r\n            {\r\n                var result = Extension.GetHashCode();\r\n                result = (result*397) ^ Location.GetHashCode();\r\n                result = (result*397) ^ Name.GetHashCode();\r\n                return result;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Implements the operator ==.\r\n        /// </summary>\r\n        /// <param name=\"left\">The left.</param>\r\n        /// <param name=\"right\">The right.</param>\r\n        /// <returns>\r\n        /// The result of the operator.\r\n        /// </returns>\r\n        public static bool operator ==(ViewLocationResult left, ViewLocationResult right)\r\n        {\r\n            return Equals(left, right);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Implements the operator !=.\r\n        /// </summary>\r\n        /// <param name=\"left\">The left.</param>\r\n        /// <param name=\"right\">The right.</param>\r\n        /// <returns>\r\n        /// The result of the operator.\r\n        /// </returns>\r\n        public static bool operator !=(ViewLocationResult left, ViewLocationResult right)\r\n        {\r\n            return !Equals(left, right);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/ViewNotFoundException.cs",
    "content": "﻿namespace Nancy.ViewEngines\r\n{\r\n    using System;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Exception that is thrown when a view could not be located.\r\n    /// </summary>\r\n    public class ViewNotFoundException : Exception\r\n    {\r\n        private readonly IRootPathProvider rootPathProvider;\r\n\r\n        /// <summary>\r\n        /// Gets the name of the view.\r\n        /// </summary>\r\n        /// <value>\r\n        /// The name of the view.\r\n        /// </value>\r\n        public string ViewName { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the available view engine extensions.\r\n        /// </summary>\r\n        /// <value>\r\n        /// The available view engine extensions.\r\n        /// </value>\r\n        public string[] AvailableViewEngineExtensions { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the inspected locations.\r\n        /// </summary>\r\n        /// <value>\r\n        /// The inspected locations.\r\n        /// </value>\r\n        public string[] InspectedLocations { get; private set; }\r\n\r\n        private string message;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ViewNotFoundException\"/>, with\r\n        /// the provided <paramref name=\"viewName\"/>, <paramref name=\"availableViewEngineExtensions\"/>,\r\n        /// <paramref name=\"inspectedLocations\"/> and <paramref name=\"rootPathProvider\"/>.\r\n        /// </summary>\r\n        /// <param name=\"viewName\">The name of the view that was being located.</param>\r\n        /// <param name=\"availableViewEngineExtensions\">List of available view extensions that can be rendered by the available view engines.</param>\r\n        /// <param name=\"inspectedLocations\">The locations that were inspected for the view.</param>\r\n        /// <param name=\"rootPathProvider\">An <see cref=\"IRootPathProvider\"/> instance.</param>\r\n        public ViewNotFoundException(string viewName, string[] availableViewEngineExtensions, string[] inspectedLocations, IRootPathProvider rootPathProvider)\r\n        {\r\n            this.rootPathProvider = rootPathProvider;\r\n            this.ViewName = viewName;\r\n            this.AvailableViewEngineExtensions = availableViewEngineExtensions;\r\n            this.InspectedLocations = inspectedLocations;\r\n\r\n            this.message = string.Format(\r\n                \"{4}Unable to locate requested view{4}{4} \\u2022 Name: {0}{4} \\u2022 Root path: {3}{4} \\u2022 Supported extensions: {4}{1} \\u2022 Inspected locations: {4}{2}{4}\" +\r\n                \"If you were expecting raw data back, make sure you set the 'Accept'-header of the request to correct format, for example 'application/json'{4}\",\r\n                this.ViewName,\r\n                string.Join(string.Empty, this.AvailableViewEngineExtensions.Select(x => string.Concat(\"  - \", x, Environment.NewLine))),\r\n                string.Join(string.Empty, this.InspectedLocations.Select(x => string.Concat(\"  - \", x, Environment.NewLine))),\r\n                this.rootPathProvider.GetRootPath(),\r\n                Environment.NewLine);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ViewNotFoundException\"/> class, with\r\n        /// the provided <paramref name=\"viewName\"/> and <paramref name=\"availableViewEngineExtensions\"/>.\r\n        /// </summary>\r\n        /// <param name=\"viewName\">The name of the view that was being located.</param>\r\n        /// <param name=\"availableViewEngineExtensions\">List of available view extensions that can be rendered by the available view engines.</param>\r\n        public ViewNotFoundException(string viewName, string[] availableViewEngineExtensions)\r\n        {\r\n            this.ViewName = viewName;\r\n            this.AvailableViewEngineExtensions = availableViewEngineExtensions;\r\n\r\n            this.message = String.Format(\r\n                    \"Unable to locate view '{0}'{2}Currently available view engine extensions: {1}{2}\",\r\n                    this.ViewName,\r\n                    string.Join(\",\", this.AvailableViewEngineExtensions),\r\n                    Environment.NewLine);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ViewNotFoundException\"/> class, with\r\n        /// the provided <paramref name=\"msg\"/>.\r\n        /// </summary>\r\n        /// <param name=\"msg\">A message describing the problem</param>\r\n        public ViewNotFoundException(string msg)\r\n        {\r\n            this.message = msg;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a message that describes the current exception.\r\n        /// </summary>\r\n        /// <returns>The error message that explains the reason for the exception, or an empty string(\"\").</returns>\r\n        public override string Message\r\n        {\r\n            get { return message; }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewEngines/ViewRenderException.cs",
    "content": "namespace Nancy.ViewEngines.Razor\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// An exception that indicates the view could not be rendered\r\n    /// </summary>\r\n    public class ViewRenderException : Exception\r\n    {\r\n        /// <summary>\r\n        /// Create an instance of <see cref=\"ViewRenderException\"/>\r\n        /// </summary>\r\n        /// <param name=\"msg\">A description of the rendering problem</param>\r\n        public ViewRenderException(string msg) : base(msg)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Create an instance of <see cref=\"ViewRenderException\"/>\r\n        /// </summary>\r\n        /// <param name=\"msg\">A description of the rendering problem</param>\r\n        /// <param name=\"innerException\">The exception that is the cause of the current exception.</param>\r\n        public ViewRenderException(string msg, Exception innerException) : base(msg, innerException)\r\n        {\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/ViewRenderer.cs",
    "content": "namespace Nancy\r\n{\r\n    using System.IO;\r\n\r\n    using Nancy.Responses.Negotiation;\r\n\r\n    /// <summary>\r\n    /// Helper class for rendering a view from a route handler.\r\n    /// </summary>\r\n    public class ViewRenderer : IHideObjectMembers\r\n    {\r\n        private readonly INancyModule module;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ViewRenderer\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"module\">The <see cref=\"INancyModule\"/> instance that is rendering the view.</param>\r\n        public ViewRenderer(INancyModule module)\r\n        {\r\n            this.module = module;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Renders the view with its name resolved from the model type, and model defined by the <paramref name=\"model\"/> parameter.\r\n        /// </summary>\r\n        /// <param name=\"model\">The model that should be passed into the view.</param>\r\n        /// <returns>A delegate that can be invoked with the <see cref=\"Stream\"/> that the view should be rendered to.</returns>\r\n        /// <remarks>The view name is model.GetType().Name with any Model suffix removed.</remarks>\r\n        public Negotiator this[dynamic model]\r\n        {\r\n            get { return this.GetNegotiator(null, model); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Renders the view with the name defined by the <paramref name=\"viewName\"/> parameter.\r\n        /// </summary>\r\n        /// <param name=\"viewName\">The name of the view to render.</param>\r\n        /// <returns>A delegate that can be invoked with the <see cref=\"Stream\"/> that the view should be rendered to.</returns>\r\n        /// <remarks>The extension in the view name is optional. If it is omitted, then Nancy will try to resolve which of the available engines that should be used to render the view.</remarks>\r\n        public Negotiator this[string viewName]\r\n        {\r\n            get { return this.GetNegotiator(viewName, null); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Renders the view with the name and model defined by the <paramref name=\"viewName\"/> and <paramref name=\"model\"/> parameters.\r\n        /// </summary>\r\n        /// <param name=\"viewName\">The name of the view to render.</param>\r\n        /// <param name=\"model\">The model that should be passed into the view.</param>\r\n        /// <returns>A delegate that can be invoked with the <see cref=\"Stream\"/> that the view should be rendered to.</returns>\r\n        /// <remarks>The extension in the view name is optional. If it is omitted, then Nancy will try to resolve which of the available engines that should be used to render the view.</remarks>\r\n        public Negotiator this[string viewName, dynamic model]\r\n        {\r\n            get { return this.GetNegotiator(viewName, model); }\r\n        }\r\n\r\n        private Negotiator GetNegotiator(string viewName, object model)\r\n        {\r\n            var negotiationContext = this.module.Context.NegotiationContext;\r\n\r\n            negotiationContext.ViewName = viewName;\r\n            negotiationContext.DefaultModel = model;\r\n            negotiationContext.PermissableMediaRanges.Clear();\r\n            negotiationContext.PermissableMediaRanges.Add(\"text/html\");\r\n\r\n            return new Negotiator(this.module.Context);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy/Xml/DefaultXmlConfigurationProvider.cs",
    "content": "﻿namespace Nancy.Xml\r\n{\r\n    using Nancy.Configuration;\r\n\r\n    /// <summary>\r\n    /// Provides the default configuration for <see cref=\"XmlConfiguration\"/>.\r\n    /// </summary>\r\n    public class DefaultXmlConfigurationProvider : NancyDefaultConfigurationProvider<XmlConfiguration>\r\n    {\r\n        /// <summary>\r\n        /// Gets the default configuration instance to register in the <see cref=\"INancyEnvironment\"/>.\r\n        /// </summary>\r\n        /// <returns>The configuration instance</returns>\r\n        /// <remarks>Will return <see cref=\"XmlConfiguration.Default\"/>.</remarks>\r\n        public override XmlConfiguration GetDefaultConfiguration()\r\n        {\r\n            return XmlConfiguration.Default;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Xml/XmlConfiguration.cs",
    "content": "﻿namespace Nancy.Xml\r\n{\r\n    using System.Text;\r\n\r\n    /// <summary>\r\n    /// Configuration for XML serialization.\r\n    /// </summary>\r\n    public class XmlConfiguration\r\n    {\r\n        /// <summary>\r\n        /// A default instance of the <see cref=\"XmlConfiguration\"/> class.\r\n        /// </summary>\r\n        public static readonly XmlConfiguration Default = new XmlConfiguration\r\n        {\r\n            EncodingEnabled = false,\r\n            DefaultEncoding = Encoding.UTF8\r\n        };\r\n\r\n        private XmlConfiguration()\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"XmlConfiguration\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"encodingEnabled\"><see langword=\"true\" /> if encoding should be enabled, otherwise <see langword=\"false\" />.</param>\r\n        /// <param name=\"defaultEncoding\">The <see cref=\"Encoding\"/> that should be used.</param>\r\n        public XmlConfiguration(bool encodingEnabled, Encoding defaultEncoding)\r\n        {\r\n            this.EncodingEnabled = encodingEnabled;\r\n            this.DefaultEncoding = defaultEncoding ?? Default.DefaultEncoding;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets whether character encoding should be enabled, or not, for XML responses.\r\n        /// </summary>\r\n        /// <value><see langword=\"true\" /> if encoding is enabled, otherwise <see langword=\"false\" />.</value>\r\n        /// <remarks>The default value is <see langword=\"false\" />.</remarks>\r\n        public bool EncodingEnabled { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the default encoding for XML responses.\r\n        /// </summary>\r\n        /// <value>The <see cref=\"Encoding\"/> used by default.</value>\r\n        /// <remarks>The default value is <see langword=\"Encoding.UTF8\" />.</remarks>\r\n        public Encoding DefaultEncoding { get; private set; }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy/Xml/XmlConfigurationExtensions.cs",
    "content": "﻿namespace Nancy.Xml\r\n{\r\n    using System.Text;\r\n    using Nancy.Configuration;\r\n\r\n    /// <summary>\r\n    /// Contains <see cref=\"XmlConfiguration\"/> configuration extensions for <see cref=\"INancyEnvironment\"/>.\r\n    /// </summary>\r\n    public static class XmlConfigurationExtensions\r\n    {\r\n        /// <summary>\r\n        /// Configures <see cref=\"XmlConfiguration\"/>.\r\n        /// </summary>\r\n        /// <param name=\"environment\"><see cref=\"INancyEnvironment\"/> that should be configured.</param>\r\n        /// <param name=\"enableEncoding\"><see langword=\"true\"/> if encoding should be enabled, otherwise <see langword=\"false\"/>.</param>\r\n        /// <param name=\"defaultEncoding\">The default <see cref=\"Encoding\"/>.</param>\r\n        public static void Xml(this INancyEnvironment environment, bool enableEncoding, Encoding defaultEncoding = null)\r\n        {\r\n            environment.AddValue(new XmlConfiguration(\r\n                enableEncoding,\r\n                defaultEncoding));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Authentication.Basic/BasicAuthentication.cs",
    "content": "﻿namespace Nancy.Authentication.Basic\r\n{\r\n    using System;\r\n    using System.Text;\r\n\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Extensions;\r\n    using Nancy.Security;\r\n\r\n    /// <summary>\r\n    /// Nancy basic authentication implementation\r\n    /// </summary>\r\n    public static class BasicAuthentication\r\n    {\r\n        private const string SCHEME = \"Basic\";\r\n\r\n        /// <summary>\r\n        /// Enables basic authentication for the application\r\n        /// </summary>\r\n        /// <param name=\"pipelines\">Pipelines to add handlers to (usually \"this\")</param>\r\n        /// <param name=\"configuration\">Forms authentication configuration</param>\r\n        public static void Enable(IPipelines pipelines, BasicAuthenticationConfiguration configuration)\r\n        {\r\n            if (pipelines == null)\r\n            {\r\n                throw new ArgumentNullException(\"pipelines\");\r\n            }\r\n\r\n            if (configuration == null)\r\n            {\r\n                throw new ArgumentNullException(\"configuration\");\r\n            }\r\n\r\n            pipelines.BeforeRequest.AddItemToStartOfPipeline(GetCredentialRetrievalHook(configuration));\r\n            pipelines.AfterRequest.AddItemToEndOfPipeline(GetAuthenticationPromptHook(configuration));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Enables basic authentication for a module\r\n        /// </summary>\r\n        /// <param name=\"module\">Module to add handlers to (usually \"this\")</param>\r\n        /// <param name=\"configuration\">Forms authentication configuration</param>\r\n        public static void Enable(INancyModule module, BasicAuthenticationConfiguration configuration)\r\n        {\r\n            if (module == null)\r\n            {\r\n                throw new ArgumentNullException(\"module\");\r\n            }\r\n\r\n            if (configuration == null)\r\n            {\r\n                throw new ArgumentNullException(\"configuration\");\r\n            }\r\n\r\n            module.RequiresAuthentication();\r\n            module.Before.AddItemToStartOfPipeline(GetCredentialRetrievalHook(configuration));\r\n            module.After.AddItemToEndOfPipeline(GetAuthenticationPromptHook(configuration));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the pre request hook for loading the authenticated user's details\r\n        /// from the auth header.\r\n        /// </summary>\r\n        /// <param name=\"configuration\">Basic authentication configuration to use</param>\r\n        /// <returns>Pre request hook delegate</returns>\r\n        private static Func<NancyContext, Response> GetCredentialRetrievalHook(BasicAuthenticationConfiguration configuration)\r\n        {\r\n            if (configuration == null)\r\n            {\r\n                throw new ArgumentNullException(\"configuration\");\r\n            }\r\n\r\n            return context =>\r\n                {\r\n                    RetrieveCredentials(context, configuration);\r\n                    return null;\r\n                };\r\n        }\r\n\r\n        private static Action<NancyContext> GetAuthenticationPromptHook(BasicAuthenticationConfiguration configuration)\r\n        {\r\n            return context =>\r\n                {\r\n                    if (context.Response.StatusCode == HttpStatusCode.Unauthorized && SendAuthenticateResponseHeader(context, configuration))\r\n                    {\r\n                        context.Response.Headers[\"WWW-Authenticate\"] = String.Format(\"{0} realm=\\\"{1}\\\"\", SCHEME, configuration.Realm);\r\n                    }\r\n                };\r\n        }\r\n\r\n        private static void RetrieveCredentials(NancyContext context, BasicAuthenticationConfiguration configuration)\r\n        {\r\n            var credentials =\r\n                ExtractCredentialsFromHeaders(context.Request);\r\n\r\n            if (credentials != null && credentials.Length == 2)\r\n            {\r\n                var user = configuration.UserValidator.Validate(credentials[0], credentials[1]);\r\n\r\n                if (user != null)\r\n                {\r\n                    context.CurrentUser = user;\r\n                }\r\n            }\r\n        }\r\n\r\n        private static string[] ExtractCredentialsFromHeaders(Request request)\r\n        {\r\n            var authorization =\r\n                request.Headers.Authorization;\r\n\r\n            if (string.IsNullOrEmpty(authorization))\r\n            {\r\n                return null;\r\n            }\r\n\r\n            if (!authorization.StartsWith(SCHEME, StringComparison.OrdinalIgnoreCase))\r\n            {\r\n                return null;\r\n            }\r\n\r\n            try\r\n            {\r\n                var encodedUserPass = authorization.Substring(SCHEME.Length).Trim();\r\n                var userPass = Encoding.UTF8.GetString(Convert.FromBase64String(encodedUserPass));\r\n\r\n                return String.IsNullOrWhiteSpace(userPass) ? null : userPass.Split(new[] {':'}, 2);\r\n            }\r\n            catch (FormatException)\r\n            {\r\n                return null;\r\n            }\r\n        }\r\n\r\n        private static bool SendAuthenticateResponseHeader(NancyContext context, BasicAuthenticationConfiguration configuration)\r\n        {\r\n            return configuration.UserPromptBehaviour == UserPromptBehaviour.Always || (configuration.UserPromptBehaviour == UserPromptBehaviour.NonAjax && !context.Request.IsAjaxRequest());\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Authentication.Basic/BasicAuthenticationConfiguration.cs",
    "content": "﻿namespace Nancy.Authentication.Basic\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Configuration options for forms authentication\r\n    /// </summary>\r\n    public class BasicAuthenticationConfiguration\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"BasicAuthenticationConfiguration\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"userValidator\">A valid instance of <see cref=\"IUserValidator\"/> class</param>\r\n        /// <param name=\"realm\">Basic authentication realm</param>\r\n        /// <param name=\"userPromptBehaviour\">Control when the browser should be instructed to prompt for credentials</param>\r\n        public BasicAuthenticationConfiguration(IUserValidator userValidator, string realm, UserPromptBehaviour userPromptBehaviour = UserPromptBehaviour.NonAjax)\r\n        {\r\n            if (userValidator == null)\r\n            {\r\n                throw new ArgumentNullException(\"userValidator\");\r\n            }\r\n\r\n            if (string.IsNullOrEmpty(realm))\r\n            {\r\n                throw new ArgumentException(\"realm\");\r\n            }\r\n\r\n            this.UserValidator = userValidator;\r\n            this.Realm = realm;\r\n            this.UserPromptBehaviour = userPromptBehaviour;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the user validator\r\n        /// </summary>\r\n        public IUserValidator UserValidator { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the basic authentication realm\r\n        /// </summary>\r\n        public string Realm { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Determines when the browser should prompt the user for credentials\r\n        /// </summary>\r\n        public UserPromptBehaviour UserPromptBehaviour { get; private set; }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Authentication.Basic/BasicHttpExtensions.cs",
    "content": "﻿namespace Nancy.Authentication.Basic\r\n{\r\n    using Nancy.Bootstrapper;\r\n\r\n    /// <summary>\r\n    /// Some simple helpers give some nice authentication syntax in the modules.\r\n    /// </summary>\r\n    public static class BasicHttpExtensions\r\n    {\r\n        /// <summary>\r\n        /// Module requires basic authentication\r\n        /// </summary>\r\n        /// <param name=\"module\">Module to enable</param>\r\n        /// <param name=\"configuration\">Basic authentication configuration</param>\r\n        public static void EnableBasicAuthentication(this INancyModule module, BasicAuthenticationConfiguration configuration)\r\n        {\r\n            BasicAuthentication.Enable(module, configuration);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Module requires basic authentication\r\n        /// </summary>\r\n        /// <param name=\"pipeline\">Bootstrapper to enable</param>\r\n        /// <param name=\"configuration\">Basic authentication configuration</param>\r\n        public static void EnableBasicAuthentication(this IPipelines pipeline, BasicAuthenticationConfiguration configuration)\r\n        {\r\n            BasicAuthentication.Enable(pipeline, configuration);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Authentication.Basic/IUserValidator.cs",
    "content": "﻿namespace Nancy.Authentication.Basic\r\n{\r\n    using System.Security.Claims;\r\n\r\n    /// <summary>\r\n    /// Provides a way to validate the username and password\r\n    /// </summary>\r\n    public interface IUserValidator\r\n    {\r\n        /// <summary>\r\n        /// Validates the username and password\r\n        /// </summary>\r\n        /// <param name=\"username\">Username</param>\r\n        /// <param name=\"password\">Password</param>\r\n        /// <returns>A value representing the authenticated user, null if the user was not authenticated.</returns>\r\n        ClaimsPrincipal Validate(string username, string password);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Authentication.Basic/Nancy.Authentication.Basic.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <Description>A basic HTTP authentication provider for Nancy.</Description>\n    <PackageTags>$(PackageTags);Authentication</PackageTags>\n    <TargetFrameworks>netstandard2.0;net452</TargetFrameworks>\n  </PropertyGroup>\n</Project>\n"
  },
  {
    "path": "src/Nancy.Authentication.Basic/UserPromptBehaviour.cs",
    "content": "﻿namespace Nancy.Authentication.Basic\r\n{\r\n    /// <summary>\r\n    /// Options to control when the browser prompts the user for credentials\r\n    /// </summary>\r\n    public enum UserPromptBehaviour\r\n    {\r\n        /// <summary>\r\n        /// Never present user with login prompt\r\n        /// </summary>\r\n        Never,\r\n\r\n        /// <summary>\r\n        /// Always present user with login prompt\r\n        /// </summary>\r\n        Always,\r\n\r\n        /// <summary>\r\n        /// Only prompt the user for credentials on non-ajax requests\r\n        /// </summary>\r\n        NonAjax\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Authentication.Forms/FormsAuthentication.cs",
    "content": "namespace Nancy.Authentication.Forms\r\n{\r\n    using System;\r\n    using Bootstrapper;\r\n    using Cookies;\r\n    using Cryptography;\r\n    using Extensions;\r\n    using Helpers;\r\n    using Security;\r\n\r\n    /// <summary>\r\n    /// Nancy forms authentication implementation\r\n    /// </summary>\r\n    public static class FormsAuthentication\r\n    {\r\n        private static string formsAuthenticationCookieName = \"_ncfa\";\r\n\r\n        // TODO - would prefer not to hold this here, but the redirect response needs it\r\n        private static FormsAuthenticationConfiguration currentConfiguration;\r\n\r\n        /// <summary>\r\n        /// Gets or sets the forms authentication cookie name\r\n        /// </summary>\r\n        public static string FormsAuthenticationCookieName\r\n        {\r\n            get\r\n            {\r\n                return formsAuthenticationCookieName;\r\n            }\r\n\r\n            set\r\n            {\r\n                formsAuthenticationCookieName = value;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Enables forms authentication for the application\r\n        /// </summary>\r\n        /// <param name=\"pipelines\">Pipelines to add handlers to (usually \"this\")</param>\r\n        /// <param name=\"configuration\">Forms authentication configuration</param>\r\n        public static void Enable(IPipelines pipelines, FormsAuthenticationConfiguration configuration)\r\n        {\r\n            if (pipelines == null)\r\n            {\r\n                throw new ArgumentNullException(\"pipelines\");\r\n            }\r\n\r\n            if (configuration == null)\r\n            {\r\n                throw new ArgumentNullException(\"configuration\");\r\n            }\r\n\r\n            configuration.EnsureConfigurationIsValid();\r\n\r\n            currentConfiguration = configuration;\r\n\r\n            pipelines.BeforeRequest.AddItemToStartOfPipeline(GetLoadAuthenticationHook(configuration));\r\n            if (!configuration.DisableRedirect)\r\n            {\r\n                pipelines.AfterRequest.AddItemToEndOfPipeline(GetRedirectToLoginHook(configuration));\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Enables forms authentication for a module\r\n        /// </summary>\r\n        /// <param name=\"module\">Module to add handlers to (usually \"this\")</param>\r\n        /// <param name=\"configuration\">Forms authentication configuration</param>\r\n        public static void Enable(INancyModule module, FormsAuthenticationConfiguration configuration)\r\n        {\r\n            if (module == null)\r\n            {\r\n                throw new ArgumentNullException(\"module\");\r\n            }\r\n\r\n            if (configuration == null)\r\n            {\r\n                throw new ArgumentNullException(\"configuration\");\r\n            }\r\n\r\n            configuration.EnsureConfigurationIsValid();\r\n\r\n            module.RequiresAuthentication();\r\n\r\n            currentConfiguration = configuration;\r\n\r\n            module.Before.AddItemToStartOfPipeline(GetLoadAuthenticationHook(configuration));\r\n\r\n            if (!configuration.DisableRedirect)\r\n            {\r\n                module.After.AddItemToEndOfPipeline(GetRedirectToLoginHook(configuration));\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a response that sets the authentication cookie and redirects\r\n        /// the user back to where they came from.\r\n        /// </summary>\r\n        /// <param name=\"context\">Current context</param>\r\n        /// <param name=\"userIdentifier\">User identifier guid</param>\r\n        /// <param name=\"cookieExpiry\">Optional expiry date for the cookie (for 'Remember me')</param>\r\n        /// <param name=\"fallbackRedirectUrl\">Url to redirect to if none in the querystring</param>\r\n        /// <returns>Nancy response with redirect.</returns>\r\n        public static Response UserLoggedInRedirectResponse(NancyContext context, Guid userIdentifier, DateTime? cookieExpiry = null, string fallbackRedirectUrl = null)\r\n        {\r\n            var redirectUrl = fallbackRedirectUrl;\r\n\r\n            if (string.IsNullOrEmpty(redirectUrl))\r\n            {\r\n                redirectUrl = context.Request.Url.BasePath;\r\n            }\r\n\r\n            if (string.IsNullOrEmpty(redirectUrl))\r\n            {\r\n                redirectUrl = \"/\";\r\n            }\r\n\r\n            string redirectQuerystringKey = GetRedirectQuerystringKey(currentConfiguration);\r\n\r\n            if (context.Request.Query[redirectQuerystringKey].HasValue)\r\n            {\r\n                var queryUrl = (string)context.Request.Query[redirectQuerystringKey];\r\n\r\n                if (context.IsLocalUrl(queryUrl))\r\n                {\r\n                    redirectUrl = queryUrl;\r\n                }\r\n            }\r\n\r\n            var response = context.GetRedirect(redirectUrl);\r\n            var authenticationCookie = BuildCookie(userIdentifier, cookieExpiry, currentConfiguration);\r\n            response.WithCookie(authenticationCookie);\r\n\r\n            return response;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Logs the user in.\r\n        /// </summary>\r\n        /// <param name=\"userIdentifier\">User identifier guid</param>\r\n        /// <param name=\"cookieExpiry\">Optional expiry date for the cookie (for 'Remember me')</param>\r\n        /// <returns>Nancy response with status <see cref=\"HttpStatusCode.OK\"/></returns>\r\n        public static Response UserLoggedInResponse(Guid userIdentifier, DateTime? cookieExpiry = null)\r\n        {\r\n            var response =\r\n                (Response)HttpStatusCode.OK;\r\n\r\n            var authenticationCookie =\r\n                BuildCookie(userIdentifier, cookieExpiry, currentConfiguration);\r\n\r\n            response.WithCookie(authenticationCookie);\r\n\r\n            return response;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Logs the user out and redirects them to a URL\r\n        /// </summary>\r\n        /// <param name=\"context\">Current context</param>\r\n        /// <param name=\"redirectUrl\">URL to redirect to</param>\r\n        /// <returns>Nancy response</returns>\r\n        public static Response LogOutAndRedirectResponse(NancyContext context, string redirectUrl)\r\n        {\r\n            var response = context.GetRedirect(redirectUrl);\r\n            var authenticationCookie = BuildLogoutCookie(currentConfiguration);\r\n            response.WithCookie(authenticationCookie);\r\n\r\n            return response;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Logs the user out.\r\n        /// </summary>\r\n        /// <returns>Nancy response</returns>\r\n        public static Response LogOutResponse()\r\n        {\r\n            var response =\r\n                (Response)HttpStatusCode.OK;\r\n\r\n            var authenticationCookie =\r\n                BuildLogoutCookie(currentConfiguration);\r\n\r\n            response.WithCookie(authenticationCookie);\r\n\r\n            return response;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the pre request hook for loading the authenticated user's details\r\n        /// from the cookie.\r\n        /// </summary>\r\n        /// <param name=\"configuration\">Forms authentication configuration to use</param>\r\n        /// <returns>Pre request hook delegate</returns>\r\n        private static Func<NancyContext, Response> GetLoadAuthenticationHook(FormsAuthenticationConfiguration configuration)\r\n        {\r\n            if (configuration == null)\r\n            {\r\n                throw new ArgumentNullException(\"configuration\");\r\n            }\r\n\r\n            return context =>\r\n                {\r\n                    var userGuid = GetAuthenticatedUserFromCookie(context, configuration);\r\n\r\n                    if (userGuid != Guid.Empty)\r\n                    {\r\n                        context.CurrentUser = configuration.UserMapper.GetUserFromIdentifier(userGuid, context);\r\n                    }\r\n\r\n                    return null;\r\n                };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the post request hook for redirecting to the login page\r\n        /// </summary>\r\n        /// <param name=\"configuration\">Forms authentication configuration to use</param>\r\n        /// <returns>Post request hook delegate</returns>\r\n        private static Action<NancyContext> GetRedirectToLoginHook(FormsAuthenticationConfiguration configuration)\r\n        {\r\n            return context =>\r\n                {\r\n                    if (context.Response.StatusCode == HttpStatusCode.Unauthorized)\r\n                    {\r\n                        string redirectQuerystringKey = GetRedirectQuerystringKey(configuration);\r\n\r\n                        context.Response = context.GetRedirect(\r\n                            string.Format(\"{0}?{1}={2}\",\r\n                            configuration.RedirectUrl,\r\n                            redirectQuerystringKey,\r\n                            context.ToFullPath(\"~\" + context.Request.Path + HttpUtility.UrlEncode(context.Request.Url.Query))));\r\n                    }\r\n                };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the authenticated user GUID from the incoming request cookie if it exists\r\n        /// and is valid.\r\n        /// </summary>\r\n        /// <param name=\"context\">Current context</param>\r\n        /// <param name=\"configuration\">Current configuration</param>\r\n        /// <returns>Returns user guid, or Guid.Empty if not present or invalid</returns>\r\n        private static Guid GetAuthenticatedUserFromCookie(NancyContext context, FormsAuthenticationConfiguration configuration)\r\n        {\r\n            string cookieValueEncrypted;\r\n            if (!context.Request.Cookies.TryGetValue(formsAuthenticationCookieName, out cookieValueEncrypted))\r\n            {\r\n                return Guid.Empty;\r\n            }\r\n\r\n            if (string.IsNullOrEmpty(cookieValueEncrypted))\r\n            {\r\n                return Guid.Empty;\r\n            }\r\n\r\n            var cookieValue = DecryptAndValidateAuthenticationCookie(cookieValueEncrypted, configuration);\r\n\r\n            Guid returnGuid;\r\n            if (string.IsNullOrEmpty(cookieValue) || !Guid.TryParse(cookieValue, out returnGuid))\r\n            {\r\n                return Guid.Empty;\r\n            }\r\n\r\n            return returnGuid;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Build the forms authentication cookie\r\n        /// </summary>\r\n        /// <param name=\"userIdentifier\">Authenticated user identifier</param>\r\n        /// <param name=\"cookieExpiry\">Optional expiry date for the cookie (for 'Remember me')</param>\r\n        /// <param name=\"configuration\">Current configuration</param>\r\n        /// <returns>Nancy cookie instance</returns>\r\n        private static INancyCookie BuildCookie(Guid userIdentifier, DateTime? cookieExpiry, FormsAuthenticationConfiguration configuration)\r\n        {\r\n            var cookieContents = EncryptAndSignCookie(userIdentifier.ToString(), configuration);\r\n\r\n            var cookie = new NancyCookie(formsAuthenticationCookieName, cookieContents, true, configuration.RequiresSSL, cookieExpiry);\r\n\r\n            if (!string.IsNullOrEmpty(configuration.Domain))\r\n            {\r\n                cookie.Domain = configuration.Domain;\r\n            }\r\n\r\n            if (!string.IsNullOrEmpty(configuration.Path))\r\n            {\r\n                cookie.Path = configuration.Path;\r\n            }\r\n\r\n            return cookie;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Builds a cookie for logging a user out\r\n        /// </summary>\r\n        /// <param name=\"configuration\">Current configuration</param>\r\n        /// <returns>Nancy cookie instance</returns>\r\n        private static INancyCookie BuildLogoutCookie(FormsAuthenticationConfiguration configuration)\r\n        {\r\n            var cookie = new NancyCookie(formsAuthenticationCookieName, String.Empty, true, configuration.RequiresSSL, DateTime.Now.AddDays(-1));\r\n\r\n            if (!string.IsNullOrEmpty(configuration.Domain))\r\n            {\r\n                cookie.Domain = configuration.Domain;\r\n            }\r\n\r\n            if (!string.IsNullOrEmpty(configuration.Path))\r\n            {\r\n                cookie.Path = configuration.Path;\r\n            }\r\n\r\n            return cookie;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Encrypt and sign the cookie contents\r\n        /// </summary>\r\n        /// <param name=\"cookieValue\">Plain text cookie value</param>\r\n        /// <param name=\"configuration\">Current configuration</param>\r\n        /// <returns>Encrypted and signed string</returns>\r\n        private static string EncryptAndSignCookie(string cookieValue, FormsAuthenticationConfiguration configuration)\r\n        {\r\n            var encryptedCookie = configuration.CryptographyConfiguration.EncryptionProvider.Encrypt(cookieValue);\r\n            var hmacBytes = GenerateHmac(encryptedCookie, configuration);\r\n            var hmacString = Convert.ToBase64String(hmacBytes);\r\n\r\n            return String.Format(\"{1}{0}\", encryptedCookie, hmacString);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Generate a hmac for the encrypted cookie string\r\n        /// </summary>\r\n        /// <param name=\"encryptedCookie\">Encrypted cookie string</param>\r\n        /// <param name=\"configuration\">Current configuration</param>\r\n        /// <returns>Hmac byte array</returns>\r\n        private static byte[] GenerateHmac(string encryptedCookie, FormsAuthenticationConfiguration configuration)\r\n        {\r\n            return configuration.CryptographyConfiguration.HmacProvider.GenerateHmac(encryptedCookie);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Decrypt and validate an encrypted and signed cookie value\r\n        /// </summary>\r\n        /// <param name=\"cookieValue\">Encrypted and signed cookie value</param>\r\n        /// <param name=\"configuration\">Current configuration</param>\r\n        /// <returns>Decrypted value, or empty on error or if failed validation</returns>\r\n        public static string DecryptAndValidateAuthenticationCookie(string cookieValue, FormsAuthenticationConfiguration configuration)\r\n        {\r\n            var hmacStringLength = Base64Helpers.GetBase64Length(configuration.CryptographyConfiguration.HmacProvider.HmacLength);\r\n\r\n            var encryptedCookie = cookieValue.Substring(hmacStringLength);\r\n            var hmacString = cookieValue.Substring(0, hmacStringLength);\r\n\r\n            var encryptionProvider = configuration.CryptographyConfiguration.EncryptionProvider;\r\n\r\n            // Check the hmacs, but don't early exit if they don't match\r\n            var hmacBytes = Convert.FromBase64String(hmacString);\r\n            var newHmac = GenerateHmac(encryptedCookie, configuration);\r\n            var hmacValid = HmacComparer.Compare(newHmac, hmacBytes, configuration.CryptographyConfiguration.HmacProvider.HmacLength);\r\n\r\n            var decrypted = encryptionProvider.Decrypt(encryptedCookie);\r\n\r\n            // Only return the decrypted result if the hmac was ok\r\n            return hmacValid ? decrypted : string.Empty;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the redirect query string key from <see cref=\"FormsAuthenticationConfiguration\"/>\r\n        /// </summary>\r\n        /// <param name=\"configuration\">The forms authentication configuration.</param>\r\n        /// <returns>Redirect Querystring key</returns>\r\n        private static string GetRedirectQuerystringKey(FormsAuthenticationConfiguration configuration)\r\n        {\r\n            string redirectQuerystringKey = null;\r\n\r\n            if (configuration != null)\r\n            {\r\n                redirectQuerystringKey = configuration.RedirectQuerystringKey;\r\n            }\r\n\r\n            if (string.IsNullOrWhiteSpace(redirectQuerystringKey))\r\n            {\r\n                redirectQuerystringKey = FormsAuthenticationConfiguration.DefaultRedirectQuerystringKey;\r\n            }\r\n\r\n            return redirectQuerystringKey;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Authentication.Forms/FormsAuthenticationConfiguration.cs",
    "content": "namespace Nancy.Authentication.Forms\r\n{\r\n    using System;\r\n    using Cryptography;\r\n\r\n    /// <summary>\r\n    /// Configuration options for forms authentication\r\n    /// </summary>\r\n    public class FormsAuthenticationConfiguration\r\n    {\r\n        internal const string DefaultRedirectQuerystringKey = \"returnUrl\";\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"FormsAuthenticationConfiguration\"/> class.\r\n        /// </summary>\r\n        public FormsAuthenticationConfiguration() : this(CryptographyConfiguration.Default)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"FormsAuthenticationConfiguration\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"cryptographyConfiguration\">Cryptography configuration</param>\r\n        public FormsAuthenticationConfiguration(CryptographyConfiguration cryptographyConfiguration)\r\n        {\r\n            CryptographyConfiguration = cryptographyConfiguration;\r\n            RedirectQuerystringKey = DefaultRedirectQuerystringKey;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the forms authentication query string key for storing the return url\r\n        /// </summary>\r\n        public string RedirectQuerystringKey { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the redirect url for pages that require authentication\r\n        /// </summary>\r\n        public string RedirectUrl { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the username/identifier mapper\r\n        /// </summary>\r\n        public IUserMapper UserMapper { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets RequiresSSL property\r\n        /// </summary>\r\n        /// <value>The flag that indicates whether SSL is required</value>\r\n        public bool RequiresSSL { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets whether to redirect to login page during unauthorized access.\r\n        /// </summary>\r\n        public bool DisableRedirect { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the domain of the auth cookie\r\n        /// </summary>\r\n        public string Domain { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the path of the auth cookie\r\n        /// </summary>\r\n        public string Path { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the cryptography configuration\r\n        /// </summary>\r\n        public CryptographyConfiguration CryptographyConfiguration { get; set; }\r\n\r\n        /// <summary>\r\n        /// Ensures the configuration is valid or not.\r\n        /// </summary>\r\n        /// <exception cref=\"InvalidOperationException\" />\r\n        public virtual void EnsureConfigurationIsValid()\r\n        {\r\n            if (!this.DisableRedirect && string.IsNullOrEmpty(this.RedirectUrl))\r\n            {\r\n                throw new InvalidOperationException(\"When DisableRedirect is false RedirectUrl cannot be null.\");\r\n            }\r\n\r\n            if (this.UserMapper == null)\r\n            {\r\n                throw new InvalidOperationException(\"UserMapper cannot be null.\");\r\n            }\r\n\r\n            if (this.CryptographyConfiguration == null)\r\n            {\r\n                throw new InvalidOperationException(\"CryptographyConfiguration cannot be null.\");\r\n            }\r\n\r\n            if (this.CryptographyConfiguration.EncryptionProvider == null)\r\n            {\r\n                throw new InvalidOperationException(\"CryptographyConfiguration EncryptionProvider cannot be null.\");\r\n            }\r\n\r\n            if (this.CryptographyConfiguration.HmacProvider == null)\r\n            {\r\n                throw new InvalidOperationException(\"CryptographyConfiguration HmacProvider cannot be null.\");\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Authentication.Forms/IUserMapper.cs",
    "content": "﻿namespace Nancy.Authentication.Forms\r\n{\r\n    using System;\r\n    using System.Security.Claims;\r\n\r\n    /// <summary>\r\n    /// Provides a mapping between forms auth guid identifiers and\r\n    /// real usernames\r\n    /// </summary>\r\n    public interface IUserMapper\r\n    {\r\n        /// <summary>\r\n        /// Get the real username from an identifier\r\n        /// </summary>\r\n        /// <param name=\"identifier\">User identifier</param>\r\n        /// <param name=\"context\">The current NancyFx context</param>\r\n        /// <returns>Matching populated IUserIdentity object, or empty</returns>\r\n        ClaimsPrincipal GetUserFromIdentifier(Guid identifier, NancyContext context);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Authentication.Forms/ModuleExtensions.cs",
    "content": "namespace Nancy.Authentication.Forms\r\n{\r\n    using System;\r\n\r\n    using Nancy.Extensions;\r\n\r\n    /// <summary>\r\n    /// Module extensions for login/logout of forms auth\r\n    /// </summary>\r\n    public static class ModuleExtensions\r\n    {\r\n        /// <summary>\r\n        /// Logs the user in and returns either an empty 200 response for ajax requests, or a redirect response for non-ajax. <seealso cref=\"RequestExtensions.IsAjaxRequest\"/>\r\n        /// </summary>\r\n        /// <param name=\"module\">Nancy module</param>\r\n        /// <param name=\"userIdentifier\">User identifier guid</param>\r\n        /// <param name=\"cookieExpiry\">Optional expiry date for the cookie (for 'Remember me')</param>\r\n        /// <param name=\"fallbackRedirectUrl\">Url to redirect to if none in the querystring</param>\r\n        /// <returns>Nancy response with redirect if request was not ajax, otherwise with OK.</returns>\r\n        public static Response Login(this INancyModule module, Guid userIdentifier, DateTime? cookieExpiry = null, string fallbackRedirectUrl = \"/\")\r\n        {\r\n            return module.Context.Request.IsAjaxRequest() ?\r\n                LoginWithoutRedirect(module, userIdentifier, cookieExpiry) :\r\n                LoginAndRedirect(module, userIdentifier, cookieExpiry, fallbackRedirectUrl);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Logs the user in with the given user guid and redirects.\r\n        /// </summary>\r\n        /// <param name=\"module\">Nancy module</param>\r\n        /// <param name=\"userIdentifier\">User identifier guid</param>\r\n        /// <param name=\"cookieExpiry\">Optional expiry date for the cookie (for 'Remember me')</param>\r\n        /// <param name=\"fallbackRedirectUrl\">Url to redirect to if none in the querystring</param>\r\n        /// <returns>Nancy response instance</returns>\r\n        public static Response LoginAndRedirect(this INancyModule module, Guid userIdentifier, DateTime? cookieExpiry = null, string fallbackRedirectUrl = \"/\")\r\n        {\r\n            return FormsAuthentication.UserLoggedInRedirectResponse(module.Context, userIdentifier, cookieExpiry, fallbackRedirectUrl);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Logs the user in with the given user guid and returns ok response.\r\n        /// </summary>\r\n        /// <param name=\"module\">Nancy module</param>\r\n        /// <param name=\"userIdentifier\">User identifier guid</param>\r\n        /// <param name=\"cookieExpiry\">Optional expiry date for the cookie (for 'Remember me')</param>\r\n        /// <returns>Nancy response instance</returns>\r\n        public static Response LoginWithoutRedirect(this INancyModule module, Guid userIdentifier, DateTime? cookieExpiry = null)\r\n        {\r\n            return FormsAuthentication.UserLoggedInResponse(userIdentifier, cookieExpiry);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Logs the user out and returns either an empty 200 response for ajax requests, or a redirect response for non-ajax. <seealso cref=\"RequestExtensions.IsAjaxRequest\"/>\r\n        /// </summary>\r\n        /// <param name=\"module\">Nancy module</param>\r\n        /// <param name=\"redirectUrl\">URL to redirect to</param>\r\n        /// <returns>Nancy response with redirect if request was not ajax, otherwise with OK.</returns>\r\n        public static Response Logout(this INancyModule module, string redirectUrl)\r\n        {\r\n            return module.Context.Request.IsAjaxRequest() ?\r\n               FormsAuthentication.LogOutResponse() :\r\n               FormsAuthentication.LogOutAndRedirectResponse(module.Context, redirectUrl);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Logs the user out and redirects\r\n        /// </summary>\r\n        /// <param name=\"module\">Nancy module</param>\r\n        /// <param name=\"redirectUrl\">URL to redirect to</param>\r\n        /// <returns>Nancy response instance</returns>\r\n        public static Response LogoutAndRedirect(this INancyModule module, string redirectUrl)\r\n        {\r\n            return FormsAuthentication.LogOutAndRedirectResponse(module.Context, redirectUrl);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Logs the user out without a redirect\r\n        /// </summary>\r\n        /// <param name=\"module\">Nancy module</param>\r\n        /// <returns>Nancy response instance</returns>\r\n        public static Response LogoutWithoutRedirect(this INancyModule module)\r\n        {\r\n            return FormsAuthentication.LogOutResponse();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Authentication.Forms/Nancy.Authentication.Forms.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <Description>A forms authentication provider for Nancy.</Description>\n    <PackageTags>$(PackageTags);Authentication</PackageTags>\n    <TargetFrameworks>netstandard2.0;net452</TargetFrameworks>\n  </PropertyGroup>\n</Project>\n"
  },
  {
    "path": "src/Nancy.Authentication.Stateless/Nancy.Authentication.Stateless.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <Description>A stateless authentication provider for Nancy.</Description>\n    <PackageTags>$(PackageTags);Authentication</PackageTags>\n    <TargetFrameworks>netstandard2.0;net452</TargetFrameworks>\n  </PropertyGroup>\n</Project>\n"
  },
  {
    "path": "src/Nancy.Authentication.Stateless/StatelessAuthentication.cs",
    "content": "namespace Nancy.Authentication.Stateless\r\n{\r\n    using System;\r\n\r\n    using Nancy.Bootstrapper;\r\n\r\n    /// <summary>\r\n    /// Nancy stateless authentication implementation\r\n    /// </summary>\r\n    public static class StatelessAuthentication\r\n    {\r\n        /// <summary>\r\n        /// Enables stateless authentication for the application\r\n        /// </summary>\r\n        /// <param name=\"pipelines\">Pipelines to add handlers to (usually \"this\")</param>\r\n        /// <param name=\"configuration\">Stateless authentication configuration</param>\r\n        public static void Enable(IPipelines pipelines, StatelessAuthenticationConfiguration configuration)\r\n        {\r\n            if (pipelines == null)\r\n            {\r\n                throw new ArgumentNullException(\"pipelines\");\r\n            }\r\n\r\n            if (configuration == null)\r\n            {\r\n                throw new ArgumentNullException(\"configuration\");\r\n            }\r\n\r\n            if (!configuration.IsValid)\r\n            {\r\n                throw new ArgumentException(\"Configuration is invalid\", \"configuration\");\r\n            }\r\n\r\n            pipelines.BeforeRequest.AddItemToStartOfPipeline(GetLoadAuthenticationHook(configuration));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Enables stateless authentication for a module\r\n        /// </summary>\r\n        /// <param name=\"module\">Module to add handlers to (usually \"this\")</param>\r\n        /// <param name=\"configuration\">Stateless authentication configuration</param>\r\n        public static void Enable(INancyModule module, StatelessAuthenticationConfiguration configuration)\r\n        {\r\n            if (module == null)\r\n            {\r\n                throw new ArgumentNullException(\"module\");\r\n            }\r\n\r\n            if (configuration == null)\r\n            {\r\n                throw new ArgumentNullException(\"configuration\");\r\n            }\r\n\r\n            if (!configuration.IsValid)\r\n            {\r\n                throw new ArgumentException(\"Configuration is invalid\", \"configuration\");\r\n            }\r\n\r\n            module.Before.AddItemToStartOfPipeline(GetLoadAuthenticationHook(configuration));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the pre request hook for loading the authenticated user's details\r\n        /// from apikey given in request.\r\n        /// </summary>\r\n        /// <param name=\"configuration\">Stateless authentication configuration to use</param>\r\n        /// <returns>Pre request hook delegate</returns>\r\n        private static Func<NancyContext, Response> GetLoadAuthenticationHook(StatelessAuthenticationConfiguration configuration)\r\n        {\r\n            if (configuration == null)\r\n            {\r\n                throw new ArgumentNullException(\"configuration\");\r\n            }\r\n\r\n            return context =>\r\n            {\r\n                context.CurrentUser = configuration.GetUserIdentity(context);\r\n\r\n                return null;\r\n            };\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Authentication.Stateless/StatelessAuthenticationConfiguration.cs",
    "content": "namespace Nancy.Authentication.Stateless\r\n{\r\n    using System;\r\n    using System.Security.Claims;\r\n\r\n    /// <summary>\r\n    /// Configuration options for stateless authentication\r\n    /// </summary>\r\n    public class StatelessAuthenticationConfiguration\r\n    {\r\n        internal readonly Func<NancyContext, ClaimsPrincipal> GetUserIdentity;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"StatelessAuthenticationConfiguration\"/> class.\r\n        /// </summary>\r\n        public StatelessAuthenticationConfiguration(Func<NancyContext, ClaimsPrincipal> getUserIdentity)\r\n        {\r\n            this.GetUserIdentity = getUserIdentity;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether the configuration is valid or not.\r\n        /// </summary>\r\n        public virtual bool IsValid\r\n        {\r\n            get\r\n            {\r\n                return this.GetUserIdentity != null;\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Embedded/Conventions/EmbeddedStaticContentConventionBuilder.cs",
    "content": "﻿namespace Nancy.Embedded.Conventions\r\n{\r\n    using System;\r\n    using System.Collections.Concurrent;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using System.Text.RegularExpressions;\r\n\r\n    using Nancy.Helpers;\r\n    using Nancy.Responses;\r\n\r\n    public class EmbeddedStaticContentConventionBuilder\r\n    {\r\n        private static readonly ConcurrentDictionary<string, Func<Response>> ResponseFactoryCache;\r\n        private static readonly Regex PathReplaceRegex = new Regex(@\"[/\\\\]\", RegexOptions.Compiled);\r\n\r\n        static EmbeddedStaticContentConventionBuilder()\r\n        {\r\n            ResponseFactoryCache = new ConcurrentDictionary<string, Func<Response>>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds a directory-based convention for embedded static convention.\r\n        /// </summary>\r\n        /// <param name=\"requestedPath\">The path that should be matched with the request.</param>\r\n        /// <param name=\"contentPath\">The path to where the content is stored in your application, relative to the root. If this is <see langword=\"null\" /> then it will be the same as <paramref name=\"requestedPath\"/>.</param>\r\n        /// <param name=\"allowedExtensions\">A list of extensions that is valid for the conventions. If not supplied, all extensions are valid.</param>\r\n        /// <returns>A <see cref=\"EmbeddedFileResponse\"/> instance for the requested embedded static contents if it was found, otherwise <see langword=\"null\"/>.</returns>\r\n        public static Func<NancyContext, string, Response> AddDirectory(string requestedPath, Assembly assembly, string contentPath = null, params string[] allowedExtensions)\r\n        {\r\n            if (!requestedPath.StartsWith(\"/\"))\r\n            {\r\n                requestedPath = string.Concat(\"/\", requestedPath);\r\n            }\r\n\r\n            return (ctx, root) =>\r\n            {\r\n                var path =\r\n                    HttpUtility.UrlDecode(ctx.Request.Path);\r\n\r\n                var fileName =\r\n                    Path.GetFileName(path);\r\n\r\n                if (string.IsNullOrEmpty(fileName))\r\n                {\r\n                    return null;\r\n                }\r\n\r\n                var pathWithoutFilename =\r\n                    GetPathWithoutFilename(fileName, path);\r\n\r\n                if (!pathWithoutFilename.StartsWith(requestedPath, StringComparison.OrdinalIgnoreCase))\r\n                {\r\n                    ctx.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat(\"[EmbeddedStaticContentConventionBuilder] The requested resource '\", path, \"' does not match convention mapped to '\", requestedPath, \"'\")));\r\n                    return null;\r\n                }\r\n\r\n                contentPath =\r\n                    GetContentPath(requestedPath, contentPath);\r\n\r\n                var responseFactory =\r\n                    ResponseFactoryCache.GetOrAdd(path, BuildContentDelegate(ctx, requestedPath, contentPath, assembly, allowedExtensions));\r\n\r\n                return responseFactory.Invoke();\r\n            };\r\n        }\r\n\r\n        private static Func<string, Func<Response>> BuildContentDelegate(NancyContext context, string requestedPath, string contentPath, Assembly assembly, string[] allowedExtensions)\r\n        {\r\n            return requestPath =>\r\n            {\r\n                context.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat(\"[EmbeddedStaticContentConventionBuilder] Attempting to resolve embedded static content '\", requestPath, \"'\")));\r\n\r\n                var extension = Path.GetExtension(requestPath);\r\n\r\n                if (allowedExtensions.Length != 0 && !allowedExtensions.Any(e => string.Equals(e, extension, StringComparison.OrdinalIgnoreCase)))\r\n                {\r\n                    context.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat(\"[EmbeddedStaticContentConventionBuilder] The requested extension '\", extension, \"' does not match any of the valid extensions for the convention '\", string.Join(\",\", allowedExtensions), \"'\")));\r\n                    return () => null;\r\n                }\r\n\r\n                var fullFilePath =\r\n                    Path.GetFullPath(GetSafeRequestPath(requestPath, requestedPath, contentPath));\r\n\r\n                var relativeFilePath =\r\n                    ResolveRelativeFilePath(fullFilePath);\r\n\r\n                var fileName = Path.Combine(\r\n                    Path.DirectorySeparatorChar.ToString(),\r\n                    GetEncodedPath(relativeFilePath));\r\n\r\n                var contentRootPath = Path.Combine(\r\n                    Path.DirectorySeparatorChar.ToString(),\r\n                    GetEncodedPath(contentPath));\r\n\r\n                if (!IsWithinContentFolder(contentRootPath, fileName))\r\n                {\r\n                    context.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat(\"[EmbeddedStaticContentConventionBuilder] The request '\", fileName, \"' is trying to access a path outside the content folder '\", contentPath, \"'\")));\r\n                    return () => null;\r\n                }\r\n\r\n                var resourceName =\r\n                    Path.GetDirectoryName(assembly.GetName().Name + fileName).Replace(Path.DirectorySeparatorChar, '.').Replace('-', '_');\r\n\r\n                fileName =\r\n                    Path.GetFileName(fileName);\r\n\r\n                if (!assembly.GetManifestResourceNames().Any(x => string.Equals(x, resourceName + \".\" + fileName, StringComparison.OrdinalIgnoreCase)))\r\n                {\r\n                    context.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat(\"[EmbeddedStaticContentConventionBuilder] The requested resource '\", requestPath, \"' was not found in assembly '\", assembly.GetName().Name, \"'\")));\r\n                    return () => null;\r\n                }\r\n\r\n                context.Trace.TraceLog.WriteLog(x => x.AppendLine(string.Concat(\"[EmbeddedStaticContentConventionBuilder] Returning file '\", fileName, \"'\")));\r\n                return () => new EmbeddedFileResponse(assembly, resourceName, fileName);\r\n            };\r\n        }\r\n\r\n        private static string ResolveRelativeFilePath(string fullFilePath)\r\n        {\r\n            var fileRootPath =\r\n                Directory.GetDirectoryRoot(fullFilePath);\r\n\r\n            return fullFilePath.Substring(fileRootPath.Length);\r\n        }\r\n\r\n        private static string GetEncodedPath(string path)\r\n        {\r\n            return PathReplaceRegex.Replace(path.TrimStart(new[] { '/' }), Path.DirectorySeparatorChar.ToString());\r\n        }\r\n\r\n        private static string GetSafeRequestPath(string requestPath, string requestedPath, string contentPath)\r\n        {\r\n            var actualContentPath =\r\n                (contentPath.Equals(\"/\") ? string.Empty : contentPath);\r\n\r\n            if (requestedPath.Equals(\"/\"))\r\n            {\r\n                return string.Concat(actualContentPath, requestPath);\r\n            }\r\n\r\n            var expression =\r\n                new Regex(Regex.Escape(requestedPath), RegexOptions.IgnoreCase);\r\n\r\n            return expression.Replace(requestPath, actualContentPath, 1);\r\n        }\r\n\r\n        private static string GetContentPath(string requestedPath, string contentPath)\r\n        {\r\n            contentPath =\r\n                contentPath ?? requestedPath;\r\n\r\n            if (!contentPath.StartsWith(\"/\"))\r\n            {\r\n                contentPath = string.Concat(\"/\", contentPath);\r\n            }\r\n\r\n            return contentPath;\r\n        }\r\n\r\n        private static string GetPathWithoutFilename(string fileName, string path)\r\n        {\r\n            var pathWithoutFileName =\r\n                path.Replace(fileName, string.Empty);\r\n\r\n            return (pathWithoutFileName.Equals(\"/\")) ?\r\n                pathWithoutFileName :\r\n                pathWithoutFileName.TrimEnd(new[] { '/' });\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns whether the given filename is contained within the content folder\r\n        /// </summary>\r\n        /// <param name=\"contentRootPath\">Content root path</param>\r\n        /// <param name=\"fileName\">Filename requested</param>\r\n        /// <returns>True if contained within the content root, false otherwise</returns>\r\n        private static bool IsWithinContentFolder(string contentRootPath, string fileName)\r\n        {\r\n            return fileName.StartsWith(contentRootPath, StringComparison.Ordinal);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Embedded/Nancy.Embedded.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <Description>Helpers for serving embedded static content with Nancy.</Description>\n    <PackageTags>$(PackageTags);Embedded;Static Content</PackageTags>\n    <TargetFrameworks>netstandard2.0;net452</TargetFrameworks>\n  </PropertyGroup>\n</Project>\n"
  },
  {
    "path": "src/Nancy.Encryption.MachineKey/MachineKeyCryptographyConfigurations.cs",
    "content": "﻿namespace Nancy.Encryption.MachineKey\r\n{\r\n    using System;\r\n\r\n    using Nancy.Cryptography;\r\n\r\n    /// <summary>\r\n    /// Helpers for creating crypto configs from machine.config crypto types\r\n    /// </summary>\r\n    public static class MachineKeyCryptographyConfigurations\r\n    {\r\n        private static readonly Lazy<CryptographyConfiguration> DefaultConfiguration =\r\n            new Lazy<CryptographyConfiguration>(() => new CryptographyConfiguration(\r\n                                                          new MachineKeyEncryptionProvider(),\r\n                                                          new MachineKeyHmacProvider()));\r\n\r\n        private static readonly Lazy<CryptographyConfiguration> NoEncryptionConfiguration =\r\n            new Lazy<CryptographyConfiguration>(() => new CryptographyConfiguration(\r\n                                                          new NoEncryptionProvider(),\r\n                                                          new MachineKeyHmacProvider()));\r\n\r\n        /// <summary>\r\n        /// Gets the default configuration for machinekey encryption.\r\n        /// Uses the machine key for both encryption and hmac generation\r\n        /// </summary>\r\n        public static CryptographyConfiguration Default\r\n        {\r\n            get\r\n            {\r\n                return DefaultConfiguration.Value;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the configuration to use machine key for HMAC, but no encryption\r\n        /// </summary>\r\n        public static CryptographyConfiguration NoEncryption\r\n        {\r\n            get\r\n            {\r\n                return NoEncryptionConfiguration.Value;\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Encryption.MachineKey/MachineKeyEncryptionProvider.cs",
    "content": "﻿namespace Nancy.Encryption.MachineKey\r\n{\r\n    using System;\r\n    using System.Text;\r\n    using System.Web.Security;\r\n\r\n    using Nancy.Cryptography;\r\n\r\n    /// <summary>\r\n    /// An encryption provider that uses the ASP.Net MachineKey\r\n    /// </summary>\r\n    public class MachineKeyEncryptionProvider : IEncryptionProvider\r\n    {\r\n        /// <summary>\r\n        /// Encrypt and base64 encode the string\r\n        /// </summary>\r\n        /// <param name=\"data\">Data to encrypt</param>\r\n        /// <returns>Encrypted string</returns>\r\n        public string Encrypt(string data)\r\n        {\r\n            var input = Encoding.UTF8.GetBytes(data);\r\n\r\n            return MachineKey.Encode(input, MachineKeyProtection.Encryption);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Decrypt string\r\n        /// </summary>\r\n        /// <param name=\"data\">Data to decrypt</param>\r\n        /// <returns>Decrypted string</returns>\r\n        public string Decrypt(string data)\r\n        {\r\n            try\r\n            {\r\n                var bytes = MachineKey.Decode(data, MachineKeyProtection.Encryption);\r\n\r\n                return Encoding.UTF8.GetString(bytes);\r\n            }\r\n            catch (Exception)\r\n            {\r\n                return string.Empty;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Encryption.MachineKey/MachineKeyHmacProvider.cs",
    "content": "﻿namespace Nancy.Encryption.MachineKey\r\n{\r\n    using System;\r\n    using System.Configuration;\r\n    using System.Globalization;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using System.Text;\r\n    using System.Web.Configuration;\r\n    using System.Web.Security;\r\n\r\n    using Nancy.Cryptography;\r\n\r\n    /// <summary>\r\n    /// A HMAC provider using the ASP.Net Machine key\r\n    /// \r\n    /// This is hacky as anything because of all kinds of horrible\r\n    /// internal sealed nonsense inside the framework.\r\n    /// </summary>\r\n    public class MachineKeyHmacProvider : IHmacProvider\r\n    {\r\n        /// <summary>\r\n        /// Gets the length of the HMAC signature in bytes\r\n        /// </summary>\r\n        public int HmacLength { get; private set; }\r\n\r\n        public MachineKeyHmacProvider()\r\n        {\r\n            this.GetHmacLength();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Create a hmac from the given data\r\n        /// </summary>\r\n        /// <param name=\"data\">Data to create hmac from</param>\r\n        /// <returns>Hmac bytes</returns>\r\n        public byte[] GenerateHmac(string data)\r\n        {\r\n            var input = Encoding.UTF8.GetBytes(data);\r\n\r\n            return this.GenerateHmac(input);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Create a hmac from the given data\r\n        /// </summary>\r\n        /// <param name=\"data\">Data to create hmac from</param>\r\n        /// <returns>Hmac bytes</returns>\r\n        public byte[] GenerateHmac(byte[] data)\r\n        {\r\n            var encoded = MachineKey.Encode(data, MachineKeyProtection.Validation);\r\n\r\n            var bytes = HexStringToByteArray(encoded);\r\n\r\n            return bytes.Skip(bytes.Length - HmacLength).ToArray();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Uses reflection to get the hmac length that machine key will generate\r\n        /// </summary>\r\n        private void GetHmacLength()\r\n        {\r\n            // Yucky reflection because it doesn't expose this for some reason :(\r\n            var machineKeyConfig = (MachineKeySection)ConfigurationManager.GetSection(\"system.web/machineKey\");\r\n            var machineKeySectionType = machineKeyConfig.GetType();\r\n            var field = machineKeySectionType.GetField(\"_HashSize\", BindingFlags.NonPublic | BindingFlags.Static);\r\n\r\n            try\r\n            {\r\n                this.HmacLength = (int)field.GetValue(null);\r\n            }\r\n            catch (Exception)\r\n            {\r\n                throw new InvalidOperationException(\"Unable to retrieve hash size from machine.config\");\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Converts a string of \"hex bytes\" to actual bytes.\r\n        /// We could just use the same method as .net does but\r\n        /// like a lot of useful things in .net, it's internal.\r\n        /// </summary>\r\n        /// <param name=\"data\">String of hex bytes</param>\r\n        /// <returns>Actual byte array</returns>\r\n        private static byte[] HexStringToByteArray(string data)\r\n        {\r\n            if (string.IsNullOrEmpty(data) || data.Length % 2 != 0)\r\n            {\r\n                return ArrayCache.Empty<byte>();\r\n            }\r\n\r\n            var output = new byte[data.Length / 2];\r\n\r\n            for (var i = 0; i < data.Length / 2; i++)\r\n            {\r\n                var numberString = new string(new[] { data[2 * i], data[2 * i + 1] });\r\n\r\n                var value = byte.Parse(numberString, NumberStyles.HexNumber);\r\n\r\n                output[i] = value;\r\n            }\r\n\r\n            return output;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Encryption.MachineKey/Nancy.Encryption.MachineKey.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <Description>System.Web MachineKey encrypton and HMAC providers for Nancy.</Description>\n    <PackageTags>$(PackageTags);Encryption</PackageTags>\n    <TargetFramework>net452</TargetFramework>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Web\" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "src/Nancy.Hosting.Aspnet/AspNetRootPathProvider.cs",
    "content": "namespace Nancy.Hosting.Aspnet\r\n{\r\n    using System.Web.Hosting;\r\n\r\n    public class AspNetRootPathProvider : IRootPathProvider\r\n    {\r\n        public string GetRootPath()\r\n        {\r\n            return HostingEnvironment.MapPath(\"~/\");\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Hosting.Aspnet/BootstrapperEntry.cs",
    "content": "namespace Nancy.Hosting.Aspnet\r\n{\r\n    public sealed class BootstrapperEntry\r\n    {\r\n        public BootstrapperEntry(string assembly, string name)\r\n        {\r\n            Assembly = assembly;\r\n            Name = name;\r\n        }\r\n\r\n        public string Assembly { get; private set; }\r\n\r\n        public string Name { get; private set; }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Hosting.Aspnet/DefaultNancyAspNetBootstrapper.cs",
    "content": "﻿namespace Nancy.Hosting.Aspnet\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Configuration;\r\n    using Nancy.Diagnostics;\r\n    using Nancy.TinyIoc;\r\n\r\n    /// <summary>\r\n    /// TinyIoC ASP.Net Bootstrapper\r\n    /// No child container support because per-request is handled by the AsPerRequestSingleton option\r\n    /// </summary>\r\n    public abstract class DefaultNancyAspNetBootstrapper : NancyBootstrapperBase<TinyIoCContainer>\r\n    {\r\n        /// <summary>\r\n        /// Gets the diagnostics for initialisation\r\n        /// </summary>\r\n        /// <returns>IDiagnostics implementation</returns>\r\n        protected override IDiagnostics GetDiagnostics()\r\n        {\r\n            return this.ApplicationContainer.Resolve<IDiagnostics>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all request startup tasks\r\n        /// </summary>\r\n        protected override IEnumerable<Type> RequestStartupTasks\r\n        {\r\n            get\r\n            {\r\n                var types = base.RequestStartupTasks.ToArray();\r\n\r\n                this.ApplicationContainer.RegisterMultiple(typeof(IRequestStartup), types).AsPerRequestSingleton();\r\n\r\n                return types;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all registered startup tasks\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance containing <see cref=\"IApplicationStartup\"/> instances. </returns>\r\n        protected override IEnumerable<IApplicationStartup> GetApplicationStartupTasks()\r\n        {\r\n            return this.ApplicationContainer.ResolveAll<IApplicationStartup>(false);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Resolves all request startup tasks\r\n        /// </summary>\r\n        /// <param name=\"container\">Container to use</param>\r\n        /// <param name=\"requestStartupTypes\">Types to register - not used</param>\r\n        /// <returns>An <see cref=\"System.Collections.Generic.IEnumerable{T}\"/> instance containing <see cref=\"IRequestStartup\"/> instances.</returns>\r\n        protected override IEnumerable<IRequestStartup> RegisterAndGetRequestStartupTasks(TinyIoCContainer container, Type[] requestStartupTypes)\r\n        {\r\n            return container.ResolveAll<IRequestStartup>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all registered application registration tasks\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance containing <see cref=\"IRegistrations\"/> instances.</returns>\r\n        protected override IEnumerable<IRegistrations> GetRegistrationTasks()\r\n        {\r\n            return this.ApplicationContainer.ResolveAll<IRegistrations>(false);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get all NancyModule implementation instances - should be multi-instance\r\n        /// </summary>\r\n        /// <param name=\"context\">Current request context</param>\r\n        /// <returns>IEnumerable of INancyModule</returns>\r\n        public sealed override IEnumerable<INancyModule> GetAllModules(NancyContext context)\r\n        {\r\n            return this.ApplicationContainer.ResolveAll<INancyModule>(false);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Retrieves a specific <see cref=\"INancyModule\"/> implementation - should be per-request lifetime\r\n        /// </summary>\r\n        /// <param name=\"moduleType\">Module type</param>\r\n        /// <param name=\"context\">The current context</param>\r\n        /// <returns>The <see cref=\"INancyModule\"/> instance</returns>\r\n        public override INancyModule GetModule(Type moduleType, NancyContext context)\r\n        {\r\n            return this.ApplicationContainer.Resolve<INancyModule>(moduleType.FullName);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates and initializes the request pipelines.\r\n        /// </summary>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> used by the request.</param>\r\n        /// <returns>An <see cref=\"IPipelines\"/> instance.</returns>\r\n        protected sealed override IPipelines InitializeRequestPipelines(NancyContext context)\r\n        {\r\n            return base.InitializeRequestPipelines(context);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Configures the container using AutoRegister followed by registration\r\n        /// of default INancyModuleCatalog and IRouteResolver.\r\n        /// </summary>\r\n        /// <param name=\"container\">Container instance</param>\r\n        protected override void ConfigureApplicationContainer(TinyIoCContainer container)\r\n        {\r\n            container.AutoRegister();\r\n            container.Register<INancyModuleCatalog>(this);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Resolve INancyEngine\r\n        /// </summary>\r\n        /// <returns>INancyEngine implementation</returns>\r\n        protected sealed override INancyEngine GetEngineInternal()\r\n        {\r\n            return this.ApplicationContainer.Resolve<INancyEngine>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Create a default, unconfigured, container\r\n        /// </summary>\r\n        /// <returns>Container instance</returns>\r\n        protected override TinyIoCContainer GetApplicationContainer()\r\n        {\r\n            return new TinyIoCContainer();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Register the bootstrapper's implemented types into the container.\r\n        /// This is necessary so a user can pass in a populated container but not have\r\n        /// to take the responsibility of registering things like INancyModuleCatalog manually.\r\n        /// </summary>\r\n        /// <param name=\"applicationContainer\">Application container to register into</param>\r\n        protected sealed override void RegisterBootstrapperTypes(TinyIoCContainer applicationContainer)\r\n        {\r\n            applicationContainer.Register<INancyModuleCatalog>(this);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Registers an <see cref=\"INancyEnvironment\"/> instance in the container.\r\n        /// </summary>\r\n        /// <param name=\"container\">The container to register into.</param>\r\n        /// <param name=\"environment\">The <see cref=\"INancyEnvironment\"/> instance to register.</param>\r\n        protected override void RegisterNancyEnvironment(TinyIoCContainer container, INancyEnvironment environment)\r\n        {\r\n            container.Register(environment);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"INancyEnvironmentConfigurator\"/> used by the application.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"INancyEnvironmentConfigurator\"/> instance.</returns>\r\n        protected override INancyEnvironmentConfigurator GetEnvironmentConfigurator()\r\n        {\r\n            return this.ApplicationContainer.Resolve<INancyEnvironmentConfigurator>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the <see cref=\"INancyEnvironment\"/> instance.\r\n        /// </summary>\r\n        /// <returns>An configured <see cref=\"INancyEnvironment\"/> instance.</returns>\r\n        /// <remarks>The boostrapper must be initialised (<see cref=\"INancyBootstrapper.Initialise\"/>) prior to calling this.</remarks>\r\n        public override INancyEnvironment GetEnvironment()\r\n        {\r\n            return this.ApplicationContainer.Resolve<INancyEnvironment>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Register the default implementations of internally used types into the container as singletons\r\n        /// </summary>\r\n        /// <param name=\"container\">Container to register into</param>\r\n        /// <param name=\"typeRegistrations\">Type registrations to register</param>\r\n        protected sealed override void RegisterTypes(TinyIoCContainer container, IEnumerable<TypeRegistration> typeRegistrations)\r\n        {\r\n            foreach (var typeRegistration in typeRegistrations)\r\n            {\r\n                switch (typeRegistration.Lifetime)\r\n                {\r\n                    case Lifetime.Transient:\r\n                        container.Register(typeRegistration.RegistrationType, typeRegistration.ImplementationType).AsMultiInstance();\r\n                        break;\r\n                    case Lifetime.Singleton:\r\n                        container.Register(typeRegistration.RegistrationType, typeRegistration.ImplementationType).AsSingleton();\r\n                        break;\r\n                    case Lifetime.PerRequest:\r\n                        container.Register(typeRegistration.RegistrationType, typeRegistration.ImplementationType).AsPerRequestSingleton();\r\n                        break;\r\n                    default:\r\n                        throw new ArgumentOutOfRangeException();\r\n                }\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Register the various collections into the container as singletons to later be resolved\r\n        /// by IEnumerable{Type} constructor dependencies.\r\n        /// </summary>\r\n        /// <param name=\"container\">Container to register into</param>\r\n        /// <param name=\"collectionTypeRegistrations\">Collection type registrations to register</param>\r\n        protected sealed override void RegisterCollectionTypes(TinyIoCContainer container, IEnumerable<CollectionTypeRegistration> collectionTypeRegistrations)\r\n        {\r\n            foreach (var collectionTypeRegistration in collectionTypeRegistrations)\r\n            {\r\n                switch (collectionTypeRegistration.Lifetime)\r\n                {\r\n                    case Lifetime.Transient:\r\n                        container.RegisterMultiple(collectionTypeRegistration.RegistrationType, collectionTypeRegistration.ImplementationTypes).AsMultiInstance();\r\n                        break;\r\n                    case Lifetime.Singleton:\r\n                        container.RegisterMultiple(collectionTypeRegistration.RegistrationType, collectionTypeRegistration.ImplementationTypes).AsSingleton();\r\n                        break;\r\n                    case Lifetime.PerRequest:\r\n                        container.RegisterMultiple(collectionTypeRegistration.RegistrationType, collectionTypeRegistration.ImplementationTypes).AsPerRequestSingleton();\r\n                        break;\r\n                    default:\r\n                        throw new ArgumentOutOfRangeException();\r\n                }\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Register the given module types into the container\r\n        /// </summary>\r\n        /// <param name=\"container\">Container to register into</param>\r\n        /// <param name=\"moduleRegistrationTypes\">NancyModule types</param>\r\n        protected sealed override void RegisterModules(TinyIoCContainer container, IEnumerable<ModuleRegistration> moduleRegistrationTypes)\r\n        {\r\n            foreach (var registrationType in moduleRegistrationTypes)\r\n            {\r\n                container.Register(typeof(INancyModule), registrationType.ModuleType, registrationType.ModuleType.FullName).AsPerRequestSingleton();\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Register the given instances into the container\r\n        /// </summary>\r\n        /// <param name=\"container\">Container to register into</param>\r\n        /// <param name=\"instanceRegistrations\">Instance registration types</param>\r\n        protected override void RegisterInstances(TinyIoCContainer container, IEnumerable<InstanceRegistration> instanceRegistrations)\r\n        {\r\n            foreach (var instanceRegistration in instanceRegistrations)\r\n            {\r\n                container.Register(\r\n                    instanceRegistration.RegistrationType,\r\n                    instanceRegistration.Implementation);\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Hosting.Aspnet/Nancy.Hosting.Aspnet.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <Description>Enables hosting Nancy on ASP.NET.</Description>\n    <PackageTags>$(PackageTags);Host</PackageTags>\n    <TargetFramework>net452</TargetFramework>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <None Update=\".\\web.config.transform\">\n      <PackagePath>content</PackagePath>\n      <Pack>true</Pack>\n    </None>\n  </ItemGroup>\n\n  <ItemGroup>\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Web\" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "src/Nancy.Hosting.Aspnet/NancyFxSection.cs",
    "content": "namespace Nancy.Hosting.Aspnet\r\n{\r\n    using System;\r\n    using System.Configuration;\r\n\r\n    public class NancyFxSection : ConfigurationSection\r\n    {\r\n        [ConfigurationProperty(\"disableoutputbuffer\")]\r\n        public DisableOutputBufferElement DisableOutputBuffer\r\n        {\r\n            get { return (DisableOutputBufferElement)this[\"disableoutputbuffer\"]; }\r\n            set { this[\"disableoutputbuffer\"] = value; }\r\n        }\r\n\r\n        [ConfigurationProperty(\"bootstrapper\")]\r\n        public BootstrapperElement Bootstrapper\r\n        {\r\n            get { return (BootstrapperElement)this[\"bootstrapper\"]; }\r\n            set { this[\"bootstrapper\"] = value; }\r\n        }\r\n\r\n        public class DisableOutputBufferElement : ConfigurationElement\r\n        {\r\n            [ConfigurationProperty(\"value\", DefaultValue = false, IsRequired = true)]\r\n            public bool Value\r\n            {\r\n                get { return (bool)this[\"value\"]; }\r\n                set { this[\"value\"] = value; }\r\n            }\r\n        }\r\n\r\n        public class BootstrapperElement : ConfigurationElement\r\n        {\r\n            [ConfigurationProperty(\"type\", DefaultValue = \"\", IsRequired = true)]\r\n            public string Type\r\n            {\r\n                get { return (string)this[\"type\"]; }\r\n                set { this[\"type\"] = value; }\r\n            }\r\n\r\n            [ConfigurationProperty(\"assembly\", DefaultValue = \"\", IsRequired = true)]\r\n            public string Assembly\r\n            {\r\n                get { return (String)this[\"assembly\"]; }\r\n                set { this[\"assembly\"] = value; }\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Hosting.Aspnet/NancyHandler.cs",
    "content": "namespace Nancy.Hosting.Aspnet\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Configuration;\r\n    using System.Globalization;\r\n    using System.Linq;\r\n    using System.Security.Cryptography.X509Certificates;\r\n    using System.Threading.Tasks;\r\n    using System.Web;\r\n\r\n    using Nancy.Extensions;\r\n    using Nancy.IO;\r\n\r\n    /// <summary>\r\n    /// Bridges the communication between Nancy and ASP.NET based hosting.\r\n    /// </summary>\r\n    public class NancyHandler\r\n    {\r\n        private readonly INancyEngine engine;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancyHandler\"/> type for the specified <paramref name=\"engine\"/>.\r\n        /// </summary>\r\n        /// <param name=\"engine\">An <see cref=\"INancyEngine\"/> instance, that should be used by the handler.</param>\r\n        public NancyHandler(INancyEngine engine)\r\n        {\r\n            this.engine = engine;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Processes the ASP.NET request with Nancy.\r\n        /// </summary>\r\n        /// <param name=\"httpContext\">The <see cref=\"HttpContextBase\"/> of the request.</param>\r\n        public async Task ProcessRequest(HttpContextBase httpContext)\r\n        {\r\n            var request = CreateNancyRequest(httpContext);\r\n\r\n            using(var nancyContext = await this.engine.HandleRequest(request).ConfigureAwait(false))\r\n            {\r\n                SetNancyResponseToHttpResponse(httpContext, nancyContext.Response);\r\n            }\r\n        }\r\n\r\n        private static Request CreateNancyRequest(HttpContextBase context)\r\n        {\r\n            var incomingHeaders = context.Request.Headers.ToDictionary();\r\n\r\n            var expectedRequestLength =\r\n                GetExpectedRequestLength(incomingHeaders);\r\n\r\n            var basePath = context.Request.ApplicationPath.TrimEnd('/');\r\n\r\n            var path = context.Request.Url.AbsolutePath.Substring(basePath.Length);\r\n            path = string.IsNullOrWhiteSpace(path) ? \"/\" : path;\r\n\r\n            var nancyUrl = new Url\r\n                               {\r\n                                   Scheme = context.Request.Url.Scheme,\r\n                                   HostName = context.Request.Url.Host,\r\n                                   Port = context.Request.Url.Port,\r\n                                   BasePath = basePath,\r\n                                   Path = path,\r\n                                   Query = context.Request.Url.Query,\r\n                               };\r\n            byte[] certificate = null;\r\n\r\n            if (context.Request.ClientCertificate != null &&\r\n                context.Request.ClientCertificate.IsPresent &&\r\n                context.Request.ClientCertificate.Certificate.Length != 0)\r\n            {\r\n                certificate = context.Request.ClientCertificate.Certificate;\r\n            }\r\n\r\n            RequestStream body = null;\r\n\r\n            if (expectedRequestLength != 0 || HasChunkedEncoding(incomingHeaders))\r\n            {\r\n                body = RequestStream.FromStream(context.Request.InputStream, expectedRequestLength, StaticConfiguration.DisableRequestStreamSwitching ?? true);\r\n            }\r\n\r\n            var protocolVersion = context.Request.ServerVariables[\"HTTP_VERSION\"];\r\n\r\n            return new Request(context.Request.HttpMethod.ToUpperInvariant(), \r\n                nancyUrl, \r\n                body, \r\n                incomingHeaders, \r\n                context.Request.UserHostAddress, \r\n                new X509Certificate2(certificate),\r\n                protocolVersion);\r\n        }\r\n\r\n        private static long GetExpectedRequestLength(IDictionary<string, IEnumerable<string>> incomingHeaders)\r\n        {\r\n            if (incomingHeaders == null)\r\n            {\r\n                return 0;\r\n            }\r\n\r\n            IEnumerable<string> values;\r\n            if (!incomingHeaders.TryGetValue(\"Content-Length\", out values))\r\n            {\r\n                return 0;\r\n            }\r\n\r\n            var headerValue = values.SingleOrDefault();\r\n\r\n            if (headerValue == null)\r\n            {\r\n                return 0;\r\n            }\r\n\r\n            long contentLength;\r\n            if (!long.TryParse(headerValue, NumberStyles.Any, CultureInfo.InvariantCulture, out contentLength))\r\n            {\r\n                return 0;\r\n            }\r\n\r\n            return contentLength;\r\n        }\r\n\r\n        private static bool HasChunkedEncoding(IDictionary<string, IEnumerable<string>> incomingHeaders)\r\n        {\r\n            IEnumerable<string> transferEncodingValue;\r\n            if (incomingHeaders == null || !incomingHeaders.TryGetValue(\"Transfer-Encoding\", out transferEncodingValue))\r\n            {\r\n                return false;\r\n            }\r\n            var transferEncodingString = transferEncodingValue.SingleOrDefault() ?? string.Empty;\r\n            return transferEncodingString.Equals(\"chunked\", StringComparison.OrdinalIgnoreCase);\r\n        }\r\n\r\n        public static void SetNancyResponseToHttpResponse(HttpContextBase context, Response response)\r\n        {\r\n            SetHttpResponseHeaders(context, response);\r\n\r\n            if (response.ContentType != null)\r\n            {\r\n                context.Response.ContentType = response.ContentType;\r\n            }\r\n\r\n            if (IsOutputBufferDisabled())\r\n            {\r\n                context.Response.BufferOutput = false;\r\n            }\r\n\r\n            context.Response.StatusCode = (int) response.StatusCode;\r\n\r\n            if (response.ReasonPhrase != null)\r\n            {\r\n                context.Response.StatusDescription = response.ReasonPhrase;\r\n            }\r\n\r\n            response.Contents.Invoke(new NancyResponseStream(context.Response));\r\n        }\r\n\r\n        private static bool IsOutputBufferDisabled()\r\n        {\r\n            var configurationSection =\r\n                ConfigurationManager.GetSection(\"nancyFx\") as NancyFxSection;\r\n\r\n            if (configurationSection == null || configurationSection.DisableOutputBuffer == null)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            return configurationSection.DisableOutputBuffer.Value;\r\n        }\r\n\r\n        private static void SetHttpResponseHeaders(HttpContextBase context, Response response)\r\n        {\r\n            foreach (var header in response.Headers.ToDictionary(x => x.Key, x => x.Value))\r\n            {\r\n                context.Response.AddHeader(header.Key, header.Value);\r\n            }\r\n\r\n            foreach(var cookie in response.Cookies.ToArray())\r\n            {\r\n                context.Response.AddHeader(\"Set-Cookie\", cookie.ToString());\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Hosting.Aspnet/NancyHttpRequestHandler.cs",
    "content": "namespace Nancy.Hosting.Aspnet\r\n{\r\n    using System;\r\n    using System.Configuration;\r\n    using System.Threading.Tasks;\r\n    using System.Web;\r\n\r\n    using Nancy.Bootstrapper;\r\n\r\n    public class NancyHttpRequestHandler : HttpTaskAsyncHandler\r\n    {\r\n        private static readonly INancyEngine engine;\r\n\r\n        static NancyHttpRequestHandler()\r\n        {\r\n            var bootstrapper = GetBootstrapper();\r\n\r\n            bootstrapper.Initialise();\r\n\r\n            engine = bootstrapper.GetEngine();\r\n        }\r\n\r\n        public override bool IsReusable\r\n        {\r\n            get { return true; }\r\n        }\r\n\r\n        private static INancyBootstrapper GetBootstrapper()\r\n        {\r\n            return GetConfigurationBootstrapper() ?? NancyBootstrapperLocator.Bootstrapper;\r\n        }\r\n\r\n        private static INancyBootstrapper GetConfigurationBootstrapper()\r\n        {\r\n            var bootstrapperEntry = GetConfiguredBootstrapperEntry();\r\n            if (bootstrapperEntry == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            var assemblyQualifiedName = string.Concat(bootstrapperEntry.Name, \", \", bootstrapperEntry.Assembly);\r\n\r\n            var bootstrapperType = Type.GetType(assemblyQualifiedName);\r\n            if (bootstrapperType == null)\r\n            {\r\n                throw new BootstrapperException(string.Format(\"Could not locate bootstrapper of type '{0}'.\", assemblyQualifiedName));\r\n            }\r\n\r\n            try\r\n            {\r\n                return Activator.CreateInstance(bootstrapperType) as INancyBootstrapper;\r\n            }\r\n            catch (Exception ex)\r\n            {\r\n                var errorMessage = string.Format(\"Could not initialize bootstrapper of type '{0}'.\", bootstrapperType.FullName);\r\n                throw new BootstrapperException(errorMessage, ex);\r\n            }\r\n        }\r\n\r\n        private static BootstrapperEntry GetConfiguredBootstrapperEntry()\r\n        {\r\n            var configurationSection =\r\n                ConfigurationManager.GetSection(\"nancyFx\") as NancyFxSection;\r\n\r\n            if (configurationSection == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            var bootstrapperOverrideType =\r\n                configurationSection.Bootstrapper.Type;\r\n\r\n            var bootstrapperOverrideAssembly =\r\n                configurationSection.Bootstrapper.Assembly;\r\n\r\n            if (string.IsNullOrWhiteSpace(bootstrapperOverrideType))\r\n            {\r\n                throw new BootstrapperException(\"The 'type' attribute of the 'bootstrapper' element under the 'nancyFx' config section is empty. Please specify the full type name.\");\r\n            }\r\n\r\n            if (string.IsNullOrWhiteSpace(bootstrapperOverrideAssembly))\r\n            {\r\n                throw new BootstrapperException(\"The 'assembly' attribute of the 'bootstrapper' element under the 'nancyFx' config section is empty. Please specify the full assembly name.\");\r\n            }\r\n\r\n            return new BootstrapperEntry(bootstrapperOverrideAssembly, bootstrapperOverrideType);\r\n        }\r\n\r\n        public override Task ProcessRequestAsync(HttpContext context)\r\n        {\r\n            var nancyHandler = new NancyHandler(engine);\r\n\r\n            return nancyHandler.ProcessRequest(new HttpContextWrapper(context));\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Hosting.Aspnet/NancyResponseStream.cs",
    "content": "﻿namespace Nancy.Hosting.Aspnet\r\n{\r\n    using System.IO;\r\n    using System.Web;\r\n\r\n    /// <summary>\r\n    /// A wrapper around an AspNet OutputStream that defers .Flush() to the parent HttpResponseBase\r\n    /// </summary>\r\n    public class NancyResponseStream : Stream\r\n    {\r\n        private readonly HttpResponseBase response;\r\n\r\n        public NancyResponseStream(HttpResponseBase response)\r\n        {\r\n            this.response = response;\r\n        }\r\n        public override bool CanRead\r\n        {\r\n            get { return this.response.OutputStream.CanRead; }\r\n        }\r\n\r\n        public override bool CanSeek\r\n        {\r\n            get { return this.response.OutputStream.CanSeek; }\r\n        }\r\n\r\n        public override bool CanWrite\r\n        {\r\n            get { return this.response.OutputStream.CanWrite; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Calls Flush() on the wrapped HttpResponseBase\r\n        /// </summary>\r\n        public override void Flush()\r\n        {\r\n            this.response.Flush();\r\n        }\r\n\r\n        public override long Length\r\n        {\r\n            get { return this.response.OutputStream.Length; }\r\n        }\r\n\r\n        public override long Position\r\n        {\r\n            get\r\n            {\r\n                return this.response.OutputStream.Position;\r\n            }\r\n            set\r\n            {\r\n                this.response.OutputStream.Position = value;\r\n            }\r\n        }\r\n\r\n        public override int Read(byte[] buffer, int offset, int count)\r\n        {\r\n            return this.response.OutputStream.Read(buffer, offset, count);\r\n        }\r\n\r\n        public override long Seek(long offset, SeekOrigin origin)\r\n        {\r\n            return this.response.OutputStream.Seek(offset, origin);\r\n        }\r\n\r\n        public override void SetLength(long value)\r\n        {\r\n            this.response.OutputStream.SetLength(value);\r\n        }\r\n\r\n        public override void Write(byte[] buffer, int offset, int count)\r\n        {\r\n            this.response.OutputStream.Write(buffer, offset, count);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Hosting.Aspnet/TinyIoCAspNetExtensions.cs",
    "content": "﻿namespace Nancy.Hosting.Aspnet\r\n{\r\n    using System;\r\n    using System.Web;\r\n\r\n    using Nancy.TinyIoc;\r\n\r\n    public class HttpContextLifetimeProvider : TinyIoCContainer.ITinyIoCObjectLifetimeProvider\r\n    {\r\n        private readonly string _KeyName = String.Format(\"TinyIoC.HttpContext.{0}\", Guid.NewGuid());\r\n\r\n        public object GetObject()\r\n        {\r\n            return HttpContext.Current.Items[_KeyName];\r\n        }\r\n\r\n        public void SetObject(object value)\r\n        {\r\n            HttpContext.Current.Items[_KeyName] = value;\r\n        }\r\n\r\n        public void ReleaseObject()\r\n        {\r\n            var item = GetObject() as IDisposable;\r\n\r\n            if (item != null)\r\n                item.Dispose();\r\n\r\n            SetObject(null);\r\n        }\r\n    }\r\n\r\n    public static class TinyIoCAspNetExtensions\r\n    {\r\n        /// <summary>\r\n        /// Registers the dependency as per request lifetime\r\n        /// </summary>\r\n        /// <param name=\"registerOptions\">Register options</param>\r\n        /// <returns>Register options</returns>\r\n        public static TinyIoCContainer.RegisterOptions AsPerRequestSingleton(this TinyIoCContainer.RegisterOptions registerOptions)\r\n        {\r\n            return TinyIoCContainer.RegisterOptions.ToCustomLifetimeManager(registerOptions, new HttpContextLifetimeProvider(), \"per request singleton\");\r\n        }\r\n\r\n        /// <summary>\r\n        /// Registers each item in the collection as per request lifetime\r\n        /// </summary>\r\n        /// <param name=\"registerOptions\">Register options</param>\r\n        /// <returns>Register options</returns>\r\n        public static TinyIoCContainer.MultiRegisterOptions AsPerRequestSingleton(this TinyIoCContainer.MultiRegisterOptions registerOptions)\r\n        {\r\n            return TinyIoCContainer.MultiRegisterOptions.ToCustomLifetimeManager(registerOptions, new HttpContextLifetimeProvider(), \"per request singleton\");\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Hosting.Aspnet/web.config.transform",
    "content": "<configuration>\r\n  <system.web>\r\n    <httpHandlers>\r\n      <add verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\"/>\r\n    </httpHandlers>\r\n  </system.web>\r\n\r\n  <system.webServer>\r\n    <validation validateIntegratedModeConfiguration=\"false\"/>\r\n    <httpErrors existingResponse=\"PassThrough\"/>\r\n    <handlers>\r\n      <add name=\"Nancy\" verb=\"*\" type=\"Nancy.Hosting.Aspnet.NancyHttpRequestHandler\" path=\"*\"/>\r\n    </handlers>\r\n  </system.webServer>\r\n</configuration>\r\n"
  },
  {
    "path": "src/Nancy.Hosting.Self/AutomaticUrlReservationCreationFailureException.cs",
    "content": "﻿namespace Nancy.Hosting.Self\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Text;\r\n\r\n    /// <summary>\r\n    /// Exception for when automatic address reservation creation fails.\r\n    /// Provides the user with manual instructions.\r\n    /// </summary>\r\n    public class AutomaticUrlReservationCreationFailureException : Exception\r\n    {\r\n        private readonly IEnumerable<string> prefixes;\r\n        private readonly string user;\r\n\r\n        public AutomaticUrlReservationCreationFailureException(IEnumerable<string> prefixes, string user)\r\n        {\r\n            this.prefixes = prefixes;\r\n            this.user = user;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a message that describes the current exception.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// The error message that explains the reason for the exception, or an empty string(\"\").\r\n        /// </returns>\r\n        /// <filterpriority>1</filterpriority>\r\n        public override string Message\r\n        {\r\n            get\r\n            {\r\n                var stringBuilder = new StringBuilder();\r\n\r\n                stringBuilder.AppendLine(\"The Nancy self host was unable to start, as no namespace reservation existed for the provided url(s).\");\r\n                stringBuilder.AppendLine();\r\n\r\n                stringBuilder.AppendLine(\"Please either enable UrlReservations.CreateAutomatically on the HostConfiguration provided to \");\r\n                stringBuilder.AppendLine(\"the NancyHost, or create the reservations manually with the (elevated) command(s):\");\r\n                stringBuilder.AppendLine();\r\n\r\n                foreach (var prefix in prefixes)\r\n                {\r\n                    var command = NetSh.GetParameters(prefix, user);\r\n                    stringBuilder.AppendLine(string.Format(\"netsh {0}\", command));\r\n                }\r\n\r\n                return stringBuilder.ToString();\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Hosting.Self/FileSystemRootPathProvider.cs",
    "content": "namespace Nancy.Hosting.Self\r\n{\r\n    using System;\r\n    using System.IO;\r\n    using System.Reflection;\r\n\r\n    public class FileSystemRootPathProvider : IRootPathProvider\r\n    {\r\n        private readonly Lazy<string> rootPath = new Lazy<string>(ExtractRootPath);\r\n\r\n        public string GetRootPath()\r\n        {\r\n            return this.rootPath.Value;\r\n        }\r\n\r\n        private static string ExtractRootPath()\r\n        {\r\n            var assembly =\r\n                Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly();\r\n\r\n            var location = assembly.Location;\r\n\r\n            return Path.GetDirectoryName(location);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Hosting.Self/HostConfiguration.cs",
    "content": "﻿namespace Nancy.Hosting.Self\r\n{\r\n    using System;\r\n    using System.Diagnostics;\r\n\r\n    /// <summary>\r\n    /// Host configuration for the self host.\r\n    /// </summary>\r\n    public sealed class HostConfiguration\r\n    {\r\n        /// <summary>\r\n        /// Gets or sets a property that determines if localhost URIs are \r\n        /// rewritten to http://+:port/ style URIs to allow for listening on \r\n        /// all IP addresses, but requiring either a URL reservation, or admin\r\n        /// access.\r\n        /// Defaults to true.\r\n        /// </summary>\r\n        public bool RewriteLocalhost { get; set; }\r\n\r\n        /// <summary>\r\n        /// Configuration around automatically creating URL reservations.\r\n        /// </summary>\r\n        public UrlReservations UrlReservations { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets a property that determines if Transfer-Encoding: Chunked is allowed\r\n        /// for the response instead of Content-Length.\r\n        /// Defaults to true.\r\n        /// </summary>\r\n        public bool AllowChunkedEncoding { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets a property that provides a callback to be called\r\n        /// if there is an unhandled exception in the self host.\r\n        /// Note: this will *not* be called for normal Nancy exceptions\r\n        /// that are handled by the Nancy handlers.\r\n        /// Defaults to writing to debug out.\r\n        /// </summary>\r\n        public Action<Exception> UnhandledExceptionCallback { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets a property that determines whether client certificates\r\n        /// are enabled or not.\r\n        /// When set to true the self host will request a client certificate if the \r\n        /// request is running over SSL.\r\n        /// Defaults to false.\r\n        /// </summary>\r\n        public bool EnableClientCertificates { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets a property determining if base URI matching can fall back to just\r\n        /// using Authority (Schema + Host + Port) as base URI if it cannot match anything in\r\n        /// the known list. This should only be set to True if you have issues with port forwarding\r\n        /// (e.g. on Azure).\r\n        /// Defaults to false.\r\n        /// </summary>\r\n        public bool AllowAuthorityFallback { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets a property determining how many total connections the NancyHost can maintain simultaneously.\r\n        /// Higher values mean more connections can be maintained at a slower average response times; while fewer\r\n        /// connections will be rejected.\r\n        /// Lower values will result in fewer conections, yet will be maintained at a faster average response time.\r\n        /// Defaults to the approximate number of processor threads.\r\n        /// </summary>\r\n        public int MaximumConnectionCount { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets approximate processor thread count by halfing the Logical Core count to \r\n        /// account for hyper-threading.\r\n        /// </summary>\r\n        private static int ProcessorThreadCount\r\n        {\r\n            get\r\n            {\r\n                // Divide by 2 for hyper-threading, and good defaults.\r\n                var threadCount = Environment.ProcessorCount >> 1;\r\n\r\n                if (threadCount < 1)\r\n                {\r\n                    // Ensure thread count is at least 1.\r\n                    return 1;\r\n                }\r\n\r\n                return threadCount;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes the default configuration.\r\n        /// MaximumConnectionCount by default is half of the Logical Core count.\r\n        /// </summary>\r\n        /// <remarks>\r\n        /// If the system running NancyHost is not using hyper-threading you may want to consider\r\n        /// supplying your own values for MaximumConnectionCount as the default assumes \r\n        /// hyperthreading is being utilized.\r\n        /// </remarks>\r\n        public HostConfiguration()\r\n        {\r\n            this.RewriteLocalhost = true;\r\n            this.UrlReservations = new UrlReservations();\r\n            this.AllowChunkedEncoding = true;\r\n            this.UnhandledExceptionCallback = e =>\r\n                {\r\n                    var message = string.Format(\"---\\n{0}\\n---\\n\", e);\r\n                    Debug.Write(message);\r\n                };\r\n            this.EnableClientCertificates = false;\r\n            this.MaximumConnectionCount = ProcessorThreadCount;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Hosting.Self/IgnoredHeaders.cs",
    "content": "﻿namespace Nancy.Hosting.Self\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    ///     A helper class that checks for a header against a list of headers that should be ignored\r\n    ///     when populating the headers of an <see cref=\"T:System.Net.HttpListenerResponse\"/> object.\r\n    /// </summary>\r\n    public static class IgnoredHeaders\r\n    {\r\n\r\n        private static readonly HashSet<string> knownHeaders = new HashSet<string>(StringComparer.OrdinalIgnoreCase)\r\n        {\r\n            \"content-length\",\r\n            \"content-type\",\r\n            \"transfer-encoding\",\r\n            \"keep-alive\"\r\n        };\r\n\r\n        /// <summary>\r\n        ///     Determines if a header is ignored when populating the headers of an\r\n        ///     <see cref=\"T:System.Net.HttpListenerResponse\"/> object.\r\n        /// </summary>\r\n        /// <param name=\"headerName\">The name of the header.</param>\r\n        /// <returns><c>true</c> if the header is ignored; otherwise, <c>false</c>.</returns>\r\n        public static bool IsIgnored(string headerName)\r\n        {\r\n            return knownHeaders.Contains(headerName);\r\n        }\r\n\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Hosting.Self/Nancy.Hosting.Self.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <Description>Enables hosting Nancy in any application.</Description>\n    <PackageTags>$(PackageTags);Host</PackageTags>\n    <TargetFrameworks>netstandard2.0;net452</TargetFrameworks>\n  </PropertyGroup>\n  <ItemGroup Condition=\"'$(TargetFramework)' == 'netstandard2.0'\">\r\n    <PackageReference Include=\"System.Security.Principal.Windows\">\r\n      <Version>4.3.0</Version>\r\n    </PackageReference>\r\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "src/Nancy.Hosting.Self/NancyHost.cs",
    "content": "﻿namespace Nancy.Hosting.Self\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Globalization;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Net;\r\n    using System.Security.Cryptography.X509Certificates;\r\n    using System.Security.Principal;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Extensions;\r\n    using Nancy.IO;\r\n    using System.Threading;\r\n\r\n    /// <summary>\r\n    /// Allows to host Nancy server inside any application - console or windows service.\r\n    /// </summary>\r\n    /// <remarks>\r\n    /// NancyHost uses <see cref=\"System.Net.HttpListener\"/> internally. Therefore, it requires full .net 4.0 profile (not client profile)\r\n    /// to run. <see cref=\"Start\"/> will launch a thread that will listen for requests and then process them. Each request is processed in\r\n    /// its own execution thread. NancyHost needs <see cref=\"SerializableAttribute\"/> in order to be used from another appdomain under\r\n    /// mono. Working with AppDomains is necessary if you want to unload the dependencies that come with NancyHost.\r\n    /// </remarks>\r\n    [Serializable]\r\n    public class NancyHost : IDisposable\r\n    {\r\n        private const int ACCESS_DENIED = 5;\r\n\r\n        private readonly IList<Uri> baseUriList;\r\n        private HttpListener listener;\r\n        private readonly INancyEngine engine;\r\n        private readonly HostConfiguration configuration;\r\n        private readonly INancyBootstrapper bootstrapper;\r\n        private bool stop = false;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancyHost\"/> class for the specified <paramref name=\"baseUris\"/>.\r\n        /// Uses the default configuration\r\n        /// </summary>\r\n        /// <param name=\"baseUris\">The <see cref=\"Uri\"/>s that the host will listen to.</param>\r\n        public NancyHost(params Uri[] baseUris)\r\n            : this(NancyBootstrapperLocator.Bootstrapper, new HostConfiguration(), baseUris) { }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancyHost\"/> class for the specified <paramref name=\"baseUris\"/>.\r\n        /// Uses the specified configuration.\r\n        /// </summary>\r\n        /// <param name=\"baseUris\">The <see cref=\"Uri\"/>s that the host will listen to.</param>\r\n        /// <param name=\"configuration\">Configuration to use</param>\r\n        public NancyHost(HostConfiguration configuration, params Uri[] baseUris)\r\n            : this(NancyBootstrapperLocator.Bootstrapper, configuration, baseUris){}\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancyHost\"/> class for the specified <paramref name=\"baseUris\"/>, using\r\n        /// the provided <paramref name=\"bootstrapper\"/>.\r\n        /// Uses the default configuration\r\n        /// </summary>\r\n        /// <param name=\"bootstrapper\">The bootstrapper that should be used to handle the request.</param>\r\n        /// <param name=\"baseUris\">The <see cref=\"Uri\"/>s that the host will listen to.</param>\r\n        public NancyHost(INancyBootstrapper bootstrapper, params Uri[] baseUris)\r\n            : this(bootstrapper, new HostConfiguration(), baseUris)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancyHost\"/> class for the specified <paramref name=\"baseUris\"/>, using\r\n        /// the provided <paramref name=\"bootstrapper\"/>.\r\n        /// Uses the specified configuration.\r\n        /// </summary>\r\n        /// <param name=\"bootstrapper\">The bootstrapper that should be used to handle the request.</param>\r\n        /// <param name=\"configuration\">Configuration to use</param>\r\n        /// <param name=\"baseUris\">The <see cref=\"Uri\"/>s that the host will listen to.</param>\r\n        public NancyHost(INancyBootstrapper bootstrapper, HostConfiguration configuration, params Uri[] baseUris)\r\n        {\r\n            this.bootstrapper = bootstrapper;\r\n            this.configuration = configuration ?? new HostConfiguration();\r\n            this.baseUriList = baseUris;\r\n\r\n            bootstrapper.Initialise();\r\n            this.engine = bootstrapper.GetEngine();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancyHost\"/> class for the specified <paramref name=\"baseUri\"/>, using\r\n        /// the provided <paramref name=\"bootstrapper\"/>.\r\n        /// Uses the default configuration\r\n        /// </summary>\r\n        /// <param name=\"baseUri\">The <see cref=\"Uri\"/> that the host will listen to.</param>\r\n        /// <param name=\"bootstrapper\">The bootstrapper that should be used to handle the request.</param>\r\n        public NancyHost(Uri baseUri, INancyBootstrapper bootstrapper)\r\n            : this(bootstrapper, new HostConfiguration(), baseUri)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancyHost\"/> class for the specified <paramref name=\"baseUri\"/>, using\r\n        /// the provided <paramref name=\"bootstrapper\"/>.\r\n        /// Uses the specified configuration.\r\n        /// </summary>\r\n        /// <param name=\"baseUri\">The <see cref=\"Uri\"/> that the host will listen to.</param>\r\n        /// <param name=\"bootstrapper\">The bootstrapper that should be used to handle the request.</param>\r\n        /// <param name=\"configuration\">Configuration to use</param>\r\n        public NancyHost(Uri baseUri, INancyBootstrapper bootstrapper, HostConfiguration configuration)\r\n            : this (bootstrapper, configuration, baseUri)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Stops the host if it is running.\r\n        /// </summary>\r\n        public void Dispose()\r\n        {\r\n            this.Stop();\r\n\r\n            this.bootstrapper.Dispose();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Start listening for incoming requests with the given configuration\r\n        /// </summary>\r\n        public void Start()\r\n        {\r\n            this.StartListener();\r\n\r\n            Task.Run(() =>\r\n            {\r\n                var semaphore = new Semaphore(this.configuration.MaximumConnectionCount, this.configuration.MaximumConnectionCount);\r\n                while (!this.stop)\r\n                {\r\n                    semaphore.WaitOne();\r\n\r\n                    this.listener.GetContextAsync().ContinueWith(async (contextTask) =>\r\n                    {\r\n                        try\r\n                        {\r\n                            semaphore.Release();\r\n                            var context = await contextTask.ConfigureAwait(false);\r\n                            await this.Process(context).ConfigureAwait(false);\r\n                        }\r\n                        catch (Exception ex)\r\n                        {\r\n                            this.configuration.UnhandledExceptionCallback.Invoke(ex);\r\n                            throw;\r\n                        }\r\n                    });\r\n                }\r\n            });\r\n        }\r\n\r\n        private void StartListener()\r\n        {\r\n            if (this.TryStartListener())\r\n            {\r\n                return;\r\n            }\r\n\r\n            if (!this.configuration.UrlReservations.CreateAutomatically)\r\n            {\r\n                throw new AutomaticUrlReservationCreationFailureException(this.GetPrefixes(), this.GetUser());\r\n            }\r\n\r\n            if (!this.TryAddUrlReservations())\r\n            {\r\n                throw new InvalidOperationException(\"Unable to configure namespace reservation\");\r\n            }\r\n\r\n            if (!this.TryStartListener())\r\n            {\r\n                throw new InvalidOperationException(\"Unable to start listener\");\r\n            }\r\n        }\r\n\r\n        private bool TryStartListener()\r\n        {\r\n            try\r\n            {\r\n                // if the listener fails to start, it gets disposed;\r\n                // so we need a new one, each time.\r\n                this.listener = new HttpListener();\r\n                foreach (var prefix in this.GetPrefixes())\r\n                {\r\n                    this.listener.Prefixes.Add(prefix);\r\n                }\r\n\r\n                this.listener.Start();\r\n\r\n                return true;\r\n            }\r\n            catch (HttpListenerException e)\r\n            {\r\n                if (e.ErrorCode == ACCESS_DENIED)\r\n                {\r\n                    return false;\r\n                }\r\n\r\n                throw;\r\n            }\r\n        }\r\n\r\n        private bool TryAddUrlReservations()\r\n        {\r\n            var user = this.GetUser();\r\n\r\n            foreach (var prefix in this.GetPrefixes())\r\n            {\r\n                if (!NetSh.AddUrlAcl(prefix, user))\r\n                {\r\n                    return false;\r\n                }\r\n            }\r\n\r\n            return true;\r\n        }\r\n\r\n        private string GetUser()\r\n        {\r\n            return !string.IsNullOrWhiteSpace(this.configuration.UrlReservations.User)\r\n                ? this.configuration.UrlReservations.User\r\n                : WindowsIdentity.GetCurrent().Name;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Stop listening for incoming requests.\r\n        /// </summary>\r\n        public void Stop()\r\n        {\r\n            if (this.listener != null && this.listener.IsListening)\r\n            {\r\n                this.stop = true;\r\n                this.listener.Stop();\r\n            }\r\n        }\r\n\r\n        internal IEnumerable<string> GetPrefixes()\r\n        {\r\n            foreach (var baseUri in this.baseUriList)\r\n            {\r\n                var prefix = new UriBuilder(baseUri).ToString();\r\n\r\n                if (this.configuration.RewriteLocalhost && !baseUri.Host.Contains(\".\"))\r\n                {\r\n                    prefix = prefix.Replace(\"localhost\", \"+\");\r\n                }\r\n\r\n                yield return prefix;\r\n            }\r\n        }\r\n\r\n        private Request ConvertRequestToNancyRequest(HttpListenerRequest request)\r\n        {\r\n            var baseUri = this.GetBaseUri(request);\r\n\r\n            if (baseUri == null)\r\n            {\r\n                throw new InvalidOperationException(string.Format(\"Unable to locate base URI for request: {0}\",request.Url));\r\n            }\r\n\r\n            var expectedRequestLength =\r\n                GetExpectedRequestLength(request.Headers.ToDictionary());\r\n\r\n\r\n            var nancyUrl = new Url\r\n            {\r\n                Scheme = request.Url.Scheme,\r\n                HostName = request.Url.Host,\r\n                Port = request.Url.IsDefaultPort ? null : (int?)request.Url.Port,\r\n                BasePath = baseUri.AbsolutePath.TrimEnd('/'),\r\n                Path = baseUri.MakeAppLocalPath(request.Url),\r\n                Query = request.Url.Query\r\n            };\r\n\r\n            X509Certificate2 certificate = null;\r\n\r\n            if (this.configuration.EnableClientCertificates)\r\n            {\r\n                var x509Certificate = request.GetClientCertificate();\r\n\r\n                if (x509Certificate != null)\r\n                {\r\n                    certificate = x509Certificate;\r\n                }\r\n            }\r\n\r\n            // NOTE: For HTTP/2 we want fieldCount = 1,\r\n            // otherwise (HTTP/1.0 and HTTP/1.1) we want fieldCount = 2\r\n            var fieldCount = request.ProtocolVersion.Major == 2 ? 1 : 2;\r\n\r\n            var protocolVersion = string.Format(\"HTTP/{0}\", request.ProtocolVersion.ToString(fieldCount));\r\n\r\n            return new Request(\r\n                request.HttpMethod,\r\n                nancyUrl,\r\n                RequestStream.FromStream(request.InputStream, expectedRequestLength, StaticConfiguration.DisableRequestStreamSwitching ?? false),\r\n                request.Headers.ToDictionary(),\r\n                (request.RemoteEndPoint != null) ? request.RemoteEndPoint.Address.ToString() : null,\r\n                certificate,\r\n                protocolVersion);\r\n        }\r\n\r\n        private Uri GetBaseUri(HttpListenerRequest request)\r\n        {\r\n            var result = this.baseUriList.FirstOrDefault(uri => uri.IsCaseInsensitiveBaseOf(request.Url));\r\n\r\n            if (result != null)\r\n            {\r\n                return result;\r\n            }\r\n\r\n            if (!this.configuration.AllowAuthorityFallback)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            return new Uri(request.Url.GetLeftPart(UriPartial.Authority));\r\n        }\r\n\r\n        private void ConvertNancyResponseToResponse(Response nancyResponse, HttpListenerResponse response)\r\n        {\r\n            foreach (var header in nancyResponse.Headers)\r\n            {\r\n                if (!IgnoredHeaders.IsIgnored(header.Key))\r\n                {\r\n                    response.AddHeader(header.Key, header.Value);\r\n                }\r\n            }\r\n\r\n            foreach (var nancyCookie in nancyResponse.Cookies)\r\n            {\r\n                response.Headers.Add(HttpResponseHeader.SetCookie, nancyCookie.ToString());\r\n            }\r\n\r\n            if (nancyResponse.ReasonPhrase != null)\r\n            {\r\n                response.StatusDescription = nancyResponse.ReasonPhrase;\r\n            }\r\n\r\n            if (nancyResponse.ContentType != null)\r\n            {\r\n                response.ContentType = nancyResponse.ContentType;\r\n            }\r\n\r\n            response.StatusCode = (int)nancyResponse.StatusCode;\r\n\r\n            if (this.configuration.AllowChunkedEncoding)\r\n            {\r\n                OutputWithDefaultTransferEncoding(nancyResponse, response);\r\n            }\r\n            else\r\n            {\r\n                OutputWithContentLength(nancyResponse, response);\r\n            }\r\n        }\r\n\r\n        private static void OutputWithDefaultTransferEncoding(Response nancyResponse, HttpListenerResponse response)\r\n        {\r\n            using (var output = response.OutputStream)\r\n            {\r\n                nancyResponse.Contents.Invoke(output);\r\n            }\r\n        }\r\n\r\n        private static void OutputWithContentLength(Response nancyResponse, HttpListenerResponse response)\r\n        {\r\n            byte[] buffer;\r\n            using (var memoryStream = new MemoryStream())\r\n            {\r\n                nancyResponse.Contents.Invoke(memoryStream);\r\n                buffer = memoryStream.ToArray();\r\n            }\r\n\r\n            string value;\r\n            var contentLength = nancyResponse.Headers.TryGetValue(\"Content-Length\", out value) ?\r\n                Convert.ToInt64(value) :\r\n                buffer.Length;\r\n\r\n            response.SendChunked = false;\r\n            response.ContentLength64 = contentLength;\r\n\r\n            using (var output = response.OutputStream)\r\n            {\r\n                using (var writer = new BinaryWriter(output))\r\n                {\r\n                    writer.Write(buffer);\r\n                    writer.Flush();\r\n                }\r\n            }\r\n        }\r\n\r\n        private static long GetExpectedRequestLength(IDictionary<string, IEnumerable<string>> incomingHeaders)\r\n        {\r\n            if (incomingHeaders == null)\r\n            {\r\n                return 0;\r\n            }\r\n\r\n            IEnumerable<string> values;\r\n            if (!incomingHeaders.TryGetValue(\"Content-Length\", out values))\r\n            {\r\n                return 0;\r\n            }\r\n\r\n            var headerValue = values.SingleOrDefault();\r\n\r\n            if (headerValue == null)\r\n            {\r\n                return 0;\r\n            }\r\n\r\n            long contentLength;\r\n\r\n            return !long.TryParse(headerValue, NumberStyles.Any, CultureInfo.InvariantCulture, out contentLength) ?\r\n                0 :\r\n                contentLength;\r\n        }\r\n\r\n        private async Task Process(HttpListenerContext ctx)\r\n        {\r\n            try\r\n            {\r\n                var nancyRequest = this.ConvertRequestToNancyRequest(ctx.Request);\r\n                using (var nancyContext = await this.engine.HandleRequest(nancyRequest).ConfigureAwait(false))\r\n                {\r\n                    try\r\n                    {\r\n                        this.ConvertNancyResponseToResponse(nancyContext.Response, ctx.Response);\r\n                    }\r\n                    catch (Exception e)\r\n                    {\r\n                        this.configuration.UnhandledExceptionCallback.Invoke(e);\r\n                    }\r\n                }\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                this.configuration.UnhandledExceptionCallback.Invoke(e);\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Hosting.Self/NetSh.cs",
    "content": "﻿namespace Nancy.Hosting.Self\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Executes NetSh commands\r\n    /// </summary>\r\n    public static class NetSh\r\n    {\r\n        private const string NetshCommand = \"netsh\";\r\n\r\n        /// <summary>\r\n        /// Add a url reservation\r\n        /// </summary>\r\n        /// <param name=\"url\">Url to add</param>\r\n        /// <param name=\"user\">User to add the reservation for</param>\r\n        /// <returns>True if successful, false otherwise.</returns>\r\n        public static bool AddUrlAcl(string url, string user)\r\n        {\r\n            try\r\n            {\r\n                var arguments = GetParameters(url, user);\r\n\r\n                return UacHelper.RunElevated(NetshCommand, arguments);\r\n            }\r\n            catch (Exception)\r\n            {\r\n                return false;\r\n            }\r\n        }\r\n\r\n        internal static string GetParameters(string url, string user)\r\n        {\r\n            return string.Format(\"http add urlacl url=\\\"{0}\\\" user=\\\"{1}\\\"\", url, user);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Hosting.Self/Properties/InternalsVisibleTo.cs",
    "content": "﻿using System.Runtime.CompilerServices;\r\n\r\n[assembly: InternalsVisibleTo(\"Nancy.Hosting.Self.Tests\")]\r\n"
  },
  {
    "path": "src/Nancy.Hosting.Self/UacHelper.cs",
    "content": "﻿namespace Nancy.Hosting.Self\r\n{\r\n    using System.Diagnostics;\r\n\r\n    /// <summary>\r\n    /// Helpers for UAC\r\n    /// </summary>\r\n    public static class UacHelper\r\n    {\r\n        /// <summary>\r\n        /// Run an executable elevated\r\n        /// </summary>\r\n        /// <param name=\"file\">File to execute</param>\r\n        /// <param name=\"args\">Arguments to pass to the executable</param>\r\n        /// <returns>True if successful, false otherwise</returns>\r\n        public static bool RunElevated(string file, string args)\r\n        {\r\n            var process = CreateProcess(args, file);\r\n\r\n            process.Start();\r\n            process.WaitForExit();\r\n\r\n            return process.ExitCode == 0;\r\n        }\r\n\r\n        private static Process CreateProcess(string args, string file)\r\n        {\r\n            return new Process\r\n            {\r\n                StartInfo = new ProcessStartInfo\r\n                {\r\n                    Verb = \"runas\",\r\n                    Arguments = args,\r\n                    FileName = file,\r\n                }\r\n            };\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Hosting.Self/UriExtensions.cs",
    "content": "namespace Nancy.Hosting.Self\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Text;\r\n\r\n    /// <summary>\r\n    /// Extension methods for working with <see cref=\"Uri\"/> instances.\r\n    /// </summary>\r\n    public static class UriExtensions\r\n    {\r\n        public static bool IsCaseInsensitiveBaseOf(this Uri source, Uri value)\r\n        {\r\n            var uriComponents = source.Host == \"localhost\" ? (UriComponents.Port | UriComponents.Scheme) : (UriComponents.HostAndPort | UriComponents.Scheme);\r\n            if (Uri.Compare(source, value, uriComponents, UriFormat.Unescaped, StringComparison.OrdinalIgnoreCase) != 0)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            var sourceSegments = source.Segments;\r\n            var valueSegments = value.Segments;\r\n\r\n            return sourceSegments.ZipCompare(valueSegments, (s1, s2) => s1.Length == 0 || SegmentEquals(s1, s2));\r\n        }\r\n\r\n        public static string MakeAppLocalPath(this Uri appBaseUri, Uri fullUri)\r\n        {\r\n            return string.Concat(\"/\", appBaseUri.Segments.ZipFill(fullUri.Segments, (x, y) => x != null && SegmentEquals(x, y) ? null : y).Join());\r\n        }\r\n\r\n        private static string AppendSlashIfNeeded(string segment)\r\n        {\r\n            if (!segment.EndsWith(\"/\"))\r\n            {\r\n                segment = string.Concat(segment, \"/\");\r\n            }\r\n\r\n            return segment;\r\n        }\r\n\r\n        private static bool SegmentEquals(string segment1, string segment2)\r\n        {\r\n            return String.Equals(AppendSlashIfNeeded(segment1), AppendSlashIfNeeded(segment2), StringComparison.OrdinalIgnoreCase);\r\n        }\r\n\r\n        private static bool ZipCompare(this IEnumerable<string> source1, IEnumerable<string> source2, Func<string, string, bool> comparison)\r\n        {\r\n            using (var enumerator1 = source1.GetEnumerator())\r\n            {\r\n                using (var enumerator2 = source2.GetEnumerator())\r\n                {\r\n                    var has1 = enumerator1.MoveNext();\r\n                    var has2 = enumerator2.MoveNext();\r\n\r\n                    while (has1 || has2)\r\n                    {\r\n                        var current1 = has1 ? enumerator1.Current : \"\";\r\n                        var current2 = has2 ? enumerator2.Current : \"\";\r\n\r\n                        if (!comparison(current1, current2))\r\n                        {\r\n                            return false;\r\n                        }\r\n\r\n                        if (has1)\r\n                        {\r\n                            has1 = enumerator1.MoveNext();\r\n                        }\r\n\r\n                        if (has2)\r\n                        {\r\n                            has2 = enumerator2.MoveNext();\r\n                        }\r\n                    }\r\n\r\n                }\r\n            }\r\n\r\n            return true;\r\n        }\r\n\r\n        private static IEnumerable<string> ZipFill(this IEnumerable<string> source1, IEnumerable<string> source2, Func<string, string, string> selector)\r\n        {\r\n            using (var enumerator1 = source1.GetEnumerator())\r\n            {\r\n                using (var enumerator2 = source2.GetEnumerator())\r\n                {\r\n                    var has1 = enumerator1.MoveNext();\r\n                    var has2 = enumerator2.MoveNext();\r\n\r\n                    while (has1 || has2)\r\n                    {\r\n                        var value1 = has1 ? enumerator1.Current : null;\r\n                        var value2 = has2 ? enumerator2.Current : null;\r\n                        var value = selector(value1, value2);\r\n\r\n                        if (value != null)\r\n                        {\r\n                            yield return value;\r\n                        }\r\n\r\n                        if (has1)\r\n                        {\r\n                            has1 = enumerator1.MoveNext();\r\n                        }\r\n\r\n                        if (has2)\r\n                        {\r\n                            has2 = enumerator2.MoveNext();\r\n                        }\r\n                    }\r\n\r\n                }\r\n            }\r\n        }\r\n\r\n        private static string Join(this IEnumerable<string> source)\r\n        {\r\n            var builder = new StringBuilder();\r\n\r\n            foreach (var value in source)\r\n            {\r\n                builder.Append(value);\r\n            }\r\n\r\n            return builder.ToString();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Hosting.Self/UrlReservations.cs",
    "content": "﻿namespace Nancy.Hosting.Self\r\n{\r\n    using System;\r\n    using System.Security.Principal;\r\n\r\n    /// <summary>\r\n    /// Configuration for automatic url reservation creation\r\n    /// </summary>\r\n    public class UrlReservations\r\n    {\r\n        private const string EveryoneAccountName = \"Everyone\";\r\n\r\n        private static readonly IdentityReference EveryoneReference =\r\n            new SecurityIdentifier(WellKnownSidType.WorldSid, null);\r\n\r\n        public UrlReservations()\r\n        {\r\n            this.CreateAutomatically = false;\r\n            this.User = GetEveryoneAccountName();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets a value indicating whether url reservations\r\n        /// are automatically created when necessary.\r\n        /// Defaults to false.\r\n        /// </summary>\r\n        public bool CreateAutomatically { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets a value for the user to use to create the url reservations for.\r\n        /// Defaults to the \"Everyone\" group.\r\n        /// </summary>\r\n        public string User { get; set; }\r\n\r\n        private static string GetEveryoneAccountName()\r\n        {\r\n            try\r\n            {\r\n                var account = EveryoneReference.Translate(typeof(NTAccount)) as NTAccount;\r\n                if (account != null)\r\n                {\r\n                    return account.Value;\r\n                }\r\n\r\n                return EveryoneAccountName;\r\n            }\r\n            catch (Exception)\r\n            {\r\n                return EveryoneAccountName;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Metadata.Modules/DefaultMetadataModuleConventions.cs",
    "content": "﻿namespace Nancy.Metadata.Modules\r\n{\r\n    using System;\r\n    using System.Collections;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// This is a wrapper around the type\r\n    /// 'IEnumerable{Func{INancyModule, IEnumerable{IMetadataModule}, IMetadataModule}}' and its\r\n    /// only purpose is to make Ninject happy which was throwing an exception\r\n    /// when constructor injecting this type.\r\n    /// </summary>\r\n    public class DefaultMetadataModuleConventions : IEnumerable<Func<INancyModule, IEnumerable<IMetadataModule>, IMetadataModule>>\r\n    {\r\n        private readonly IEnumerable<Func<INancyModule, IEnumerable<IMetadataModule>, IMetadataModule>> conventions;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultMetadataModuleConventions\"/> class.\r\n        /// </summary>\r\n        public DefaultMetadataModuleConventions()\r\n        {\r\n            this.conventions = this.ConfigureMetadataModuleConventions();\r\n        }\r\n\r\n        public IEnumerator<Func<INancyModule, IEnumerable<IMetadataModule>, IMetadataModule>> GetEnumerator()\r\n        {\r\n            return this.conventions.GetEnumerator();\r\n        }\r\n\r\n        IEnumerator IEnumerable.GetEnumerator()\r\n        {\r\n            return this.GetEnumerator();\r\n        }\r\n\r\n        private static string ReplaceModuleWithMetadataModule(string moduleName)\r\n        {\r\n            var i = moduleName.LastIndexOf(\"Module\");\r\n            return moduleName.Substring(0, i) + \"MetadataModule\";\r\n        }\r\n\r\n        private IEnumerable<Func<INancyModule, IEnumerable<IMetadataModule>, IMetadataModule>> ConfigureMetadataModuleConventions()\r\n        {\r\n            return new List<Func<INancyModule, IEnumerable<IMetadataModule>, IMetadataModule>>\r\n                {\r\n                    // 0 Handles: ./BlahModule -> ./BlahMetadataModule\r\n                    (module, metadataModules) =>\r\n                        {\r\n                            var moduleType = module.GetType();\r\n                            var moduleName = moduleType.FullName;\r\n                            var metadataModuleName = ReplaceModuleWithMetadataModule(moduleName);\r\n\r\n                            return metadataModules.FirstOrDefault(m =>\r\n                                    string.Compare(m.GetType().FullName, metadataModuleName, StringComparison.OrdinalIgnoreCase) == 0);\r\n                        },\r\n\r\n                    // 1 Handles: ./BlahModule -> ./Metadata/BlahMetadataModule\r\n                    (module, metadataModules) =>\r\n                        {\r\n                            var moduleType = module.GetType();\r\n                            var moduleName = moduleType.FullName;\r\n                            var parts = moduleName.Split('.').ToList();\r\n                            parts.Insert(parts.Count - 1, \"Metadata\");\r\n\r\n                            var metadataModuleName = ReplaceModuleWithMetadataModule(string.Join(\".\", (IEnumerable<string>)parts));\r\n\r\n                            return metadataModules.FirstOrDefault(m =>\r\n                                    string.Compare(m.GetType().FullName, metadataModuleName, StringComparison.OrdinalIgnoreCase) == 0);\r\n                        },\r\n\r\n                    // 2 Handles: ./Modules/BlahModule -> ../Metadata/BlahMetadataModule\r\n                    (module, metadataModules) =>\r\n                        {\r\n                            var moduleType = module.GetType();\r\n                            var moduleName = moduleType.FullName;\r\n                            var parts = moduleName.Split('.').ToList();\r\n                            parts[parts.Count - 2] = \"Metadata\";\r\n\r\n                            var metadataModuleName = ReplaceModuleWithMetadataModule(string.Join(\".\", (IEnumerable<string>)parts));\r\n\r\n                            return metadataModules.FirstOrDefault(m =>\r\n                                    string.Compare(m.GetType().FullName, metadataModuleName, StringComparison.OrdinalIgnoreCase) == 0);\r\n                        }\r\n                };\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Metadata.Modules/DefaultMetadataModuleResolver.cs",
    "content": "﻿namespace Nancy.Metadata.Modules\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Default implementation on how metadata modules are resolved by Nancy.\r\n    /// </summary>\r\n    public class DefaultMetadataModuleResolver : IMetadataModuleResolver\r\n    {\r\n        private readonly DefaultMetadataModuleConventions conventions;\r\n\r\n        private readonly IEnumerable<IMetadataModule> metadataModules;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultMetadataModuleResolver\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"conventions\">The conventions that the resolver should use to determine which metadata module to return.</param>\r\n        /// <param name=\"metadataModules\">The metadata modules to use resolve against.</param>\r\n        public DefaultMetadataModuleResolver(DefaultMetadataModuleConventions conventions, IEnumerable<IMetadataModule> metadataModules)\r\n        {\r\n            if (conventions == null)\r\n            {\r\n                throw new InvalidOperationException(\"Cannot create an instance of DefaultMetadataModuleResolver with conventions parameter having null value.\");\r\n            }\r\n\r\n            if (metadataModules == null)\r\n            {\r\n                throw new InvalidOperationException(\"Cannot create an instance of DefaultMetadataModuleResolver with metadataModules parameter having null value.\");\r\n            }\r\n\r\n            this.conventions = conventions;\r\n            this.metadataModules = metadataModules;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Resolves a metadata module instance based on the provided information.\r\n        /// </summary>\r\n        /// <param name=\"module\">The <see cref=\"INancyModule\"/>.</param>\r\n        /// <returns>An <see cref=\"IMetadataModule\"/> instance if one could be found, otherwise <see langword=\"null\"/>.</returns>\r\n        public IMetadataModule GetMetadataModule(INancyModule module)\r\n        {\r\n            return this.conventions\r\n                .Select(convention => this.SafeInvokeConvention(convention, module))\r\n                .FirstOrDefault(metadataModule => metadataModule != null);\r\n        }\r\n\r\n        private IMetadataModule SafeInvokeConvention(Func<INancyModule, IEnumerable<IMetadataModule>, IMetadataModule> convention, INancyModule module)\r\n        {\r\n            try\r\n            {\r\n                return convention.Invoke(module, this.metadataModules);\r\n            }\r\n            catch\r\n            {\r\n                return null;\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Metadata.Modules/IMetadataModule.cs",
    "content": "﻿namespace Nancy.Metadata.Modules\r\n{\r\n    using System;\r\n\r\n    using Nancy.Routing;\r\n\r\n    /// <summary>\r\n    /// Defines facilities for obtaining metadata for a given <see cref=\"RouteDescription\"/>.\r\n    /// </summary>\r\n    public interface IMetadataModule\r\n    {\r\n        /// <summary>\r\n        /// Gets the <see cref=\"Type\"/> of metadata the <see cref=\"IMetadataModule\"/> returns.\r\n        /// </summary>\r\n        Type MetadataType { get; }\r\n\r\n        /// <summary>\r\n        /// Returns metadata for the given <see cref=\"RouteDescription\"/>.\r\n        /// </summary>\r\n        /// <param name=\"description\">The route to obtain metadata for.</param>\r\n        /// <returns>An instance of <see cref=\"MetadataType\"/> if one exists, otherwise null.</returns>\r\n        object GetMetadata(RouteDescription description);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Metadata.Modules/IMetadataModuleResolver.cs",
    "content": "﻿namespace Nancy.Metadata.Modules\r\n{\r\n    /// <summary>\r\n    /// Defines the functionality for resolving the metadata module for a given <see cref=\"INancyModule\"/>.\r\n    /// </summary>\r\n    public interface IMetadataModuleResolver\r\n    {\r\n        /// <summary>\r\n        /// Resolves a metadata module instance based on the provided information.\r\n        /// </summary>\r\n        /// <param name=\"module\">The <see cref=\"INancyModule\"/>.</param>\r\n        /// <returns>An <see cref=\"IMetadataModule\"/> instance if one could be found, otherwise <see langword=\"null\"/>.</returns>\r\n        IMetadataModule GetMetadataModule(INancyModule module);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Metadata.Modules/MetadataModule.cs",
    "content": "﻿namespace Nancy.Metadata.Modules\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    using Nancy.Routing;\r\n\r\n    /// <summary>\r\n    /// Base class containing the functionality for obtaining metadata for a given <see cref=\"RouteDescription\"/>.\r\n    /// </summary>\r\n    public abstract class MetadataModule<TMetadata> : IMetadataModule where TMetadata : class\r\n    {\r\n        private readonly IDictionary<string, Func<RouteDescription, TMetadata>> metadata;\r\n\r\n        protected MetadataModule()\r\n        {\r\n            this.metadata = new Dictionary<string, Func<RouteDescription, TMetadata>>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets <see cref=\"RouteMetadataBuilder\"/> for describing routes.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"RouteMetadataBuilder\"/> instance.</value>\r\n        public RouteMetadataBuilder Describe\r\n        {\r\n            get { return new RouteMetadataBuilder(this); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"Type\"/> of metadata based on <typeparamref name=\"TMetadata\" />.\r\n        /// </summary>\r\n        public Type MetadataType\r\n        {\r\n            get\r\n            {\r\n                return typeof(TMetadata);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns metadata for the given <see cref=\"RouteDescription\"/>.\r\n        /// </summary>\r\n        /// <param name=\"description\">The route to obtain metadata for.</param>\r\n        /// <returns>An instance of <see cref=\"MetadataType\"/> if one exists, otherwise null.</returns>\r\n        public object GetMetadata(RouteDescription description)\r\n        {\r\n            Func<RouteDescription, TMetadata> func;\r\n            if (this.metadata.TryGetValue(description.Name, out func))\r\n            {\r\n                return func.Invoke(description);\r\n            }\r\n\r\n            return null;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Helper class for configuring a route metadata handler in a module.\r\n        /// </summary>\r\n        public class RouteMetadataBuilder\r\n        {\r\n            private readonly MetadataModule<TMetadata> parentModule;\r\n\r\n            /// <summary>\r\n            /// Initializes a new instance of the <see cref=\"RouteMetadataBuilder\"/> class.\r\n            /// </summary>\r\n            /// <param name=\"metadataModule\">The <see cref=\"MetadataModule{TMetadata}\"/> that the route is being configured for.</param>\r\n            public RouteMetadataBuilder(MetadataModule<TMetadata> metadataModule)\r\n            {\r\n                this.parentModule = metadataModule;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Describes metadata for a route with the specified <paramref name=\"name\"/>.\r\n            /// </summary>\r\n            /// <value>A delegate that is used to return the route metadata.</value>\r\n            public Func<RouteDescription, TMetadata> this[string name]\r\n            {\r\n                set { this.AddRouteMetadata(name, value); }\r\n            }\r\n\r\n            protected void AddRouteMetadata(string name, Func<RouteDescription, TMetadata> value)\r\n            {\r\n                this.parentModule.metadata.Add(name, value);\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Metadata.Modules/MetadataModuleRegistrations.cs",
    "content": "﻿namespace Nancy.Metadata.Modules\r\n{\r\n    using Nancy.Bootstrapper;\r\n\r\n    /// <summary>\r\n    /// Performs application registations for metadata modules.\r\n    /// </summary>\r\n    public class MetadataModuleRegistrations : Registrations\r\n    {\r\n        /// <summary>\r\n        /// Creates a new instance of the <see cref=\"MetadataModuleRegistrations\"/> class, that performs\r\n        /// the default registrations of the metadata modules types.\r\n        /// </summary>\r\n        /// <param name=\"typeCatalog\">An <see cref=\"ITypeCatalog\"/> instance.</param>\r\n        public MetadataModuleRegistrations(ITypeCatalog typeCatalog) : base(typeCatalog)\r\n        {\r\n            this.Register<DefaultMetadataModuleConventions>();\r\n            this.RegisterAll<IMetadataModule>();\r\n            this.RegisterWithDefault<IMetadataModuleResolver>(typeof(DefaultMetadataModuleResolver));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Metadata.Modules/MetadataModuleRouteMetadataProvider.cs",
    "content": "﻿namespace Nancy.Metadata.Modules\r\n{\r\n    using System;\r\n\r\n    using Nancy.Routing;\r\n\r\n    /// <summary>\r\n    /// Provides metadata for routes by obtaining it from <see cref=\"IMetadataModule\"/> instances associated with <see cref=\"INancyModule\"/>.\r\n    /// </summary>\r\n    public class MetadataModuleRouteMetadataProvider : IRouteMetadataProvider\r\n    {\r\n        private readonly IMetadataModuleResolver resolver;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"MetadataModuleRouteMetadataProvider\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"resolver\">Resolves <see cref=\"IMetadataModule\"/> instances.</param>\r\n        public MetadataModuleRouteMetadataProvider(IMetadataModuleResolver resolver)\r\n        {\r\n            this.resolver = resolver;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"Type\"/> of the metadata that is created by the provider.\r\n        /// </summary>\r\n        /// <param name=\"module\">The <see cref=\"INancyModule\"/> instance that the route is declared in.</param>\r\n        /// <param name=\"routeDescription\">A <see cref=\"RouteDescription\"/> for the route.</param>\r\n        /// <returns>A <see cref=\"Type\"/> instance, or null if none are found.</returns>\r\n        public Type GetMetadataType(INancyModule module, RouteDescription routeDescription)\r\n        {\r\n            var metadataModule = this.resolver.GetMetadataModule(module);\r\n\r\n            return metadataModule != null ? metadataModule.MetadataType : null;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the metadata for the provided route by obtaining it from an associated <see cref=\"IMetadataModule\"/>.\r\n        /// </summary>\r\n        /// <param name=\"module\">The <see cref=\"INancyModule\"/> instance that the route is declared in.</param>\r\n        /// <param name=\"routeDescription\">A <see cref=\"RouteDescription\"/> for the route.</param>\r\n        /// <returns>An object representing the metadata for the given route, or null if none are found.</returns>\r\n        public object GetMetadata(INancyModule module, RouteDescription routeDescription)\r\n        {\r\n            var metadataModule = this.resolver.GetMetadataModule(module);\r\n\r\n            return metadataModule != null ? metadataModule.GetMetadata(routeDescription) : null;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Metadata.Modules/Nancy.Metadata.Modules.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <Description>Nancy metadata modules to describe your APIs.</Description>\n    <PackageTags>$(PackageTags);Metadata</PackageTags>\n    <TargetFrameworks>netstandard2.0;net452</TargetFrameworks>\n  </PropertyGroup>\n</Project>\n"
  },
  {
    "path": "src/Nancy.Owin/AppBuilderExtensions.cs",
    "content": "﻿// ReSharper disable CheckNamespace\r\nnamespace Owin\r\n// ReSharper restore CheckNamespace\r\n{\r\n    using System;\r\n    using System.Threading;\r\n\r\n    using Nancy.Owin;\r\n\r\n    /// <summary>\r\n    /// OWIN extensions for Nancy\r\n    /// </summary>\r\n    public static class AppBuilderExtensions\r\n    {\r\n        private const string AppDisposingKey = \"host.OnAppDisposing\";\r\n\r\n        /// <summary>\r\n        /// Adds Nancy to the OWIN pipeline.\r\n        /// </summary>\r\n        /// <param name=\"builder\">The application builder.</param>\r\n        /// <param name=\"options\">The Nancy options.</param>\r\n        /// <returns>IAppBuilder.</returns>\r\n        public static IAppBuilder UseNancy(this IAppBuilder builder, NancyOptions options = null)\r\n        {\r\n            var nancyOptions = options ?? new NancyOptions();\r\n\r\n            HookDisposal(builder, nancyOptions);\r\n\r\n            return builder.Use(NancyMiddleware.UseNancy(nancyOptions));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds Nancy to the OWIN pipeline.\r\n        /// </summary>\r\n        /// <param name=\"builder\">The application builder.</param>\r\n        /// <param name=\"configuration\">A configuration builder action.</param>\r\n        /// <returns>IAppBuilder.</returns>\r\n        public static IAppBuilder UseNancy(this IAppBuilder builder, Action<NancyOptions> configuration)\r\n        {\r\n            var options = new NancyOptions();\r\n            configuration(options);\r\n            return UseNancy(builder, options);\r\n        }\r\n\r\n        private static void HookDisposal(IAppBuilder builder, NancyOptions nancyOptions)\r\n        {\r\n            object value;\r\n            if (!builder.Properties.TryGetValue(AppDisposingKey, out value))\r\n            {\r\n                return;\r\n            }\r\n\r\n            var appDisposing = value as CancellationToken?;\r\n\r\n            if (appDisposing.HasValue)\r\n            {\r\n                appDisposing.Value.Register(nancyOptions.Bootstrapper.Dispose);\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Owin/Nancy.Owin.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <Description>Nancy extensions for OWIN hosting.</Description>\n    <PackageTags>$(PackageTags);OWIN</PackageTags>\n    <TargetFramework>net452</TargetFramework>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <PackageReference Include=\"OWIN\" Version=\"1.0.0\" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "src/Nancy.Testing/Accept.cs",
    "content": "namespace Nancy.Testing\r\n{\r\n    /// <summary>\r\n    /// Constants for accept header media ranges\r\n    /// </summary>\r\n    public static class Accept\r\n    {\r\n        /// <summary>\r\n        /// Json media range\r\n        /// </summary>\r\n        /// <value>application/json</value>\r\n        public const string Json = \"application/json\";\r\n\r\n        /// <summary>\r\n        /// Html media range\r\n        /// </summary>\r\n        /// <value>text/html</value>\r\n        public const string Html = \"text/html\";\r\n\r\n        /// <summary>\r\n        /// Text media range\r\n        /// </summary>\r\n        /// <value>>text/plain</value>\r\n        public const string Text = \"text/plain\";\r\n\r\n        /// <summary>\r\n        /// Xml media range\r\n        /// </summary>\r\n        /// <value>application/xml</value>\r\n        public const string Xml = \"application/xml\";\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Testing/AndConnector.cs",
    "content": "namespace Nancy.Testing\r\n{\r\n    public class AndConnector<TSource> : IHideObjectMembers\r\n    {\r\n        private TSource source;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"AndConnector{TSource}\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"source\">\r\n        /// Source object\r\n        /// </param>\r\n        public AndConnector(TSource source)\r\n        {\r\n            this.source = source;\r\n        }\r\n\r\n        /// <summary>\r\n        /// And\r\n        /// </summary>\r\n        public TSource And\r\n        {\r\n            get\r\n            {\r\n                return this.source;\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Testing/AssertEqualityComparer.cs",
    "content": "﻿namespace Nancy.Testing\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Reflection;\r\n\r\n    public class AssertEqualityComparer<T> : IEqualityComparer<T>\r\n    {\r\n        private static bool IsTypeNullable(Type type)\r\n        {\r\n            return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);\r\n        }\r\n\r\n        public bool Equals(T expected, T actual)\r\n        {\r\n            var type =\r\n                typeof(T);\r\n\r\n            if (!type.GetTypeInfo().IsValueType || IsTypeNullable(type))\r\n            {\r\n                var actualIsNull =\r\n                    (Object.Equals(actual, default(T)));\r\n\r\n                var expectedIsNull =\r\n                    (Object.Equals(expected, default(T)));\r\n\r\n                if (actualIsNull || expectedIsNull)\r\n                {\r\n                    return false;\r\n                }\r\n            }\r\n\r\n            var equality = actual as IEquatable<T>;\r\n            if (equality != null)\r\n            {\r\n                return equality.Equals(expected);\r\n            }\r\n\r\n            var genericComparable = actual as IComparable<T>;\r\n            if (genericComparable != null)\r\n            {\r\n                return genericComparable.CompareTo(expected) == 0;\r\n            }\r\n\r\n            var comparable = actual as IComparable;\r\n            if (comparable != null)\r\n            {\r\n                return comparable.CompareTo(expected) == 0;\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        public int GetHashCode(T actual)\r\n        {\r\n            throw new NotSupportedException();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Testing/AssertException.cs",
    "content": "namespace Nancy.Testing\r\n{\r\n    using System;\r\n    using System.Runtime.Serialization;\r\n\r\n    /// <summary>\r\n    /// Exception that is thrown by assert extensions.\r\n    /// </summary>\r\n    public class AssertException : Exception\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"AssertException\"/> class.\r\n        /// </summary>\r\n        public AssertException()\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"AssertException\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"message\">The exception message.</param>\r\n        public AssertException(string message) : base(message)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"AssertException\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"message\">The exception message.</param>\r\n        /// <param name=\"innerException\">The inner exception.</param>\r\n        public AssertException(string message, Exception innerException) : base(message, innerException)\r\n        {\r\n        }\r\n\r\n#if !NETSTANDARD1_6\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"AssertException\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"info\">The <see cref=\"T:System.Runtime.Serialization.SerializationInfo\"/> that holds the serialized object data about the exception being thrown.</param>\r\n        /// <param name=\"context\">The <see cref=\"T:System.Runtime.Serialization.StreamingContext\"/> that contains contextual information about the source or destination.</param>\r\n        /// <exception cref=\"T:System.ArgumentNullException\">The <paramref name=\"info\"/> parameter is null. </exception>\r\n        /// <exception cref=\"T:System.Runtime.Serialization.SerializationException\">The class name is null or <see cref=\"P:System.Exception.HResult\"/> is zero (0). </exception>\r\n        protected AssertException(SerializationInfo info, StreamingContext context) : base(info, context)\r\n        {\r\n        }\r\n#endif\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Testing/AssertExtensions.cs",
    "content": "namespace Nancy.Testing\r\n{\r\n    using System;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Defines assert extensions for HTML validation.\r\n    /// </summary>\r\n    public static class AssertExtensions\r\n    {\r\n        /// <summary>\r\n        /// Asserts that an element should exist at least once\r\n        /// </summary>\r\n        public static AndConnector<NodeWrapper> ShouldExist(this NodeWrapper node)\r\n        {\r\n            Asserts.NotNull(node);\r\n\r\n            return new AndConnector<NodeWrapper>(node);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Asserts that an element should exist at least once\r\n        /// </summary>\r\n        public static AndConnector<QueryWrapper> ShouldExist(this QueryWrapper query)\r\n        {\r\n            if (!query.Any())\r\n            {\r\n                throw new AssertException(\"The selector did not match any elements in the document.\");\r\n            }\r\n\r\n            return new AndConnector<QueryWrapper>(query);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Asserts that an element does not exist\r\n        /// </summary>\r\n        public static AndConnector<QueryWrapper> ShouldNotExist(this QueryWrapper query)\r\n        {\r\n            if (query.Any())\r\n            {\r\n                var message = string.Format(\"The selector matched {0} element(s) in the document.\", query.Count());\r\n                throw new AssertException(message);\r\n            }\r\n\r\n            return new AndConnector<QueryWrapper>(query);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Asserts that an element or element should exist one, and only once\r\n        /// </summary>\r\n        public static AndConnector<NodeWrapper> ShouldExistOnce(this QueryWrapper query)\r\n        {\r\n            return new AndConnector<NodeWrapper>(Asserts.Single(query));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Asserts that an element or element should exist exactly the specified number of times\r\n        /// <param name=\"expectedNumberOfOccurrences\">The expected number of times the element should exist</param>\r\n        /// </summary>\r\n        public static AndConnector<QueryWrapper> ShouldExistExactly(this QueryWrapper query, int expectedNumberOfOccurrences)\r\n        {\r\n            var nodeWrappers = Asserts.Exactly(query, expectedNumberOfOccurrences);\r\n            return new AndConnector<QueryWrapper>(nodeWrappers as QueryWrapper);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Asserts that an element should be of a specific class\r\n        /// </summary>\r\n        public static AndConnector<NodeWrapper> ShouldBeOfClass(this NodeWrapper node, string className)\r\n        {\r\n            Asserts.Equal(className, node.Attributes[\"class\"]);\r\n\r\n            return new AndConnector<NodeWrapper>(node);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Asserts that all elements should be of a specific class\r\n        /// </summary>\r\n        public static AndConnector<QueryWrapper> ShouldBeOfClass(this QueryWrapper query, string className)\r\n        {\r\n            query.ShouldExist();\r\n\r\n            foreach (var node in query)\r\n            {\r\n                node.ShouldBeOfClass(className);\r\n            }\r\n\r\n            return new AndConnector<QueryWrapper>(query);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Asserts that a node contains the specified text\r\n        /// </summary>\r\n        public static AndConnector<NodeWrapper> ShouldContain(this NodeWrapper node, string contents, StringComparison comparisonType = StringComparison.Ordinal)\r\n        {\r\n            Asserts.Contains(contents, node.InnerText, comparisonType);\r\n\r\n            return new AndConnector<NodeWrapper>(node);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Asserts that every node contains the specified text\r\n        /// </summary>\r\n        public static AndConnector<QueryWrapper> AllShouldContain(this QueryWrapper query, string contents, StringComparison comparisonType = StringComparison.Ordinal)\r\n        {\r\n            query.ShouldExist();\r\n\r\n            Asserts.All(contents, query.Select(x => x.InnerText), x => x.IndexOf(contents, comparisonType) >= 0);\r\n\r\n            return new AndConnector<QueryWrapper>(query);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Asserts that any node contains the specified text\r\n        /// </summary>\r\n        public static AndConnector<QueryWrapper> AnyShouldContain(this QueryWrapper query, string contents, StringComparison comparisonType = StringComparison.Ordinal)\r\n        {\r\n            query.ShouldExist();\r\n\r\n            Asserts.Any(contents, query.Select(x => x.InnerText), x => x.IndexOf(contents, comparisonType) >= 0);\r\n\r\n            return new AndConnector<QueryWrapper>(query);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Asserts that an element has a specific attribute\r\n        /// </summary>\r\n        public static AndConnector<NodeWrapper> ShouldContainAttribute(this NodeWrapper node, string name)\r\n        {\r\n            Asserts.True(node.HasAttribute(name));\r\n\r\n            return new AndConnector<NodeWrapper>(node);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Asserts that an element has a specific attribute with a specified value\r\n        /// </summary>\r\n        public static AndConnector<NodeWrapper> ShouldContainAttribute(this NodeWrapper node, string name, string value, StringComparison comparisonType = StringComparison.Ordinal)\r\n        {\r\n            Asserts.Equal(value, node.Attributes[name], comparisonType);\r\n\r\n            return new AndConnector<NodeWrapper>(node);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Asserts that an element has a specific attribute\r\n        /// </summary>\r\n        public static AndConnector<QueryWrapper> ShouldContainAttribute(this QueryWrapper query, string name)\r\n        {\r\n            query.ShouldExist();\r\n\r\n            foreach (var node in query)\r\n            {\r\n                node.ShouldContainAttribute(name);\r\n            }\r\n\r\n            return new AndConnector<QueryWrapper>(query);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Asserts that an element has a specific attribute with a specified value\r\n        /// </summary>\r\n        public static AndConnector<QueryWrapper> ShouldContainAttribute(this QueryWrapper query, string name, string value, StringComparison comparisonType = StringComparison.Ordinal)\r\n        {\r\n            query.ShouldExist();\r\n\r\n            foreach (var node in query)\r\n            {\r\n                node.ShouldContainAttribute(name, value);\r\n            }\r\n\r\n            return new AndConnector<QueryWrapper>(query);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Testing/Asserts.cs",
    "content": "﻿namespace Nancy.Testing\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Contains method for verifying the results of a test.\r\n    /// </summary>\r\n    public static class Asserts\r\n    {\r\n        public static void Contains<T>(T expected, IEnumerable<T> actual, IEqualityComparer<T> comparer = null)\r\n        {\r\n            comparer = comparer ?? new AssertEqualityComparer<T>();\r\n\r\n            Any(expected, actual, value => comparer.Equals(expected, value));\r\n        }\r\n\r\n        public static void Any<T>(T expected, IEnumerable<T> actual, Func<T, bool> comparer)\r\n        {\r\n            if (actual != null)\r\n            {\r\n                if (actual.Any(comparer))\r\n                {\r\n                    return;\r\n                }\r\n            }\r\n\r\n            throw new AssertException(\"The expected value was not found in the collection.\");\r\n        }\r\n\r\n        public static void All<T>(T expected, IEnumerable<T> actual, Func<T, bool> comparer)\r\n        {\r\n            if (actual != null)\r\n            {\r\n                if (actual.All(comparer))\r\n                {\r\n                    return;\r\n                }\r\n            }\r\n\r\n            throw new AssertException(\"All elements in the collection did not contain the expected value.\");\r\n        }\r\n\r\n        public static void Contains(string expected, string actual, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)\r\n        {\r\n            if (expected == null || actual.IndexOf(expected, comparisonType) < 0)\r\n            {\r\n                throw new AssertException(string.Format(\"The expected value '{0}' was not a sub-string of the actual value '{1}'.\", expected, actual));\r\n            }\r\n        }\r\n\r\n        public static void Equal<T>(T expected, T actual)\r\n        {\r\n            var comparer =\r\n                new AssertEqualityComparer<T>();\r\n\r\n            if (!comparer.Equals(actual, expected))\r\n            {\r\n                throw new AssertException(string.Format(\"The expected value '{0}' was not equal to the actual value '{1}'.\", expected, actual));\r\n            }\r\n        }\r\n\r\n        public static void Equal(string expected, string actual, StringComparison comparisonType = StringComparison.Ordinal)\r\n        {\r\n            if (!String.Equals(expected, actual, comparisonType))\r\n            {\r\n                throw new AssertException(string.Format(\"The expected value '{0}' was not equal to the actual value '{1}'.\", expected, actual));\r\n            }\r\n        }\r\n\r\n        public static void False(bool condition)\r\n        {\r\n            if (condition)\r\n            {\r\n                throw new AssertException(\"The condition was not false.\");\r\n            }\r\n        }\r\n\r\n        public static void NotNull(object actual)\r\n        {\r\n            if (actual == null)\r\n            {\r\n                throw new AssertException(\"The value was null.\");\r\n            }\r\n        }\r\n\r\n        public static void Null(object actual)\r\n        {\r\n            if (actual != null)\r\n            {\r\n                throw new AssertException(\"The value was not null.\");\r\n            }\r\n        }\r\n\r\n        public static void Same<T>(T actual, T expected)\r\n        {\r\n            var isTheSameInstance =\r\n                ReferenceEquals(actual, expected);\r\n\r\n            if (!isTheSameInstance)\r\n            {\r\n                throw new AssertException(string.Format(\"The expected value '{0}' was not same to the actual value '{1}'\", expected, actual));\r\n            }\r\n        }\r\n\r\n        public static T Single<T>(IEnumerable<T> values)\r\n        {\r\n            if (values == null)\r\n            {\r\n                throw new AssertException(\"The collection was null.\");\r\n            }\r\n\r\n            if (!values.Any())\r\n            {\r\n                throw new AssertException(\"The collection contained no values.\");\r\n            }\r\n\r\n            if (values.Count() > 1)\r\n            {\r\n                throw new AssertException(\"The collection contained more than one value.\");\r\n            }\r\n\r\n            return values.First();\r\n        }\r\n\r\n        public static IEnumerable<T> Exactly<T>(IEnumerable<T> values, int numberOfOccurrances)\r\n        {\r\n            if (values == null)\r\n            {\r\n                throw new AssertException(\"The collection was null.\");\r\n            }\r\n\r\n            var elements = values.Count();\r\n            if (elements != numberOfOccurrances)\r\n            {\r\n                var message =\r\n                    string.Format(\r\n                        \"The collection didn't exactly contain the expected number of occurances.\\nActual: {0}\\nExpected: {1}\",\r\n                        elements, numberOfOccurrances);\r\n                throw new AssertException(message);\r\n            }\r\n\r\n            return values;\r\n        }\r\n\r\n        public static void True(bool condition)\r\n        {\r\n            if (!condition)\r\n            {\r\n                throw new AssertException(\"The condition was not true\");\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Testing/Browser.cs",
    "content": "namespace Nancy.Testing\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Text;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Configuration;\r\n    using Nancy.Helpers;\r\n    using Nancy.IO;\r\n\r\n    /// <summary>\r\n    /// Provides the capability of executing a request with Nancy, using a specific configuration provided by an <see cref=\"INancyBootstrapper\"/> instance.\r\n    /// </summary>\r\n    public class Browser : IHideObjectMembers\r\n    {\r\n        private readonly Action<BrowserContext> defaultBrowserContext;\r\n        private readonly INancyEngine engine;\r\n        private readonly INancyEnvironment environment;\r\n\r\n        private readonly IDictionary<string, string> cookies = new Dictionary<string, string>();\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"Browser\"/> class, with the\r\n        /// provided <see cref=\"ConfigurableBootstrapper\"/> configuration.\r\n        /// </summary>\r\n        /// <param name=\"action\">The <see cref=\"ConfigurableBootstrapper\"/> configuration that should be used by the bootstrapper.</param>\r\n        /// <param name=\"defaults\">The default <see cref=\"BrowserContext\"/> that should be used in a all requests through this browser object.</param>\r\n        public Browser(Action<ConfigurableBootstrapper.ConfigurableBootstrapperConfigurator> action, Action<BrowserContext> defaults = null)\r\n            : this(new ConfigurableBootstrapper(action), defaults)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"Browser\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"bootstrapper\">A <see cref=\"INancyBootstrapper\"/> instance that determines the Nancy configuration that should be used by the browser.</param>\r\n        /// <param name=\"defaults\">The default <see cref=\"BrowserContext\"/> that should be used in a all requests through this browser object.</param>\r\n        public Browser(INancyBootstrapper bootstrapper, Action<BrowserContext> defaults = null)\r\n        {\r\n            bootstrapper.Initialise();\r\n            this.engine = bootstrapper.GetEngine();\r\n            this.environment = bootstrapper.GetEnvironment();\r\n            this.defaultBrowserContext = defaults ?? DefaultBrowserContext;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs a DELETE request against Nancy.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that is being requested.</param>\r\n        /// <param name=\"browserContext\">An closure for providing browser context for the request.</param>\r\n        /// <returns>An <see cref=\"BrowserResponse\"/> instance of the executed request.</returns>\r\n        public Task<BrowserResponse> Delete(string path, Action<BrowserContext> browserContext = null)\r\n        {\r\n            return this.HandleRequest(\"DELETE\", path, browserContext);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs a DELETE request against Nancy.\r\n        /// </summary>\r\n        /// <param name=\"url\">The url that is being requested.</param>\r\n        /// <param name=\"browserContext\">An closure for providing browser context for the request.</param>\r\n        /// <returns>An <see cref=\"BrowserResponse\"/> instance of the executed request.</returns>\r\n        public Task<BrowserResponse> Delete(Url url, Action<BrowserContext> browserContext = null)\r\n        {\r\n            return this.HandleRequest(\"DELETE\", url, browserContext);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs a GET request against Nancy.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that is being requested.</param>\r\n        /// <param name=\"browserContext\">An closure for providing browser context for the request.</param>\r\n        /// <returns>An <see cref=\"BrowserResponse\"/> instance of the executed request.</returns>\r\n        public Task<BrowserResponse> Get(string path, Action<BrowserContext> browserContext = null)\r\n        {\r\n            return this.HandleRequest(\"GET\", path, browserContext);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs a GET request against Nancy.\r\n        /// </summary>\r\n        /// <param name=\"url\">The url that is being requested.</param>\r\n        /// <param name=\"browserContext\">An closure for providing browser context for the request.</param>\r\n        /// <returns>An <see cref=\"BrowserResponse\"/> instance of the executed request.</returns>\r\n        public Task<BrowserResponse> Get(Url url, Action<BrowserContext> browserContext = null)\r\n        {\r\n            return this.HandleRequest(\"GET\", url, browserContext);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs a HEAD request against Nancy.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that is being requested.</param>\r\n        /// <param name=\"browserContext\">An closure for providing browser context for the request.</param>\r\n        /// <returns>An <see cref=\"BrowserResponse\"/> instance of the executed request.</returns>\r\n        public Task<BrowserResponse> Head(string path, Action<BrowserContext> browserContext = null)\r\n        {\r\n            return this.HandleRequest(\"HEAD\", path, browserContext);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs a HEAD request against Nancy.\r\n        /// </summary>\r\n        /// <param name=\"url\">The url that is being requested.</param>\r\n        /// <param name=\"browserContext\">An closure for providing browser context for the request.</param>\r\n        /// <returns>An <see cref=\"BrowserResponse\"/> instance of the executed request.</returns>\r\n        public Task<BrowserResponse> Head(Url url, Action<BrowserContext> browserContext = null)\r\n        {\r\n            return this.HandleRequest(\"HEAD\", url, browserContext);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs a OPTIONS request against Nancy.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that is being requested.</param>\r\n        /// <param name=\"browserContext\">An closure for providing browser context for the request.</param>\r\n        /// <returns>An <see cref=\"BrowserResponse\"/> instance of the executed request.</returns>\r\n        public Task<BrowserResponse> Options(string path, Action<BrowserContext> browserContext = null)\r\n        {\r\n            return this.HandleRequest(\"OPTIONS\", path, browserContext);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs a OPTIONS request against Nancy.\r\n        /// </summary>\r\n        /// <param name=\"url\">The url that is being requested.</param>\r\n        /// <param name=\"browserContext\">An closure for providing browser context for the request.</param>\r\n        /// <returns>An <see cref=\"BrowserResponse\"/> instance of the executed request.</returns>\r\n        public Task<BrowserResponse> Options(Url url, Action<BrowserContext> browserContext = null)\r\n        {\r\n            return this.HandleRequest(\"OPTIONS\", url, browserContext);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs a PATCH request against Nancy.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that is being requested.</param>\r\n        /// <param name=\"browserContext\">An closure for providing browser context for the request.</param>\r\n        /// <returns>An <see cref=\"BrowserResponse\"/> instance of the executed request.</returns>\r\n        public Task<BrowserResponse> Patch(string path, Action<BrowserContext> browserContext = null)\r\n        {\r\n            return this.HandleRequest(\"PATCH\", path, browserContext);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs a PATCH request against Nancy.\r\n        /// </summary>\r\n        /// <param name=\"url\">The url that is being requested.</param>\r\n        /// <param name=\"browserContext\">An closure for providing browser context for the request.</param>\r\n        /// <returns>An <see cref=\"BrowserResponse\"/> instance of the executed request.</returns>\r\n        public Task<BrowserResponse> Patch(Url url, Action<BrowserContext> browserContext = null)\r\n        {\r\n            return this.HandleRequest(\"PATCH\", url, browserContext);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs a POST request against Nancy.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that is being requested.</param>\r\n        /// <param name=\"browserContext\">An closure for providing browser context for the request.</param>\r\n        /// <returns>An <see cref=\"BrowserResponse\"/> instance of the executed request.</returns>\r\n        public Task<BrowserResponse> Post(string path, Action<BrowserContext> browserContext = null)\r\n        {\r\n            return this.HandleRequest(\"POST\", path, browserContext);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs a POST request against Nancy.\r\n        /// </summary>\r\n        /// <param name=\"url\">The url that is being requested.</param>\r\n        /// <param name=\"browserContext\">An closure for providing browser context for the request.</param>\r\n        /// <returns>An <see cref=\"BrowserResponse\"/> instance of the executed request.</returns>\r\n        public Task<BrowserResponse> Post(Url url, Action<BrowserContext> browserContext = null)\r\n        {\r\n            return this.HandleRequest(\"POST\", url, browserContext);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs a PUT request against Nancy.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path that is being requested.</param>\r\n        /// <param name=\"browserContext\">An closure for providing browser context for the request.</param>\r\n        /// <returns>An <see cref=\"BrowserResponse\"/> instance of the executed request.</returns>\r\n        public Task<BrowserResponse> Put(string path, Action<BrowserContext> browserContext = null)\r\n        {\r\n            return this.HandleRequest(\"PUT\", path, browserContext);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs a PUT request against Nancy.\r\n        /// </summary>\r\n        /// <param name=\"url\">The url that is being requested.</param>\r\n        /// <param name=\"browserContext\">An closure for providing browser context for the request.</param>\r\n        /// <returns>An <see cref=\"BrowserResponse\"/> instance of the executed request.</returns>\r\n        public Task<BrowserResponse> Put(Url url, Action<BrowserContext> browserContext = null)\r\n        {\r\n            return this.HandleRequest(\"PUT\", url, browserContext);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs a request of the HTTP <paramref name=\"method\"/>, on the given <paramref name=\"url\"/>, using the\r\n        /// provided <paramref name=\"browserContext\"/> configuration.\r\n        /// </summary>\r\n        /// <param name=\"method\">HTTP method to send the request as.</param>\r\n        /// <param name=\"url\">The URl of the request.</param>\r\n        /// <param name=\"browserContext\">An closure for providing browser context for the request.</param>\r\n        /// <returns>An <see cref=\"BrowserResponse\"/> instance of the executed request.</returns>\r\n        public async Task<BrowserResponse> HandleRequest(string method, Url url, Action<BrowserContext> browserContext)\r\n        {\r\n            var browserContextValues =\r\n                BuildBrowserContextValues(browserContext ?? (with => { }));\r\n\r\n            var request =\r\n                CreateRequest(method, url, browserContextValues);\r\n\r\n            var context = await this.engine.HandleRequest(request).ConfigureAwait(false);\r\n\r\n            var response = new BrowserResponse(context, this, (BrowserContext)browserContextValues);\r\n\r\n            this.CaptureCookies(response);\r\n\r\n            return response;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs a request of the HTTP <paramref name=\"method\"/>, on the given <paramref name=\"path\"/>, using the\r\n        /// provided <paramref name=\"browserContext\"/> configuration.\r\n        /// </summary>\r\n        /// <param name=\"method\">HTTP method to send the request as.</param>\r\n        /// <param name=\"path\">The path that is being requested.</param>\r\n        /// <param name=\"browserContext\">An closure for providing browser context for the request.</param>\r\n        /// <returns>An <see cref=\"BrowserResponse\"/> instance of the executed request.</returns>\r\n        public Task<BrowserResponse> HandleRequest(string method, string path, Action<BrowserContext> browserContext)\r\n        {\r\n            var url = Uri.IsWellFormedUriString(path, UriKind.Relative) ?\r\n                new Url { Path = path } :\r\n                (Url)new Uri(path);\r\n\r\n            return this.HandleRequest(method, url, browserContext);\r\n        }\r\n\r\n        private static void DefaultBrowserContext(BrowserContext context)\r\n        {\r\n            context.HttpRequest();\r\n        }\r\n\r\n        private void SetCookies(BrowserContext context)\r\n        {\r\n            if (!this.cookies.Any())\r\n            {\r\n                return;\r\n            }\r\n\r\n            var cookieString = this.cookies.Aggregate(string.Empty, (current, cookie) => current + string.Format(\"{0}={1};\", HttpUtility.UrlEncode(cookie.Key), HttpUtility.UrlEncode(cookie.Value)));\r\n\r\n            context.Header(\"Cookie\", cookieString);\r\n        }\r\n\r\n        private void CaptureCookies(BrowserResponse response)\r\n        {\r\n            if (response.Cookies == null || !response.Cookies.Any())\r\n            {\r\n                return;\r\n            }\r\n\r\n            foreach (var cookie in response.Cookies)\r\n            {\r\n                if (string.IsNullOrEmpty(cookie.Value))\r\n                {\r\n                    this.cookies.Remove(cookie.Name);\r\n                }\r\n                else\r\n                {\r\n                    this.cookies[cookie.Name] = cookie.Value;\r\n                }\r\n            }\r\n        }\r\n\r\n        private static void BuildRequestBody(IBrowserContextValues contextValues)\r\n        {\r\n            if (contextValues.Body != null)\r\n            {\r\n                return;\r\n            }\r\n\r\n            var useFormValues = !string.IsNullOrEmpty(contextValues.FormValues);\r\n            var bodyContents = useFormValues ? contextValues.FormValues : contextValues.BodyString;\r\n            var bodyBytes = bodyContents != null ? Encoding.UTF8.GetBytes(bodyContents) : ArrayCache.Empty<byte>();\r\n\r\n            if (useFormValues && !contextValues.Headers.ContainsKey(\"Content-Type\"))\r\n            {\r\n                contextValues.Headers[\"Content-Type\"] = new[] { \"application/x-www-form-urlencoded\" };\r\n            }\r\n\r\n            contextValues.Body = new MemoryStream(bodyBytes);\r\n        }\r\n\r\n        private IBrowserContextValues BuildBrowserContextValues(Action<BrowserContext> browserContext)\r\n        {\r\n            var context =\r\n                new BrowserContext(this.environment);\r\n\r\n            this.SetCookies(context);\r\n\r\n            this.defaultBrowserContext.Invoke(context);\r\n            browserContext.Invoke(context);\r\n\r\n            var contextValues =\r\n                (IBrowserContextValues)context;\r\n\r\n            if (!contextValues.Headers.ContainsKey(\"user-agent\"))\r\n            {\r\n                contextValues.Headers.Add(\"user-agent\", new[] { \"Nancy.Testing.Browser\" });\r\n            }\r\n\r\n            return contextValues;\r\n        }\r\n\r\n        private static Request CreateRequest(string method, Url url, IBrowserContextValues contextValues)\r\n        {\r\n            BuildRequestBody(contextValues);\r\n\r\n            var requestStream =\r\n                RequestStream.FromStream(contextValues.Body, 0, true);\r\n\r\n            var certBytes = contextValues.ClientCertificate ?? null;\r\n\r\n            var requestUrl = url;\r\n            requestUrl.Scheme = string.IsNullOrWhiteSpace(contextValues.Protocol) ? requestUrl.Scheme : contextValues.Protocol;\r\n            requestUrl.HostName = string.IsNullOrWhiteSpace(contextValues.HostName) ? requestUrl.HostName : contextValues.HostName;\r\n            requestUrl.Query = string.IsNullOrWhiteSpace(url.Query) ? (contextValues.QueryString ?? string.Empty) : url.Query;\r\n\r\n            return new Request(method, requestUrl, requestStream, contextValues.Headers, contextValues.UserHostAddress, certBytes);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Testing/BrowserContext.cs",
    "content": "﻿namespace Nancy.Testing\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Reflection;\r\n    using System.Security.Cryptography.X509Certificates;\r\n    using Configuration;\r\n    using Nancy.Helpers;\r\n\r\n    /// <summary>\r\n    /// Defines the context that a <see cref=\"Browser\"/> instance should run under.\r\n    /// </summary>\r\n    public class BrowserContext : IBrowserContextValues\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"BrowserContext\"/> class,\r\n        /// with the provided <see cref=\"INancyEnvironment\"/>.\r\n        /// </summary>\r\n        /// <param name=\"environment\">An <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        public BrowserContext(INancyEnvironment environment)\r\n        {\r\n            this.Environment = environment;\r\n            this.Values.Headers = new Dictionary<string, IEnumerable<string>>(StringComparer.OrdinalIgnoreCase);\r\n            this.Values.Protocol = string.Empty;\r\n            this.Values.QueryString = string.Empty;\r\n            this.Values.BodyString = string.Empty;\r\n            this.Values.FormValues = string.Empty;\r\n            this.Values.HostName = string.Empty;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"INancyEnvironment\"/> instance used by the <see cref=\"Browser\"/>.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"INancyEnvironment\"/> instance.</value>\r\n        public INancyEnvironment Environment { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the that should be sent with the HTTP request.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"Stream\"/> that contains the body that should be sent with the HTTP request.</value>\r\n        Stream IBrowserContextValues.Body { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the protocol that should be sent with the HTTP request.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> contains the protocol that should be sent with the HTTP request..</value>\r\n        string IBrowserContextValues.Protocol { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the querystring\r\n        /// </summary>\r\n        string IBrowserContextValues.QueryString { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the user host name\r\n        /// </summary>\r\n        string IBrowserContextValues.HostName { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the user host address\r\n        /// </summary>\r\n        string IBrowserContextValues.UserHostAddress { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the ClientCertificate\r\n        /// </summary>\r\n        X509Certificate2 IBrowserContextValues.ClientCertificate { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the body string\r\n        /// </summary>\r\n        string IBrowserContextValues.BodyString { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the form values string\r\n        /// </summary>\r\n        string IBrowserContextValues.FormValues { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the headers that should be sent with the HTTP request.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IDictionary{TKey,TValue}\"/> instance that contains the headers that should be sent with the HTTP request.</value>\r\n        IDictionary<string, IEnumerable<string>> IBrowserContextValues.Headers { get; set; }\r\n\r\n        /// <summary>\r\n        /// Adds a body to the HTTP request.\r\n        /// </summary>\r\n        /// <param name=\"body\">A string that should be used as the HTTP request body.</param>\r\n        public void Body(string body)\r\n        {\r\n            this.Values.BodyString = body;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds a body to the HTTP request.\r\n        /// </summary>\r\n        /// <param name=\"body\">A string that should be used as the HTTP request body.</param>\r\n        /// <param name=\"contentType\">Content type of the HTTP request body.</param>\r\n        public void Body(string body, string contentType)\r\n        {\r\n            this.Values.BodyString = body;\r\n            this.Header(\"Content-Type\", contentType);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds a body to the HTTP request.\r\n        /// </summary>\r\n        /// <param name=\"body\">A stream that should be used as the HTTP request body.</param>\r\n        /// <param name=\"contentType\">Content type of the HTTP request body. Defaults to 'application/octet-stream'</param>\r\n        public void Body(Stream body, string contentType = null)\r\n        {\r\n            this.Values.Body = body;\r\n            this.Header(\"Content-Type\", contentType ?? \"application/octet-stream\");\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds an application/x-www-form-urlencoded form value.\r\n        /// </summary>\r\n        /// <param name=\"key\">The name of the form element.</param>\r\n        /// <param name=\"value\">The value of the form element.</param>\r\n        public void FormValue(string key, string value)\r\n        {\r\n            if (!string.IsNullOrEmpty(this.Values.BodyString))\r\n            {\r\n                throw new InvalidOperationException(\"Form value cannot be set as well as body string\");\r\n            }\r\n\r\n            this.Values.FormValues += string.Format(\r\n                \"{0}{1}={2}\",\r\n                this.Values.FormValues.Length == 0 ? string.Empty : \"&\",\r\n                key,\r\n                HttpUtility.UrlEncode(value));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds a header to the HTTP request.\r\n        /// </summary>\r\n        /// <param name=\"name\">The name of the header.</param>\r\n        /// <param name=\"value\">The value of the header.</param>\r\n        public void Header(string name, string value)\r\n        {\r\n            if (!this.Values.Headers.ContainsKey(name))\r\n            {\r\n                this.Values.Headers.Add(name, new List<string>());\r\n            }\r\n\r\n            var values = (List<string>)this.Values.Headers[name];\r\n            values.Add(value);\r\n\r\n            this.Values.Headers[name] = values;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Configures the request to be sent over HTTP.\r\n        /// </summary>\r\n        public void HttpRequest()\r\n        {\r\n            this.Values.Protocol = \"http\";\r\n        }\r\n\r\n        /// <summary>\r\n        /// Configures the request to be sent over HTTPS.\r\n        /// </summary>\r\n        public void HttpsRequest()\r\n        {\r\n            this.Values.Protocol = \"https\";\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds a query string entry\r\n        /// </summary>\r\n        public void Query(string key, string value)\r\n        {\r\n            this.Values.QueryString += string.Format(\r\n                \"{0}{1}={2}\",\r\n                this.Values.QueryString.Length == 0 ? \"?\" : \"&\",\r\n                key,\r\n                HttpUtility.UrlEncode(value));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Sets the user host address.\r\n        /// </summary>\r\n        public void UserHostAddress(string userHostAddress)\r\n        {\r\n            this.Values.UserHostAddress = userHostAddress;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Sets the host name.\r\n        /// </summary>\r\n        /// <param name=\"hostName\">is the host name of request url string</param>\r\n        public void HostName(string hostName)\r\n        {\r\n            this.Values.HostName = hostName;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Sets the ClientCertificate to a default embedded certificate\r\n        /// <remarks>The default certificate is embedded using the Nancy.Testing.NancyTestingCert.pfx resource name (secured with password \"nancy\")</remarks>\r\n        /// </summary>\r\n        public void Certificate()\r\n        {\r\n            X509Certificate2 certificate2;\r\n\r\n            using (\r\n                var pkcs12 =\r\n                    typeof (BrowserContext).GetTypeInfo().Assembly\r\n                            .GetManifestResourceStream(\"Nancy.Testing.Resources.NancyTestingCert.pfx\"))\r\n            {\r\n                using (var br = new BinaryReader(pkcs12))\r\n                {\r\n                    certificate2 = new X509Certificate2(br.ReadBytes((int)pkcs12.Length), \"nancy\",\r\n                                                        X509KeyStorageFlags.Exportable);\r\n                }\r\n            }\r\n\r\n            this.Values.ClientCertificate = certificate2;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Sets the ClientCertificate\r\n        /// </summary>\r\n        /// <param name=\"certificate\">the certificate in bytes</param>\r\n        public void Certificate(byte[] certificate)\r\n        {\r\n            this.Values.ClientCertificate = new X509Certificate2(certificate);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Sets the ClientCertificate\r\n        /// </summary>\r\n        /// <param name=\"certificate\">the certificate</param>\r\n        public void Certificate(X509Certificate2 certificate)\r\n        {\r\n            this.Values.ClientCertificate = certificate;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Find a certificate in a store on the computer.\r\n        /// </summary>\r\n        /// <param name=\"storeLocation\">The location of the store (LocalMachine, CurrentUser)</param>\r\n        /// <param name=\"storeName\">The name of the store (e.q. My)</param>\r\n        /// <param name=\"findType\">By which field you want to find the certificate (Commonname, Thumbprint, etc)</param>\r\n        /// <param name=\"findBy\">The \"Common name\" or \"thumbprint\" you are looking for</param>\r\n        public void Certificate(StoreLocation storeLocation, StoreName storeName, X509FindType findType, object findBy)\r\n        {\r\n            var store = new X509Store(storeName, storeLocation);\r\n\r\n            store.Open(OpenFlags.ReadOnly);\r\n            var certificatesFound = store.Certificates.Find(findType, findBy, false);\r\n\r\n            if (certificatesFound.Count <= 0)\r\n            {\r\n                throw new InvalidOperationException(string.Format(\"No certificates found in {0} {1} with a {2} that looks like \\\"{3}\\\"\", storeLocation, storeName, findType, findBy));\r\n            }\r\n\r\n            this.Values.ClientCertificate = certificatesFound[0];\r\n        }\r\n\r\n        private IBrowserContextValues Values\r\n        {\r\n            get { return this; }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Testing/BrowserContextExtensions.cs",
    "content": "﻿namespace Nancy.Testing\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Globalization;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Text;\r\n\r\n    using Nancy.Authentication.Forms;\r\n    using Nancy.Configuration;\r\n    using Nancy.Extensions;\r\n    using Nancy.Helpers;\r\n    using Nancy.Responses;\r\n    using Nancy.Responses.Negotiation;\r\n    using Nancy.Xml;\r\n\r\n    /// <summary>\r\n    /// Defines extensions for the <see cref=\"BrowserContext\"/> type.\r\n    /// </summary>\r\n    public static class BrowserContextExtensions\r\n    {\r\n        /// <summary>\r\n        /// Adds a multipart/form-data encoded request body to the <see cref=\"Browser\"/>, using the default boundary name.\r\n        /// </summary>\r\n        /// <param name=\"browserContext\">The <see cref=\"BrowserContext\"/> that the data should be added to.</param>\r\n        /// <param name=\"multipartFormData\">The multipart/form-data encoded data that should be added.</param>\r\n        public static void MultiPartFormData(this BrowserContext browserContext, BrowserContextMultipartFormData multipartFormData)\r\n        {\r\n            MultiPartFormData(browserContext, multipartFormData, BrowserContextMultipartFormData.DefaultBoundaryName);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds a multipart/form-data encoded request body to the <see cref=\"Browser\"/>.\r\n        /// </summary>\r\n        /// <param name=\"browserContext\">The <see cref=\"BrowserContext\"/> that the data should be added to.</param>\r\n        /// <param name=\"multipartFormData\">The multipart/form-data encoded data that should be added.</param>\r\n        /// <param name=\"boundaryName\">The name of the boundary to be used</param>\r\n        public static void MultiPartFormData(this BrowserContext browserContext, BrowserContextMultipartFormData multipartFormData, string boundaryName)\r\n        {\r\n            var contextValues =\r\n                (IBrowserContextValues)browserContext;\r\n\r\n            contextValues.Body = multipartFormData.Body;\r\n            contextValues.Headers[\"Content-Type\"] = new[] { \"multipart/form-data; boundary=\" + boundaryName };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds a application/json request body to the <see cref=\"Browser\"/>.\r\n        /// </summary>\r\n        /// <param name=\"browserContext\">The <see cref=\"BrowserContext\"/> that the data should be added to.</param>\r\n        /// <param name=\"model\">The model to be serialized to json.</param>\r\n        /// <param name=\"serializer\">Optionally opt in to using a different JSON serializer.</param>\r\n        public static void JsonBody<TModel>(this BrowserContext browserContext, TModel model, ISerializer serializer = null)\r\n        {\r\n            if (serializer == null)\r\n            {\r\n                serializer = new DefaultJsonSerializer(browserContext.Environment);\r\n            }\r\n\r\n            var contextValues =\r\n                (IBrowserContextValues)browserContext;\r\n\r\n            contextValues.Body = new MemoryStream();\r\n\r\n            serializer.Serialize(\"application/json\", model, contextValues.Body);\r\n            browserContext.Header(\"Content-Type\", \"application/json\");\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds a application/xml request body to the <see cref=\"Browser\"/>.\r\n        /// </summary>\r\n        /// <param name=\"browserContext\">The <see cref=\"BrowserContext\"/> that the data should be added to.</param>\r\n        /// <param name=\"model\">The model to be serialized to xml.</param>\r\n        /// <param name=\"serializer\">Optionally opt in to using a different XML serializer.</param>\r\n        public static void XMLBody<TModel>(this BrowserContext browserContext, TModel model, ISerializer serializer = null)\r\n        {\r\n            if (serializer == null)\r\n            {\r\n                serializer = new DefaultXmlSerializer(browserContext.Environment);\r\n            }\r\n\r\n            var contextValues =\r\n                (IBrowserContextValues)browserContext;\r\n\r\n            contextValues.Body = new MemoryStream();\r\n\r\n            serializer.Serialize(\"application/xml\", model, contextValues.Body);\r\n            browserContext.Header(\"Content-Type\", \"application/xml\");\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds basic authorization credentials to the headers of the <see cref=\"Browser\"/>.\r\n        /// </summary>\r\n        /// <param name=\"browserContext\">The <see cref=\"BrowserContext\"/> that the data should be added to.</param>\r\n        /// <param name=\"username\">The username to be encoded.</param>\r\n        /// <param name=\"password\">The password to be encoded.</param>\r\n        public static void BasicAuth(this BrowserContext browserContext, string username, string password)\r\n        {\r\n            var credentials = string.Format(\"{0}:{1}\", username, password);\r\n\r\n            var encodedCredentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials));\r\n\r\n            browserContext.Header(\"Authorization\", \"Basic \" + encodedCredentials);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds a cookie to the headers of the <see cref=\"Browser\"/>.\r\n        /// </summary>\r\n        /// <param name=\"browserContext\">The <see cref=\"BrowserContext\"/> that the data should be added to.</param>\r\n        /// <param name=\"cookies\">The collection of cookies to add to the cookie request header.</param>\r\n        public static void Cookie(this BrowserContext browserContext, IDictionary<string, string> cookies)\r\n        {\r\n            if (!cookies.Any())\r\n            {\r\n                return;\r\n            }\r\n\r\n            foreach (var cookie in cookies)\r\n            {\r\n                browserContext.Cookie(cookie.Key, cookie.Value);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds a cookie to the headers of the <see cref=\"Browser\"/>.\r\n        /// </summary>\r\n        /// <param name=\"browserContext\">The <see cref=\"BrowserContext\"/> that the data should be added to.</param>\r\n        /// <param name=\"key\">The name of the cookie.</param>\r\n        /// <param name=\"value\">The value of the cookie.</param>\r\n        public static void Cookie(this BrowserContext browserContext, string key, string value)\r\n        {\r\n            var contextValues =\r\n                (IBrowserContextValues)browserContext;\r\n\r\n            if (!contextValues.Headers.ContainsKey(\"Cookie\"))\r\n            {\r\n                contextValues.Headers.Add(\"Cookie\", new List<string> { string.Empty });\r\n            }\r\n\r\n            var values = (List<string>)contextValues.Headers[\"Cookie\"];\r\n            values[0] += string.Format(\"{0}={1};\", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds a header to indicate this request is an \"ajax request\"\r\n        /// <seealso cref=\"RequestExtensions.IsAjaxRequest\"/>\r\n        /// </summary>\r\n        /// <param name=\"browserContext\">The <see cref=\"BrowserContext\"/> that the data should be added to.</param>\r\n        public static void AjaxRequest(this BrowserContext browserContext)\r\n        {\r\n            browserContext.Header(\"X-Requested-With\", \"XMLHttpRequest\");\r\n        }\r\n\r\n        /// <summary>\r\n        /// Adds forms authentication cookie to the headers of the <see cref=\"Browser\"/>.\r\n        /// </summary>\r\n        /// <param name=\"browserContext\">The <see cref=\"BrowserContext\"/> that the data should be added to.</param>\r\n        /// <param name=\"userId\">The user identifier</param>\r\n        /// <param name=\"formsAuthenticationConfiguration\">Current configuration.</param>\r\n        public static void FormsAuth(this BrowserContext browserContext, Guid userId, FormsAuthenticationConfiguration formsAuthenticationConfiguration)\r\n        {\r\n            var encryptedId = formsAuthenticationConfiguration.CryptographyConfiguration.EncryptionProvider.Encrypt(userId.ToString());\r\n\r\n            var hmacBytes = formsAuthenticationConfiguration.CryptographyConfiguration.HmacProvider.GenerateHmac(encryptedId);\r\n\r\n            var hmacString = Convert.ToBase64String(hmacBytes);\r\n\r\n            var cookieContents = String.Format(\"{1}{0}\", encryptedId, hmacString);\r\n\r\n            Cookie(browserContext, FormsAuthentication.FormsAuthenticationCookieName, cookieContents);\r\n        }\r\n\r\n        public static void Accept(this BrowserContext browserContext, MediaRange mediaRange)\r\n        {\r\n            browserContext.Accept(mediaRange, 1.0m);\r\n        }\r\n\r\n        public static void Accept(this BrowserContext browserContext, MediaRange mediaRange, decimal quality)\r\n        {\r\n            var contextValues =\r\n                (IBrowserContextValues)browserContext;\r\n\r\n            if (contextValues.Headers.ContainsKey(\"accept\"))\r\n            {\r\n                if (contextValues.Headers[\"accept\"].Count().Equals(1))\r\n                {\r\n                    if (contextValues.Headers[\"accept\"].Any(x => x.Equals(\"*/*\")))\r\n                    {\r\n                        contextValues.Headers.Remove(\"accept\");\r\n                    }\r\n                }\r\n            }\r\n\r\n            var mediaTypeWithQuality =\r\n                string.Concat(mediaRange, \";q=\", Convert.ToString(quality, CultureInfo.InvariantCulture));\r\n\r\n            browserContext.Header(\"accept\", mediaTypeWithQuality);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Testing/BrowserContextMultipartFormData.cs",
    "content": "﻿namespace Nancy.Testing\r\n{\r\n    using System;\r\n    using System.IO;\r\n    using System.Text;\r\n\r\n    /// <summary>\r\n    /// Contains the functionality for setting up a multipart/form-data encoded request body that should be used by an <see cref=\"Browser\"/> instance.\r\n    /// </summary>\r\n    public class BrowserContextMultipartFormData\r\n    {\r\n        public const string DefaultBoundaryName = \"--NancyMultiPartBoundary123124\";\r\n\r\n        private readonly string boundaryName;\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"BrowserContextMultipartFormData\"/> class using the default boundary name\r\n        /// </summary>\r\n        /// <param name=\"configuration\">The configuration that should be used to create the multipart/form-data encoded data.</param>\r\n        public BrowserContextMultipartFormData(Action<BrowserContextMultipartFormDataConfigurator> configuration)\r\n            : this(configuration, DefaultBoundaryName)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"BrowserContextMultipartFormData\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"configuration\">The configuration that should be used to create the multipart/form-data encoded data.</param>\r\n        /// <param name=\"boundaryName\">Boundary name to be used</param>\r\n        public BrowserContextMultipartFormData(Action<BrowserContextMultipartFormDataConfigurator> configuration, string boundaryName)\r\n        {\r\n            this.boundaryName = boundaryName;\r\n            this.Body = new MemoryStream();\r\n\r\n            var configurator =\r\n                new BrowserContextMultipartFormDataConfigurator(this.Body, boundaryName);\r\n\r\n            configuration.Invoke(configurator);\r\n            this.TerminateBoundary();\r\n            this.Body.Position = 0;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"Stream\"/> that should be used by the HTTP request to pass in the multipart/form-data encoded values.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"Stream\"/> that contains the multipart/form-data encoded values.</value>\r\n        public Stream Body { get; private set; }\r\n\r\n        private void TerminateBoundary()\r\n        {\r\n            var endBoundary = String.Format(\"\\r\\n--{0}--\\r\\n\", this.boundaryName);\r\n\r\n            var encodedHeaders =\r\n                Encoding.ASCII.GetBytes(endBoundary);\r\n\r\n            this.Body.Write(encodedHeaders, 0, encodedHeaders.Length);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Provides an API for configuring a multipart/form-data encoded request body.\r\n        /// </summary>\r\n        public class BrowserContextMultipartFormDataConfigurator\r\n        {\r\n            private const string CRLF = \"\\r\\n\";\r\n            private readonly Stream body;\r\n            private readonly string boundary;\r\n\r\n            /// <summary>\r\n            /// Initializes a new instance of the <see cref=\"BrowserContextMultipartFormDataConfigurator\"/> class.\r\n            /// </summary>\r\n            /// <param name=\"body\">The <see cref=\"Stream\"/> that the values should be written to.</param>\r\n            /// <param name=\"boundary\">The multipart/form-data boundary that should be used in the request body.</param>\r\n            public BrowserContextMultipartFormDataConfigurator(Stream body, string boundary)\r\n            {\r\n                this.body = body;\r\n                this.boundary = boundary;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a file to the request body.\r\n            /// </summary>\r\n            /// <param name=\"name\">The name of the file http element that was used to upload the file.</param>\r\n            /// <param name=\"fileName\">Name of the file.</param>\r\n            /// <param name=\"contentType\">The mime type of file.</param>\r\n            /// <param name=\"file\">The content of the file</param>\r\n            public void AddFile(string name, string fileName, string contentType, Stream file)\r\n            {\r\n                this.AddFieldHeaders(name, contentType, fileName);\r\n                this.AddContent(file);\r\n            }\r\n\r\n            public void AddFormField(string name, string contentType, string data)\r\n            {\r\n                this.AddFormField(name, contentType, new MemoryStream(Encoding.ASCII.GetBytes(data)));\r\n            }\r\n\r\n            public void AddFormField(string name, string contentType, Stream data)\r\n            {\r\n                this.AddFieldHeaders(name, contentType);\r\n                this.AddContent(data);\r\n            }\r\n\r\n            private void AddContent(Stream data)\r\n            {\r\n                data.Position = 0;\r\n                data.CopyTo(this.body);\r\n            }\r\n\r\n            private void AddFieldHeaders(string name, string contentType, string filename = null)\r\n            {\r\n                var builder = new StringBuilder();\r\n\r\n                builder.Append(CRLF);\r\n                builder.Append(\"--\" + this.boundary);\r\n                builder.Append(CRLF);\r\n                builder.AppendFormat(@\"Content-Disposition: form-data; name=\"\"{0}\"\"\", name);\r\n                if (!String.IsNullOrWhiteSpace(filename))\r\n                {\r\n                    builder.AppendFormat(@\"; filename=\"\"{0}\"\"\", filename);\r\n                }\r\n                builder.Append(CRLF);\r\n                builder.AppendFormat(@\"Content-Type: {0}\", contentType);\r\n                builder.Append(CRLF);\r\n                builder.Append(CRLF);\r\n\r\n                var encodedHeaders =\r\n                    Encoding.ASCII.GetBytes(builder.ToString());\r\n\r\n                this.body.Write(encodedHeaders, 0, encodedHeaders.Length);\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Testing/BrowserResponse.cs",
    "content": "﻿namespace Nancy.Testing\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using Nancy.Cookies;\r\n\r\n    /// <summary>\r\n    /// The value that is returned from a route that was invoked by a <see cref=\"Browser\"/> instance.\r\n    /// </summary>\r\n    public class BrowserResponse\r\n    {\r\n        private readonly Browser hostBrowser;\r\n        private readonly BrowserContext browserContext;\r\n        private BrowserResponseBodyWrapper body;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"BrowserResponse\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> that <see cref=\"Browser\"/> was invoked with.</param>\r\n        /// <param name=\"hostBrowser\">Host browser object</param>\r\n        /// <param name=\"browserContext\">An <see cref=\"BrowserContext\"/> instance.</param>\r\n        /// <exception cref=\"ArgumentNullException\">The value of the <paramref name=\"context\"/> parameter was <see langword=\"null\"/>.</exception>\r\n        public BrowserResponse(NancyContext context, Browser hostBrowser, BrowserContext browserContext)\r\n        {\r\n            if (context == null)\r\n            {\r\n                throw new ArgumentNullException(\"context\", \"The value of the context parameter cannot be null.\");\r\n            }\r\n\r\n            if (hostBrowser == null)\r\n            {\r\n                throw new ArgumentNullException(\"hostBrowser\", \"The value of the hostBrowser parameter cannot be null.\");\r\n            }\r\n\r\n            this.hostBrowser = hostBrowser;\r\n            this.browserContext = browserContext;\r\n\r\n            this.Context = context;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the HTTP response body as a <see cref=\"BrowserResponseBodyWrapper\"/> instance.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"BrowserResponseBodyWrapper\"/> instance.</value>\r\n        public BrowserResponseBodyWrapper Body\r\n        {\r\n            get\r\n            {\r\n                return this.body ?? (this.body = new BrowserResponseBodyWrapper(this.Context.Response, this.browserContext));\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the content-type of the response.\r\n        /// </summary>\r\n        /// <value>A string containing the content-type.</value>\r\n        public string ContentType\r\n        {\r\n            get { return this.Context.Response.ContentType; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the context that the <see cref=\"Browser\"/> was invoked with.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"NancyContext\"/> instance.</value>\r\n        public NancyContext Context { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the headers of the response.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"IDictionary{TKey,TValue}\"/> instance, that contains the response headers.</value>\r\n        public IDictionary<string, string> Headers\r\n        {\r\n            get { return this.Context.Response.Headers; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the HTTP status code of the response.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"HttpStatusCode\"/> enumerable value.</value>\r\n        public HttpStatusCode StatusCode\r\n        {\r\n            get { return this.Context.Response.StatusCode; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the description of the HTTP status code.\r\n        /// </summary>\r\n        /// <value>The HTTP status code description.</value>\r\n        public string ReasonPhrase\r\n        {\r\n            get { return this.Context.Response.ReasonPhrase; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the cookies from the response\r\n        /// </summary>\r\n        public IEnumerable<INancyCookie> Cookies\r\n        {\r\n            get { return this.Context.Response.Cookies; }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Testing/BrowserResponseBodyWrapper.cs",
    "content": "namespace Nancy.Testing\r\n{\r\n    using System.Collections;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using Nancy.IO;\r\n\r\n    /// <summary>\r\n    /// Wrapper for the HTTP response body that is used by the <see cref=\"BrowserResponse\"/> class.\r\n    /// </summary>\r\n    public class BrowserResponseBodyWrapper : IEnumerable<byte>\r\n    {\r\n        private readonly IEnumerable<byte> responseBytes;\r\n        private readonly string contentType;\r\n        private DocumentWrapper responseDocument;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"BrowserResponseBodyWrapper\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"response\">The <see cref=\"Response\"/> to wrap.</param>\r\n        /// <param name=\"browserContext\">The <see cref=\"BrowserContext\"/> of the request that generated the response.</param>\r\n        public BrowserResponseBodyWrapper(Response response, BrowserContext browserContext)\r\n        {\r\n            this.BrowserContext = browserContext;\r\n            var contentStream = GetContentStream(response);\r\n\r\n            this.responseBytes = contentStream.ToArray();\r\n            this.contentType = response.ContentType;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the content type of the wrapped response.\r\n        /// </summary>\r\n        /// <returns>A string containing the content type.</returns>\r\n        public string ContentType\r\n        {\r\n            get { return this.contentType; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"BrowserContext\"/> of the request that generated the response.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"BrowserContext\"/> intance.</value>\r\n        public BrowserContext BrowserContext { get; private set; }\r\n\r\n        private static MemoryStream GetContentStream(Response response)\r\n        {\r\n            var contentsStream = new MemoryStream();\r\n\r\n            var unclosableStream = new UnclosableStreamWrapper(contentsStream);\r\n\r\n            response.Contents.Invoke(unclosableStream);\r\n            contentsStream.Position = 0;\r\n\r\n            return contentsStream;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a <see cref=\"QueryWrapper\"/> for the provided <paramref name=\"selector\"/>.\r\n        /// </summary>\r\n        /// <param name=\"selector\">The CSS3 selector that should be applied.</param>\r\n        /// <returns>A <see cref=\"QueryWrapper\"/> instance.</returns>\r\n        public QueryWrapper this[string selector]\r\n        {\r\n            get\r\n            {\r\n                if (this.responseDocument == null)\r\n                {\r\n                    this.responseDocument = new DocumentWrapper(this.responseBytes);\r\n                }\r\n\r\n                return this.responseDocument[selector];\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an enumerator that iterates through the collection.\r\n        /// </summary>\r\n        /// <returns>A <see cref=\"IEnumerator{T}\"/> that can be used to iterate through the collection.</returns>\r\n        public IEnumerator<byte> GetEnumerator()\r\n        {\r\n            return this.responseBytes.GetEnumerator();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an enumerator that iterates through a collection.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerator{T}\"/> object that can be used to iterate through the collection.</returns>\r\n        IEnumerator IEnumerable.GetEnumerator()\r\n        {\r\n            return this.GetEnumerator();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Testing/BrowserResponseBodyWrapperExtensions.cs",
    "content": "namespace Nancy.Testing\r\n{\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Text;\r\n    using System.Xml;\r\n\r\n    using Nancy.ModelBinding;\r\n    using Nancy.ModelBinding.DefaultBodyDeserializers;\r\n\r\n    /// <summary>\r\n    /// Extension method for formatting the contents of a <see cref=\"BrowserResponseBodyWrapper\"/>.\r\n    /// </summary>\r\n    public static class BrowserResponseBodyWrapperExtensions\r\n    {\r\n        /// <summary>\r\n        /// Gets the HTTP response body wrapped in a <see cref=\"Stream\"/>.\r\n        /// </summary>\r\n        /// <param name=\"bodyWrapper\">An instance of the <see cref=\"BrowserResponseBodyWrapper\"/> that the extension should be invoked on.</param>\r\n        /// <returns>A <see cref=\"Stream\"/> representation of the HTTP response body.</returns>\r\n        public static Stream AsStream(this BrowserResponseBodyWrapper bodyWrapper)\r\n        {\r\n            return new MemoryStream(bodyWrapper.ToArray());\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the HTTP response body wrapped in a string.\r\n        /// </summary>\r\n        /// <param name=\"bodyWrapper\">An instance of the <see cref=\"BrowserResponseBodyWrapper\"/> that the extension should be invoked on.</param>\r\n        /// <value>A string containing the HTTP response body.</value>\r\n        public static string AsString(this BrowserResponseBodyWrapper bodyWrapper)\r\n        {\r\n            return Encoding.UTF8.GetString(bodyWrapper.ToArray());\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the HTTP response body as a <see cref=\"XmlDocument\"/>\r\n        /// </summary>\r\n        /// <param name=\"bodyWrapper\">An instance of the <see cref=\"BrowserResponseBodyWrapper\"/> that the extension should be invoked on.</param>\r\n        /// <value>A <see cref=\"XmlDocument\"/> representation of the HTTP response body.</value>\r\n        public static XmlDocument AsXmlDocument(this BrowserResponseBodyWrapper bodyWrapper)\r\n        {\r\n            var document = new XmlDocument();\r\n\r\n            document.LoadXml(bodyWrapper.AsString());\r\n\r\n            return document;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the deserialized representation of the JSON in the response body using the default JSON body deserializer.\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">The type that the JSON response body should be deserialized to.</typeparam>\r\n        /// <param name=\"bodyWrapper\">An instance of the <see cref=\"BrowserResponseBodyWrapper\"/> that the extension should be invoked on.</param>\r\n        /// <value>A <typeparamref name=\"TModel\"/> instance representation of the HTTP response body.</value>\r\n        public static TModel DeserializeJson<TModel>(this BrowserResponseBodyWrapper bodyWrapper)\r\n        {\r\n            var bodyDeserializer = new JsonBodyDeserializer(bodyWrapper.BrowserContext.Environment);\r\n\r\n            return bodyWrapper.Deserialize<TModel>(bodyDeserializer);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the deserialized representation of the XML in the response body using the default XML body deserializer.\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">The type that the XML response body should be deserialized to.</typeparam>\r\n        /// <param name=\"bodyWrapper\">An instance of the <see cref=\"BrowserResponseBodyWrapper\"/> that the extension should be invoked on.</param>\r\n        /// <value>A <typeparamref name=\"TModel\"/> instance representation of the HTTP response body.</value>\r\n        public static TModel DeserializeXml<TModel>(this BrowserResponseBodyWrapper bodyWrapper)\r\n        {\r\n            var bodyDeserializer = new XmlBodyDeserializer();\r\n\r\n            return bodyWrapper.Deserialize<TModel>(bodyDeserializer);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the deserialized representation of the response body using the specified body deserializer.\r\n        /// </summary>\r\n        /// <typeparam name=\"TModel\">The type that the response body should be deserialized to.</typeparam>\r\n        /// <param name=\"bodyWrapper\">An instance of the <see cref=\"BrowserResponseBodyWrapper\"/> that the extension should be invoked on.</param>\r\n        /// <param name=\"bodyDeserializer\">An instance of the <see cref=\"IBodyDeserializer\"/> that should be used to deserialize the response body.</param>\r\n        /// <value>A <typeparamref name=\"TModel\"/> instance representation of the HTTP response body.</value>\r\n        public static TModel Deserialize<TModel>(this BrowserResponseBodyWrapper bodyWrapper, IBodyDeserializer bodyDeserializer)\r\n        {\r\n            var bindingContext = new BindingContext { DestinationType = typeof(TModel) };\r\n\r\n            return (TModel)bodyDeserializer.Deserialize(bodyWrapper.ContentType, bodyWrapper.AsStream(), bindingContext);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Testing/BrowserResponseExtensions.cs",
    "content": "namespace Nancy.Testing\r\n{\r\n    using System;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Threading.Tasks;\r\n    using System.Xml.Linq;\r\n\r\n    /// <summary>\r\n    /// Defines extensions for the <see cref=\"BrowserResponse\"/> type.\r\n    /// </summary>\r\n    public static class BrowserResponseExtensions\r\n    {\r\n        /// <summary>\r\n        /// Asserts that a redirect to a certain location took place.\r\n        /// </summary>\r\n        /// <param name=\"response\">The <see cref=\"BrowserResponse\"/> that the assert should be made on.</param>\r\n        /// <param name=\"location\">The location that should have been redirected to.</param>\r\n        /// <param name=\"stringComparer\">The string comparer that should be used by the assertion. The default value is <see cref=\"StringComparison.Ordinal\"/>.</param>\r\n        public static void ShouldHaveRedirectedTo(this BrowserResponse response, string location, StringComparison stringComparer = StringComparison.Ordinal)\r\n        {\r\n            var validRedirectStatuses = new[]\r\n            {\r\n                HttpStatusCode.MovedPermanently,\r\n                HttpStatusCode.SeeOther,\r\n                HttpStatusCode.TemporaryRedirect\r\n            };\r\n\r\n            if (!validRedirectStatuses.Any(x => x == response.StatusCode))\r\n            {\r\n                throw new AssertException(\r\n                    string.Format(\"Status code should be one of 'MovedPermanently, SeeOther, TemporaryRedirect', but was {0}.\", response.StatusCode));\r\n            }\r\n\r\n            if (!response.Headers[\"Location\"].Equals(location, stringComparer))\r\n            {\r\n                throw new AssertException(string.Format(\"Location should have been: {0}, but was {1}\", location, response.Headers[\"Location\"]));\r\n            }\r\n        }\r\n\r\n        public static XDocument BodyAsXml(this BrowserResponse response)\r\n        {\r\n            using (var contentsStream = new MemoryStream())\r\n            {\r\n                response.Context.Response.Contents.Invoke(contentsStream);\r\n                contentsStream.Position = 0;\r\n                return XDocument.Load(contentsStream);\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Testing/ConfigurableBootstrapper.cs",
    "content": "namespace Nancy.Testing\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Configuration;\r\n    using Nancy.Conventions;\r\n    using Nancy.Culture;\r\n    using Nancy.Diagnostics;\r\n    using Nancy.ErrorHandling;\r\n    using Nancy.Localization;\r\n    using Nancy.ModelBinding;\r\n    using Nancy.Responses.Negotiation;\r\n    using Nancy.Routing;\r\n    using Nancy.Routing.Constraints;\r\n    using Nancy.Routing.Trie;\r\n    using Nancy.Security;\r\n    using Nancy.TinyIoc;\r\n    using Nancy.Validation;\r\n    using Nancy.ViewEngines;\r\n\r\n    /// <summary>\r\n    /// A Nancy bootstrapper that can be configured with either Type or Instance overrides for all Nancy types.\r\n    /// </summary>\r\n    public class ConfigurableBootstrapper : NancyBootstrapperWithRequestContainerBase<TinyIoCContainer>, IPipelines, INancyModuleCatalog\r\n    {\r\n        private readonly List<object> registeredTypes;\r\n        private readonly List<InstanceRegistration> registeredInstances;\r\n        private readonly NancyInternalConfiguration configuration;\r\n        private readonly ConfigurableModuleCatalog catalog;\r\n        private bool enableAutoRegistration;\r\n        private readonly List<Action<TinyIoCContainer, IPipelines>> applicationStartupActions;\r\n        private readonly List<Action<TinyIoCContainer, IPipelines, NancyContext>> requestStartupActions;\r\n        private readonly Assembly nancyAssembly = typeof(NancyEngine).GetTypeInfo().Assembly;\r\n        private Action<INancyEnvironment> configure;\r\n        private readonly IList<Action<NancyInternalConfiguration>> configurationOverrides;\r\n\r\n        /// <summary>\r\n        /// Test project name suffixes that will be stripped from the test name project\r\n        /// in order to try and resolve the name of the assembly that is under test so\r\n        /// that all of its references can be loaded into the application domain.\r\n        /// </summary>\r\n        public static IList<string> TestAssemblySuffixes = new[] { \"test\", \"tests\", \"unittests\", \"specs\", \"specifications\" };\r\n\r\n        private bool allDiscoveredModules;\r\n        private bool autoRegistrations = true;\r\n        private bool disableAutoApplicationStartupRegistration;\r\n        private bool disableAutoRequestStartupRegistration;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ConfigurableBootstrapper\"/> class.\r\n        /// </summary>\r\n        public ConfigurableBootstrapper()\r\n            : this(null)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ConfigurableBootstrapper\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"configuration\">The configuration that should be used by the bootstrapper.</param>\r\n        public ConfigurableBootstrapper(Action<ConfigurableBootstrapperConfigurator> configuration)\r\n        {\r\n            this.catalog = new ConfigurableModuleCatalog();\r\n            this.configuration = NancyInternalConfiguration.Default.Invoke(this.TypeCatalog);\r\n            this.registeredTypes = new List<object>();\r\n            this.registeredInstances = new List<InstanceRegistration>();\r\n            this.applicationStartupActions = new List<Action<TinyIoCContainer, IPipelines>>();\r\n            this.requestStartupActions = new List<Action<TinyIoCContainer, IPipelines, NancyContext>>();\r\n            this.configurationOverrides = new List<Action<NancyInternalConfiguration>>();\r\n\r\n            if (configuration != null)\r\n            {\r\n                var configurator =\r\n                    new ConfigurableBootstrapperConfigurator(this);\r\n\r\n                configurator.StatusCodeHandler<PassThroughStatusCodeHandler>();\r\n                configuration.Invoke(configurator);\r\n\r\n                foreach (var configurationOverride in this.configurationOverrides)\r\n                {\r\n                    configurationOverride.Invoke(this.configuration);\r\n                }\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Configures the Nancy environment\r\n        /// </summary>\r\n        /// <param name=\"environment\">The <see cref=\"INancyEnvironment\"/> instance to configure</param>\r\n        public override void Configure(INancyEnvironment environment)\r\n        {\r\n            if (this.configure != null)\r\n            {\r\n                this.configure.Invoke(environment);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initialise the bootstrapper - can be used for adding pre/post hooks and\r\n        /// any other initialisation tasks that aren't specifically container setup\r\n        /// related\r\n        /// </summary>\r\n        /// <param name=\"container\">Container instance for resolving types if required.</param>\r\n        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)\r\n        {\r\n            base.ApplicationStartup(container, pipelines);\r\n            foreach (var action in this.applicationStartupActions)\r\n            {\r\n                action.Invoke(container, pipelines);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initialise the request - can be used for adding pre/post hooks and\r\n        /// any other per-request initialisation tasks that aren't specifically container setup\r\n        /// related\r\n        /// </summary>\r\n        /// <param name=\"container\">Container</param>\r\n        /// <param name=\"pipelines\">Current pipelines</param>\r\n        /// <param name=\"context\">Current context</param>\r\n        protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)\r\n        {\r\n            base.RequestStartup(container, pipelines, context);\r\n            foreach (var action in this.requestStartupActions)\r\n            {\r\n                action.Invoke(container, pipelines, context);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get all NancyModule implementation instances\r\n        /// </summary>\r\n        /// <param name=\"context\">The current context</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance containing <see cref=\"INancyModule\"/> instances.</returns>\r\n        public new IEnumerable<INancyModule> GetAllModules(NancyContext context)\r\n        {\r\n            return base.GetAllModules(context).Union(this.catalog.GetAllModules(context));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the <see cref=\"INancyEnvironment\"/> instance.\r\n        /// </summary>\r\n        /// <returns>An configured <see cref=\"INancyEnvironment\"/> instance.</returns>\r\n        /// <remarks>The boostrapper must be initialised (<see cref=\"INancyBootstrapper.Initialise\"/>) prior to calling this.</remarks>\r\n        public override INancyEnvironment GetEnvironment()\r\n        {\r\n            return base.ApplicationContainer.Resolve<INancyEnvironment>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Retrieve a specific module instance from the container\r\n        /// </summary>\r\n        /// <param name=\"container\">Container to use</param>\r\n        /// <param name=\"moduleType\">Type of the module</param>\r\n        /// <returns>INancyModule instance</returns>\r\n        protected override INancyModule GetModule(TinyIoCContainer container, Type moduleType)\r\n        {\r\n            var module =\r\n                this.catalog.GetModule(moduleType, null);\r\n\r\n            if (module != null)\r\n            {\r\n                return module;\r\n            }\r\n\r\n            container.Register(typeof(INancyModule), moduleType);\r\n            return container.Resolve<INancyModule>();\r\n        }\r\n\r\n        private IEnumerable<ModuleRegistration> GetModuleRegistrations()\r\n        {\r\n            return this.registeredTypes.Where(x => x is ModuleRegistration).Cast<ModuleRegistration>();\r\n        }\r\n\r\n        private IEnumerable<TypeRegistration> GetTypeRegistrations()\r\n        {\r\n            return this.registeredTypes.Where(x => x is TypeRegistration).Cast<TypeRegistration>();\r\n        }\r\n\r\n        private IEnumerable<CollectionTypeRegistration> GetCollectionTypeRegistrations()\r\n        {\r\n            return this.registeredTypes.Where(x => x.GetType() == typeof(CollectionTypeRegistration)).Cast<CollectionTypeRegistration>();\r\n        }\r\n\r\n        private static string GetSafePathExtension(string name)\r\n        {\r\n            return Path.GetExtension(name) ?? string.Empty;\r\n        }\r\n\r\n        private IEnumerable<Type> Resolve<T>()\r\n        {\r\n            var types = this.GetTypeRegistrations()\r\n                .Where(x => x.RegistrationType == typeof(T))\r\n                .Select(x => x.ImplementationType)\r\n                .ToList();\r\n\r\n            return (types.Any()) ? types : null;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Nancy internal configuration\r\n        /// </summary>\r\n        protected override sealed Func<ITypeCatalog, NancyInternalConfiguration> InternalConfiguration\r\n        {\r\n            get { return x => this.configuration; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Nancy conventions\r\n        /// </summary>\r\n        protected override NancyConventions Conventions\r\n        {\r\n            get\r\n            {\r\n                var conventions = this.registeredInstances\r\n                    .Where(x => x.RegistrationType == typeof(NancyConventions))\r\n                    .Select(x => x.Implementation)\r\n                    .Cast<NancyConventions>()\r\n                    .FirstOrDefault();\r\n\r\n                return conventions ?? base.Conventions;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all available module types\r\n        /// </summary>\r\n        protected override IEnumerable<ModuleRegistration> Modules\r\n        {\r\n            get\r\n            {\r\n                var moduleRegistrations =\r\n                    this.GetModuleRegistrations().ToList();\r\n\r\n                if (moduleRegistrations.Any())\r\n                {\r\n                    return moduleRegistrations;\r\n                }\r\n\r\n                return this.allDiscoveredModules ? base.Modules : ArrayCache.Empty<ModuleRegistration>();\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the available view engine types\r\n        /// </summary>\r\n        protected override IEnumerable<Type> ViewEngines\r\n        {\r\n            get { return this.Resolve<IViewEngine>() ?? base.ViewEngines; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the available custom model binders\r\n        /// </summary>\r\n        protected override IEnumerable<Type> ModelBinders\r\n        {\r\n            get { return this.Resolve<IModelBinder>() ?? base.ModelBinders; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the available custom type converters\r\n        /// </summary>\r\n        protected override IEnumerable<Type> TypeConverters\r\n        {\r\n            get { return this.Resolve<ITypeConverter>() ?? base.TypeConverters; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the available custom body deserializers\r\n        /// </summary>\r\n        protected override IEnumerable<Type> BodyDeserializers\r\n        {\r\n            get { return this.Resolve<IBodyDeserializer>() ?? base.BodyDeserializers; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all startup tasks\r\n        /// </summary>\r\n        protected override IEnumerable<Type> ApplicationStartupTasks\r\n        {\r\n            get\r\n            {\r\n                var tasks = base.ApplicationStartupTasks;\r\n\r\n                var user = (this.Resolve<IApplicationStartup>() ?? Enumerable.Empty<Type>()).ToArray();\r\n\r\n                if (this.disableAutoApplicationStartupRegistration || user.Any())\r\n                {\r\n                    tasks = tasks.Where(x => x.GetTypeInfo().Assembly.GetName().Name.StartsWith(\"Nancy\", StringComparison.OrdinalIgnoreCase));\r\n                }\r\n\r\n                return tasks.Union(user);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all request startup tasks\r\n        /// </summary>\r\n        protected override IEnumerable<Type> RequestStartupTasks\r\n        {\r\n            get\r\n            {\r\n                var tasks = base.RequestStartupTasks;\r\n\r\n                var user = (this.Resolve<IRequestStartup>() ?? Enumerable.Empty<Type>()).ToArray();\r\n\r\n                if (this.disableAutoRequestStartupRegistration || user.Any())\r\n                {\r\n                    tasks = tasks.Where(x => x.GetTypeInfo().Assembly.GetName().Name.StartsWith(\"Nancy\", StringComparison.OrdinalIgnoreCase));\r\n                }\r\n\r\n                return tasks.Union(user);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the root path provider\r\n        /// </summary>\r\n        protected override IRootPathProvider RootPathProvider\r\n        {\r\n            get { return new DefaultRootPathProvider(); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Configures the container using AutoRegister followed by registration\r\n        /// of default INancyModuleCatalog and IRouteResolver.\r\n        /// </summary>\r\n        /// <param name=\"container\">Container instance</param>\r\n        protected override void ConfigureApplicationContainer(TinyIoCContainer container)\r\n        {\r\n            if (this.enableAutoRegistration)\r\n            {\r\n                container.AutoRegister();\r\n                this.RegisterBootstrapperTypes(container);\r\n            }\r\n\r\n            RegisterTypesInternal(this.ApplicationContainer, this.GetTypeRegistrations());\r\n            RegisterCollectionTypesInternal(this.ApplicationContainer, this.GetCollectionTypeRegistrations());\r\n            RegisterInstancesInternal(this.ApplicationContainer, this.registeredInstances);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a per request child/nested container\r\n        /// </summary>\r\n        /// <param name=\"context\">Current context</param>\r\n        /// <returns>Request container instance</returns>\r\n        protected override TinyIoCContainer CreateRequestContainer(NancyContext context)\r\n        {\r\n            return this.ApplicationContainer.GetChildContainer();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Retrieve all module instances from the container\r\n        /// </summary>\r\n        /// <param name=\"container\">Container to use</param>\r\n        /// <returns>Collection of INancyModule instances</returns>\r\n        protected override IEnumerable<INancyModule> GetAllModules(TinyIoCContainer container)\r\n        {\r\n            return container.ResolveAll<INancyModule>(false);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the application level container\r\n        /// </summary>\r\n        /// <returns>Container instance</returns>\r\n        protected override TinyIoCContainer GetApplicationContainer()\r\n        {\r\n            return new TinyIoCContainer();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Resolve INancyEngine\r\n        /// </summary>\r\n        /// <returns>INancyEngine implementation</returns>\r\n        protected override INancyEngine GetEngineInternal()\r\n        {\r\n            try\r\n            {\r\n                return this.ApplicationContainer.Resolve<INancyEngine>();\r\n            }\r\n            catch (InvalidOperationException ex)\r\n            {\r\n                throw new InvalidOperationException(\r\n                    \"Something went wrong when trying to satisfy one of the dependencies during composition, make sure that you've registered all new dependencies in the container and specified either a module to test, or set AllDiscoveredModules in the ConfigurableBootstrapper. Inspect the innerexception for more details.\",\r\n                    ex.InnerException);\r\n            }\r\n        }\r\n\r\n\r\n        /// <summary>\r\n        /// Gets the diagnostics for initialization\r\n        /// </summary>\r\n        /// <returns>IDiagnostics implementation</returns>\r\n        protected override IDiagnostics GetDiagnostics()\r\n        {\r\n            return this.ApplicationContainer.Resolve<IDiagnostics>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all registered startup tasks\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance containing <see cref=\"IApplicationStartup\"/> instances. </returns>\r\n        protected override IEnumerable<IApplicationStartup> GetApplicationStartupTasks()\r\n        {\r\n            return this.ApplicationContainer.ResolveAll<IApplicationStartup>(false);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all registered request startup tasks\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"System.Collections.Generic.IEnumerable{T}\"/> instance containing <see cref=\"IRequestStartup\"/> instances.</returns>\r\n        protected override IEnumerable<IRequestStartup> RegisterAndGetRequestStartupTasks(TinyIoCContainer container, Type[] requestStartupTypes)\r\n        {\r\n            container.RegisterMultiple(typeof(IRequestStartup), requestStartupTypes);\r\n\r\n            return container.ResolveAll<IRequestStartup>(false);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all registered application registration tasks\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance containing <see cref=\"IRegistrations\"/> instances.</returns>\r\n        protected override IEnumerable<IRegistrations> GetRegistrationTasks()\r\n        {\r\n            if (this.autoRegistrations)\r\n            {\r\n                return this.ApplicationContainer.ResolveAll<IRegistrations>(false);\r\n            }\r\n\r\n            return this.ApplicationContainer.ResolveAll<IRegistrations>(false)\r\n                       .Where(x => x.GetType().GetTypeInfo().Assembly == nancyAssembly);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Register the bootstrapper's implemented types into the container.\r\n        /// This is necessary so a user can pass in a populated container but not have\r\n        /// to take the responsibility of registering things like INancyModuleCatalog manually.\r\n        /// </summary>\r\n        /// <param name=\"applicationContainer\">Application container to register into</param>\r\n        protected override void RegisterBootstrapperTypes(TinyIoCContainer applicationContainer)\r\n        {\r\n            var moduleCatalog = this.registeredInstances\r\n                .Where(x => x.RegistrationType == typeof(INancyModuleCatalog))\r\n                .Select(x => x.Implementation)\r\n                .Cast<INancyModuleCatalog>()\r\n                .FirstOrDefault() ?? this;\r\n\r\n            applicationContainer.Register<INancyModuleCatalog>(moduleCatalog);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Register the default implementations of internally used types into the container as singletons\r\n        /// </summary>\r\n        /// <param name=\"container\">Container to register into</param>\r\n        /// <param name=\"typeRegistrations\">Type registrations to register</param>\r\n        protected override void RegisterTypes(TinyIoCContainer container, IEnumerable<TypeRegistration> typeRegistrations)\r\n        {\r\n            var configuredTypes =\r\n                this.GetTypeRegistrations().ToList();\r\n\r\n            var filtered = typeRegistrations\r\n                .Where(x => !configuredTypes.Any(y => y.RegistrationType == x.RegistrationType))\r\n                .Where(x => !this.registeredInstances.Any(y => y.RegistrationType == x.RegistrationType));\r\n\r\n            RegisterTypesInternal(container, filtered);\r\n        }\r\n\r\n        private static void RegisterTypesInternal(TinyIoCContainer container, IEnumerable<TypeRegistration> filtered)\r\n        {\r\n            foreach (var typeRegistration in filtered)\r\n            {\r\n                container.Register(typeRegistration.RegistrationType, typeRegistration.ImplementationType).AsSingleton();\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Register the various collections into the container as singletons to later be resolved\r\n        /// by IEnumerable{Type} constructor dependencies.\r\n        /// </summary>\r\n        /// <param name=\"container\">Container to register into</param>\r\n        /// <param name=\"collectionTypeRegistrations\">Collection type registrations to register</param>\r\n        protected override void RegisterCollectionTypes(TinyIoCContainer container, IEnumerable<CollectionTypeRegistration> collectionTypeRegistrations)\r\n        {\r\n            var configuredCollectionTypes =\r\n                this.GetCollectionTypeRegistrations().ToList();\r\n\r\n            var filtered = collectionTypeRegistrations\r\n                .Where(x => !configuredCollectionTypes.Any(y => y.RegistrationType == x.RegistrationType));\r\n\r\n            RegisterCollectionTypesInternal(container, filtered);\r\n        }\r\n\r\n        private static void RegisterCollectionTypesInternal(TinyIoCContainer container, IEnumerable<CollectionTypeRegistration> filtered)\r\n        {\r\n            foreach (var collectionTypeRegistration in filtered)\r\n            {\r\n                container.RegisterMultiple(collectionTypeRegistration.RegistrationType,\r\n                    collectionTypeRegistration.ImplementationTypes);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Register the given instances into the container\r\n        /// </summary>\r\n        /// <param name=\"container\">Container to register into</param>\r\n        /// <param name=\"instanceRegistrations\">Instance registration types</param>\r\n        protected override void RegisterInstances(TinyIoCContainer container, IEnumerable<InstanceRegistration> instanceRegistrations)\r\n        {\r\n            var configuredInstanceRegistrations = this.GetTypeRegistrations();\r\n\r\n            var fileteredInstanceRegistrations = instanceRegistrations\r\n                .Where(x => !this.registeredInstances.Any(y => y.RegistrationType == x.RegistrationType))\r\n                .Where(x => !configuredInstanceRegistrations.Any(y => y.RegistrationType == x.RegistrationType))\r\n                .ToList();\r\n\r\n            RegisterInstancesInternal(container, fileteredInstanceRegistrations);\r\n        }\r\n\r\n        private static void RegisterInstancesInternal(TinyIoCContainer container, IEnumerable<InstanceRegistration> fileteredInstanceRegistrations)\r\n        {\r\n            foreach (var instanceRegistration in fileteredInstanceRegistrations)\r\n            {\r\n                container.Register(\r\n                    instanceRegistration.RegistrationType,\r\n                    instanceRegistration.Implementation);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Register the given module types into the request container\r\n        /// </summary>\r\n        /// <param name=\"container\">Container to register into</param>\r\n        /// <param name=\"moduleRegistrationTypes\">NancyModule types</param>\r\n        protected override void RegisterRequestContainerModules(TinyIoCContainer container, IEnumerable<ModuleRegistration> moduleRegistrationTypes)\r\n        {\r\n            foreach (var moduleRegistrationType in moduleRegistrationTypes)\r\n            {\r\n                container.Register(\r\n                    typeof(INancyModule),\r\n                    moduleRegistrationType.ModuleType,\r\n                    moduleRegistrationType.ModuleType.FullName).\r\n                    AsSingleton();\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"INancyEnvironmentConfigurator\"/> used by th.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"INancyEnvironmentConfigurator\"/> instance.</returns>\r\n        protected override INancyEnvironmentConfigurator GetEnvironmentConfigurator()\r\n        {\r\n            return this.ApplicationContainer.Resolve<INancyEnvironmentConfigurator>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Registers an <see cref=\"INancyEnvironment\"/> instance in the container.\r\n        /// </summary>\r\n        /// <param name=\"container\">The container to register into.</param>\r\n        /// <param name=\"environment\">The <see cref=\"INancyEnvironment\"/> instance to register.</param>\r\n        protected override void RegisterNancyEnvironment(TinyIoCContainer container, INancyEnvironment environment)\r\n        {\r\n            container.Register(environment);\r\n        }\r\n\r\n        /// <summary>\r\n        /// <para>\r\n        /// The pre-request hook\r\n        /// </para>\r\n        /// <para>\r\n        /// The PreRequest hook is called prior to processing a request. If a hook returns\r\n        /// a non-null response then processing is aborted and the response provided is\r\n        /// returned.\r\n        /// </para>\r\n        /// </summary>\r\n        public BeforePipeline BeforeRequest\r\n        {\r\n            get { return this.ApplicationPipelines.BeforeRequest; }\r\n            set { this.ApplicationPipelines.BeforeRequest = value; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// <para>\r\n        /// The post-request hook\r\n        /// </para>\r\n        /// <para>\r\n        /// The post-request hook is called after the response is created. It can be used\r\n        /// to rewrite the response or add/remove items from the context.\r\n        /// </para>\r\n        /// </summary>\r\n        public AfterPipeline AfterRequest\r\n        {\r\n            get { return this.ApplicationPipelines.AfterRequest; }\r\n            set { this.ApplicationPipelines.AfterRequest = value; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// <para>\r\n        /// The error hook\r\n        /// </para>\r\n        /// <para>\r\n        /// The error hook is called if an exception is thrown at any time during the pipeline.\r\n        /// If no error hook exists a standard InternalServerError response is returned\r\n        /// </para>\r\n        /// </summary>\r\n        public ErrorPipeline OnError\r\n        {\r\n            get { return this.ApplicationPipelines.OnError; }\r\n            set { this.ApplicationPipelines.OnError = value; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Provides an API for configuring a <see cref=\"ConfigurableBootstrapper\"/> instance.\r\n        /// </summary>\r\n        public class ConfigurableBootstrapperConfigurator\r\n        {\r\n            private readonly ConfigurableBootstrapper bootstrapper;\r\n\r\n            /// <summary>\r\n            /// Initializes a new instance of the <see cref=\"ConfigurableBootstrapperConfigurator\"/> class.\r\n            /// </summary>\r\n            /// <param name=\"bootstrapper\">The bootstrapper that should be configured.</param>\r\n            public ConfigurableBootstrapperConfigurator(ConfigurableBootstrapper bootstrapper)\r\n            {\r\n                this.bootstrapper = bootstrapper;\r\n                this.Diagnostics<DisabledDiagnostics>();\r\n            }\r\n\r\n            public ConfigurableBootstrapperConfigurator AllDiscoveredModules()\r\n            {\r\n                this.bootstrapper.allDiscoveredModules = true;\r\n\r\n                return this;\r\n            }\r\n\r\n            public ConfigurableBootstrapperConfigurator Binder(IBinder binder)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IBinder), binder));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IBinder\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IBinder\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator Binder<T>() where T : IBinder\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.Binder = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the <see cref=\"INancyEnvironment\"/>.\r\n            /// </summary>\r\n            /// <param name=\"configuration\">The configuration to apply to the environment.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator Configure(Action<INancyEnvironment> configuration)\r\n            {\r\n                this.bootstrapper.configure = configuration;\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"INancyContextFactory\"/>.\r\n            /// </summary>\r\n            /// <param name=\"contextFactory\">The <see cref=\"INancyContextFactory\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ContextFactory(INancyContextFactory contextFactory)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(INancyContextFactory), contextFactory));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"INancyContextFactory\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"INancyContextFactory\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ContextFactory<T>() where T : INancyContextFactory\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.ContextFactory = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"INancyDefaultConfigurationProvider\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IRouteMetadataProvider\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator DefaultConfigurationProvider<T>() where T : INancyDefaultConfigurationProvider\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.DefaultConfigurationProviders = new List<Type>(new[] { typeof(T) }));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided <see cref=\"INancyDefaultConfigurationProvider\"/> types.\r\n            /// </summary>\r\n            /// <param name=\"defaultConfigurationProviders\">The <see cref=\"INancyDefaultConfigurationProvider\"/> types that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator DefaultConfigurationProviders(params Type[] defaultConfigurationProviders)\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.DefaultConfigurationProviders = defaultConfigurationProviders);\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instances of <see cref=\"INancyDefaultConfigurationProvider\"/>.\r\n            /// </summary>\r\n            /// <param name=\"defaultConfigurationProvider\">The <see cref=\"INancyDefaultConfigurationProvider\"/> types that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator DefaultConfigurationProviders(INancyDefaultConfigurationProvider defaultConfigurationProvider)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(INancyDefaultConfigurationProvider), defaultConfigurationProvider));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instances of <see cref=\"INancyDefaultConfigurationProvider\"/>.\r\n            /// </summary>\r\n            /// <param name=\"defaultConfigurationProviders\">The <see cref=\"INancyDefaultConfigurationProvider\"/> types that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator DefaultConfigurationProviders(params INancyDefaultConfigurationProvider[] defaultConfigurationProviders)\r\n            {\r\n                foreach (var defaultConfigurationProvider in defaultConfigurationProviders)\r\n                {\r\n                    this.bootstrapper.registeredInstances.Add(\r\n                        new InstanceRegistration(typeof(INancyDefaultConfigurationProvider), defaultConfigurationProvider));\r\n                }\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided type as a dependency.\r\n            /// </summary>\r\n            /// <param name=\"type\">The type of the dependency that should be used registered with the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator Dependency<T>(Type type)\r\n            {\r\n                this.bootstrapper.registeredTypes.Add(new TypeRegistration(typeof(T), type));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to register the specified type as a dependency.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the dependency that should be registered with the bootstrapper.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            /// <remarks>This method will register the type for all the interfaces it implements and the type itself.</remarks>\r\n            public ConfigurableBootstrapperConfigurator Dependency<T>()\r\n            {\r\n                this.bootstrapper.registeredTypes.Add(new TypeRegistration(typeof(T), typeof(T)));\r\n\r\n                foreach (var interfaceType in GetSafeInterfaces(typeof(T)))\r\n                {\r\n                    this.bootstrapper.registeredTypes.Add(new TypeRegistration(interfaceType, typeof(T)));\r\n                }\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance as a dependency.\r\n            /// </summary>\r\n            /// <param name=\"instance\">The dependency instance that should be used registered with the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            /// <remarks>This method will register the instance for all the interfaces it implements and the type itself.</remarks>\r\n            public ConfigurableBootstrapperConfigurator Dependency<T>(T instance)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(new InstanceRegistration(typeof(T), instance));\r\n\r\n                var interfacesToRegisterBy = GetSafeInterfaces(instance.GetType()).Where(i => !i.Equals(typeof(T)));\r\n                foreach (var interfaceType in interfacesToRegisterBy)\r\n                {\r\n                    this.bootstrapper.registeredInstances.Add(new InstanceRegistration(interfaceType, instance));\r\n                }\r\n\r\n                return this;\r\n            }\r\n\r\n            private static IEnumerable<Type> GetSafeInterfaces(Type type)\r\n            {\r\n                return type.GetInterfaces().Where(x => x != typeof(IDisposable));\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to register the specified types and instances as a dependencies.\r\n            /// </summary>\r\n            /// <param name=\"dependencies\">An array of maps between the interfaces and instances that should be registered with the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator MappedDependencies<T, K>(IEnumerable<Tuple<T, K>> dependencies)\r\n                where T : Type\r\n                where K : class\r\n            {\r\n                foreach (var dependency in dependencies)\r\n                {\r\n                    this.bootstrapper.registeredInstances.Add(\r\n                        new InstanceRegistration(dependency.Item1, dependency.Item2));\r\n                }\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to register the specified instances as a dependencies.\r\n            /// </summary>\r\n            /// <param name=\"dependencies\">The instances of the dependencies that should be registered with the bootstrapper.</param>\r\n            /// <typeparam name=\"T\">The type that the dependencies should be registered as.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator Dependencies<T>(params T[] dependencies)\r\n            {\r\n                foreach (var dependency in dependencies)\r\n                {\r\n                    this.Dependency(dependency);\r\n                }\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided types as a dependency.\r\n            /// </summary>\r\n            /// <param name=\"dependencies\">The types that should be used registered as dependencies with the bootstrapper.</param>\r\n            /// <typeparam name=\"T\">The type that the dependencies should be registered as.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator Dependencies<T>(params Type[] dependencies)\r\n            {\r\n                foreach (var dependency in dependencies)\r\n                {\r\n                    this.Dependency<T>(dependency);\r\n                }\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Enables the auto registration behavior of the bootstrapper\r\n            /// </summary>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator EnableAutoRegistration()\r\n            {\r\n                this.bootstrapper.enableAutoRegistration = true;\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IStatusCodeHandler\"/>.\r\n            /// </summary>\r\n            /// <param name=\"statusCodeHandlers\">The <see cref=\"IStatusCodeHandler\"/> types that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator StatusCodeHandlers(params Type[] statusCodeHandlers)\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.StatusCodeHandlers = new List<Type>(statusCodeHandlers));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IStatusCodeHandler\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IStatusCodeHandler\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator StatusCodeHandler<T>() where T : IStatusCodeHandler\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.StatusCodeHandlers = new List<Type>(new[] { typeof(T) }));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"INancyEnvironmentConfigurator\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"INancyEnvironmentConfigurator\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator EnvironmentConfigurator<T>() where T : INancyEnvironmentConfigurator\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.EnvironmentConfigurator = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"INancyEnvironmentConfigurator\"/>.\r\n            /// </summary>\r\n            /// <param name=\"environmentConfigurator\">The <see cref=\"INancyEnvironmentConfigurator\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator EnvironmentConfigurator(INancyEnvironmentConfigurator environmentConfigurator)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(INancyEnvironmentConfigurator), environmentConfigurator));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"INancyEnvironmentFactory\"/>.\r\n            /// </summary>\r\n            /// <param name=\"environmentFactory\">The <see cref=\"INancyEnvironmentFactory\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator EnvironmentFactory(INancyEnvironmentFactory environmentFactory)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(INancyEnvironmentConfigurator), environmentFactory));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"INancyEnvironmentFactory\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"INancyEnvironmentFactory\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator EnvironmentFactory<T>() where T : INancyEnvironmentFactory\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.EnvironmentFactory = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IFieldNameConverter\"/>.\r\n            /// </summary>\r\n            /// <param name=\"fieldNameConverter\">The <see cref=\"IFieldNameConverter\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator FieldNameConverter(IFieldNameConverter fieldNameConverter)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IFieldNameConverter), fieldNameConverter));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IFieldNameConverter\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IFieldNameConverter\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator FieldNameConverter<T>() where T : IFieldNameConverter\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.FieldNameConverter = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IModelBinderLocator\"/>.\r\n            /// </summary>\r\n            /// <param name=\"modelBinderLocator\">The <see cref=\"IModelBinderLocator\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ModelBinderLocator(IModelBinderLocator modelBinderLocator)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IModelBinderLocator), modelBinderLocator));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IModelBinderLocator\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IModelBinderLocator\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ModelBinderLocator<T>() where T : IModelBinderLocator\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.ModelBinderLocator = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create a <see cref=\"INancyModule\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"INancyModule\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator Module<T>() where T : INancyModule\r\n            {\r\n                return this.Modules(typeof(T));\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to register the provided <see cref=\"INancyModule\"/> instance.\r\n            /// </summary>\r\n            /// <param name=\"module\">The <see cref=\"INancyModule\"/> instance to register.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator Module(INancyModule module)\r\n            {\r\n                this.bootstrapper.catalog.RegisterModuleInstance(module);\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create <see cref=\"INancyModule\"/> instances of the specified types.\r\n            /// </summary>\r\n            /// <param name=\"modules\">The types of the <see cref=\"INancyModule\"/> that the bootstrapper should use.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator Modules(params Type[] modules)\r\n            {\r\n                var moduleRegistrations =\r\n                    from module in modules\r\n                    select new ModuleRegistration(module);\r\n\r\n                this.bootstrapper.registeredTypes.AddRange(moduleRegistrations);\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"INancyEngine\"/>.\r\n            /// </summary>\r\n            /// <param name=\"engine\">The <see cref=\"INancyEngine\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator NancyEngine(INancyEngine engine)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(INancyEngine), engine));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"INancyEngine\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"INancyEngine\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator NancyEngine<T>() where T : INancyEngine\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.NancyEngine = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"INancyModuleBuilder\"/>.\r\n            /// </summary>\r\n            /// <param name=\"nancyModuleBuilder\">The <see cref=\"INancyModuleBuilder\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator NancyModuleBuilder(INancyModuleBuilder nancyModuleBuilder)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(INancyModuleBuilder), nancyModuleBuilder));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"INancyModuleBuilder\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"INancyModuleBuilder\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator NancyModuleBuilder<T>() where T : INancyModuleBuilder\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.NancyModuleBuilder = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IRenderContextFactory\"/>.\r\n            /// </summary>\r\n            /// <param name=\"renderContextFactory\">The <see cref=\"IRenderContextFactory\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RenderContextFactory(IRenderContextFactory renderContextFactory)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IRenderContextFactory), renderContextFactory));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IRenderContextFactory\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IRenderContextFactory\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RenderContextFactory<T>() where T : IRenderContextFactory\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.RenderContextFactory = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IRequestTraceFactory\"/>.\r\n            /// </summary>\r\n            /// <param name=\"requestTraceFactory\">The <see cref=\"IRequestTraceFactory\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RequestTraceFactory(IRequestTraceFactory requestTraceFactory)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IRequestTraceFactory), requestTraceFactory));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IRequestTraceFactory\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IRequestTraceFactory\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RequestTraceFactory<T>() where T : IRequestTraceFactory\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.RequestTraceFactory = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IResponseFormatterFactory\"/>.\r\n            /// </summary>\r\n            /// <param name=\"responseFormatterFactory\">The <see cref=\"IResponseFormatterFactory\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ResponseFormatterFactory(IResponseFormatterFactory responseFormatterFactory)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IResponseFormatterFactory), responseFormatterFactory));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IResponseFormatterFactory\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IResponseFormatterFactory\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ResponseFormatterFactory<T>() where T : IResponseFormatterFactory\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.ResponseFormatterFactory = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IRouteCache\"/>.\r\n            /// </summary>\r\n            /// <param name=\"routeCache\">The <see cref=\"IRouteCache\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RouteCache(IRouteCache routeCache)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IRouteCache), routeCache));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IRouteCache\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IRouteCache\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RouteCache<T>() where T : IRouteCache\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.RouteCache = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IRouteCacheProvider\"/>.\r\n            /// </summary>\r\n            /// <param name=\"routeCacheProvider\">The <see cref=\"IRouteCacheProvider\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RouteCacheProvider(IRouteCacheProvider routeCacheProvider)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IRouteCacheProvider), routeCacheProvider));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IRouteCacheProvider\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IRouteCacheProvider\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RouteCacheProvider<T>() where T : IRouteCacheProvider\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.RouteCacheProvider = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IRootPathProvider\"/>.\r\n            /// </summary>\r\n            /// <param name=\"rootPathProvider\">The <see cref=\"IRootPathProvider\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RootPathProvider(IRootPathProvider rootPathProvider)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IRootPathProvider), rootPathProvider));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IRootPathProvider\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IRootPathProvider\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RootPathProvider<T>() where T : IRootPathProvider\r\n            {\r\n                this.bootstrapper.registeredTypes.Add(\r\n                    new TypeRegistration(typeof(IRootPathProvider), typeof(T)));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IRouteInvoker\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IRouteInvoker\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RouteInvoker<T>() where T : IRouteInvoker\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.RouteInvoker = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IRouteInvoker\"/>.\r\n            /// </summary>\r\n            /// <param name=\"routeInvoker\">The <see cref=\"IRouteInvoker\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RouteInvoker(IRouteInvoker routeInvoker)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IRouteInvoker), routeInvoker));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IRouteResolver\"/>.\r\n            /// </summary>\r\n            /// <param name=\"routeResolver\">The <see cref=\"IRouteResolver\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RouteResolver(IRouteResolver routeResolver)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IRouteResolver), routeResolver));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IRouteResolver\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IRouteResolver\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RouteResolver<T>() where T : IRouteResolver\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.RouteResolver = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IModelValidatorLocator\"/>.\r\n            /// </summary>\r\n            /// <param name=\"modelValidatorLocator\">The <see cref=\"IModelValidatorLocator\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ModelValidatorLocator(IModelValidatorLocator modelValidatorLocator)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IModelValidatorLocator), modelValidatorLocator));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IModelValidatorLocator\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IModelValidatorLocator\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ModelValidatorLocator<T>() where T : IModelValidatorLocator\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.ModelValidatorLocator = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IRequestDispatcher\"/>.\r\n            /// </summary>\r\n            /// <param name=\"requestDispatcher\">The <see cref=\"IRequestDispatcher\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RequestDispatcher(IRequestDispatcher requestDispatcher)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IRequestDispatcher), requestDispatcher));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IRequestDispatcher\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IRequestDispatcher\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RequestDispatcher<T>() where T : IRequestDispatcher\r\n            {\r\n                this.bootstrapper.registeredTypes.Add(\r\n                    new TypeRegistration(typeof(IRequestDispatcher), typeof(T)));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IResourceAssemblyProvider\"/>.\r\n            /// </summary>\r\n            /// <param name=\"resourceAssemblyProvider\">The <see cref=\"IResourceAssemblyProvider\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ResourceAssemblyProvider(IResourceAssemblyProvider resourceAssemblyProvider)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IResourceAssemblyProvider), resourceAssemblyProvider));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IResourceAssemblyProvider\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IResourceAssemblyProvider\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ResourceAssemblyProvider<T>() where T : IResourceAssemblyProvider\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.ResourceAssemblyProvider = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IResourceReader\"/>.\r\n            /// </summary>\r\n            /// <param name=\"resourceReader\">The <see cref=\"IResourceReader\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ResourceReader(IResourceReader resourceReader)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IResourceReader), resourceReader));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IResourceReader\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IResourceReader\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ResourceReader<T>() where T : IResourceReader\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.ResourceReader = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IRouteDescriptionProvider\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IRouteDescriptionProvider\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RouteDescriptionProvider<T>() where T : IRouteDescriptionProvider\r\n            {\r\n                this.bootstrapper.registeredTypes.Add(\r\n                    new TypeRegistration(typeof(IRouteDescriptionProvider), typeof(T)));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IRouteDescriptionProvider\"/>.\r\n            /// </summary>\r\n            /// <param name=\"routeDescriptionProvider\">The <see cref=\"IRouteDescriptionProvider\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RouteDescriptionProvider(IRouteDescriptionProvider routeDescriptionProvider)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IRouteDescriptionProvider), routeDescriptionProvider));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IRouteMetadataProvider\"/>.\r\n            /// </summary>\r\n            /// <param name=\"routeMetadataProviders\">The <see cref=\"IRouteMetadataProvider\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RouteMetadataProvider(IRouteMetadataProvider routeMetadataProviders)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IRouteMetadataProvider), routeMetadataProviders));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IRouteMetadataProvider\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IRouteMetadataProvider\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RouteMetadataProvider<T>() where T : IRouteMetadataProvider\r\n            {\r\n                this.bootstrapper.registeredTypes.Add(\r\n                    new CollectionTypeRegistration(typeof(IRouteMetadataProvider), new[] { typeof(T) }));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided <see cref=\"IRouteMetadataProvider\"/> types.\r\n            /// </summary>\r\n            /// <param name=\"routeMetadataProviders\">The <see cref=\"IRouteMetadataProvider\"/> types that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RouteMetadataProviders(params Type[] routeMetadataProviders)\r\n            {\r\n                this.bootstrapper.registeredTypes.Add(\r\n                    new CollectionTypeRegistration(typeof(IRouteMetadataProvider), routeMetadataProviders));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instances of <see cref=\"IRouteMetadataProvider\"/>.\r\n            /// </summary>\r\n            /// <param name=\"routeMetadataProviders\">The <see cref=\"IRouteMetadataProvider\"/> types that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RouteMetadataProviders(params IRouteMetadataProvider[] routeMetadataProviders)\r\n            {\r\n                foreach (var routeMetadataProvider in routeMetadataProviders)\r\n                {\r\n                    this.bootstrapper.registeredTypes.Add(\r\n                        new InstanceRegistration(typeof(IRouteMetadataProvider), routeMetadataProvider));\r\n                }\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IRouteSegmentExtractor\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IRouteSegmentExtractor\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RouteSegmentExtractor<T>() where T : IRouteSegmentExtractor\r\n            {\r\n                this.bootstrapper.registeredTypes.Add(\r\n                    new TypeRegistration(typeof(IRouteSegmentExtractor), typeof(T)));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IRouteSegmentExtractor\"/>.\r\n            /// </summary>\r\n            /// <param name=\"routeSegmentExtractor\">The <see cref=\"IRouteSegmentExtractor\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RouteSegmentExtractor(IRouteSegmentExtractor routeSegmentExtractor)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IRouteSegmentExtractor), routeSegmentExtractor));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IResponseProcessor\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IResponseProcessor\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ResponseProcessor<T>() where T : IResponseProcessor\r\n            {\r\n                this.bootstrapper.registeredTypes.Add(\r\n                    new CollectionTypeRegistration(typeof(IResponseProcessor), new[] { typeof(T) }));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided <see cref=\"IResponseProcessor\"/> types.\r\n            /// </summary>\r\n            /// <param name=\"responseProcessors\">The <see cref=\"IResponseProcessor\"/> types that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ResponseProcessors(params Type[] responseProcessors)\r\n            {\r\n                this.bootstrapper.registeredTypes.Add(\r\n                    new CollectionTypeRegistration(typeof(IResponseProcessor), responseProcessors));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IRuntimeEnvironmentInformation\"/>.\r\n            /// </summary>\r\n            /// <param name=\"runtimeEnvironmentInformation\">The <see cref=\"IRuntimeEnvironmentInformation\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RuntimeEnvironmentInformation(IRuntimeEnvironmentInformation runtimeEnvironmentInformation)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IRuntimeEnvironmentInformation), runtimeEnvironmentInformation));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IRuntimeEnvironmentInformation\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IRuntimeEnvironmentInformation\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RuntimeEnvironmentInformation<T>() where T : IRuntimeEnvironmentInformation\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.RuntimeEnvironmentInformation = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"ITextResource\"/>.\r\n            /// </summary>\r\n            /// <param name=\"textResource\">The <see cref=\"ITextResource\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator TextResource(ITextResource textResource)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(ITextResource), textResource));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"ITextResource\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"ITextResource\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator TextResource<T>() where T : ITextResource\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.TextResource = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IViewCache\"/>.\r\n            /// </summary>\r\n            /// <param name=\"viewCache\">The <see cref=\"IViewCache\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ViewCache(IViewCache viewCache)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IViewCache), viewCache));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IViewCache\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IViewCache\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ViewCache<T>() where T : IViewCache\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.ViewCache = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IViewEngine\"/>.\r\n            /// </summary>\r\n            /// <param name=\"viewEngine\">The <see cref=\"IViewEngine\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ViewEngine(IViewEngine viewEngine)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IViewEngine), viewEngine));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IViewEngine\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IViewEngine\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ViewEngine<T>() where T : IViewEngine\r\n            {\r\n                this.bootstrapper.registeredTypes.Add(\r\n                    new CollectionTypeRegistration(typeof(IViewEngine), new[] { typeof(T) }));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided <see cref=\"IViewEngine\"/> types.\r\n            /// </summary>\r\n            /// <param name=\"viewEngines\">The <see cref=\"IViewEngine\"/> types that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ViewEngines(params Type[] viewEngines)\r\n            {\r\n                this.bootstrapper.registeredTypes.Add(\r\n                    new CollectionTypeRegistration(typeof(IViewEngine), viewEngines));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IViewFactory\"/>.\r\n            /// </summary>\r\n            /// <param name=\"viewFactory\">The <see cref=\"IViewFactory\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ViewFactory(IViewFactory viewFactory)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IViewFactory), viewFactory));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IViewFactory\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IViewFactory\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ViewFactory<T>() where T : IViewFactory\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.ViewFactory = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IViewLocationProvider\"/>.\r\n            /// </summary>\r\n            /// <param name=\"viewLocationProvider\">The <see cref=\"IViewLocationProvider\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ViewLocationProvider(IViewLocationProvider viewLocationProvider)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IViewLocationProvider), viewLocationProvider));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IViewLocationProvider\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IViewLocationProvider\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ViewLocationProvider<T>() where T : IViewLocationProvider\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.ViewLocationProvider = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IViewLocator\"/>.\r\n            /// </summary>\r\n            /// <param name=\"viewLocator\">The <see cref=\"IViewLocator\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ViewLocator(IViewLocator viewLocator)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IViewLocator), viewLocator));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IViewLocator\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IViewLocator\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ViewLocator<T>() where T : IViewLocator\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.ViewLocator = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IViewResolver\"/>.\r\n            /// </summary>\r\n            /// <param name=\"viewResolver\">The <see cref=\"IViewResolver\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ViewResolver(IViewResolver viewResolver)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IViewResolver), viewResolver));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IViewResolver\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IViewResolver\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ViewResolver<T>() where T : IViewResolver\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.ViewResolver = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"ICsrfTokenValidator\"/>.\r\n            /// </summary>\r\n            /// <param name=\"tokenValidator\">The <see cref=\"ICsrfTokenValidator\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator CsrfTokenValidator(ICsrfTokenValidator tokenValidator)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(ICsrfTokenValidator), tokenValidator));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"ICsrfTokenValidator\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"ICsrfTokenValidator\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator CsrfTokenValidator<T>() where T : ICsrfTokenValidator\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.CsrfTokenValidator = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IObjectSerializer\"/>.\r\n            /// </summary>\r\n            /// <param name=\"objectSerializer\">The <see cref=\"IObjectSerializer\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ObjectSerializer(IObjectSerializer objectSerializer)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IObjectSerializer), objectSerializer));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IObjectSerializer\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IObjectSerializer\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ObjectSerializer<T>() where T : IObjectSerializer\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.ObjectSerializer = typeof(T));\r\n                return this;\r\n            }\r\n\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use a specific serializer\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">Serializer type</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator Serializer<T>() where T : ISerializer\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.Serializers = new List<Type> { typeof(T) });\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use specific serializers\r\n            /// </summary>\r\n            /// <param name=\"serializers\">Collection of serializer types</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator Serializers(params Type[] serializers)\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.Serializers = new List<Type>(serializers));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IDiagnostics\"/>.\r\n            /// </summary>\r\n            /// <param name=\"diagnostics\">The <see cref=\"IDiagnostics\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator Diagnostics(IDiagnostics diagnostics)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IDiagnostics), diagnostics));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IDiagnostics\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IDiagnostics\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator Diagnostics<T>() where T : IDiagnostics\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.Diagnostics = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"ICultureService \"/>.\r\n            /// </summary>\r\n            /// <param name=\"cultureService\">The <see cref=\"ICultureService \"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator CultureService(ICultureService cultureService)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(ICultureService), cultureService));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"ICultureService\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"ICultureService\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator CultureService<T>() where T : ICultureService\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.CultureService = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"ICultureService \"/>.\r\n            /// </summary>\r\n            /// <param name=\"staticContentProvider\">The <see cref=\"IStaticContentProvider \"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator StaticContentProvider(IStaticContentProvider staticContentProvider)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IStaticContentProvider), staticContentProvider));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IStaticContentProvider\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IStaticContentProvider\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator StaticContentProvider<T>() where T : IStaticContentProvider\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.StaticContentProvider = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IRouteResolverTrie \"/>.\r\n            /// </summary>\r\n            /// <param name=\"routeResolverTrie\">The <see cref=\"IStaticContentProvider \"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RouteResolverTrie(IRouteResolverTrie routeResolverTrie)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IRouteResolverTrie), routeResolverTrie));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IRouteResolverTrie\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IRouteResolverTrie\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RouteResolverTrie<T>() where T : IRouteResolverTrie\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.RouteResolverTrie = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"ITrieNodeFactory \"/>.\r\n            /// </summary>\r\n            /// <param name=\"nodeFactory\">The <see cref=\"ITrieNodeFactory \"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator TrieNodeFactory(ITrieNodeFactory nodeFactory)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(ITrieNodeFactory), nodeFactory));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"ITrieNodeFactory\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"ITrieNodeFactory\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator TrieNodeFactory<T>() where T : ITrieNodeFactory\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.TrieNodeFactory = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IRouteSegmentConstraint\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IRouteSegmentConstraint\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RouteSegmentConstraint<T>() where T : IRouteSegmentConstraint\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.RouteSegmentConstraints = new List<Type> { typeof(T) });\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use specific route segment constraints.\r\n            /// </summary>\r\n            /// <param name=\"types\">Collection of route segment constraint types.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RouteSegmentConstraints(params Type[] types)\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.RouteSegmentConstraints = new List<Type>(types));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IResponseNegotiator\"/>.\r\n            /// </summary>\r\n            /// <param name=\"negotiator\">The <see cref=\"IResponseNegotiator\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ResponseNegotiator(IResponseNegotiator negotiator)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(IResponseNegotiator), negotiator));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"IResponseNegotiator\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IResponseNegotiator\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ResponseNegotiator<T>() where T : IResponseNegotiator\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.ResponseNegotiator = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to create an <see cref=\"ISerializerFactory\"/> instance of the specified type.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"ISerializerFactory\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator SerializerFactory<T>() where T : ISerializerFactory\r\n            {\r\n                this.bootstrapper.configurationOverrides.Add(x => x.SerializerFactory = typeof(T));\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IResponseNegotiator\"/>.\r\n            /// </summary>\r\n            /// <param name=\"serializer\">The <see cref=\"IResponseNegotiator\"/> instance that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator SerializerFactory(ISerializerFactory serializer)\r\n            {\r\n                this.bootstrapper.registeredInstances.Add(\r\n                    new InstanceRegistration(typeof(ISerializerFactory), serializer));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IApplicationStartup\"/>.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IApplicationStartup\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ApplicationStartupTask<T>() where T : IApplicationStartup\r\n            {\r\n                this.bootstrapper.registeredTypes.Add(\r\n                    new TypeRegistration(typeof(IApplicationStartup), typeof(T)));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided <see cref=\"IApplicationStartup\"/> types.\r\n            /// </summary>\r\n            /// <param name=\"applicationStartupTypes\">The <see cref=\"IApplicationStartup\"/> types that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ApplicationStartupTasks(params Type[] applicationStartupTypes)\r\n            {\r\n                foreach (var type in applicationStartupTypes)\r\n                {\r\n                    this.bootstrapper.registeredTypes.Add(\r\n                        new TypeRegistration(typeof(IApplicationStartup), type));\r\n                }\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided instance of <see cref=\"IRequestStartup\"/>.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The type of the <see cref=\"IApplicationStartup\"/> that the bootstrapper should use.</typeparam>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RequestStartupTask<T>() where T : IRequestStartup\r\n            {\r\n                this.bootstrapper.registeredTypes.Add(\r\n                    new TypeRegistration(typeof(IRequestStartup), typeof(T)));\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Configures the bootstrapper to use the provided <see cref=\"IRequestStartup\"/> types.\r\n            /// </summary>\r\n            /// <param name=\"requestStartupTypes\">The <see cref=\"IRequestStartup\"/> types that should be used by the bootstrapper.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RequestStartupTasks(params Type[] requestStartupTypes)\r\n            {\r\n                foreach (var type in requestStartupTypes)\r\n                {\r\n                    this.bootstrapper.registeredTypes.Add(\r\n                        new TypeRegistration(typeof(IRequestStartup), type));\r\n                }\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Disables automatic registration of user-defined <see cref=\"IApplicationStartup\"/> instances. It\r\n            /// will not prevent auto-registration of implementations bundled with Nancy.\r\n            /// </summary>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator DisableAutoApplicationStartupRegistration()\r\n            {\r\n                this.bootstrapper.disableAutoApplicationStartupRegistration = true;\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Disables automatic registration of user-defined <see cref=\"IRequestStartup\"/> instances. It\r\n            /// will not prevent auto-registration of implementations bundled with Nancy.\r\n            /// </summary>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator DisableAutoRequestStartupRegistration()\r\n            {\r\n                this.bootstrapper.disableAutoRequestStartupRegistration = true;\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a hook to the application startup pipeline. This can be called multiple times to add\r\n            /// more hooks.\r\n            /// </summary>\r\n            /// <param name=\"action\">The pipeline hook.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator ApplicationStartup(Action<TinyIoCContainer, IPipelines> action)\r\n            {\r\n                this.bootstrapper.applicationStartupActions.Add(action);\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a hook to the request startup pipeline. This can be called multiple times to add\r\n            /// more hooks.\r\n            /// </summary>\r\n            /// <param name=\"action\">The pipeline hook.</param>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator RequestStartup(Action<TinyIoCContainer, IPipelines, NancyContext> action)\r\n            {\r\n                this.bootstrapper.requestStartupActions.Add(action);\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Disables registrations performed by <see cref=\"IRegistrations\"/> instances.\r\n            /// </summary>\r\n            /// <returns>A reference to the current <see cref=\"ConfigurableBootstrapperConfigurator\"/>.</returns>\r\n            public ConfigurableBootstrapperConfigurator DisableAutoRegistrations()\r\n            {\r\n                this.bootstrapper.autoRegistrations = false;\r\n                return this;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Provides the functionality to register <see cref=\"INancyModule\"/> instances in a <see cref=\"INancyModuleCatalog\"/>.\r\n        /// </summary>\r\n        public class ConfigurableModuleCatalog : INancyModuleCatalog\r\n        {\r\n            private readonly IDictionary<string, INancyModule> moduleInstances;\r\n\r\n            /// <summary>\r\n            /// Initializes a new instance of the <see cref=\"ConfigurableModuleCatalog\"/> class.\r\n            /// </summary>\r\n            public ConfigurableModuleCatalog()\r\n            {\r\n                this.moduleInstances = new Dictionary<string, INancyModule>();\r\n            }\r\n\r\n            /// <summary>\r\n            /// Get all NancyModule implementation instances - should be per-request lifetime\r\n            /// </summary>\r\n            /// <param name=\"context\">The current context</param>\r\n            /// <returns>An <see cref=\"IEnumerable{T}\"/> instance containing <see cref=\"INancyModule\"/> instances.</returns>\r\n            public IEnumerable<INancyModule> GetAllModules(NancyContext context)\r\n            {\r\n                return this.moduleInstances.Values;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Retrieves a specific <see cref=\"INancyModule\"/> implementation - should be per-request lifetime\r\n            /// </summary>\r\n            /// <param name=\"moduleType\">Module type</param>\r\n            /// <param name=\"context\">The current context</param>\r\n            /// <returns>The <see cref=\"INancyModule\"/> instance</returns>\r\n            public INancyModule GetModule(Type moduleType, NancyContext context)\r\n            {\r\n                INancyModule module;\r\n                return this.moduleInstances.TryGetValue(moduleType.FullName, out module) ? module : null;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Registers a <see cref=\"INancyModule\"/> instance.\r\n            /// </summary>\r\n            /// <param name=\"module\">The <see cref=\"INancyModule\"/> instance to register.</param>\r\n            public void RegisterModuleInstance(INancyModule module)\r\n            {\r\n                this.moduleInstances.Add(module.GetType().FullName, module);\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Testing/ConfigurableNancyModule.cs",
    "content": "﻿namespace Nancy.Testing\r\n{\r\n    using System;\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n\r\n    /// <summary>\r\n    /// Provides a way to define a Nancy module though an API.\r\n    /// </summary>\r\n    public class ConfigurableNancyModule : NancyModule\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ConfigurableNancyModule\"/> class.\r\n        /// </summary>\r\n        public ConfigurableNancyModule()\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ConfigurableNancyModule\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"closure\">The configuration of the module.</param>\r\n        public ConfigurableNancyModule(Action<ConfigurableNancyModuleConfigurator> closure)\r\n            : this(string.Empty, closure)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"ConfigurableNancyModule\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"modulePath\">The path that all routes in the module should be relative too.</param>\r\n        /// <param name=\"closure\">The configuration of the module.</param>\r\n        public ConfigurableNancyModule(string modulePath, Action<ConfigurableNancyModuleConfigurator> closure)\r\n            : base(modulePath)\r\n        {\r\n            var configurator =\r\n                new ConfigurableNancyModuleConfigurator(this);\r\n\r\n            closure.Invoke(configurator);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Provides an API for configuring a <see cref=\"ConfigurableNancyModule\"/> instance.\r\n        /// </summary>\r\n        public class ConfigurableNancyModuleConfigurator : IHideObjectMembers\r\n        {\r\n            private readonly ConfigurableNancyModule wrappedModule;\r\n\r\n            /// <summary>\r\n            /// Initializes a new instance of the <see cref=\"ConfigurableNancyModuleConfigurator\"/> class.\r\n            /// </summary>\r\n            /// <param name=\"module\">The <see cref=\"ConfigurableNancyModule\"/> that should be configured.</param>\r\n            public ConfigurableNancyModuleConfigurator(ConfigurableNancyModule module)\r\n            {\r\n                this.wrappedModule = module;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds an after-request process pipeline to the wrappedModule.\r\n            /// </summary>\r\n            /// <param name=\"after\">An <see cref=\"AfterPipeline\"/> instance.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator After(AfterPipeline after)\r\n            {\r\n                this.wrappedModule.After = after;\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a before-request process pipeline to the wrappedModule.\r\n            /// </summary>\r\n            /// <param name=\"before\">An <see cref=\"BeforePipeline\"/> instance.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Before(BeforePipeline before)\r\n            {\r\n                this.wrappedModule.Before = before;\r\n\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for DELETE requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            /// <remarks>This will add a route with a condition that is always evaluates to <see langword=\"true\"/> and an action that returns <see cref=\"HttpStatusCode.OK\"/>.</remarks>\r\n            public ConfigurableNancyModuleConfigurator Delete(string path, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Delete<object>(path, (args, module) => HttpStatusCode.OK, condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for DELETE requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Delete(string path, Func<dynamic, NancyModule, object> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Delete<object>(path, (args, module) => action((DynamicDictionary)args, module), condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for DELETE requests.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The return type of the route.</typeparam>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Delete<T>(string path, Func<dynamic, NancyModule, T> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Delete(path, (args, module) => Task.FromResult(action((DynamicDictionary)args, module)), condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for DELETE requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Delete(string path, Func<dynamic, NancyModule, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Delete<object>(path, action, condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for DELETE requests.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The return type of the route.</typeparam>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Delete<T>(string path, Func<dynamic, NancyModule, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Delete(path, (args, ct, module) => action((DynamicDictionary)args, module), condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for DELETE requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Delete(string path, Func<dynamic, CancellationToken, NancyModule, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Delete<object>(path, action, condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for DELETE requests.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The return type of the route.</typeparam>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Delete<T>(string path, Func<dynamic, CancellationToken, NancyModule, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                this.wrappedModule.Delete(path, (args, ct) => action((DynamicDictionary)args, ct, this.wrappedModule), condition ?? (ctx => true), name ?? string.Empty);\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for GET requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            /// <remarks>This will add a route with a condition that is always evaluates to <see langword=\"true\"/> and an action that returns <see cref=\"HttpStatusCode.OK\"/>.</remarks>\r\n            public ConfigurableNancyModuleConfigurator Get(string path, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Get<object>(path, (args, module) => HttpStatusCode.OK, condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for GET requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            public ConfigurableNancyModuleConfigurator Get(string path, Func<dynamic, NancyModule, object> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Get<object>(path, (args, module) => action((DynamicDictionary)args, module), condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for GET requests.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The return type of the route.</typeparam>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Get<T>(string path, Func<dynamic, NancyModule, T> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Get(path, (args, module) => Task.FromResult(action((DynamicDictionary)args, module)), condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for GET requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Get(string path, Func<dynamic, NancyModule, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Get<object>(path, action, condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for GET requests.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The return type of the route.</typeparam>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Get<T>(string path, Func<dynamic, NancyModule, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Get(path, (args, ct, module) => action((DynamicDictionary)args, module), condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for GET requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Get(string path, Func<dynamic, CancellationToken, NancyModule, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Get<object>(path, action, condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for GET requests.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The return type of the route.</typeparam>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Get<T>(string path, Func<dynamic, CancellationToken, NancyModule, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                this.wrappedModule.Get(path, (args, ct) => action((DynamicDictionary)args, ct, this.wrappedModule), condition ?? (ctx => true), name ?? string.Empty);\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for HEAD requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            /// <remarks>This will add a route with a condition that is always evaluates to <see langword=\"true\"/> and an action that returns <see cref=\"HttpStatusCode.OK\"/>.</remarks>\r\n            public ConfigurableNancyModuleConfigurator Head(string path, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Head<object>(path, (args, module) => HttpStatusCode.OK, condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for HEAD requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            public ConfigurableNancyModuleConfigurator Head(string path, Func<dynamic, NancyModule, object> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Head<object>(path, (args, module) => action((DynamicDictionary)args, module), condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for HEAD requests.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The return type of the route.</typeparam>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Head<T>(string path, Func<dynamic, NancyModule, T> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Head(path, (args, module) => Task.FromResult(action((DynamicDictionary)args, module)), condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for HEAD requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Head(string path, Func<dynamic, NancyModule, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Head<object>(path, action, condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for HEAD requests.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The return type of the route.</typeparam>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Head<T>(string path, Func<dynamic, NancyModule, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Head(path, (args, ct, module) => action((DynamicDictionary)args, module), condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for HEAD requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Head(string path, Func<dynamic, CancellationToken, NancyModule, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Head<object>(path, action, condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for HEAD requests.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The return type of the route.</typeparam>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Head<T>(string path, Func<dynamic, CancellationToken, NancyModule, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                this.wrappedModule.Head(path, (args, ct) => action((DynamicDictionary)args, ct, this.wrappedModule), condition ?? (ctx => true), name ?? string.Empty);\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for OPTIONS requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            /// <remarks>This will add a route with a condition that is always evaluates to <see langword=\"true\"/> and an action that returns <see cref=\"HttpStatusCode.OK\"/>.</remarks>\r\n            public ConfigurableNancyModuleConfigurator Options(string path, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Options<object>(path, (args, module) => HttpStatusCode.OK, condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for OPTIONS requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            public ConfigurableNancyModuleConfigurator Options(string path, Func<dynamic, NancyModule, object> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Options<object>(path, (args, module) => action((DynamicDictionary)args, module), condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for OPTIONS requests.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The return type of the route.</typeparam>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Options<T>(string path, Func<dynamic, NancyModule, T> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Options(path, (args, module) => Task.FromResult(action((DynamicDictionary)args, module)), condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for OPTIONS requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Options(string path, Func<dynamic, NancyModule, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Options<object>(path, action, condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for OPTIONS requests.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The return type of the route.</typeparam>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Options<T>(string path, Func<dynamic, NancyModule, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Options(path, (args, ct, module) => action((DynamicDictionary)args, module), condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for OPTIONS requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Options(string path, Func<dynamic, CancellationToken, NancyModule, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Options<object>(path, action, condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for OPTIONS requests.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The return type of the route.</typeparam>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Options<T>(string path, Func<dynamic, CancellationToken, NancyModule, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                this.wrappedModule.Options(path, (args, ct) => action((DynamicDictionary)args, ct, this.wrappedModule), condition ?? (ctx => true), name ?? string.Empty);\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for PATCH requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            /// <remarks>This will add a route with a condition that is always evaluates to <see langword=\"true\"/> and an action that returns <see cref=\"HttpStatusCode.OK\"/>.</remarks>\r\n            public ConfigurableNancyModuleConfigurator Patch(string path, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Patch<object>(path, (args, module) => HttpStatusCode.OK, condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for PATCH requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            public ConfigurableNancyModuleConfigurator Patch(string path, Func<dynamic, NancyModule, object> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Patch<object>(path, (args, module) => action((DynamicDictionary)args, module), condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for PATCH requests.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The return type of the route.</typeparam>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Patch<T>(string path, Func<dynamic, NancyModule, T> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Patch(path, (args, module) => Task.FromResult(action((DynamicDictionary)args, module)), condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for PATCH requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Patch(string path, Func<dynamic, NancyModule, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Patch<object>(path, action, condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for PATCH requests.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The return type of the route.</typeparam>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Patch<T>(string path, Func<dynamic, NancyModule, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Patch(path, (args, ct, module) => action((DynamicDictionary)args, module), condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for PATCH requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Patch(string path, Func<dynamic, CancellationToken, NancyModule, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Patch<object>(path, action, condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for PATCH requests.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The return type of the route.</typeparam>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Patch<T>(string path, Func<dynamic, CancellationToken, NancyModule, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                this.wrappedModule.Patch(path, (args, ct) => action((DynamicDictionary)args, ct, this.wrappedModule), condition ?? (ctx => true), name ?? string.Empty);\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for POST requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            /// <remarks>This will add a route with a condition that is always evaluates to <see langword=\"true\"/> and an action that returns <see cref=\"HttpStatusCode.OK\"/>.</remarks>\r\n            public ConfigurableNancyModuleConfigurator Post(string path, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Post<object>(path, (args, module) => HttpStatusCode.OK, condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for POST requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            public ConfigurableNancyModuleConfigurator Post(string path, Func<dynamic, NancyModule, object> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Post<object>(path, (args, module) => action((DynamicDictionary)args, module), condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for POST requests.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The return type of the route.</typeparam>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Post<T>(string path, Func<dynamic, NancyModule, T> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Post(path, (args, module) => Task.FromResult(action((DynamicDictionary)args, module)), condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for POST requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Post(string path, Func<dynamic, NancyModule, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Post<object>(path, action, condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for POST requests.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The return type of the route.</typeparam>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Post<T>(string path, Func<dynamic, NancyModule, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Post(path, (args, ct, module) => action((DynamicDictionary)args, module), condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for POST requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Post(string path, Func<dynamic, CancellationToken, NancyModule, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Post<object>(path, action, condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for POST requests.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The return type of the route.</typeparam>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Post<T>(string path, Func<dynamic, CancellationToken, NancyModule, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                this.wrappedModule.Post(path, (args, ct) => action((DynamicDictionary)args, ct, this.wrappedModule), condition ?? (ctx => true), name ?? string.Empty);\r\n                return this;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for PUT requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            /// <remarks>This will add a route with a condition that is always evaluates to <see langword=\"true\"/> and an action that returns <see cref=\"HttpStatusCode.OK\"/>.</remarks>\r\n            public ConfigurableNancyModuleConfigurator Put(string path, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Put<object>(path, (args, module) => HttpStatusCode.OK, condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for PUT requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            public ConfigurableNancyModuleConfigurator Put(string path, Func<dynamic, NancyModule, object> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Put<object>(path, (args, module) => action((DynamicDictionary)args, module), condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for PUT requests.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The return type of the route.</typeparam>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Put<T>(string path, Func<dynamic, NancyModule, T> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Put(path, (args, module) => Task.FromResult(action((DynamicDictionary)args, module)), condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for PUT requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Put(string path, Func<dynamic, NancyModule, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Put<object>(path, action, condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for PUT requests.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The return type of the route.</typeparam>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Put<T>(string path, Func<dynamic, NancyModule, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Put(path, (args, ct, module) => action((DynamicDictionary)args, module), condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for PUT requests.\r\n            /// </summary>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Put(string path, Func<dynamic, CancellationToken, NancyModule, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                return this.Put<object>(path, action, condition, name);\r\n            }\r\n\r\n            /// <summary>\r\n            /// Adds a route that is valid for PUT requests.\r\n            /// </summary>\r\n            /// <typeparam name=\"T\">The return type of the route.</typeparam>\r\n            /// <param name=\"path\">The path that the route should be registered for.</param>\r\n            /// <param name=\"action\">Action that will be invoked when the route it hit</param>\r\n            /// <param name=\"condition\">A condition to determine if the route can be hit.</param>\r\n            /// <param name=\"name\">Name of the route.</param>\r\n            /// <returns>An instance to the current <see cref=\"ConfigurableNancyModuleConfigurator\"/>.</returns>\r\n            public ConfigurableNancyModuleConfigurator Put<T>(string path, Func<dynamic, CancellationToken, NancyModule, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null)\r\n            {\r\n                this.wrappedModule.Put(path, (args, ct) => action((DynamicDictionary)args, ct, this.wrappedModule), condition ?? (ctx => true), name ?? string.Empty);\r\n                return this;\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Testing/DocumentWrapper.cs",
    "content": "﻿namespace Nancy.Testing\r\n{\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using AngleSharp.Dom.Html;\r\n    using AngleSharp.Parser.Html;\r\n\r\n    /// <summary>\r\n    /// A basic wrapper around CsQuery\r\n    /// </summary>\r\n    public class DocumentWrapper\r\n    {\r\n        private readonly IHtmlDocument document;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DocumentWrapper\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"buffer\">The document represented as a byte array.</param>\r\n        public DocumentWrapper(IEnumerable<byte> buffer)\r\n        {\r\n            var parser = new HtmlParser();\r\n            using (var stream = new MemoryStream(buffer.ToArray()))\r\n            {\r\n                this.document = parser.Parse(stream);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets elements from CSS3 selectors\r\n        /// </summary>\r\n        /// <param name=\"selector\">The CSS3 selector that should be applied.</param>\r\n        /// <returns>A <see cref=\"QueryWrapper\"/> instance.</returns>\r\n        public QueryWrapper this[string selector]\r\n        {\r\n            get { return new QueryWrapper(this.document.QuerySelectorAll(selector).ToArray()); }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Testing/IBrowserContextValues.cs",
    "content": "﻿namespace Nancy.Testing\r\n{\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Security.Cryptography.X509Certificates;\r\n\r\n    /// <summary>\r\n    /// Provides an API ontop of <see cref=\"BrowserContext\"/> for extracting values.\r\n    /// </summary>\r\n    public interface IBrowserContextValues : IHideObjectMembers\r\n    {\r\n        /// <summary>\r\n        /// Gets or sets the stream that should be sent with the HTTP request.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"Stream\"/> that contains the body that should be sent with the HTTP request.</value>\r\n        Stream Body { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the body string\r\n        /// </summary>\r\n        string BodyString { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the form values string\r\n        /// </summary>\r\n        /// <remarks>If <see cref=\"BodyString\"/> is assigned a value, the <see cref=\"FormValues\"/> will be ignored.</remarks>\r\n        string FormValues { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the headers that should be sent with the HTTP request.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IDictionary{TKey,TValue}\"/> instance that contains the headers that should be sent with the HTTP request.</value>\r\n        IDictionary<string, IEnumerable<string>> Headers { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the protocol that should be sent with the HTTP request.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> contains the protocol that should be sent with the HTTP request.</value>\r\n        string Protocol { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the querystring\r\n        /// </summary>\r\n        string QueryString { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the basePath string\r\n        /// </summary>\r\n        string HostName { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the user host address\r\n        /// </summary>\r\n        string UserHostAddress { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the ClientCertificate\r\n        /// </summary>\r\n        X509Certificate2 ClientCertificate { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Testing/IndexHelper.cs",
    "content": "namespace Nancy.Testing\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// A helper class for providing classes with \"named indexers\".\r\n    /// </summary>\r\n    /// <typeparam name=\"TKey\">The indexer key type</typeparam>\r\n    /// <typeparam name=\"TValue\">The indexer return value type.</typeparam>\r\n    public class IndexHelper<TKey, TValue>\r\n    {\r\n        private readonly Func<TKey, TValue> indexDelegate;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"IndexHelper&lt;TKey, TValue&gt;\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"indexDelegate\">The index delegate.</param>\r\n        public IndexHelper(Func<TKey, TValue> indexDelegate)\r\n        {\r\n            this.indexDelegate = indexDelegate;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the <typeparamref name=\"TValue\"/> with the specified key.\r\n        /// </summary>\r\n        /// <value>The value of the indexer.</value>\r\n        public TValue this[TKey key]\r\n        {\r\n            get { return this.indexDelegate(key); }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Testing/Nancy.Testing.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <Description>Test harness for Nancy applications.</Description>\n    <PackageTags>$(PackageTags);Testing</PackageTags>\n    <TargetFrameworks>netstandard2.0;net452</TargetFrameworks>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <EmbeddedResource Include=\"Resources\\NancyTestingCert.pfx\" Exclude=\"bin\\**;obj\\**;**\\*.xproj;packages\\**;@(EmbeddedResource)\" />\n  </ItemGroup>\n\n  <ItemGroup>\n    <ProjectReference Include=\"../Nancy.Authentication.Forms/Nancy.Authentication.Forms.csproj\" />\n  </ItemGroup>\n\n  <ItemGroup>\n    <PackageReference Include=\"AngleSharp\" Version=\"0.9.8.1\" />\n  </ItemGroup>\n\n  <ItemGroup Condition=\" '$(TargetFramework)' == 'netstandard1.6' \">\n    <PackageReference Include=\"System.Xml.XDocument\" Version=\"4.3.0\" />\n    <PackageReference Include=\"System.Xml.XmlDocument\" Version=\"4.3.0\" />\n  </ItemGroup>\n\n  <ItemGroup Condition=\" '$(TargetFramework)' == 'net452' \">\n    <Reference Include=\"System.IO\" />\n    <Reference Include=\"System.Runtime\" />\n    <Reference Include=\"System.Xml.Linq\" />\n    <Reference Include=\"System.Xml\" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "src/Nancy.Testing/NancyContextExtensions.cs",
    "content": "namespace Nancy.Testing\r\n{\r\n    using System;\r\n    using System.IO;\r\n    using System.Xml.Serialization;\r\n    using Nancy.Extensions;\r\n    using Nancy.Json;\r\n\r\n    /// <summary>\r\n    /// Defines extensions for the <see cref=\"NancyContext\"/> type.\r\n    /// </summary>\r\n    public static class NancyContextExtensions\r\n    {\r\n        private const string DOCUMENT_WRAPPER_KEY_NAME = \"@@@@DOCUMENT_WRAPPER@@@@\";\r\n        private const string JSONRESPONSE_KEY_NAME = \"@@@@JSONRESPONSE@@@@\";\r\n        private const string XMLRESPONSE_KEY_NAME = \"@@@@XMLRESPONSE@@@@\";\r\n\r\n        private static T Cache<T>(NancyContext context, string key, Func<T> getData)\r\n        {\r\n            // We only really want to generate this once, so we'll stick it in the context\r\n            // This isn't ideal, but we don't want to hide the guts of the context from the\r\n            // tests this will have to do.\r\n            object value;\r\n            if (context.Items.TryGetValue(key, out value))\r\n            {\r\n                return (T)value;\r\n            }\r\n\r\n            T data = getData.Invoke();\r\n            context.Items[key] = data;\r\n            return data;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns the HTTP response body, of the specified <see cref=\"NancyContext\"/>, wrapped in an <see cref=\"DocumentWrapper\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> instance that the HTTP response body should be retrieved from.</param>\r\n        /// <returns>A <see cref=\"DocumentWrapper\"/> instance, wrapping the HTTP response body of the context.</returns>\r\n        public static DocumentWrapper DocumentBody(this NancyContext context)\r\n        {\r\n            return Cache(context, DOCUMENT_WRAPPER_KEY_NAME, () =>\r\n            {\r\n                using (var contentsStream = new MemoryStream())\r\n                {\r\n                    context.Response.Contents.Invoke(contentsStream);\r\n                    contentsStream.Position = 0;\r\n                    return new DocumentWrapper(contentsStream.GetBufferSegment());\r\n                }\r\n            });\r\n        }\r\n\r\n        public static TModel JsonBody<TModel>(this NancyContext context)\r\n        {\r\n            return context.JsonBody<TModel>(new JavaScriptSerializer());\r\n        }\r\n\r\n        public static TModel JsonBody<TModel>(this NancyContext context, JavaScriptSerializer serializer)\r\n        {\r\n            return Cache(context, JSONRESPONSE_KEY_NAME, () =>\r\n            {\r\n                using (var contentsStream = new MemoryStream())\r\n                {\r\n                    context.Response.Contents.Invoke(contentsStream);\r\n                    contentsStream.Position = 0;\r\n                    using (var contents = new StreamReader(contentsStream))\r\n                    {\r\n                        var model = serializer.Deserialize<TModel>(contents.ReadToEnd());\r\n                        return model;\r\n                    }\r\n                }\r\n            });\r\n        }\r\n\r\n        public static TModel XmlBody<TModel>(this NancyContext context)\r\n        {\r\n            return Cache(context, XMLRESPONSE_KEY_NAME, () =>\r\n            {\r\n                using (var contentsStream = new MemoryStream())\r\n                {\r\n                    context.Response.Contents.Invoke(contentsStream);\r\n                    contentsStream.Position = 0;\r\n                    var serializer = new XmlSerializer(typeof(TModel));\r\n                    var model = serializer.Deserialize(contentsStream);\r\n                    return (TModel)model;\r\n                }\r\n            });\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Testing/NodeWrapper.cs",
    "content": "namespace Nancy.Testing\r\n{\r\n    using AngleSharp.Dom;\r\n\r\n    /// <summary>\r\n    /// Simple wrapper around a <see cref=\"IElement\"/>.\r\n    /// </summary>\r\n    public class NodeWrapper\r\n    {\r\n        private readonly IElement element;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NodeWrapper\"/> class, for\r\n        /// the provided <paramref name=\"element\"/>.\r\n        /// </summary>\r\n        /// <param name=\"element\">The dom element that should be wrapped.</param>\r\n        public NodeWrapper(IElement element)\r\n        {\r\n            this.element = element;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Tests for the presence of an attribute with the specified name.\r\n        /// </summary>\r\n        /// <param name=\"name\">The name of the attribute to test for.</param>\r\n        /// <returns>True if the node contains an attribute with the specified name, false otherwise.</returns>\r\n        public bool HasAttribute(string name)\r\n        {\r\n            return this.element.HasAttribute(name);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the attributes of the element\r\n        /// </summary>\r\n        public IndexHelper<string, string> Attributes\r\n        {\r\n            get\r\n            {\r\n                return new IndexHelper<string, string>(x =>\r\n                {\r\n                    var attribute = this.element.Attributes[x];\r\n\r\n                    return (attribute != null)\r\n                        ? attribute.Value\r\n                        : null;\r\n                });\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the inner text of the node.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"string\"/> containing the inner text of the node.</value>\r\n        public string InnerText\r\n        {\r\n            get { return this.element.TextContent; }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Testing/PassThroughStatusHandler.cs",
    "content": "namespace Nancy.Testing\r\n{\r\n    using System;\r\n\r\n    using Nancy.ErrorHandling;\r\n    using Nancy.Extensions;\r\n\r\n    public class PassThroughStatusCodeHandler : IStatusCodeHandler\r\n    {\r\n        public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context)\r\n        {\r\n            Exception exception;\r\n            if (!context.TryGetException(out exception) || exception == null)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            return statusCode == HttpStatusCode.InternalServerError;\r\n        }\r\n\r\n        public void Handle(HttpStatusCode statusCode, NancyContext context)\r\n        {\r\n            throw new Exception(\"ConfigurableBootstrapper Exception\", context.GetException());\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Testing/PathHelper.cs",
    "content": "namespace Nancy.Testing\r\n{\r\n    using System;\r\n    using System.IO;\r\n    using System.Linq;\r\n\r\n    public static class PathHelper\r\n    {\r\n        /// <summary>\r\n        /// Traverses up a directory tree\r\n        /// </summary>\r\n        /// <param name=\"path\">Start path.</param>\r\n        /// <param name=\"levels\">Levels to climb.</param>\r\n        /// <returns>A <see cref=\"string\"/> containing the new path.</returns>\r\n        public static string GetParent(string path, int levels)\r\n        {\r\n            if (string.IsNullOrEmpty(path))\r\n            {\r\n                throw new ArgumentException(\"path cannot be null or empty\", \"path\");\r\n            }\r\n\r\n            if (levels < 0)\r\n            {\r\n                throw new ArgumentException(\"levels cannot be negative\", \"levels\");\r\n            }\r\n\r\n            if (levels == 0)\r\n            {\r\n                return path;\r\n            }\r\n\r\n            var parts = path.Split(Path.DirectorySeparatorChar);\r\n\r\n            if (parts.Length <= levels)\r\n            {\r\n                throw new InvalidOperationException(\"Cannot go up beyond the root.\");\r\n            }\r\n\r\n            return\r\n                parts.Take(parts.Length - levels).Aggregate(\r\n                    (p1, p2) => String.Format(\"{0}{1}{2}\", p1, Path.DirectorySeparatorChar, p2));\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Testing/QueryWrapper.cs",
    "content": "﻿namespace Nancy.Testing\r\n{\r\n    using System.Collections;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using AngleSharp.Dom;\r\n\r\n    /// <summary>\r\n    /// Simple wrapper around a collection of <see cref=\"IElement\"/> instances.\r\n    /// </summary>\r\n    public class QueryWrapper : IEnumerable<NodeWrapper>\r\n    {\r\n        private readonly IReadOnlyCollection<IElement> elements;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"QueryWrapper\"/> class, using\r\n        /// the provided <paramref name=\"elements\"/>.\r\n        /// </summary>\r\n        /// <param name=\"elements\">The elements that were the result of query.</param>\r\n        public QueryWrapper(IReadOnlyCollection<IElement> elements)\r\n        {\r\n            this.elements = elements;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets elements from CSS3 selectors\r\n        /// </summary>\r\n        /// <param name=\"selector\">CSS3 selector</param>\r\n        /// <returns>A <see cref=\"QueryWrapper\"/> instance</returns>\r\n        public QueryWrapper this[string selector]\r\n        {\r\n            get\r\n            {\r\n                return new QueryWrapper(this.elements.SelectMany(element => element.QuerySelectorAll(selector)).ToArray());\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an enumerator that iterates through the collection.\r\n        /// </summary>\r\n        /// <returns>A <see cref=\"IEnumerator{T}\"/> that can be used to iterate through the collection.</returns>\r\n        public IEnumerator<NodeWrapper> GetEnumerator()\r\n        {\r\n            return this.elements.Select(element => new NodeWrapper(element)).GetEnumerator();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an enumerator that iterates through a collection.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerator\"/> object that can be used to iterate through the collection.</returns>\r\n        IEnumerator IEnumerable.GetEnumerator()\r\n        {\r\n            return this.GetEnumerator();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Testing/StaticConfigurationContext.cs",
    "content": "namespace Nancy.Testing\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Helper class for running tests with <see cref=\"StaticConfiguration\"/> setup in a certain way. This\r\n    /// class was designed to be used with a using-statement. Upon disposable the previous static configuration\r\n    /// values will be reset, leaving it in the state is was before the test.\r\n    /// </summary>\r\n    public class StaticConfigurationContext : IDisposable\r\n    {\r\n        private readonly StaticConfigurationValues existingConfiguration = new StaticConfigurationValues();\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"StaticConfigurationContext\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"closure\">The configuration context.</param>\r\n        public StaticConfigurationContext(Action<StaticConfigurationValues> closure)\r\n        {\r\n            this.existingConfiguration.CaseSensitive = StaticConfiguration.CaseSensitive;\r\n            this.existingConfiguration.RequestQueryFormMultipartLimit = StaticConfiguration.RequestQueryFormMultipartLimit;\r\n\r\n            var temporaryConfiguration =\r\n                new StaticConfigurationValues();\r\n\r\n            closure.Invoke(temporaryConfiguration);\r\n\r\n            AssignStaticConfigurationValues(temporaryConfiguration);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.\r\n        /// </summary>\r\n        public void Dispose()\r\n        {\r\n            AssignStaticConfigurationValues(this.existingConfiguration);\r\n        }\r\n\r\n        private static void AssignStaticConfigurationValues(StaticConfigurationValues values)\r\n        {\r\n            StaticConfiguration.CaseSensitive = values.CaseSensitive;\r\n            StaticConfiguration.RequestQueryFormMultipartLimit = values.RequestQueryFormMultipartLimit;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Helper class used to persist state of <see cref=\"StaticConfiguration\"/> members.\r\n        /// </summary>\r\n        public class StaticConfigurationValues\r\n        {\r\n            public bool CaseSensitive { get; set; }\r\n\r\n            public int RequestQueryFormMultipartLimit { get; set; }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Testing/TestingViewBrowserResponseExtensions.cs",
    "content": "﻿namespace Nancy.Testing\r\n{\r\n    /// <summary>\r\n    /// Extension methods for easy access of the properties\r\n    /// stored in the view context by the testing view factory\r\n    /// </summary>\r\n    public static class TestingViewBrowserResponseExtensions\r\n    {\r\n        /// <summary>\r\n        /// Get the model on the view\r\n        /// </summary>\r\n        /// <typeparam name=\"TType\">the type of the model</typeparam>\r\n        /// <param name=\"response\">The <see cref=\"BrowserResponse\"/> that the assert should be made on.</param>\r\n        /// <returns>a model of the <typeparamref name=\"TType\">type</typeparamref></returns>\r\n        /// <remarks>This method requires that the <c>Browser</c> utilize the <see cref=\"TestingViewFactory\"/></remarks>\r\n        public static TType GetModel<TType>(this BrowserResponse response)\r\n        {\r\n            return (TType)response.Context.Items[TestingViewContextKeys.VIEWMODEL];\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns the name of the view\r\n        /// </summary>\r\n        /// <param name=\"response\">The <see cref=\"BrowserResponse\"/> that the assert should be made on.</param>\r\n        /// <returns>the name of the view</returns>\r\n        /// <remarks>This method requires that the <c>Browser</c> utilize the <see cref=\"TestingViewFactory\"/></remarks>\r\n        public static string GetViewName(this BrowserResponse response)\r\n        {\r\n            return GetContextValue(response, TestingViewContextKeys.VIEWNAME);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns the name of the module\r\n        /// </summary>\r\n        /// <param name=\"response\">The <see cref=\"BrowserResponse\"/> that the assert should be made on.</param>\r\n        /// <returns>the name of the module</returns>\r\n        /// <remarks>This method requires that the <c>Browser</c> utilize the <see cref=\"TestingViewFactory\"/></remarks>\r\n        public static string GetModuleName(this BrowserResponse response)\r\n        {\r\n            return GetContextValue(response, TestingViewContextKeys.MODULENAME);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns the name of the module\r\n        /// </summary>\r\n        /// <param name=\"response\">The <see cref=\"BrowserResponse\"/> that the assert should be made on.</param>\r\n        /// <returns>the name of the module</returns>\r\n        /// <remarks>This method requires that the <c>Browser</c> utilize the <see cref=\"TestingViewFactory\"/></remarks>\r\n        public static string GetModulePath(this BrowserResponse response)\r\n        {\r\n            return GetContextValue(response, TestingViewContextKeys.MODULEPATH);\r\n        }\r\n\r\n        private static string GetContextValue(BrowserResponse response, string key)\r\n        {\r\n            object val;\r\n            if (!response.Context.Items.TryGetValue(key, out val))\r\n            {\r\n                return string.Empty;\r\n            }\r\n\r\n            var value = (string)val;\r\n            return string.IsNullOrEmpty(value) ? string.Empty : value;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Testing/TestingViewContextKeys.cs",
    "content": "﻿namespace Nancy.Testing\r\n{\r\n    /// <summary>\r\n    /// The key names for where the testing view context data is stored\r\n    /// </summary>\r\n    public static class TestingViewContextKeys\r\n    {\r\n        /// <summary>\r\n        ///  The key in ViewLocationContext.Item for the view model\r\n        /// </summary>\r\n        public const string VIEWMODEL = \"__Nancy_Testing_ViewModel\";\r\n        /// <summary>\r\n        ///  The key in ViewLocationContext.Item for the view name\r\n        /// </summary>\r\n        public const string VIEWNAME = \"__Nancy_Testing_ViewName\";\r\n        /// <summary>\r\n        ///  The key in ViewLocationContext.Item for the model name\r\n        /// </summary>\r\n        public const string MODULENAME = \"__Nancy_Testing_ModuleName\";\r\n        /// <summary>\r\n        ///  The key in ViewLocationContext.Item for the module path        \r\n        /// </summary>\r\n        public const string MODULEPATH = \"__Nancy_Testing_ModulePath\";\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Testing/TestingViewFactory.cs",
    "content": "﻿namespace Nancy.Testing\r\n{\r\n    using Nancy.ViewEngines;\r\n\r\n    /// <summary>\r\n    /// A view factory decorator, aimed for test,\r\n    /// that exposes some interesting properties about the generated view\r\n    /// </summary>\r\n    public class TestingViewFactory : IViewFactory\r\n    {\r\n        private readonly DefaultViewFactory decoratedViewFactory;\r\n\r\n\r\n        /// <summary>\r\n        /// Creates the view based on the view factory sent to the constructor\r\n        /// </summary>\r\n        /// <param name=\"viewFactory\">the view factory that is decorated</param>\r\n        public TestingViewFactory(DefaultViewFactory viewFactory)\r\n        {\r\n            this.decoratedViewFactory = viewFactory;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Renders the view and then call into the viewfactory\r\n        /// that the TestingViewFactory is decorating\r\n        /// </summary>\r\n        /// <param name=\"viewName\">The name of the view to render.</param>\r\n        /// <param name=\"model\">The module path of the module that is rendering the view.</param>\r\n        /// <param name=\"viewLocationContext\">A <see cref=\"ViewLocationContext\"/> instance, containing information about the context for which the view is being rendered.</param>\r\n        /// <returns>A response.</returns>\r\n        public Response RenderView(string viewName, dynamic model, ViewLocationContext viewLocationContext)\r\n        {\r\n            // Intercept and store interesting stuff\r\n            viewLocationContext.Context.Items[TestingViewContextKeys.VIEWMODEL] = model;\r\n            viewLocationContext.Context.Items[TestingViewContextKeys.VIEWNAME] = viewName;\r\n            viewLocationContext.Context.Items[TestingViewContextKeys.MODULENAME] = viewLocationContext.ModuleName;\r\n            viewLocationContext.Context.Items[TestingViewContextKeys.MODULEPATH] = viewLocationContext.ModulePath;\r\n\r\n            return this.decoratedViewFactory.RenderView(viewName, model, viewLocationContext);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Validation.DataAnnotations/DataAnnotationsRegistrations.cs",
    "content": "namespace Nancy.Validation.DataAnnotations\r\n{\r\n    using Nancy.Bootstrapper;\r\n\r\n    /// <summary>\r\n    /// Application registrations for Data Annotations validation types.\r\n    /// </summary>\r\n    public class DataAnnotationsRegistrations : Registrations\r\n    {\r\n        /// <summary>\r\n        /// Creates a new instance of the <see cref=\"DataAnnotationsRegistrations\"/> class, that performs\r\n        /// the default registrations of the Data Annotations types.\r\n        /// </summary>\r\n        /// <param name=\"typeCatalog\">An <see cref=\"ITypeCatalog\"/> instance.</param>\r\n        public DataAnnotationsRegistrations(ITypeCatalog typeCatalog) : base(typeCatalog)\r\n        {\r\n            this.RegisterAll<IDataAnnotationsValidatorAdapter>();\r\n            this.RegisterWithDefault<IPropertyValidatorFactory>(typeof(DefaultPropertyValidatorFactory));\r\n            this.RegisterWithDefault<IValidatableObjectAdapter>(typeof(DefaultValidatableObjectAdapter));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Validation.DataAnnotations/DataAnnotationsValidator.cs",
    "content": "﻿namespace Nancy.Validation.DataAnnotations\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// The default Data Annotations implementation of <see cref=\"IModelValidator\"/>.\r\n    /// </summary>\r\n    public class DataAnnotationsValidator : IModelValidator\r\n    {\r\n        private ModelValidationDescriptor descriptor;\r\n        private readonly IValidatableObjectAdapter validatableObjectAdapter;\r\n        private readonly IEnumerable<IPropertyValidator> validators;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DataAnnotationsValidator\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"typeForValidation\">The type for validation.</param>\r\n        /// <param name=\"factory\">The <see cref=\"IPropertyValidatorFactory\"/> instance that should be used by the validator.</param>\r\n        /// <param name=\"validatableObjectAdapter\">The <see cref=\"validatableObjectAdapter\"/> instance that should be used by the validator.</param>\r\n        public DataAnnotationsValidator(Type typeForValidation, IPropertyValidatorFactory factory, IValidatableObjectAdapter validatableObjectAdapter)\r\n        {\r\n            this.ModelType = typeForValidation;\r\n            this.validatableObjectAdapter = validatableObjectAdapter;\r\n            this.validators = factory.GetValidators(typeForValidation);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the description of the validator.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"ModelValidationDescriptor\"/> instance.</returns>\r\n        public ModelValidationDescriptor Description\r\n        {\r\n            get { return this.descriptor ?? (this.descriptor = GetModelValidationDescriptor()); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"System.Type\"/> of the model that is being validated by the validator.\r\n        /// </summary>\r\n        public Type ModelType { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Validates the specified instance.\r\n        /// </summary>\r\n        /// <param name=\"instance\">The instance that should be validated.</param>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> of the current request.</param>\r\n        /// <returns>A <see cref=\"ModelValidationResult\"/> with the result of the validation.</returns>\r\n        public ModelValidationResult Validate(object instance, NancyContext context)\r\n        {\r\n            var errors = \r\n                new List<ModelValidationError>();\r\n\r\n            foreach (var validator in this.validators)\r\n            {\r\n                var results =\r\n                    validator.Validate(instance, context);\r\n\r\n                errors.AddRange(results);\r\n            }\r\n\r\n            errors.AddRange(this.validatableObjectAdapter.Validate(instance, context));\r\n\r\n            return new ModelValidationResult(errors);\r\n        }\r\n\r\n        private ModelValidationDescriptor GetModelValidationDescriptor()\r\n        {\r\n            var rules = \r\n                this.validators.SelectMany(x => x.GetRules());\r\n\r\n            return new ModelValidationDescriptor(rules, this.ModelType);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.DataAnnotations/DataAnnotationsValidatorAdapter.cs",
    "content": "﻿namespace Nancy.Validation.DataAnnotations\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.ComponentModel;\r\n    using System.ComponentModel.DataAnnotations;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// A default implementation of an <see cref=\"IDataAnnotationsValidatorAdapter\"/>.\r\n    /// </summary>\r\n    public abstract class DataAnnotationsValidatorAdapter : IDataAnnotationsValidatorAdapter\r\n    {\r\n        private static readonly Lazy<bool> isRunningOnMono = new Lazy<bool>(() => Type.GetType(\"Mono.Runtime\") != null);\r\n        protected readonly string ruleType;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DataAnnotationsValidatorAdapter\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"ruleType\">Type of the rule.</param>\r\n        protected DataAnnotationsValidatorAdapter(string ruleType)\r\n        {\r\n            this.ruleType = ruleType;\r\n        }\r\n\r\n        // http://www.mono-project.com/Guide%3a_Porting_Winforms_Applications#Runtime_Conditionals\r\n        private static bool IsRunningOnMono\r\n        {\r\n            get { return isRunningOnMono.Value; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a boolean that indicates if the adapter can handle the\r\n        /// provided <paramref name=\"attribute\"/>.\r\n        /// </summary>\r\n        /// <param name=\"attribute\">The <see cref=\"ValidationAttribute\"/> that should be handled.</param>\r\n        /// <returns><see langword=\"true\" /> if the attribute can be handles, otherwise <see langword=\"false\" />.</returns>\r\n        public abstract bool CanHandle(ValidationAttribute attribute);\r\n\r\n        /// <summary>\r\n        /// Gets the rules the adapter provides.\r\n        /// </summary>\r\n        /// <param name=\"attribute\">The <see cref=\"ValidationAttribute\"/> that should be handled.</param>\r\n        /// <param name=\"descriptor\">A <see cref=\"PropertyDescriptor\"/> instance for the property that is being validated.</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"ModelValidationRule\"/> instances.</returns>\r\n        public virtual IEnumerable<ModelValidationRule> GetRules(ValidationAttribute attribute, PropertyDescriptor descriptor)\r\n        {\r\n            yield return new ModelValidationRule(ruleType, attribute.FormatErrorMessage, new [] { descriptor == null ? string.Empty : descriptor.Name });\r\n        }\r\n\r\n        /// <summary>\r\n        /// Validates the given instance.\r\n        /// </summary>\r\n        /// <param name=\"instance\">The instance that should be validated.</param>\r\n        /// <param name=\"attribute\">The <see cref=\"ValidationAttribute\"/> that should be handled.</param>\r\n        /// <param name=\"descriptor\">A <see cref=\"PropertyDescriptor\"/> instance for the property that is being validated.</param>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> of the current request.</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"ModelValidationRule\"/> instances.</returns>\r\n        public virtual IEnumerable<ModelValidationError> Validate(object instance, ValidationAttribute attribute, PropertyDescriptor descriptor, NancyContext context)\r\n        {\r\n            var validationContext =\r\n                new ValidationContext(instance, null, null)\r\n                {\r\n                    MemberName = descriptor == null ? null : descriptor.Name\r\n                };\r\n\r\n            // When running on Mono the Display attribute is not auto populated so for now we do it ourselves\r\n            if (IsRunningOnMono)\r\n            {\r\n                var displayName = this.GetDisplayNameForMember(instance, validationContext.MemberName);\r\n                if (!string.IsNullOrEmpty(displayName))\r\n                {\r\n                    validationContext.DisplayName = displayName;\r\n                }\r\n            }\r\n\r\n            if (descriptor != null)\r\n            {\r\n                // Display(Name) will auto populate the context, while DisplayName() needs to be manually set\r\n                if (validationContext.MemberName == validationContext.DisplayName && !string.IsNullOrEmpty(descriptor.DisplayName))\r\n                {\r\n                    validationContext.DisplayName = descriptor.DisplayName;\r\n                }\r\n\r\n                instance = descriptor.GetValue(instance);\r\n            }\r\n\r\n            var result =\r\n                attribute.GetValidationResult(instance, validationContext);\r\n\r\n            if (result != null)\r\n            {\r\n                yield return this.GetValidationError(result, validationContext, attribute);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a <see cref=\"ModelValidationError\"/> instance based on the supplied <see cref=\"ValidationResult\"/>.\r\n        /// </summary>\r\n        /// <param name=\"result\">The <see cref=\"ValidationResult\"/> to create a <see cref=\"ModelValidationError\"/> for.</param>\r\n        /// <param name=\"context\">The <see cref=\"ValidationContext\"/> of the supplied <see cref=\"ValidationResult\"/>.</param>\r\n        /// <param name=\"attribute\">The <see cref=\"ValidationAttribute\"/> being validated.</param>\r\n        /// <returns>A <see cref=\"ModelValidationError\"/> of member names.</returns>\r\n        protected virtual ModelValidationError GetValidationError(ValidationResult result, ValidationContext context, ValidationAttribute attribute)\r\n        {\r\n            return new ModelValidationError(result.MemberNames, result.ErrorMessage);\r\n        }\r\n\r\n        private DisplayAttribute GetDisplayAttribute(object instance, string memberName)\r\n        {\r\n            if (string.IsNullOrEmpty(memberName))\r\n            {\r\n                return null;\r\n            }\r\n\r\n            var member = instance.GetType().GetProperty(memberName);\r\n\r\n            return member.GetCustomAttributes(typeof(DisplayAttribute), false)\r\n                         .Cast<DisplayAttribute>()\r\n                         .FirstOrDefault();\r\n        }\r\n\r\n        private string GetDisplayNameForMember(object instance, string memberName)\r\n        {\r\n            var attribute = this.GetDisplayAttribute(instance, memberName);\r\n\r\n            string displayName = null;\r\n\r\n            if (attribute != null)\r\n            {\r\n                displayName = attribute.GetName();\r\n            }\r\n\r\n            return displayName ?? memberName;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Validation.DataAnnotations/DataAnnotationsValidatorFactory.cs",
    "content": "﻿namespace Nancy.Validation.DataAnnotations\r\n{\r\n    using System;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Creates and <see cref=\"IModelValidator\"/> for DataAnnotations.\r\n    /// </summary>\r\n    public class DataAnnotationsValidatorFactory : IModelValidatorFactory\r\n    {\r\n        private readonly IPropertyValidatorFactory factory;\r\n        private readonly IValidatableObjectAdapter validatableObjectAdapter;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DataAnnotationsValidatorAdapter\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"factory\">The <see cref=\"IPropertyValidatorFactory\"/> instance that should be used by the factory.</param>\r\n        /// <param name=\"validatableObjectAdapter\">The <see cref=\"validatableObjectAdapter\"/> instance that should be used by the factory.</param>\r\n        public DataAnnotationsValidatorFactory(IPropertyValidatorFactory factory, IValidatableObjectAdapter validatableObjectAdapter)\r\n        {\r\n            this.factory = factory;\r\n            this.validatableObjectAdapter = validatableObjectAdapter;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a data annotations <see cref=\"IModelValidator\"/> instance for the given type.\r\n        /// </summary>\r\n        /// <param name=\"type\">The type.</param>\r\n        /// <returns>An <see cref=\"IModelValidator\"/> instance. If no data annotation rules were found for the specified <paramref name=\"type\"/> then <see langword=\"null\"/> is returned.</returns>\r\n        public IModelValidator Create(Type type) \r\n        {\r\n            var validator = \r\n                new DataAnnotationsValidator(type, this.factory, this.validatableObjectAdapter);\r\n\r\n            return validator.Description.Rules.Any() ?\r\n                validator :\r\n                null;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.DataAnnotations/DefaultPropertyValidatorFactory.cs",
    "content": "﻿namespace Nancy.Validation.DataAnnotations\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.ComponentModel;\r\n    using System.ComponentModel.DataAnnotations;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Default implementation of the <see cref=\"IPropertyValidatorFactory\"/> interface.\r\n    /// </summary>\r\n    public class DefaultPropertyValidatorFactory : IPropertyValidatorFactory\r\n    {\r\n        private readonly IEnumerable<IDataAnnotationsValidatorAdapter> adapters;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultPropertyValidatorFactory\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"adapters\">The <see cref=\"IDataAnnotationsValidatorAdapter\"/> instances that are available to the factory.</param>\r\n        public DefaultPropertyValidatorFactory(IEnumerable<IDataAnnotationsValidatorAdapter> adapters)\r\n        {\r\n            this.adapters = adapters;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"PropertyValidator\"/> instances for the specified <paramref name=\"type\"/>.\r\n        /// </summary>\r\n        /// <param name=\"type\">The <see cref=\"Type\"/> that the validators should be retrieved for.</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance, containing <see cref=\"IPropertyValidator\"/> objects.</returns>\r\n        public IEnumerable<IPropertyValidator> GetValidators(Type type)\r\n        {\r\n            var typeDescriptor =\r\n                new AssociatedMetadataTypeTypeDescriptionProvider(type).GetTypeDescriptor(type);\r\n\r\n            var results =\r\n                new List<IPropertyValidator>();\r\n\r\n            results.Add(this.GetTypeValidator(typeDescriptor));\r\n            results.AddRange(this.GetPropertyValidators(typeDescriptor));\r\n\r\n            return results;\r\n        }\r\n\r\n        private IEnumerable<PropertyValidator> GetPropertyValidators(ICustomTypeDescriptor typeDescriptor)\r\n        {\r\n            var propertyDescriptors =\r\n                typeDescriptor.GetProperties();\r\n\r\n            foreach (PropertyDescriptor descriptor in propertyDescriptors)\r\n            {\r\n                var attributes =\r\n                    descriptor.Attributes.OfType<ValidationAttribute>();\r\n\r\n                var validator =\r\n                    new PropertyValidator\r\n                    {\r\n                        AttributeAdaptors = this.GetAttributeAdaptors(attributes),\r\n                        Descriptor = descriptor\r\n                    };\r\n\r\n                yield return validator;\r\n            }\r\n        }\r\n\r\n        private PropertyValidator GetTypeValidator(ICustomTypeDescriptor typeDescriptor)\r\n        {\r\n            var classAttributes =\r\n                typeDescriptor.GetAttributes().OfType<ValidationAttribute>();\r\n\r\n            var classValidator =\r\n                new PropertyValidator\r\n                {\r\n                    AttributeAdaptors = this.GetAttributeAdaptors(classAttributes)\r\n                };\r\n            return classValidator;\r\n        }\r\n\r\n        private IDictionary<ValidationAttribute, IEnumerable<IDataAnnotationsValidatorAdapter>> GetAttributeAdaptors(IEnumerable<ValidationAttribute> attributes)\r\n        {\r\n            var mappings = \r\n                new Dictionary<ValidationAttribute, IEnumerable<IDataAnnotationsValidatorAdapter>>();\r\n\r\n            foreach (var attribute in attributes)\r\n            {\r\n                var results =\r\n                    this.GetAdaptersForAttribute(attribute);\r\n\r\n                mappings.Add(attribute, results);\r\n            }\r\n\r\n            return mappings;\r\n        }\r\n\r\n        private IEnumerable<IDataAnnotationsValidatorAdapter> GetAdaptersForAttribute(ValidationAttribute attribute)\r\n        {\r\n            return this.adapters.Where(x => x.CanHandle(attribute));\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.DataAnnotations/DefaultValidatableObjectAdapter.cs",
    "content": "﻿namespace Nancy.Validation.DataAnnotations\r\n{\r\n    using System.Collections.Generic;\r\n    using System.ComponentModel.DataAnnotations;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    /// Default adapter for models that implements the <see cref=\"IValidatableObject\"/> interface.\r\n    /// </summary>\r\n    public class DefaultValidatableObjectAdapter : IValidatableObjectAdapter\r\n    {\r\n        /// <summary>\r\n        /// Validates the specified instance.\r\n        /// </summary>\r\n        /// <param name=\"instance\">The instance.</param>\r\n        /// <param name=\"context1\"></param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance, containing <see cref=\"ModelValidationError\"/> objects.</returns>\r\n        public IEnumerable<ModelValidationError> Validate(object instance, NancyContext context1)\r\n        {\r\n            var validateable =\r\n                instance as IValidatableObject;\r\n\r\n            if (validateable == null)\r\n            {\r\n                return Enumerable.Empty<ModelValidationError>();\r\n            }\r\n\r\n            var context =\r\n                new ValidationContext(instance, null, null);\r\n\r\n            var result =\r\n                validateable.Validate(context);\r\n\r\n            return result.Select(r => new ModelValidationError(r.MemberNames, r.ErrorMessage));\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.DataAnnotations/IDataAnnotationsValidatorAdapter.cs",
    "content": "﻿namespace Nancy.Validation.DataAnnotations\r\n{\r\n    using System.Collections.Generic;\r\n    using System.ComponentModel;\r\n    using System.ComponentModel.DataAnnotations;\r\n\r\n    /// <summary>\r\n    /// Adapts DataAnnotations validator attributes into Nancy Validators.\r\n    /// </summary>\r\n    public interface IDataAnnotationsValidatorAdapter\r\n    {\r\n        /// <summary>\r\n        /// Gets a boolean that indicates if the adapter can handle the\r\n        /// provided <paramref name=\"attribute\"/>.\r\n        /// </summary>\r\n        /// <param name=\"attribute\">The <see cref=\"ValidationAttribute\"/> that should be handled.</param>\r\n        /// <returns><see langword=\"true\" /> if the attribute can be handles, otherwise <see langword=\"false\" />.</returns>\r\n        bool CanHandle(ValidationAttribute attribute);\r\n\r\n        /// <summary>\r\n        /// Gets the rules the adapter provides.\r\n        /// </summary>\r\n        /// <param name=\"attribute\">The <see cref=\"ValidationAttribute\"/> that should be handled.</param>\r\n        /// <param name=\"descriptor\">A <see cref=\"PropertyDescriptor\"/> instance for the property that is being validated.</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"ModelValidationRule\"/> instances.</returns>\r\n        IEnumerable<ModelValidationRule> GetRules(ValidationAttribute attribute, PropertyDescriptor descriptor);\r\n\r\n        /// <summary>\r\n        /// Validates the given instance.\r\n        /// </summary>\r\n        /// <param name=\"instance\">The instance that should be validated.</param>\r\n        /// <param name=\"attribute\">The <see cref=\"ValidationAttribute\"/> that should be handled.</param>\r\n        /// <param name=\"descriptor\">A <see cref=\"PropertyDescriptor\"/> instance for the property that is being validated.</param>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> of the current request.</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"ModelValidationRule\"/> instances.</returns>\r\n        IEnumerable<ModelValidationError> Validate(object instance, ValidationAttribute attribute, PropertyDescriptor descriptor, NancyContext context);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.DataAnnotations/IPropertyValidator.cs",
    "content": "﻿namespace Nancy.Validation.DataAnnotations\r\n{\r\n    using System.Collections.Generic;\r\n    using System.ComponentModel;\r\n    using System.ComponentModel.DataAnnotations;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality for validating a property.\r\n    /// </summary>\r\n    public interface IPropertyValidator\r\n    {\r\n        /// <summary>\r\n        /// Gets or sets the <see cref=\"IDataAnnotationsValidatorAdapter\"/> instances that should be associated with\r\n        /// each of the <see cref=\"ValidationAttribute\"/> that are specified for the property that is being validated.\r\n        /// </summary>\r\n        IDictionary<ValidationAttribute, IEnumerable<IDataAnnotationsValidatorAdapter>> AttributeAdaptors { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the <see cref=\"PropertyDescriptor\"/> for the property that is being validated.\r\n        /// </summary>\r\n        PropertyDescriptor Descriptor { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets the validation rules for the property that is being validated.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance, containing <see cref=\"ModelValidationRule\"/> objects.</returns>\r\n        IEnumerable<ModelValidationRule> GetRules();\r\n\r\n        /// <summary>\r\n        /// Gets the validation result for the specified <paramref name=\"instance\"/>.\r\n        /// </summary>\r\n        /// <param name=\"instance\">The instance that should be validated.</param>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> of the current request.</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance, containing <see cref=\"ModelValidationError\"/> objects.</returns>\r\n        IEnumerable<ModelValidationError> Validate(object instance, NancyContext context);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.DataAnnotations/IPropertyValidatorFactory.cs",
    "content": "﻿namespace Nancy.Validation.DataAnnotations\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality for retrieving <see cref=\"PropertyValidator\"/> instances\r\n    /// from a specified <see cref=\"Type\"/>.\r\n    /// </summary>\r\n    public interface IPropertyValidatorFactory\r\n    {\r\n        /// <summary>\r\n        /// Gets the <see cref=\"PropertyValidator\"/> instances for the specified <paramref name=\"type\"/>.\r\n        /// </summary>\r\n        /// <param name=\"type\">The <see cref=\"Type\"/> that the validators should be retrieved for.</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance, containing <see cref=\"IPropertyValidator\"/> objects.</returns>\r\n        IEnumerable<IPropertyValidator> GetValidators(Type type);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.DataAnnotations/IValidatableObjectAdapter.cs",
    "content": "﻿namespace Nancy.Validation.DataAnnotations\r\n{\r\n    using System.Collections.Generic;\r\n    using System.ComponentModel.DataAnnotations;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality for an adapter for models that implements the <see cref=\"IValidatableObject\"/> interface.\r\n    /// </summary>\r\n    public interface IValidatableObjectAdapter\r\n    {\r\n        /// <summary>\r\n        /// Validates the given instance.\r\n        /// </summary>\r\n        /// <param name=\"instance\">The instance.</param>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> of the current request.</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"ModelValidationRule\"/> instances.</returns>\r\n        IEnumerable<ModelValidationError> Validate(object instance, NancyContext context);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.DataAnnotations/Nancy.Validation.DataAnnotations.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <Description>Adds Data Annotation validation support to Nancy.</Description>\n    <PackageTags>$(PackageTags);Validation;DataAnnotations</PackageTags>\n    <TargetFramework>net452</TargetFramework>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <Reference Include=\"System.ComponentModel.DataAnnotations\" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "src/Nancy.Validation.DataAnnotations/PropertyValidator.cs",
    "content": "﻿namespace Nancy.Validation.DataAnnotations\r\n{\r\n    using System.Collections.Generic;\r\n    using System.ComponentModel;\r\n    using System.ComponentModel.DataAnnotations;\r\n\r\n    /// <summary>\r\n    /// Validates a specified property against a set of Data Annotation <see cref=\"ValidationAttribute\"/>\r\n    /// and <see cref=\"IDataAnnotationsValidatorAdapter\"/> instances.\r\n    /// </summary>\r\n    public class PropertyValidator : IPropertyValidator\r\n    {\r\n        /// <summary>\r\n        /// Gets or sets the <see cref=\"IDataAnnotationsValidatorAdapter\"/> instances that should be associated with\r\n        /// each of the <see cref=\"ValidationAttribute\"/> that are specified for the property that is being validated.\r\n        /// </summary>\r\n        public IDictionary<ValidationAttribute, IEnumerable<IDataAnnotationsValidatorAdapter>> AttributeAdaptors { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the <see cref=\"PropertyDescriptor\"/> for the property that is being validated.\r\n        /// </summary>\r\n        public PropertyDescriptor Descriptor { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets the validation rules for the property that is being validated.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance, containing <see cref=\"ModelValidationRule\"/> objects.</returns>\r\n        public IEnumerable<ModelValidationRule> GetRules()\r\n        {\r\n            var rules =\r\n                new List<ModelValidationRule>();\r\n\r\n            foreach (var attributeAdapter in this.AttributeAdaptors)\r\n            {\r\n                foreach (var adapter in attributeAdapter.Value)\r\n                {\r\n                    var results =\r\n                        adapter.GetRules(attributeAdapter.Key, this.Descriptor);\r\n\r\n                    rules.AddRange(results);\r\n                }\r\n            }\r\n\r\n            return rules;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the validation result for the specified <paramref name=\"instance\"/>.\r\n        /// </summary>\r\n        /// <param name=\"instance\">The instance that should be validated.</param>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> of the current request.</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance, containing <see cref=\"ModelValidationError\"/> objects.</returns>\r\n        public IEnumerable<ModelValidationError> Validate(object instance, NancyContext context)\r\n        {\r\n            var errors =\r\n                new List<ModelValidationError>();\r\n\r\n            foreach (var attributeAdapter in this.AttributeAdaptors)\r\n            {\r\n                foreach (var adapter in attributeAdapter.Value)\r\n                {\r\n                    var results =\r\n                        adapter.Validate(instance, attributeAdapter.Key, this.Descriptor, context);\r\n\r\n                    errors.AddRange(results);\r\n                }\r\n            }\r\n\r\n            return errors;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.DataAnnotations/RangeValidatorAdapter.cs",
    "content": "﻿namespace Nancy.Validation.DataAnnotations\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.ComponentModel;\r\n    using System.ComponentModel.DataAnnotations;\r\n\r\n    using Nancy.Validation.Rules;\r\n\r\n    /// <summary>\r\n    /// An adapter for the <see cref=\"RangeAttribute\"/>.\r\n    /// </summary>\r\n    public class RangeValidatorAdapter : DataAnnotationsValidatorAdapter\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"RangeValidatorAdapter\"/> class.\r\n        /// </summary>\r\n        public RangeValidatorAdapter() : base(\"Comparison\")\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a boolean that indicates if the adapter can handle the\r\n        /// provided <paramref name=\"attribute\"/>.\r\n        /// </summary>\r\n        /// <param name=\"attribute\">The <see cref=\"ValidationAttribute\"/> that should be handled.</param>\r\n        /// <returns><see langword=\"true\" /> if the attribute can be handles, otherwise <see langword=\"false\" />.</returns>\r\n        public override bool CanHandle(ValidationAttribute attribute)\r\n        {\r\n            return attribute is RangeAttribute;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the rules the adapter provides.\r\n        /// </summary>\r\n        /// <param name=\"attribute\">The <see cref=\"ValidationAttribute\"/> that should be handled.</param>\r\n        /// <param name=\"descriptor\">A <see cref=\"PropertyDescriptor\"/> instance for the property that is being validated.</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"ModelValidationRule\"/> instances.</returns>\r\n        public override IEnumerable<ModelValidationRule> GetRules(ValidationAttribute attribute, PropertyDescriptor descriptor)\r\n        {\r\n            var ra = (RangeAttribute)attribute;\r\n\r\n            yield return new ComparisonValidationRule(attribute.FormatErrorMessage,\r\n                new[] { descriptor.Name },\r\n                ComparisonOperator.GreaterThanOrEqual,\r\n                Convert(ra.OperandType, ra.Minimum));\r\n\r\n            yield return new ComparisonValidationRule(attribute.FormatErrorMessage,\r\n                new[] { descriptor.Name },\r\n                ComparisonOperator.LessThanOrEqual,\r\n                Convert(ra.OperandType, ra.Maximum));\r\n        }\r\n\r\n        private static object Convert(Type type, object value)\r\n        {\r\n            if(value == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            if(value is string)\r\n            {\r\n                var converter = \r\n                    TypeDescriptor.GetConverter(type);\r\n\r\n                return converter.ConvertFromString((string)value);\r\n            }\r\n\r\n            return System.Convert.ChangeType(value, type);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.DataAnnotations/RegexValidatorAdapter.cs",
    "content": "﻿namespace Nancy.Validation.DataAnnotations\r\n{\r\n    using System.Collections.Generic;\r\n    using System.ComponentModel;\r\n    using System.ComponentModel.DataAnnotations;\r\n\r\n    using Nancy.Validation.Rules;\r\n\r\n    /// <summary>\r\n    /// An adapter for the <see cref=\"RegularExpressionAttribute\"/>.\r\n    /// </summary>\r\n    public class RegexValidatorAdapter : DataAnnotationsValidatorAdapter\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"RegexValidatorAdapter\"/> class.\r\n        /// </summary>\r\n        public RegexValidatorAdapter() : base(\"Regex\")\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a boolean that indicates if the adapter can handle the\r\n        /// provided <paramref name=\"attribute\"/>.\r\n        /// </summary>\r\n        /// <param name=\"attribute\">The <see cref=\"ValidationAttribute\"/> that should be handled.</param>\r\n        /// <returns><see langword=\"true\" /> if the attribute can be handles, otherwise <see langword=\"false\" />.</returns>\r\n        public override bool CanHandle(ValidationAttribute attribute)\r\n        {\r\n            return attribute is RegularExpressionAttribute;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the rules the adapter provides.\r\n        /// </summary>\r\n        /// <param name=\"attribute\">The <see cref=\"ValidationAttribute\"/> that should be handled.</param>\r\n        /// <param name=\"descriptor\">A <see cref=\"PropertyDescriptor\"/> instance for the property that is being validated.</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"ModelValidationRule\"/> instances.</returns>\r\n        public override IEnumerable<ModelValidationRule> GetRules(ValidationAttribute attribute, PropertyDescriptor descriptor)\r\n        {\r\n            yield return new RegexValidationRule(attribute.FormatErrorMessage,\r\n                new[] { descriptor.Name },\r\n                ((RegularExpressionAttribute)attribute).Pattern);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.DataAnnotations/RequiredValidatorAdapter.cs",
    "content": "﻿namespace Nancy.Validation.DataAnnotations\r\n{\r\n    using System.Collections.Generic;\r\n    using System.ComponentModel;\r\n    using System.ComponentModel.DataAnnotations;\r\n\r\n    using Nancy.Validation.Rules;\r\n\r\n    /// <summary>\r\n    /// An adapter for the <see cref=\"System.ComponentModel.DataAnnotations.RequiredAttribute\"/>.\r\n    /// </summary>\r\n    public class RequiredValidatorAdapter : DataAnnotationsValidatorAdapter\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"RequiredValidatorAdapter\"/> class.\r\n        /// </summary>\r\n        public RequiredValidatorAdapter() : base(\"Required\")\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a boolean that indicates if the adapter can handle the\r\n        /// provided <paramref name=\"attribute\"/>.\r\n        /// </summary>\r\n        /// <param name=\"attribute\">The <see cref=\"ValidationAttribute\"/> that should be handled.</param>\r\n        /// <returns><see langword=\"true\" /> if the attribute can be handles, otherwise <see langword=\"false\" />.</returns>\r\n        public override bool CanHandle(ValidationAttribute attribute)\r\n        {\r\n            return attribute is RequiredAttribute;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the rules the adapter provides.\r\n        /// </summary>\r\n        /// <param name=\"attribute\">The <see cref=\"ValidationAttribute\"/> that should be handled.</param>\r\n        /// <param name=\"descriptor\">A <see cref=\"PropertyDescriptor\"/> instance for the property that is being validated.</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"ModelValidationRule\"/> instances.</returns>\r\n        public override IEnumerable<ModelValidationRule> GetRules(ValidationAttribute attribute, PropertyDescriptor descriptor)\r\n        {\r\n            var requiredAttribute = (RequiredAttribute) attribute;\r\n\r\n            yield return new NotNullValidationRule(attribute.FormatErrorMessage, new[] { descriptor.Name });\r\n\r\n            if (!requiredAttribute.AllowEmptyStrings)\r\n            {\r\n                yield return new NotEmptyValidationRule(attribute.FormatErrorMessage, new[] { descriptor.Name });\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Validation.DataAnnotations/StringLengthValidatorAdapter.cs",
    "content": "﻿namespace Nancy.Validation.DataAnnotations\r\n{\r\n    using System.Collections.Generic;\r\n    using System.ComponentModel;\r\n    using System.ComponentModel.DataAnnotations;\r\n\r\n    using Nancy.Validation.Rules;\r\n\r\n    /// <summary>\r\n    /// An adapter for the <see cref=\"System.ComponentModel.DataAnnotations.StringLengthAttribute\"/>.\r\n    /// </summary>\r\n    public class StringLengthValidatorAdapter : DataAnnotationsValidatorAdapter\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"StringLengthValidatorAdapter\"/> class.\r\n        /// </summary>\r\n        public StringLengthValidatorAdapter() : base(\"StringLength\")\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a boolean that indicates if the adapter can handle the\r\n        /// provided <paramref name=\"attribute\"/>.\r\n        /// </summary>\r\n        /// <param name=\"attribute\">The <see cref=\"ValidationAttribute\"/> that should be handled.</param>\r\n        /// <returns><see langword=\"true\" /> if the attribute can be handles, otherwise <see langword=\"false\" />.</returns>\r\n        public override bool CanHandle(ValidationAttribute attribute)\r\n        {\r\n            return attribute is StringLengthAttribute;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the rules the adapter provides.\r\n        /// </summary>\r\n        /// <param name=\"attribute\">The <see cref=\"ValidationAttribute\"/> that should be handled.</param>\r\n        /// <param name=\"descriptor\">A <see cref=\"PropertyDescriptor\"/> instance for the property that is being validated.</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"ModelValidationRule\"/> instances.</returns>\r\n        public override IEnumerable<ModelValidationRule> GetRules(ValidationAttribute attribute, PropertyDescriptor descriptor)\r\n        {\r\n            yield return new StringLengthValidationRule(attribute.FormatErrorMessage,\r\n                new[] { descriptor.Name },\r\n                ((StringLengthAttribute)attribute).MinimumLength,\r\n                ((StringLengthAttribute)attribute).MaximumLength);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Validation.FluentValidation/AdapterBase.cs",
    "content": "﻿namespace Nancy.Validation.FluentValidation\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    using global::FluentValidation.Internal;\r\n    using global::FluentValidation.Validators;\r\n\r\n    /// <summary>\r\n    /// Defines the core functionality of an adapter between Fluent Validation validators and Nancy validation rules.\r\n    /// </summary>\r\n    public abstract class AdapterBase : IFluentAdapter\r\n    {\r\n        /// <summary>\r\n        /// Gets whether or not the adapter can handle the provided <see cref=\"IPropertyValidator\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"validator\">The <see cref=\"IPropertyValidator\"/> instance to check for compatibility with the adapter.</param>\r\n        /// <returns><see langword=\"true\" /> if the adapter can handle the validator, otherwise <see langword=\"false\" />.</returns>\r\n        public abstract bool CanHandle(IPropertyValidator validator);\r\n\r\n        /// <summary>\r\n        /// Get the <see cref=\"ModelValidationRule\"/> instances that are mapped from the fluent validation rule.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"ModelValidationRule\"/> instances.</returns>\r\n        public abstract IEnumerable<ModelValidationRule> GetRules(PropertyRule rule, IPropertyValidator validator);\r\n\r\n        /// <summary>\r\n        /// Gets the name of the members that the validator applied to.\r\n        /// </summary>\r\n        /// <returns>A string containing the name of members that the validator is applied to.</returns>\r\n        protected virtual IEnumerable<string> GetMemberNames(PropertyRule rule)\r\n        {\r\n            yield return rule.PropertyName;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the formatted error message of the validator.\r\n        /// </summary>\r\n        /// <returns>A formatted error message string.</returns>\r\n        protected virtual Func<string, string> FormatMessage(PropertyRule rule, IPropertyValidator validator)\r\n        {\r\n            return displayName =>\r\n            {\r\n                return new MessageFormatter()\r\n                    .AppendPropertyName(displayName ?? rule.GetDisplayName())\r\n                    .BuildMessage(validator.ErrorMessageSource.GetString());\r\n            };\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.FluentValidation/DefaultFluentAdapterFactory.cs",
    "content": "namespace Nancy.Validation.FluentValidation\r\n{\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    using global::FluentValidation.Validators;\r\n\r\n    /// <summary>\r\n    /// Default implementation of the <see cref=\"IFluentAdapterFactory\"/> interface.\r\n    /// </summary>\r\n    public class DefaultFluentAdapterFactory : IFluentAdapterFactory\r\n    {\r\n        private readonly IEnumerable<IFluentAdapter> adapters;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultFluentAdapterFactory\"/> class.\r\n        /// </summary>\r\n        public DefaultFluentAdapterFactory(IEnumerable<IFluentAdapter> adapters)\r\n        {\r\n            this.adapters = adapters;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a <see cref=\"IFluentAdapter\"/> instance based on the provided <paramref name=\"propertyValidator\"/>.\r\n        /// </summary>\r\n        /// <param name=\"propertyValidator\">The <see cref=\"IPropertyValidator\"/> for which the adapter should be created.</param>\r\n        /// <returns>An <see cref=\"IFluentAdapter\"/> instance.</returns>\r\n        public IFluentAdapter Create(IPropertyValidator propertyValidator)\r\n        {\r\n            var adapter =\r\n                this.adapters.SingleOrDefault(x => x.CanHandle(propertyValidator));\r\n\r\n            return adapter ?? new FallbackAdapter();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.FluentValidation/EmailAdapter.cs",
    "content": "﻿namespace Nancy.Validation.FluentValidation\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using global::FluentValidation.Internal;\r\n    using global::FluentValidation.Validators;\r\n\r\n    using Nancy.Validation.Rules;\r\n\r\n    /// <summary>\r\n    /// Adapter between the Fluent Validation <see cref=\"EmailValidator\"/> and the Nancy validation rules.\r\n    /// </summary>\r\n    public class EmailAdapter : AdapterBase\r\n    {\r\n        /// <summary>\r\n        /// Gets whether or not the adapter can handle the provided <see cref=\"IPropertyValidator\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"validator\">The <see cref=\"IPropertyValidator\"/> instance to check for compatibility with the adapter.</param>\r\n        /// <returns><see langword=\"true\" /> if the adapter can handle the validator, otherwise <see langword=\"false\" />.</returns>\r\n        public override bool CanHandle(IPropertyValidator validator)\r\n        {\r\n            return validator is EmailValidator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the <see cref=\"ModelValidationRule\"/> instances that are mapped from the fluent validation rule.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"ModelValidationRule\"/> instances.</returns>\r\n        public override IEnumerable<ModelValidationRule> GetRules(PropertyRule rule, IPropertyValidator validator)\r\n        {\r\n            yield return new RegexValidationRule(\r\n                base.FormatMessage(rule, validator),\r\n                base.GetMemberNames(rule),\r\n                ((IEmailValidator)validator).Expression);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.FluentValidation/EqualAdapter.cs",
    "content": "﻿namespace Nancy.Validation.FluentValidation\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using global::FluentValidation.Internal;\r\n    using global::FluentValidation.Validators;\r\n\r\n    using Nancy.Validation.Rules;\r\n\r\n    /// <summary>\r\n    /// Adapter between the Fluent Validation <see cref=\"EqualAdapter\"/> and the Nancy validation rules.\r\n    /// </summary>\r\n    public class EqualAdapter : AdapterBase\r\n    {\r\n        /// <summary>\r\n        /// Gets whether or not the adapter can handle the provided <see cref=\"IPropertyValidator\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"validator\">The <see cref=\"IPropertyValidator\"/> instance to check for compatibility with the adapter.</param>\r\n        /// <returns><see langword=\"true\" /> if the adapter can handle the validator, otherwise <see langword=\"false\" />.</returns>\r\n        public override bool CanHandle(IPropertyValidator validator)\r\n        {\r\n            return validator is EqualValidator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the <see cref=\"ModelValidationRule\"/> instances that are mapped from the fluent validation rule.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"ModelValidationRule\"/> instances.</returns>\r\n        public override IEnumerable<ModelValidationRule> GetRules(PropertyRule rule, IPropertyValidator validator)\r\n        {\r\n            yield return new ComparisonValidationRule(\r\n                base.FormatMessage(rule, validator),\r\n                base.GetMemberNames(rule),\r\n                ComparisonOperator.Equal,\r\n                ((EqualValidator)validator).ValueToCompare);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.FluentValidation/ExactLengthAdapater.cs",
    "content": "namespace Nancy.Validation.FluentValidation\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using global::FluentValidation.Internal;\r\n    using global::FluentValidation.Validators;\r\n\r\n    using Nancy.Validation.Rules;\r\n\r\n    /// <summary>\r\n    /// Adapter between the Fluent Validation <see cref=\"ExactLengthValidator\"/> and the Nancy validation rules.\r\n    /// </summary>\r\n    public class ExactLengthAdapater : AdapterBase\r\n    {\r\n        /// <summary>\r\n        /// Gets whether or not the adapter can handle the provided <see cref=\"IPropertyValidator\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"validator\">The <see cref=\"IPropertyValidator\"/> instance to check for compatibility with the adapter.</param>\r\n        /// <returns><see langword=\"true\" /> if the adapter can handle the validator, otherwise <see langword=\"false\" />.</returns>\r\n        public override bool CanHandle(IPropertyValidator validator)\r\n        {\r\n            return validator is ExactLengthValidator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the <see cref=\"ModelValidationRule\"/> instances that are mapped from the fluent validation rule.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"ModelValidationRule\"/> instances.</returns>\r\n        public override IEnumerable<ModelValidationRule> GetRules(PropertyRule rule, IPropertyValidator validator)\r\n        {\r\n            yield return new StringLengthValidationRule(\r\n                base.FormatMessage(rule, validator),\r\n                base.GetMemberNames(rule),\r\n                ((ExactLengthValidator)validator).Min,\r\n                ((ExactLengthValidator)validator).Max);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.FluentValidation/ExclusiveBetweenAdapter.cs",
    "content": "﻿namespace Nancy.Validation.FluentValidation\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using global::FluentValidation.Internal;\r\n    using global::FluentValidation.Validators;\r\n\r\n    using Nancy.Validation.Rules;\r\n\r\n    /// <summary>\r\n    /// Adapter between the Fluent Validation <see cref=\"ExclusiveBetweenValidator\"/> and the Nancy validation rules.\r\n    /// </summary>\r\n    public class ExclusiveBetweenAdapter : AdapterBase\r\n    {\r\n        /// <summary>\r\n        /// Gets whether or not the adapter can handle the provided <see cref=\"IPropertyValidator\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"validator\">The <see cref=\"IPropertyValidator\"/> instance to check for compatibility with the adapter.</param>\r\n        /// <returns><see langword=\"true\" /> if the adapter can handle the validator, otherwise <see langword=\"false\" />.</returns>\r\n        public override bool CanHandle(IPropertyValidator validator)\r\n        {\r\n            return validator is ExclusiveBetweenValidator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the <see cref=\"ModelValidationRule\"/> instances that are mapped from the fluent validation rule.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"ModelValidationRule\"/> instances.</returns>\r\n        public override IEnumerable<ModelValidationRule> GetRules(PropertyRule rule, IPropertyValidator validator)\r\n        {\r\n            yield return new ComparisonValidationRule(\r\n                base.FormatMessage(rule, validator),\r\n                base.GetMemberNames(rule),\r\n                ComparisonOperator.GreaterThan,\r\n                ((ExclusiveBetweenValidator)validator).From);\r\n\r\n            yield return new ComparisonValidationRule(\r\n                base.FormatMessage(rule, validator),\r\n                base.GetMemberNames(rule),\r\n                ComparisonOperator.LessThan,\r\n                ((ExclusiveBetweenValidator)validator).To);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.FluentValidation/FallbackAdapter.cs",
    "content": "﻿namespace Nancy.Validation.FluentValidation\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using global::FluentValidation.Internal;\r\n    using global::FluentValidation.Validators;\r\n\r\n    /// <summary>\r\n    /// Implementation of <see cref=\"IFluentAdapterFactory\"/> that will always return <see langword=\"false\"/>\r\n    /// when <see cref=\"CanHandle\"/> is called. This adapter will be used when no other of the available\r\n    /// adapters are able to handle the validator.\r\n    /// </summary>\r\n    public class FallbackAdapter : AdapterBase\r\n    {\r\n        /// <summary>\r\n        /// Gets whether or not the adapter can handle the provided <see cref=\"IPropertyValidator\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"validator\">The <see cref=\"IPropertyValidator\"/> instance to check for compatibility with the adapter.</param>\r\n        /// <returns><see langword=\"true\" /> if the adapter can handle the validator, otherwise <see langword=\"false\" />.</returns>\r\n        public override bool CanHandle(IPropertyValidator validator)\r\n        {\r\n            return false;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the <see cref=\"ModelValidationRule\"/> instances that are mapped from the fluent validation rule.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"ModelValidationRule\"/> instances.</returns>\r\n        public override IEnumerable<ModelValidationRule> GetRules(PropertyRule rule, IPropertyValidator validator)\r\n        {\r\n            yield return new ModelValidationRule(\r\n                \"Custom\",\r\n                base.FormatMessage(rule, validator),\r\n                base.GetMemberNames(rule));\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.FluentValidation/FluentValidationRegistrations.cs",
    "content": "namespace Nancy.Validation.FluentValidation\r\n{\r\n    using global::FluentValidation;\r\n\r\n    using Nancy.Bootstrapper;\r\n\r\n    /// <summary>\r\n    /// Application registrations for Fluent Validation types.\r\n    /// </summary>\r\n    public class FluentValidationRegistrations : Registrations\r\n    {\r\n        /// <summary>\r\n        /// Creates a new instance of the <see cref=\"FluentValidationRegistrations\"/> class, that performs\r\n        /// the default registrations of the Fluent Validation types.\r\n        /// </summary>\r\n        /// <param name=\"typeCatalog\">An <see cref=\"ITypeCatalog\"/> instance.</param>\r\n        public FluentValidationRegistrations(ITypeCatalog typeCatalog) : base(typeCatalog)\r\n        {\r\n            this.Register<IFluentAdapterFactory>(typeof(DefaultFluentAdapterFactory));\r\n            this.RegisterAll<IFluentAdapter>();\r\n            this.RegisterAll<IValidator>();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.Validation.FluentValidation/FluentValidationValidator.cs",
    "content": "namespace Nancy.Validation.FluentValidation\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    using global::FluentValidation;\r\n    using global::FluentValidation.Internal;\r\n    using global::FluentValidation.Results;\r\n    using global::FluentValidation.Validators;\r\n\r\n    /// <summary>\r\n    /// The default Fluent Validation implementation of <see cref=\"IValidator\"/>.\r\n    /// </summary>\r\n    public class FluentValidationValidator : IModelValidator\r\n    {\r\n        private readonly IValidator validator;\r\n        private readonly IFluentAdapterFactory factory;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"FluentValidationValidator\"/> class for the\r\n        /// specified <see cref=\"IValidator\"/>.\r\n        /// </summary>\r\n        /// <param name=\"validator\">The Fluent Validation validator that should be used.</param>\r\n        /// <param name=\"factory\">Factory for creating adapters for the type that is being validated.</param>\r\n        /// <param name=\"modelType\">The type of the model that is being validated.</param>\r\n        public FluentValidationValidator(IValidator validator, IFluentAdapterFactory factory, Type modelType)\r\n         {\r\n            this.ModelType = modelType;\r\n            this.validator = validator;\r\n            this.factory = factory;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the description of the validator.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"ModelValidationDescriptor\"/> instance.</value>\r\n        public ModelValidationDescriptor Description\r\n        {\r\n            get { return CreateDescriptor(); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"System.Type\"/> of the model that is being validated by the validator.\r\n        /// </summary>\r\n        public Type ModelType { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Validates the specified instance.\r\n        /// </summary>\r\n        /// <param name=\"instance\">The instance that should be validated.</param>\r\n        /// <param name=\"context\">The <see cref=\"NancyContext\"/> of the current request.</param>\r\n        /// <returns>A <see cref=\"ModelValidationResult\"/> with the result of the validation.</returns>\r\n        public ModelValidationResult Validate(object instance, NancyContext context)\r\n        {\r\n            var result =\r\n                this.validator.Validate(instance);\r\n\r\n            var errors =\r\n                GetErrors(result);\r\n\r\n            return new ModelValidationResult(errors);\r\n        }\r\n\r\n        private ModelValidationDescriptor CreateDescriptor()\r\n        {\r\n            var fluentDescriptor =\r\n                this.validator.CreateDescriptor();\r\n\r\n            var rules = new List<ModelValidationRule>();\r\n\r\n            var membersWithValidators = \r\n                fluentDescriptor.GetMembersWithValidators();\r\n\r\n            foreach (var memberWithValidators in membersWithValidators)\r\n            {\r\n                var fluentRules = fluentDescriptor\r\n                    .GetRulesForMember(memberWithValidators.Key)\r\n                    .OfType<PropertyRule>();\r\n\r\n                foreach (var rule in fluentRules)\r\n                {\r\n                    foreach (var v in rule.Validators)\r\n                    {\r\n                        rules.AddRange(GetValidationRule(rule, v));\r\n                    }\r\n                }\r\n            }\r\n\r\n            return new ModelValidationDescriptor(rules, this.ModelType);\r\n        }\r\n\r\n        private static IEnumerable<ModelValidationError> GetErrors(ValidationResult results)\r\n        {\r\n            return results.IsValid ? \r\n                Enumerable.Empty<ModelValidationError>() :\r\n                results.Errors.Select(error => new ModelValidationError(new[] { error.PropertyName }, error.ErrorMessage));\r\n        }\r\n\r\n        private IEnumerable<ModelValidationRule> GetValidationRule(PropertyRule rule, IPropertyValidator propertyValidator)\r\n        {\r\n            return this.factory.Create(propertyValidator).GetRules(rule, propertyValidator);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.FluentValidation/FluentValidationValidatorFactory.cs",
    "content": "﻿namespace Nancy.Validation.FluentValidation\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using global::FluentValidation;\r\n\r\n    /// <summary>\r\n    /// Creates and <see cref=\"IValidator\"/> for Fluent Validation.\r\n    /// </summary>\r\n    public class FluentValidationValidatorFactory : IModelValidatorFactory\r\n    {\r\n        private readonly IFluentAdapterFactory adapterFactory;\r\n        private readonly IEnumerable<IValidator> validators;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"FluentValidationValidatorFactory\"/> instance, with the\r\n        /// provided <see cref=\"IFluentAdapterFactory\"/>.\r\n        /// </summary>\r\n        /// <param name=\"adapterFactory\">The factory that should be usdd to create <see cref=\"IFluentAdapter\"/> instances.</param>\r\n        /// <param name=\"validators\">The <see cref=\"IValidator\"/> instance that are available for validation.</param>\r\n        public FluentValidationValidatorFactory(IFluentAdapterFactory adapterFactory, IEnumerable<IValidator> validators)\r\n        {\r\n            this.adapterFactory = adapterFactory;\r\n            this.validators = validators;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates a <see cref=\"IModelValidator\"/> instance for the given type.\r\n        /// </summary>\r\n        /// <param name=\"type\">The type of the model that is being validated.</param>\r\n        /// <returns>An <see cref=\"IModelValidator\"/> instance. If no fluent validation rules were found for the specified <paramref name=\"type\"/> then <see langword=\"null\"/> is returned.</returns>\r\n        public IModelValidator Create(Type type)\r\n        {\r\n            var instance =\r\n                GetValidatorInstance(type);\r\n\r\n            return (instance != null) ?\r\n                new FluentValidationValidator(instance, this.adapterFactory, type) :\r\n                null;\r\n        }\r\n\r\n        private IValidator GetValidatorInstance(Type type)\r\n        {\r\n            var fullType =\r\n                CreateValidatorType(type);\r\n            var available = this.validators\r\n                .Where(validator => fullType.GetTypeInfo().IsAssignableFrom(validator.GetType()))\r\n                .ToArray();\r\n\r\n            if (available.Length > 1)\r\n            {\r\n                var names = string.Join(\", \", available.Select(v => v.GetType().Name));\r\n                var message = string.Concat(\r\n                    \"Ambiguous choice between multiple validators for type \",\r\n\t\t\t\t\ttype.Name,\r\n\t\t\t\t\t\". The validators available are: \",\r\n\t\t\t\t\tnames);\r\n\r\n                throw new InvalidOperationException(message);\r\n            }\r\n\r\n            return available.FirstOrDefault();\r\n        }\r\n\r\n        private static Type CreateValidatorType(Type type)\r\n        {\r\n            return typeof(AbstractValidator<>).MakeGenericType(type);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.FluentValidation/GreaterThanAdapter.cs",
    "content": "﻿namespace Nancy.Validation.FluentValidation\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using global::FluentValidation.Internal;\r\n    using global::FluentValidation.Validators;\r\n\r\n    using Nancy.Validation.Rules;\r\n\r\n    /// <summary>\r\n    /// Adapter between the Fluent Validation <see cref=\"GreaterThanValidator\"/> and the Nancy validation rules.\r\n    /// </summary>\r\n    public class GreaterThanAdapter : AdapterBase\r\n    {\r\n        /// <summary>\r\n        /// Gets whether or not the adapter can handle the provided <see cref=\"IPropertyValidator\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"validator\">The <see cref=\"IPropertyValidator\"/> instance to check for compatibility with the adapter.</param>\r\n        /// <returns><see langword=\"true\" /> if the adapter can handle the validator, otherwise <see langword=\"false\" />.</returns>\r\n        public override bool CanHandle(IPropertyValidator validator)\r\n        {\r\n            return validator is GreaterThanValidator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the <see cref=\"ModelValidationRule\"/> instances that are mapped from the fluent validation rule.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"ModelValidationRule\"/> instances.</returns>\r\n        public override IEnumerable<ModelValidationRule> GetRules(PropertyRule rule, IPropertyValidator validator)\r\n        {\r\n            yield return new ComparisonValidationRule(\r\n                base.FormatMessage(rule, validator),\r\n                base.GetMemberNames(rule),\r\n                ComparisonOperator.GreaterThan,\r\n                ((GreaterThanValidator)validator).ValueToCompare);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.FluentValidation/GreaterThanOrEqualAdapter.cs",
    "content": "﻿namespace Nancy.Validation.FluentValidation\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using global::FluentValidation.Internal;\r\n    using global::FluentValidation.Validators;\r\n\r\n    using Nancy.Validation.Rules;\r\n\r\n    /// <summary>\r\n    /// Adapter between the Fluent Validation <see cref=\"GreaterThanOrEqualValidator\"/> and the Nancy validation rules.\r\n    /// </summary>\r\n    public class GreaterThanOrEqualAdapter : AdapterBase\r\n    {\r\n        /// <summary>\r\n        /// Gets whether or not the adapter can handle the provided <see cref=\"IPropertyValidator\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"validator\">The <see cref=\"IPropertyValidator\"/> instance to check for compatibility with the adapter.</param>\r\n        /// <returns><see langword=\"true\" /> if the adapter can handle the validator, otherwise <see langword=\"false\" />.</returns>\r\n        public override bool CanHandle(IPropertyValidator validator)\r\n        {\r\n            return validator is GreaterThanOrEqualValidator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the <see cref=\"ModelValidationRule\"/> instances that are mapped from the fluent validation rule.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"ModelValidationRule\"/> instances.</returns>\r\n        public override IEnumerable<ModelValidationRule> GetRules(PropertyRule rule, IPropertyValidator validator)\r\n        {\r\n            yield return new ComparisonValidationRule(\r\n                base.FormatMessage(rule, validator),\r\n                base.GetMemberNames(rule),\r\n                ComparisonOperator.GreaterThanOrEqual,\r\n                ((GreaterThanOrEqualValidator)validator).ValueToCompare);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.FluentValidation/IFluentAdapter.cs",
    "content": "﻿namespace Nancy.Validation.FluentValidation\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using global::FluentValidation.Internal;\r\n    using global::FluentValidation.Validators;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality of a Fluent Validation adapter.\r\n    /// </summary>\r\n    public interface IFluentAdapter\r\n    {\r\n        /// <summary>\r\n        /// Gets whether or not the adapter can handle the provided <see cref=\"IPropertyValidator\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"validator\">The <see cref=\"IPropertyValidator\"/> instance to check for compatibility with the adapter.</param>\r\n        /// <returns><see langword=\"true\" /> if the adapter can handle the validator, otherwise <see langword=\"false\" />.</returns>\r\n        bool CanHandle(IPropertyValidator validator);\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"ModelValidationRule\"/>'s for the Fluent Validation validator.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance, containing <see cref=\"ModelValidationRule\"/> instances.</returns>\r\n        IEnumerable<ModelValidationRule> GetRules(PropertyRule rule, IPropertyValidator validator);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.FluentValidation/IFluentAdapterFactory.cs",
    "content": "namespace Nancy.Validation.FluentValidation\r\n{\r\n    using global::FluentValidation.Validators;\r\n\r\n    /// <summary>\r\n    /// Defines the functionality of a factory for creating <see cref=\"IFluentAdapter\"/> instances.\r\n    /// </summary>\r\n    public interface IFluentAdapterFactory\r\n    {\r\n        /// <summary>\r\n        /// Creates a <see cref=\"IFluentAdapter\"/> instance based on the provided <paramref name=\"propertyValidator\"/>.\r\n        /// </summary>\r\n        /// <param name=\"propertyValidator\">The <see cref=\"IPropertyValidator\"/> for which the adapter should be created.</param>\r\n        /// <returns>An <see cref=\"IFluentAdapter\"/> instance.</returns>\r\n        IFluentAdapter Create(IPropertyValidator propertyValidator);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.FluentValidation/InclusiveBetweenAdapter.cs",
    "content": "﻿namespace Nancy.Validation.FluentValidation\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using global::FluentValidation.Internal;\r\n    using global::FluentValidation.Validators;\r\n\r\n    using Nancy.Validation.Rules;\r\n\r\n    /// <summary>\r\n    /// Adapter between the Fluent Validation <see cref=\"InclusiveBetweenValidator\"/> and the Nancy validation rules.\r\n    /// </summary>\r\n    public class InclusiveBetweenAdapter : AdapterBase\r\n    {\r\n        /// <summary>\r\n        /// Gets whether or not the adapter can handle the provided <see cref=\"IPropertyValidator\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"validator\">The <see cref=\"IPropertyValidator\"/> instance to check for compatibility with the adapter.</param>\r\n        /// <returns><see langword=\"true\" /> if the adapter can handle the validator, otherwise <see langword=\"false\" />.</returns>\r\n        public override bool CanHandle(IPropertyValidator validator)\r\n        {\r\n            return validator is InclusiveBetweenValidator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the <see cref=\"ModelValidationRule\"/> instances that are mapped from the fluent validation rule.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"ModelValidationRule\"/> instances.</returns>\r\n        public override IEnumerable<ModelValidationRule> GetRules(PropertyRule rule, IPropertyValidator validator)\r\n        {\r\n            yield return new ComparisonValidationRule(\r\n                base.FormatMessage(rule, validator),\r\n                base.GetMemberNames(rule),\r\n                ComparisonOperator.GreaterThanOrEqual,\r\n                ((InclusiveBetweenValidator)validator).From);\r\n\r\n            yield return new ComparisonValidationRule(\r\n                base.FormatMessage(rule, validator),\r\n                base.GetMemberNames(rule),\r\n                ComparisonOperator.LessThanOrEqual,\r\n                ((InclusiveBetweenValidator)validator).To);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.FluentValidation/LengthAdapter.cs",
    "content": "﻿namespace Nancy.Validation.FluentValidation\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using global::FluentValidation.Internal;\r\n    using global::FluentValidation.Validators;\r\n\r\n    using Nancy.Validation.Rules;\r\n\r\n    /// <summary>\r\n    /// Adapter between the Fluent Validation <see cref=\"LengthValidator\"/> and the Nancy validation rules.\r\n    /// </summary>\r\n    public class LengthAdapter : AdapterBase\r\n    {\r\n        /// <summary>\r\n        /// Gets whether or not the adapter can handle the provided <see cref=\"IPropertyValidator\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"validator\">The <see cref=\"IPropertyValidator\"/> instance to check for compatibility with the adapter.</param>\r\n        /// <returns><see langword=\"true\" /> if the adapter can handle the validator, otherwise <see langword=\"false\" />.</returns>\r\n        public override bool CanHandle(IPropertyValidator validator)\r\n        {\r\n            return validator is LengthValidator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the <see cref=\"ModelValidationRule\"/> instances that are mapped from the fluent validation rule.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"ModelValidationRule\"/> instances.</returns>\r\n        public override IEnumerable<ModelValidationRule> GetRules(PropertyRule rule, IPropertyValidator validator)\r\n        {\r\n            yield return new StringLengthValidationRule(\r\n                base.FormatMessage(rule, validator),\r\n                base.GetMemberNames(rule),\r\n                ((ILengthValidator)validator).Min,\r\n                ((ILengthValidator)validator).Max);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.FluentValidation/LessThanAdapter.cs",
    "content": "﻿namespace Nancy.Validation.FluentValidation\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using global::FluentValidation.Internal;\r\n    using global::FluentValidation.Validators;\r\n\r\n    using Nancy.Validation.Rules;\r\n\r\n    /// <summary>\r\n    /// Adapter between the Fluent Validation <see cref=\"LessThanAdapter\"/> and the Nancy validation rules.\r\n    /// </summary>\r\n    public class LessThanAdapter : AdapterBase\r\n    {\r\n        /// <summary>\r\n        /// Gets whether or not the adapter can handle the provided <see cref=\"IPropertyValidator\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"validator\">The <see cref=\"IPropertyValidator\"/> instance to check for compatibility with the adapter.</param>\r\n        /// <returns><see langword=\"true\" /> if the adapter can handle the validator, otherwise <see langword=\"false\" />.</returns>\r\n        public override bool CanHandle(IPropertyValidator validator)\r\n        {\r\n            return validator is LessThanValidator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the <see cref=\"ModelValidationRule\"/> instances that are mapped from the fluent validation rule.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"ModelValidationRule\"/> instances.</returns>\r\n        public override IEnumerable<ModelValidationRule> GetRules(PropertyRule rule, IPropertyValidator validator)\r\n        {\r\n            yield return new ComparisonValidationRule(\r\n                base.FormatMessage(rule, validator),\r\n                base.GetMemberNames(rule),\r\n                ComparisonOperator.LessThan,\r\n                ((LessThanValidator)validator).ValueToCompare);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.FluentValidation/LessThanOrEqualAdapter.cs",
    "content": "﻿namespace Nancy.Validation.FluentValidation\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using global::FluentValidation.Internal;\r\n    using global::FluentValidation.Validators;\r\n\r\n    using Nancy.Validation.Rules;\r\n\r\n    /// <summary>\r\n    /// Adapter between the Fluent Validation <see cref=\"LessThanOrEqualValidator\"/> and the Nancy validation rules.\r\n    /// </summary>\r\n    public class LessThanOrEqualAdapter : AdapterBase\r\n    {\r\n        /// <summary>\r\n        /// Gets whether or not the adapter can handle the provided <see cref=\"IPropertyValidator\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"validator\">The <see cref=\"IPropertyValidator\"/> instance to check for compatibility with the adapter.</param>\r\n        /// <returns><see langword=\"true\" /> if the adapter can handle the validator, otherwise <see langword=\"false\" />.</returns>\r\n        public override bool CanHandle(IPropertyValidator validator)\r\n        {\r\n            return validator is LessThanOrEqualValidator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the <see cref=\"ModelValidationRule\"/> instances that are mapped from the fluent validation rule.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"ModelValidationRule\"/> instances.</returns>\r\n        public override IEnumerable<ModelValidationRule> GetRules(PropertyRule rule, IPropertyValidator validator)\r\n        {\r\n            yield return new ComparisonValidationRule(\r\n                base.FormatMessage(rule, validator),\r\n                base.GetMemberNames(rule),\r\n                ComparisonOperator.LessThanOrEqual,\r\n                ((LessThanOrEqualValidator)validator).ValueToCompare);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.FluentValidation/Nancy.Validation.FluentValidation.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <Description>Adds Fluent Validation support to Nancy.</Description>\n    <PackageTags>$(PackageTags);Validation;FluentValidation</PackageTags>\n    <TargetFrameworks>netstandard2.0;net452</TargetFrameworks>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <PackageReference Include=\"FluentValidation\" Version=\"6.3.4-alpha\" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "src/Nancy.Validation.FluentValidation/NotEmptyAdapter.cs",
    "content": "namespace Nancy.Validation.FluentValidation\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using global::FluentValidation.Internal;\r\n    using global::FluentValidation.Validators;\r\n\r\n    using Nancy.Validation.Rules;\r\n\r\n    /// <summary>\r\n    /// Adapter between the Fluent Validation <see cref=\"NotEmptyValidator\"/> and the Nancy validation rules.\r\n    /// </summary>\r\n    public class NotEmptyAdapter : AdapterBase\r\n    {\r\n        /// <summary>\r\n        /// Gets whether or not the adapter can handle the provided <see cref=\"IPropertyValidator\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"validator\">The <see cref=\"IPropertyValidator\"/> instance to check for compatibility with the adapter.</param>\r\n        /// <returns><see langword=\"true\" /> if the adapter can handle the validator, otherwise <see langword=\"false\" />.</returns>\r\n        public override bool CanHandle(IPropertyValidator validator)\r\n        {\r\n            return validator is NotEmptyValidator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the <see cref=\"ModelValidationRule\"/> instances that are mapped from the fluent validation rule.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"ModelValidationRule\"/> instances.</returns>\r\n        public override IEnumerable<ModelValidationRule> GetRules(PropertyRule rule, IPropertyValidator validator)\r\n        {\r\n            yield return new NotEmptyValidationRule(\r\n                base.FormatMessage(rule, validator),\r\n                base.GetMemberNames(rule));\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.FluentValidation/NotEqualAdapter.cs",
    "content": "﻿namespace Nancy.Validation.FluentValidation\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using global::FluentValidation.Internal;\r\n    using global::FluentValidation.Validators;\r\n\r\n    using Nancy.Validation.Rules;\r\n\r\n    /// <summary>\r\n    /// Adapter between the Fluent Validation <see cref=\"NotEqualValidator\"/> and the Nancy validation rules.\r\n    /// </summary>\r\n    public class NotEqualAdapter : AdapterBase\r\n    {\r\n        /// <summary>\r\n        /// Gets whether or not the adapter can handle the provided <see cref=\"IPropertyValidator\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"validator\">The <see cref=\"IPropertyValidator\"/> instance to check for compatibility with the adapter.</param>\r\n        /// <returns><see langword=\"true\" /> if the adapter can handle the validator, otherwise <see langword=\"false\" />.</returns>\r\n        public override bool CanHandle(IPropertyValidator validator)\r\n        {\r\n            return validator is NotEqualValidator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the <see cref=\"ModelValidationRule\"/> instances that are mapped from the fluent validation rule.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"ModelValidationRule\"/> instances.</returns>\r\n        public override IEnumerable<ModelValidationRule> GetRules(PropertyRule rule, IPropertyValidator validator)\r\n        {\r\n            yield return new ComparisonValidationRule(\r\n                base.FormatMessage(rule, validator),\r\n                base.GetMemberNames(rule),\r\n                ComparisonOperator.NotEqual,\r\n                ((NotEqualValidator)validator).ValueToCompare);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.FluentValidation/NotNullAdapter.cs",
    "content": "﻿namespace Nancy.Validation.FluentValidation\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using global::FluentValidation.Internal;\r\n    using global::FluentValidation.Validators;\r\n\r\n    using Nancy.Validation.Rules;\r\n\r\n    /// <summary>\r\n    /// Adapter between the Fluent Validation <see cref=\"NotNullValidator\"/> and the Nancy validation rules.\r\n    /// </summary>\r\n    public class NotNullAdapter : AdapterBase\r\n    {\r\n        /// <summary>\r\n        /// Gets whether or not the adapter can handle the provided <see cref=\"IPropertyValidator\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"validator\">The <see cref=\"IPropertyValidator\"/> instance to check for compatibility with the adapter.</param>\r\n        /// <returns><see langword=\"true\" /> if the adapter can handle the validator, otherwise <see langword=\"false\" />.</returns>\r\n        public override bool CanHandle(IPropertyValidator validator)\r\n        {\r\n            return validator is NotNullValidator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the <see cref=\"ModelValidationRule\"/> instances that are mapped from the fluent validation rule.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"ModelValidationRule\"/> instances.</returns>\r\n        public override IEnumerable<ModelValidationRule> GetRules(PropertyRule rule, IPropertyValidator validator)\r\n        {\r\n            yield return new NotNullValidationRule(\r\n                base.FormatMessage(rule, validator),\r\n                base.GetMemberNames(rule));\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.Validation.FluentValidation/RegularExpressionAdapter.cs",
    "content": "﻿namespace Nancy.Validation.FluentValidation\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using global::FluentValidation.Internal;\r\n    using global::FluentValidation.Validators;\r\n\r\n    using Nancy.Validation.Rules;\r\n\r\n    /// <summary>\r\n    /// Adapter between the Fluent Validation <see cref=\"RegularExpressionValidator\"/> and the Nancy validation rules.\r\n    /// </summary>\r\n    public class RegularExpressionAdapter : AdapterBase\r\n    {\r\n        /// <summary>\r\n        /// Gets whether or not the adapter can handle the provided <see cref=\"IPropertyValidator\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"validator\">The <see cref=\"IPropertyValidator\"/> instance to check for compatability with the adapter.</param>\r\n        /// <returns><see langword=\"true\" /> if the adapter can handle the validator, otherwise <see langword=\"false\" />.</returns>\r\n        public override bool CanHandle(IPropertyValidator validator)\r\n        {\r\n            return validator is RegularExpressionValidator;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the <see cref=\"ModelValidationRule\"/> instances that are mapped from the fluent validation rule.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> of <see cref=\"ModelValidationRule\"/> instances.</returns>\r\n        public override IEnumerable<ModelValidationRule> GetRules(PropertyRule rule, IPropertyValidator validator)\r\n        {\r\n            yield return new RegexValidationRule(\r\n                FormatMessage(rule, validator),\r\n                GetMemberNames(rule),\r\n                ((IRegularExpressionValidator)validator).Expression);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.ViewEngines.DotLiquid/DefaultFileSystemFactory.cs",
    "content": "﻿namespace Nancy.ViewEngines.DotLiquid\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using global::DotLiquid.FileSystems;\r\n\r\n    /// <summary>\r\n    /// Default implementation of the <see cref=\"IFileSystemFactory\"/> interface.\r\n    /// </summary>\r\n    /// <remarks>This implementation always returns instances of the <see cref=\"LiquidNancyFileSystem\"/> type.</remarks>\r\n    public class DefaultFileSystemFactory : IFileSystemFactory\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultFileSystemFactory\"/> class\r\n        /// </summary>\r\n        public DefaultFileSystemFactory()\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a <see cref=\"IFileSystem\"/> instance for the provided <paramref name=\"context\"/>.\r\n        /// </summary>\r\n        /// <param name=\"context\">The context that the filesystem should be created for.</param>\r\n        /// <param name=\"extensions\"></param>\r\n        /// <returns>An <see cref=\"IFileSystem\"/> instance.</returns>\r\n        public IFileSystem GetFileSystem(ViewEngineStartupContext context, IEnumerable<string> extensions)\r\n        {\r\n            return new LiquidNancyFileSystem(context, extensions);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.ViewEngines.DotLiquid/DotLiquidRegistrations.cs",
    "content": "﻿namespace Nancy.ViewEngines.DotLiquid\r\n{\r\n    using global::DotLiquid.NamingConventions;\r\n\r\n    using Nancy.Bootstrapper;\r\n\r\n    /// <summary>\r\n    /// Used to register the default naming conventions for the ViewEngine. The naming convention affects DotLiquid Drops and filters.\r\n    /// See <a href=\"https://github.com/formosatek/dotliquid/wiki/DotLiquid-Drops#tips\">DotLiquid's documentation</a> on the subject for more information.\r\n    ///\r\n    /// This can be overridden in a bootstrapper.\r\n    /// </summary>\r\n    public class DotLiquidRegistrations : Registrations\r\n    {\r\n        /// <summary>\r\n        /// Register the <c>RubyNamingConvention</c> as the default.\r\n        /// </summary>\r\n        /// <param name=\"typeCatalog\">An <see cref=\"ITypeCatalog\"/> instance.</param>\r\n        public DotLiquidRegistrations(ITypeCatalog typeCatalog) : base(typeCatalog)\r\n        {\r\n            this.RegisterWithDefault<INamingConvention>(typeof(RubyNamingConvention));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.ViewEngines.DotLiquid/DotLiquidViewEngine.cs",
    "content": "﻿namespace Nancy.ViewEngines.DotLiquid\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n\r\n    using global::DotLiquid;\r\n    using global::DotLiquid.Exceptions;\r\n    using global::DotLiquid.FileSystems;\r\n    using global::DotLiquid.NamingConventions;\r\n    using Nancy.Extensions;\r\n    using Nancy.Responses;\r\n\r\n    /// <summary>\r\n    /// View engine for rendering dotLiquid views.\r\n    /// </summary>\r\n    public class DotLiquidViewEngine : IViewEngine\r\n    {\r\n        private readonly IFileSystemFactory fileSystemFactory;\r\n        private readonly INamingConvention namingConvention;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DotLiquidViewEngine\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"namingConvention\">Determines the DotLiquid naming convention that will be used for filters and Drops. This will default to the <c>RubyNamingConvention</c>.</param>\r\n        /// <remarks>The instance will use the <see cref=\"DefaultFileSystemFactory\"/> internally.</remarks>\r\n        public DotLiquidViewEngine(INamingConvention namingConvention)\r\n            : this(new DefaultFileSystemFactory(), namingConvention)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DotLiquidViewEngine\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"fileSystemFactory\">Factory used to retrieve the <see cref=\"IFileSystem\"/> instance that should be used by the engine.</param>\r\n        /// <param name=\"namingConvention\">The naming convention used by filters and DotLiquid's <c>Drop</c>s</param>\r\n        public DotLiquidViewEngine(IFileSystemFactory fileSystemFactory, INamingConvention namingConvention)\r\n        {\r\n            this.fileSystemFactory = fileSystemFactory;\r\n            this.namingConvention = namingConvention;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the extensions file extensions that are supported by the view engine.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> instance containing the extensions.</value>\r\n        /// <remarks>The extensions should not have a leading dot in the name.</remarks>\r\n        public IEnumerable<string> Extensions\r\n        {\r\n            get { yield return \"liquid\"; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initialize the view engine (if necessary)\r\n        /// </summary>\r\n        /// <param name=\"viewEngineStartupContext\">Startup context</param>\r\n        public void Initialize(ViewEngineStartupContext viewEngineStartupContext)\r\n        {\r\n            Template.FileSystem = this.fileSystemFactory.GetFileSystem(viewEngineStartupContext, this.Extensions);\r\n            Template.NamingConvention = this.namingConvention;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Renders the view.\r\n        /// </summary>\r\n        /// <param name=\"viewLocationResult\">A <see cref=\"ViewLocationResult\"/> instance, containing information on how to get the view template.</param>\r\n        /// <param name=\"model\">The model that should be passed into the view</param>\r\n        /// <param name=\"renderContext\"></param>\r\n        /// <returns>A response</returns>\r\n        public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)\r\n        {\r\n            Template parsed;\r\n            Hash hashedModel;\r\n            HttpStatusCode status;\r\n\r\n            try\r\n            {\r\n                // Set the parsed template\r\n                parsed = renderContext.ViewCache.GetOrAdd(\r\n                    viewLocationResult,\r\n                    x =>\r\n                    {\r\n                        using (var reader = viewLocationResult.Contents.Invoke())\r\n                            return Template.Parse(reader.ReadToEnd());\r\n                    });\r\n\r\n                hashedModel = Hash.FromAnonymousObject(new\r\n                {\r\n                    Model = new DynamicDrop(model),\r\n                    ViewBag = new DynamicDrop(renderContext.Context.ViewBag)\r\n                });\r\n\r\n                // If we got past that, we have a good response\r\n                status = HttpStatusCode.OK;\r\n\r\n            }\r\n            catch (SyntaxException syntaxException)\r\n            {\r\n                // Syntax Exceptions cause a 500\r\n                status = HttpStatusCode.InternalServerError;\r\n\r\n                // Build the error message\r\n                var errorMessage = string.Format(\"Syntax error in liquid view <strong>'{0}'</strong><br/><br/>{1}\",\r\n                    string.Format(\"{0}/{1}.{2}\", viewLocationResult.Location, viewLocationResult.Name, viewLocationResult.Extension),\r\n                    syntaxException.Message);\r\n\r\n                // Create the error model with a Nancy DynamicDictionary because i can ;)\r\n                var errorModel = new DynamicDictionary\r\n                {\r\n                    new KeyValuePair<string, dynamic>(\"ErrorMessage\", errorMessage)\r\n                };\r\n\r\n                // Hash up the Error model so DotLiquid will understand it\r\n                hashedModel =\r\n                    Hash.FromAnonymousObject(new\r\n                    {\r\n                        Model = new DynamicDrop(errorModel)\r\n                    });\r\n\r\n                // Grab the error HTML from the embedded resource and build up the DotLiquid template.\r\n                var errorHtml = LoadResource(@\"500.liquid\");\r\n                parsed = Template.Parse(errorHtml);\r\n            }\r\n            catch (Exception ex)\r\n            {\r\n                status = HttpStatusCode.InternalServerError;\r\n                // Build the error message\r\n                var errorMessage = string.Format(\"Error: {0}\", ex.Message);\r\n\r\n                // Create the error model with a Nancy DynamicDictionary because i can ;)\r\n                var errorModel = new DynamicDictionary\r\n                {\r\n                    new KeyValuePair<string, dynamic>(\"ErrorMessage\", errorMessage)\r\n                };\r\n\r\n                // Hash up the Error model so DotLiquid will understand it\r\n                hashedModel =\r\n                    Hash.FromAnonymousObject(new\r\n                    {\r\n                        Model = new DynamicDrop(errorModel)\r\n                    });\r\n\r\n                // Grab the error HTML from the embedded resource\r\n                var errorHtml = LoadResource(@\"500.liquid\");\r\n                parsed = Template.Parse(errorHtml);\r\n            }\r\n\r\n            // Build the response\r\n            return new HtmlResponse(statusCode: status, contents: stream =>\r\n            {\r\n                parsed.Render(stream, new RenderParameters\r\n                {\r\n                    LocalVariables = hashedModel,\r\n                    Registers = Hash.FromAnonymousObject(new { nancy = renderContext })\r\n                });\r\n            });\r\n        }\r\n\r\n        private static string LoadResource(string filename)\r\n        {\r\n            var resourceStream = typeof(DotLiquidViewEngine).GetAssembly().GetManifestResourceStream(string.Format(\"Nancy.ViewEngines.DotLiquid.Resources.{0}\", filename));\r\n\r\n            if (resourceStream == null)\r\n            {\r\n                return string.Empty;\r\n            }\r\n\r\n            using (var reader = new StreamReader(resourceStream))\r\n            {\r\n                return reader.ReadToEnd();\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.ViewEngines.DotLiquid/DynamicDrop.cs",
    "content": "﻿namespace Nancy.ViewEngines.DotLiquid\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Dynamic;\r\n\r\n    using global::DotLiquid;\r\n\r\n    public class DynamicDrop : Drop\r\n    {\r\n        private readonly dynamic model;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DynamicDrop\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"model\">The view model.</param>\r\n        public DynamicDrop(dynamic model)\r\n        {\r\n            this.model = GetValidModelType(model);\r\n        }\r\n\r\n        public override object BeforeMethod(string propertyName)\r\n        {\r\n            if (model == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            if (string.IsNullOrEmpty(propertyName))\r\n            {\r\n                return null;\r\n            }\r\n\r\n            Type modelType = this.model.GetType();\r\n            object value = null;\r\n            if(modelType.Equals(typeof(Dictionary<string, object>)))\r\n            {\r\n                value = GetExpandoObjectValue(propertyName);\r\n            }\r\n            else if (modelType.Equals(typeof(DynamicDictionary)))\r\n            {\r\n                value = GetDynamicDictionaryObjectValue(propertyName);\r\n            }\r\n            else\r\n            {\r\n                value = GetPropertyValue(propertyName);\r\n            }\r\n            return value;\r\n        }\r\n\r\n        private object GetExpandoObjectValue(string propertyName)\r\n        {\r\n            return (!this.model.ContainsKey(propertyName)) ?\r\n                null :\r\n                this.model[propertyName];\r\n        }\r\n\r\n        private object GetDynamicDictionaryObjectValue(string propertyName)\r\n        {\r\n            DynamicDictionaryValue dictionaryValue = this.model[propertyName] as DynamicDictionaryValue;\r\n            return dictionaryValue == null || !dictionaryValue.HasValue ? null : dictionaryValue.Value;\r\n        }\r\n\r\n        private object GetPropertyValue(string propertyName)\r\n        {\r\n            var property = this.model.GetType().GetProperty(propertyName);\r\n\r\n            return (property == null) ?\r\n                null : \r\n                property.GetValue(this.model, null);\r\n        }\r\n\r\n        private static dynamic GetValidModelType(dynamic model)\r\n        {\r\n            if (model == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            return model.GetType().Equals(typeof(ExpandoObject))\r\n                ? new Dictionary<string, object>(model, StaticConfiguration.CaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase)\r\n                : model;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.ViewEngines.DotLiquid/IFileSystemFactory.cs",
    "content": "namespace Nancy.ViewEngines.DotLiquid\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using global::DotLiquid.FileSystems;\r\n\r\n    /// <summary>\r\n    /// Factory for creating a <see cref=\"IFileSystem\"/> instance.\r\n    /// </summary>\r\n    public interface IFileSystemFactory\r\n    {\r\n        /// <summary>\r\n        /// Gets a <see cref=\"IFileSystem\"/> instance for the provided <paramref name=\"context\"/>.\r\n        /// </summary>\r\n        /// <param name=\"context\">The context that the filesystem should be created for.</param>\r\n        /// <param name=\"extensions\">View extensions to search for</param>\r\n        /// <returns>An <see cref=\"IFileSystem\"/> instance.</returns>\r\n        IFileSystem GetFileSystem(ViewEngineStartupContext context, IEnumerable<string> extensions);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.ViewEngines.DotLiquid/LiquidNancyFileSystem.cs",
    "content": "﻿namespace Nancy.ViewEngines.DotLiquid\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    using global::DotLiquid;\r\n    using global::DotLiquid.Exceptions;\r\n    using global::DotLiquid.FileSystems;\r\n\r\n    using liquid = global::DotLiquid;\r\n\r\n    /// <summary>\r\n    /// <see cref=\"IFileSystem\"/> implementation around the Nancy templates.\r\n    /// </summary>\r\n    public class LiquidNancyFileSystem : IFileSystem\r\n    {\r\n        private readonly ViewEngineStartupContext viewEngineStartupContext;\r\n\r\n        private readonly IEnumerable<string> extensions;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"LiquidNancyFileSystem\"/> class,\r\n        /// with the provided <paramref name=\"context\"/>.\r\n        /// </summary>\r\n        /// <param name=\"context\">The context that the engine can operate in.</param>\r\n        /// <param name=\"extensions\"></param>\r\n        public LiquidNancyFileSystem(ViewEngineStartupContext context, IEnumerable<string> extensions)\r\n        {\r\n            viewEngineStartupContext = context;\r\n            this.extensions = extensions;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Reads the content of the template specified by the <paramref name=\"templateName\"/> parameter.\r\n        /// </summary>\r\n        /// <param name=\"context\">The <see cref=\"Context\"/> of the call.</param>\r\n        /// <param name=\"templateName\">The name of the template to read.</param>\r\n        /// <exception cref=\"liquid.Exceptions.FileSystemException\">The specified template could not be located.</exception>\r\n        /// <returns>The content of the template.</returns>\r\n        public string ReadTemplateFile(liquid.Context context, string templateName)\r\n        {\r\n            IRenderContext renderContext = context.Registers[\"nancy\"] as IRenderContext;\r\n            if (renderContext != null)\r\n            {\r\n                // Clean up the template name\r\n                templateName = GetCleanTemplateName(templateName);\r\n\r\n                // Try to find a matching template using established view conventions\r\n                ViewLocationResult viewLocation = null;\r\n                if (extensions.Any(\r\n                    s => templateName.EndsWith(s, StringComparison.OrdinalIgnoreCase)))\r\n                {\r\n                    // The template name does end with a valid extension, just try to find it\r\n                    viewLocation = renderContext.LocateView(templateName, null);\r\n                }\r\n                else\r\n                {\r\n                    // The template name does not end with a valid extension, try all the possibilities\r\n                    foreach (string extension in extensions)\r\n                    {\r\n                        viewLocation = renderContext.LocateView(String.Concat(templateName, \".\", extension), null);\r\n                        if (viewLocation != null) break;\r\n                    }\r\n                }\r\n\r\n                // If we found one, get the template and pass it back\r\n                // Eventually, it would be better to pass back the actual template from the cache if it's already been parsed\r\n                // Or to parse here and store it in the cache before passing it back in not\r\n                if (viewLocation != null)\r\n                {\r\n                    using (var reader = viewLocation.Contents.Invoke())\r\n                        return reader.ReadToEnd();\r\n                }\r\n            }\r\n            throw new FileSystemException(\"Template file {0} not found\", new[] { templateName });\r\n        }\r\n\r\n        private string GetCleanTemplateName(string templateName)\r\n        {\r\n            return templateName\r\n                .Replace(@\"\"\"\", \"\")\r\n                .Replace(\"'\", \"\")\r\n                .Replace(@\"\\\", \"/\");\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.ViewEngines.DotLiquid/Nancy.ViewEngines.DotLiquid.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <Description>Enables using the DotLiquid view engine with Nancy.</Description>\n    <PackageTags>$(PackageTags);View Engine;DotLiquid</PackageTags>\n    <TargetFramework>net452</TargetFramework>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <PackageReference Include=\"DotLiquid\" Version=\"2.0.64\" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "src/Nancy.ViewEngines.DotLiquid/Resources/500.liquid",
    "content": "<!DOCTYPE html>\r\n<html>\r\n<head>\r\n    <title>Nancy - 500 Internal Server Error</title>\r\n    <style>\r\n        html {\r\n            height: 100%;\r\n        }\r\n\r\n        body {\r\n            background: linear-gradient(-180deg, #000000, #434343) #000 fixed;\r\n            color: #333;\r\n            display: table;\r\n            font-family: sans-serif;\r\n            height: 100%;\r\n            margin: 0;\r\n            width: 100%;\r\n        }\r\n\r\n        img {\r\n            float: left;\r\n            margin-right: 40px;\r\n        }\r\n\r\n        h1 {\r\n            font-family: sans-serif;\r\n            margin-bottom: 5px;\r\n        }\r\n\r\n        h1, h2 {\r\n            color: #333;\r\n        }\r\n\r\n        .container {\r\n            display: table-cell;\r\n            vertical-align: middle;\r\n            padding: 20px;\r\n        }\r\n\r\n        .box {\r\n            background-color: #f6f8f8;\r\n            border-radius: 4px;\r\n            box-shadow: 0 2px 4px 0 rgba(0, 0, 0, .3);\r\n            margin: 0 auto;\r\n            max-width: 960px;\r\n            padding: 25px;\r\n        }\r\n\r\n        .header {\r\n            border-bottom: #ccc 1px dotted;\r\n            padding-bottom: 20px;\r\n            overflow: hidden;\r\n            vertical-align: middle;\r\n        }\r\n\r\n        .header div {\r\n            float: left;\r\n        }\r\n\r\n        footer {\r\n            color: #f6f8f8;\r\n            font-size: 12px;\r\n            margin-top: 10px;\r\n            text-align: center;\r\n        }\r\n\r\n        pre {\r\n            background-image: -webkit-repeating-linear-gradient(top, #efefef 0px, #efefef 22px, #e0e0e0 22px, #e0e0e0 44px);\r\n            background-image: -moz-repeating-linear-gradient(top, #efefef 0px, #efefef 22px, #e0e0e0 22px, #e0e0e0 44px);\r\n            background-image: -ms-repeating-linear-gradient(top, #efefef 0px, #efefef 22px, #e0e0e0 22px, #e0e0e0 44px);\r\n            background-image: -o-repeating-linear-gradient(top, #efefef 0px, #efefef 22px, #e0e0e0 22px, #e0e0e0 44px);\r\n            background-image: repeating-linear-gradient(top, #efefef 0px, #efefef 22px, #e0e0e0 22px, #e0e0e0 44px);\r\n            color: #555;\r\n            display:block;\r\n            font: normal 14px/22px Monaco, Monospace;\r\n            margin-bottom: 0;\r\n            overflow: auto;\r\n            padding: 0 1em;\r\n            white-space: pre-wrap;\r\n        }\r\n\r\n        footer a,\r\n        footer a:hover,\r\n        footer a:visited {\r\n            color: #6daf00;\r\n        }\r\n\r\n        a,\r\n        a:hover,\r\n        a:visited {\r\n            color: #e74c3c;\r\n        }\r\n    </style>\r\n</head>\r\n<body>\r\n    <div class=\"container\">\r\n        <div class=\"box\">\r\n            <div class=\"header\">\r\n                <img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHMAAACWCAYAAADtyrfXAAAwR0lEQVR4Xu2cB1gUVxeG71LEhmCldxQUFRBQQLpUC6IIghUbKAiKXRAr1l5i7SUmlth77/HXmGg0iUlMNJpijUZNTCzs+b87M+sCCyxo1IA7ed5nZ4dieXPKPfci01waNGjQUFJs3No4NG3Va2FYXFqERkAxsbKyqmlra3uidu3aIxwcHHTetUQ7j7b6th5ts12bdb4XHt/vRbN2KTl+UUkZ3i16amlsqcHCwkLP0tLyjI2NDdnb238CqZXfhcTaTdpp2zeJ7lC7SdvrzoEd/w6LT8sJjkkh/6jeBJFyj9CEeS5BnXQ1xtRghsvc3Px7a2trsrOzOwmhNd+myDpeMc51PNsdcvCKka+a4EjzsnxyQmIhsg1EtuxJHmEJ5BLUmer7xW/G51TWGFODiYmJNZxeQZQS0u639rjetETHprHVHb1j50LQU0ABUXHy71eb0j+LGa3p25B8W/WkxuHdCCmXiySIJKTgU5YukbU0xtRgbGxsBamXkXoJafcmorTxm5BYzydOt55P+551m7a/A6EEodSmvx+lrDSg2JQOdHqEHT0dyKh/VCA1ataFGvh3ED4H9ZQsXSPJpH7z72o4hNbWGFODkZGRCaReQNolNEePEKWR/6ZIRJiPk2/cGUAQShBKnpGtqUtWlLzjSl3yHlee/DpH0rBof3IP6UJezXsQF27XuC1ZubYm43qhVN0+gAztmv2mbx3Y5L2UdPLkyYrnz58P/uyzzwacOHFi8r59+8Zs2bKl/dKlSw3yC6hZs2Z1SD1hampKSLtPUUuTXldiw4COxoiwFfX9O7yAUHICXKh/bBQN3VyB2o1rQM1TYsl2aHmq1cGa3CCySXh3Cm/fT4hKq0atycQpnKrZ+lIVS2/St/J/AZkd3huBX3/9tezGjRuev/zyy+qff/750fXr1+nH7y7TV5cu0pkzZ+jQoUO0ffv23z/++OMeAwcOlOUTWhlsR9olpF05hGYj9ZZ4eYAOVM85sNNAdKgPIJQgVIALDWzZlnqnxlHnWY7UbDajeilW5BYdTS6h8eQbmUj884Papgip1rR+BFW386MqVlyknxwi098bkXfu3HH9/fffd//xxx85jx49osfXv6an00MoJ1Wfng63oxs75xGiVBC6bds2+dq1a6fNmjUrj6zq1avrQehyRCkh7fIoXQmp5YsjsVFwFxkalxB0oV9DKEEo6AhBnA7kFtyZLqwxp1srytOg3m2pcT9XMuypT87hscQ/PzQ2jRqHdRNEeiPV1qwTQAZcpKUvQeRkICvzEm/dulXh4cOHk/7888+nf//9Nz179oxycnJIfnAmnYivRq2sGE31ZJTTR49+PLlTiND9+/fT5s2b5atXrx6eXwqEaoEJtWrVkktpdy8wLEqkW0hXO7fgLp9AaA6EEie3ULfQjhSf4UMZg+PowdwK9CBLh4bHhZBLWBx5RnTndVJIsQGte5Otexuq4xFJhtZNIdKHi1wJtMu8yAcPHjj89ddf5//55x96/vy5KFEuJyKQ85x++ukahYSEEPIpfdmO0f0NWfTVV18Raijt3LmT1q9f/ww1VKWpqFq1qqxatWp9a9So8Rxpl0fpFxBqkV8i1oOVwCj30K5/QihBKDXiKIUKJIwKobTNjCLGWFGP7nH0XZ9q1L1lmCC9acteFBzdF8uQWCxNEsnWtYUkElgH7gR6ZV7k48ePQxCJ9/JKlK67V0nez5Cca+kSBFBFHUY3OjB6tHsm/fjjj3Tu3DkhOjdt2kRr1qw53K1btwJTGKRGIUr/5GkXa9JrqKUN+PMmEd21moR3i8aa8AfIJA6EEoRy8gj1bZ1EkQkDqO0YD3KbKCOzxFpIo53JHfKD2/UVainqJJqjeKqNiETDA5HeEBnwKUTql3mRiMa2T58+ffLixQuFxLzIc4hmh9OPcYyyPRidjGQkH25Dj27fIDRHdOnSJTp27BivnYRmSL5o0SIXVshlaGjojSi9hbRLSLu/13Zyi/Ns3n0/hMohlCCU1zpJKEcp1AdNTfOO/SkkNpX4qK5RTz+yjHaDaDFqw9qnCanYIwQTH/84qmrjoxB5GSLL/qDgyZMnYaiL/+SLRlX+fkS0JYNoWgDRh0n04s5VwtcSGiX67rvv6NNPP6Vdu3bxVEsrVqwYw8UVIbQOovSykbEpuQXFCDUOQglCOQUKxQ6IIDK0fSoFtu1DPniPz+WpGO+TCYMERGhPPoclK5eWZFQnULEE+Rki7d4HkXUh8gEXWdKLy+e1FR0vT7VCI7R3717auHEjrVq1ar/aea5VHXNX/zaPvVsKAiShILdQAKGSyHQKjYPI6GQhQj0lkYhEHpHCvSPqpGdYAkQGKETeh0iXMi8S9bEcRJ6VovGVZCI104MH9+nK1W/o6JmNtH7/GFq8oxfN3trizthDbBKYCIaCOFAbCEsXrAG1IWQll8R5KbRFXqFIu2hoxIjEviQFQaRv60QhipF6+TJFnABF9ECzk0RmDZqTab1gSaTfE4gMZO/DBZFdpYgsMX8+vUVf3VpHO7/pQwtPu9DEI5UIotSRA86OOSgL8GudlA2h5MMpRCiEKUXGQ2S7FKH5QQQLaRdLFGGch60vquMZQ03xteZOIYq15HOIjGHvy4Vm50Rx5cnx3+3HF+nY1bG09Kw7ZR/W4XJeicRZTs+xWSyHUMgpXKhHSAcKjEyglp0HUDOIxNcIz1FDhdSKUR4ktiMbtygyb9iSrJ0jIFJYS+ZAZPJ7IxJ1Thsy76uT+Mff1+nkT5No4ZmGNO6QFpfxWqQttULNS+QbxoKcPEIBhArR2CSsC5lb25OFpRX5RsSjc+0LyYp9SYXIGLLBQMDcuSWmO4G515JjVKY7ZXw4IEOa/bGgepkjf0FX7u2idV+2ovFH9F5LXvYhPRq/3p3aj2LUb0UtCo7rSQHoRAOwaewPIFUSChRCEZ1eobFU08iUjIxNyCssnnevgkjXoFz7khBp4dyKajkEcZGKJcgiiCybx0OG7mYyoFVIJ5sNocTBOpPu379Pt27fpNNfr6edZ8fT1k9H0cdH+9PS/R1p9p4AGr+/WolEDlytT+e/30MY8VGFSlXIp2WC0MBgGSEJ7SMKVUYpZPairon9aPPWHeTqGUgOrn7kj8gtYIOZLFwiycgxWLmWtArYApFl71jIsD3MIPswGzD7FPt6+gl2e+R+thVSmyvEXr16tdpvv/02/Pbt2zk3b94kzGMF+P2vv/5K2CmhH374gS5evEinTp0SlhxrNi6noevq05hiiOw4qhIdOrJfWK6cPPUpoqsDNYtJ4bVPFMopQGh42y702dkzdOH4JtqzsD91a+lBPmFxGBiobjAb1w3NJdL/GERWKlMSh+9hlcYfZoPnfMpuLTzLCCJp5klGS88xmnqcybP26R//+daVifdxYZhOGOERBupCZAJ+LzzDTgkfBmAW+5Mg9Pjx47R9x3bqPbcrJa4xKlJoTIYubd26ha5cuUK6uuWoZVwSBcf25XVPKbRdMqRKQqW0GxKTTF1SR9G+TUvp3pDqdDrGkD5rjWF+fGVq5hcubDDbN44WNphN6oXl2pf0uwiR1cuMxFH7K2hPPirrMusku8oFjj7AaNhuRkMlRuxjtPh/9enqrc+EqQ0W+0J6xRz2JWiIFPfCxyGVCxUi9OzZs4TNaBq3LIvaTvOmlM0Fi+wxS0YzZk2l06dP044dO6mRbwthYhPCKVRoMjVpBkk2dhTQqjM179CPhoyYQP6tUCMDO9DiuHq0JLCaEJHYYOb7krlF/gSRlmVG5OSjFf3HH5b9b+xBRohMyFNl0ekg+uPxbUEgpCkG6YWiGAggQoWUe+HCBTp8+DAtWbeQYqc2p8gF5WnUgbwih29llJgWK3z/YcOGUXSn3sJCH+QVCl4KBWGY6ljaOhD2PamOUyNBOtaSL4cCndsG0dHWumTeIBwimys3mC1970KkU9mpjbtlgRC4EMKWgQ3gCLgGnipEzjnhTo/+uidIVMhSd0Eoj1Ah7aK28m0uYZC+ccsG6jg9iiJm16C0rXlltkk2FcTfu3eP4rr2pghEGA4hUxhQCAXikFwSiugU15HRSWTv5IFmpxfvaKWhQCdh3to7pintaq4rNDs17P2loYDPY4j0VRFQRjvYmqBV9iHTTbf++JaKHKI/vEX00znwmXgvyYR8XkeFxuibb74R6ua2bVup+6x4aj7LlLp+pBTZbxWjTZs3EM4JUaeERIrsOhAy+3PyCpWk8qbHwTuGzLDYx0BdEOsnHlYmj9Dca8l2NL+7A41vXFkSKawln2EJEsnepwvRUv7e46urixzZ3bxMdOdHLk6A7l0j+uVioTJx3oeS53YTZMauVMocvSBSSMtLlq+BvFRq0SkdYziOUigQRCLqxCbGqTnVcAijqnbBGMlF8+mOciiAJQgONpO9RxRdTtOnIDtjxVoyByJ7vG8ia88+afW/f549piKvJw+FbhUHrfhxDmEJQr9+RfK/HijSrLBcwcGul/uVaR/0oohZtSh6uShy1C492rt/O3Xu2o1GTl4gpE0gCgUKoYhGYWmB9aEgsiZE4rgjn9hwUA9b8HlrnqFAu4imdLmzFlUxqsdFyrGWzHzfRLYD93d/27dY9ZEf1poxYwbJZDJydnYmykFtRdqFTKGjxbpT2Hw+cuQIlhxbqe/cnhQ+R5/aQeYYNF0J2dVoz74D1KxtDyG9tuoyMI9QRKRwCgByChGppHrtEL78ENeSkL6rjzGlN6xI+uaefC05p0xNd76986HOzJOVWmAIEImlhwPqol4uiTpgEsgB9NXN9UVbvPUd0fN/qFmzZsQYEwgMDBSeyX/+Mk83i/OydPDgQdTFTdRrVgcK/UCb2qNOjtzHyKKuHo2bOp9aJwyCTBGFUESjsEWlXqQSA9sgIUqb+fvQjV5aVLOWLUT6rYNInTIjcsMlF7u1XxoeWXWe0YovGC04w+QzTrCHGBJ8inXk3Kz9bC8i5WUdu/HgVNEyIY2uf0Hff/89RUVFUZs2bYR7unaWcp4+Iex3Kjae+ZFKYZ25buM6ipsRRCHzmNAARQ3RxhqxDbXpNpiiQOuEwYJMdLLCIWQ0MEqR9RUig7m0orH0pe2J1WmoSwWqZOZ1AM8qlBmRC85UbLfyvPbvfKoz+RijaScYYcpD/P2yzxktB5OPMsrcq5R57fcj6tPs/RtEP18Qj4SgftLV/xH9fv1lvcS4j7799ls+0hOOhCz+cAG1muFAwR8w6rSQkVd4CLXpPoQDmUOoNUT6YZbq5BenKtJRvcjKln5UydyLQrzq0dVuMjKpWutjPK9aJiRm7dPWnX1KNmXJOZYzEbKG5RsKDN7FaNBOcViA1JtH5rmfF6mXycl5LqZcgHvhaxQpFqfYhQbp6NGjQvMzatFwCp1dhYJmM/KP8xRFSoTHpQoHk+v5llwk6iEkeiMKm1A1S48X5/tWlA+tx65AQMUyIRKpswrmqjtnneKSlAKHQGDSRkZtlzEKRbprNpcJaa8N3vffppT58flIUj1tpx7FkuTu3bt5RnnrkWI7zgiloDky8updj6dVQWKrzunYtupOzgEdJZExKiKrFibSKoAqWzTlEgVsfes+39rP4OMzUSynii5rVyZEQl4NpM3TYw9KEYjo67eVUbd1jFouZhQ4p2DC5jPKkKIz+7Au3fzjKz4wKPEhLUSlcIQSkx9hfblz5w4atzSLwmeYUZM0S2rdbYAgM7hdH3SqnbGkKLFIpFQfCPQUJNao60rhQ2tQ1gYZPRrC/m5hxnZAgKwsTHDKI23+j6fUvpsZFudiBAZxYWrA5yHlKqNz9blQ+vufJ+oiNM88FssRoVZi14NHpXC4edm6JRQ7vRm59q1FLRNSKSKuL3lGdBGaHIgUpzXS2tBSENlCFGkfXEhdFCXqWzYm93grSvxQm/ptRgeO9D3bmz2AAOuyMo4bz+eecavYi4gF7BcIuoiI+xE8RUotVCT/WPImUSK6WoHR4MC3I4XOVHlSXXWoDtmiSGmnBPudfDkirC3XbfkYI7w4ckm0opBO3ck3MgEjOOFgslKkp3qRlYW66EWBLRMUKZXiZ1fk/8MKbF7J6FIfRn5j2Z8eU1gft8lMq7SLdEVNPJm6hSVCqDlqozZ/DrFaSL1BGXvYUy464WMmTGCaLxSjscUiRikQOfoAkCSOOqBAiw59O1EQBal5tr5wzyUK22LY3xQi8tq1a/Tll18KPz+yftvHlDinEzVIsKPG0S3IK7KzeF4VItVHpGpd5OdZt+zYR55da1DyRpnwe04G01A+7g1i1GOs2Au4T2bkOomtd57ADEqzTBugVcBUxwpcB6RgjCQM60u85hGIzlYki7OPI6ONXyTS7bu/kWJTGgjTH9RHodlBjeSpVdjuOn7iOC3+ZAF1mx1Lfpm2VDWwIjUKiS62yCo2XCSX6CNIrGoNmaaNqXPPAfTT9Z+o83wtQWIfkLGB0Z3RjLIGMuoJqe0RoYhKcpnIqOF4drF+Niv0NLrJUFbXeCgbCzYaD2HZ1fyYoYHdf7jWQlwVcEEpkZNPXgECR0hkcvaKjdG0w/XozLcb6ZdffxHGdBAonCaARN7sCDVy896NNHx5OrWfGUyhM2tS8wWMbAMZaePUgJ1zoDqRUl30fVkXK+P1g4WrSEdPX1irbt27mnojKnt/wigdIq9OYbQ4hVGnVYwS8b7DakaNJjFCVFKD8YzqjWO/OY5lbrkFmCYwe7PhbBVkPodIMh7MqFoQy4HItaDDf1IkpOmALYI8dQJV5EmgIRougREgkNGMQ+605fQYOvn5Tjp77jQdPLGflm9fSENX9KEOHzSlmIXmqNlawhIofTuj1E8YOTWTkba2NtW0dOLryIJFSnUREqWI9CKXxoHCAGLOnDm0Z88e8kuoJHzfFIi7OIvR9t6MYlEmeuF9z/WQ+iFSLI9KyERUUl2kXocx7EHtUczXJJjZmISzHWbJ7LnpMEgcKlK9FSNI5DwBV8F/r95C3uhCBXJ5xRSoXKOKDObs5Mho8PaK1G9TZUrdVJ7StmhhrcoFSuB+wHYtmnioLs087kX9Z/pQfRcHMqhpgZ3/CDJViLRrJtTFKhZefPMYIhtTFWNHWrV6DbVq1Uqoz5+e/pT8OhlSLwhLhrhzaNgOJzGKmStK7LFOpNMaCMxEVEKk0zhGiEqqgzRsl8H+MIlgv1mkMTIfzshEIXMII8OGokyJB6Dcf0ok5DUHzxUCs4onEPKKFjhIYuAOkQGc7XkFQijWtSIj9hrTnJMBOLEgMmFbAIW19SC9igY4HedNhjb+PJWK0xsbH8oYMw0ptQrVrVtX6JLnzZtH5z4/RyGJNQVpfcA5dN/HEhlFzxIFdpfo9jFkIs2adkc0Qmg9MSoJUUlW6HQtOHhuNlwZlUb9INA+j8zHoPx/RiTkmYPbRQrk8tQJ3JlL4I7iC0yTQFdN4w7UESTOPh5AsySmHwkgz1ZGJNPSpvLVagsi+w+fSBZ2zkINjoiIoPbt2xMuQWT0UGuhuekLLs5kdEgUCXkiCZyPOKLMKpEQ1QMSM8WotOcyUwDem2cwyp1iayYItZJy8fA/IxPSdCBw36sIHKxeoFJeEQI5fTmbGWUfqCcInJmbYwGUscOGTOoyYkxGOhVr0HVslQ0YMIAuX74sNFSLFy/GgP4k9ZjgLETfQIi6gmZnC0S2naMQqKQr6LKWUUfIrBrBqGJzRF03RjYQZzeSkTWi0VKMSmWKBTWi2Yt8Mu8Anf/KKC+1yAZGKU+9QC6uJAI3i6QAaQ2IyKz/UmDmbivK2mNPkw970Yjd9tQ8U9wH1dXV5cscYe/z888/J1zY+/yEek12R2rVptFoam4iwhb3hsj5XBxYK74mb4NoZKAB+8RxZYdVLMc8jD00DGFUAVKrd0I0DkBUIiIt8kUlp3pzlci88k6XJ4gILRAGtkDKPyoNjDqBatInKEgenmnToO361H+rXh6BfTifCCAyG9KMowE0Zp+T0IUmcjbIBLpDSAUDRpUrVxZmuriEIf3CxfModpwxUqsuLVjB6N5glIs0RjFLefSJdEVk9tsDkQdEBkBo8nZhafK3ZTPmYxzEvqgeiggNZ6TfBhGItGuUyqhWGu5TQQpEJiOKA5k8n8yj71KkKdgN5P22vW4Do14gQNeqQ6P22tDEgy40ap89vt4gj8DeHEhLAuMPuNG0IwH4miqK5QNQdqAmTozwI+18miQsQUaNy6TYidWpF6JuD6LwpxR8HqIpfiWjzmvBhyKpu7hAkXREZX+QiowTv5r92X4F09O3Z5WM/Fj/msHsW8NQlqMPsQaI1MqgfBgjvRAA0VU8JYlKZr8rkWbgCiAASSoCS9bAFCEQ6RMRWJ4G76gK4ZXxTLcwgVL0cWQ06VBTCPXILRAou0/rJoiSGjWEnysJCPGi9tMMaNAaRt9NZnS4F9LqeNTBNXz9CNaI9z0/UQrsJ5EG+u4RZtK/YwqkrRCgU4lV1LdjnpDbr5ITW1u5MfuqSiD7C1DFAMj0UpEZ/C5E6oGTgABkvJkGJgUM2m5I4w82pAmHXPBMN4/ApHwCe0lwccmfVKQphwNQJ524PKDagZo5M+EwmH5NLWo1kdEHPK2ils3ow6j1XKVAgBQq0neXJFAida9Iym5hl+hG7IoCa54OMAT2uPPVrc0SDbzZ7Gr+7IxUJy+BNCB7FzKng7/BXwDCCmpgwKs3MECGdGqP5sUfC383vNdB9BUqUCX6hqJjnQyZY/e55xKobGC6INr0jZFmrSBrFqMjkPcDJPYYgvq4TCkwXgRRB7kf5RXIozEFJIPekNxuBbtQDAEyoA10ytdkOlVsmeydSJREhoNJoB24D0HFqn9AkldkBwrEyBuy04hmHAtAdHlBpF6xBHYXQVRWoez9nhDZGLXVnxLXVxIFSnQGMQsY2TRllInXn8cw2tSTUeREiFuVW6ASpE/qtjGvwD6c3SK9kHWil7H9rLRckFEONAC+4CGgdHUNjHqBBda/zN22NA2daPrWapJA1QYGSweIq4wGpyY+zwSY0fCdjjThgB+2qaoiErVo5J5GGPvVlhoYZf3rAlnrFzK63Q81PhVpdX4egZAnEstZAfmg5xYuLi+9QRJIQEZps5StKK4AItIF1e79eaecZaae1rsS6gn+ABBW5ARGosDoU9fAoFaaCM2LagTKqP8WI0hyRtT5oskJoEkHRSZKZO12VUQg5rYmNG6fD95rv6x//SHrazQ5p3ohNWZxWYULbAcQcdQWIKKFdB2/Bs9XAi6dDww2gY14v1xnXHFF3v3ztya9P2m+0Hqk7vdGKewXg9osE+k2Esjelsg64BYg8PoCC69/EFYd0emgMv/M2OWoEAjZPjRshwOObZgipXrRBOGZHyLZ8GUE9v3EFCk3gJLW1xBq4GxIuYsmZ2YSoxYzChYIIEYkGkAkok6UmYwITEMWStmKSIXADnjWGqLDkK4jFlT8PGZZ7YSFJ0YaEpGsEJFaJ67udGuxzOpCnfHiRKiquET5B9wE3m9DpD64CEhJMeofkOSVpIFB6qyBpYi1SgeavsWcMnbWo7TNpniu8zJ9dvuoHKRaYmfDQBGBQAuf64bIDKB+G0xoH5qcq30QXQMgZ7FqBCoFKqJREglaL0FNXczfi5GZgCzRi3fUm/GKyOyKzBGDNB2+iJH/HJ1bgXMMJscuc7HML2DF2Sl2AQuqXnJCZjDLYGSUojJsn/E2ZM4HBJ6Bf1ugSgQO3GZBA7Za5O1AJZT1TyLf8gG1D891acj2BjQWIufsbELXJpej3T0YNR8LecuLFthGImopXiUiIbPlIh59/CShSMRC8cRhFARH87QLmdGr8AzvA+cx8pgqe9JoUvn5/jPNBKnp6+MNm0yv+JkrMoJlljjSq5Wksta8BGRvOr1yiUfANYgsoANVKxDiihYIII+/ymj0XneePlUFKuSpCpTQot6IwqzdXjRmbwCt2dyQfs/UpamJEDFTjUBIixJBJIpEqciUzvx+IB5G85vFyAfftykEeQMvznRGTYDbFEYNJjByGi977DhCZ4pVN60dfFvMdrRy4G6UrCLzKajxJmVOAXPAVgCRhdY/IMlTK1BlCwkS9LlA1Epnof712VhdvUBlB4q6aESZu5rQaEgcvSeAdn1kT7f6QW4qo1YLcslTIxDpVKAViFoiycR9i9wykbIDJJlcpOc0Ro0hzxXynFELGwKnbH50RHy1gziLnohI1T1NuYG9yoy22ZsSWRGkgQFSelVtYIonMH/9U0mhSRsMMCjwQBMTACGeWNhrqwhUXf+JJKytwgUKjNntT6dWmNP3vSFvMGQsKZlAgCjkSKIVMpFWw3PLnM3Id6ZSpiuk2faDuHRIHC2KdBwj7mvaDIZIPLfIyC0TDIJIB5Xdk9Q3JbMCqA+eAKTUktc/VYGF1j/ca0FqdQjWK1Kgagcqo/TNTjRqpzedX1iLziAKIrK4uDwCIa5ogS04C0WaA4XMVgqZ88UfqQjKJdN7OqISDY19f4hoI2LaC++RSh1GiacNbDNUtsKUR0dcVCJz+pvc4joAKBVAYkkFlryBKUKgUp5q/YuDtNMzZXQYjU7IWEhQIxDyVAVy+DJDIopL54JxHw6JIZAo/PARJPogGptMYtRoLKQNQsqMZ1QjlJE+qBjBqGp7RGEyonIoGAGZmUqZRojUWuniVpihj0rdXPymZIYCuRiVxWtg1AtUW/+ASvQV2YHGgE+R7g50Rwoc9+oCwzlStxrMT9tzYaMhDCKcIaE+IqnuQKTONERbslgHTTpBThSiLJjdN6jLthr5s3s1ghlVChFPHRjEMKrZAx/vK+5rVucdbGcIx9fohUF+gIrMjDclczcggLT6GgLVNzCQV5TAwhuYaHCID8u5yLG55JVYoMQ8sS4G8hSaLUqsAwnWSJ3mXSCvPcS0AS1xH4FnkGKNX9sujWVCQHVdA+Zc05tNN27GbguRGs4jVRSrj1dDPKsShHt/RpX9xGcGdQSJcnAKVH4TIs3B3wDbUiodqKpApbzXF7ico74D5WlwA5YJXyBCAkcWKlApT41ATgi+XzAQfj5mNqSvFO99URe9xoqR6olXb55iIdtpDNtXP1s4YumRS4AW9jINa/mwSETq+Jp+bGX1JmxllXpsvp4jW6RbFzRgc8u7sYlVm7Ksqo1Zd0hsBHTeVFR2At8DND0FC+ysRmC8AjUNTLviCsyXPmdAytVkyBiSS+DC4glUylMKFCUqCYbctigvbUCURGvOJ4hwlJuG4un1tuAqKOpknTYoByqAShzpXhdovY2pjw/4GiAi/6UGBsQUS6D6BiYN4u4OQiT3FaSpFzhPvcCgOSKBnNmQvTSvwEiJVmgE/ZdwkQLOYMJ/fcsrEMiRYtU2MOo70OKM0IrfgcaB60h1Q3pAzhy19U9V4NzCBQZI+IOINZLAjaLAlqAFaL4BKXaaIPIZqAq8/usy1wAMCP6NBgYUbwID1DcwB9GcrOvKyG/SvywQjZSfBJfZcoNCINggSowAgSteRuXPQAZ0/ssi9cFjwDvYnFcVWPIRmvoGZhokfdubkU9G4QJV658kML+8PAIBOlhfiaBFkKcQKBEOwtYrolJgV2k4VRANCDxENN587QZGTfosbgeaAO4MQ+RDZugH6hoYSV4xBfpwZjBqKhH6YV6BnFDgu0yQeAUQyCwNMpeAi9ji8oTAe+9OoDKFRkDc2SmMZnWBgKlqGhg1An0LEeg9XcR3riRPImSdSDAaQdcpgsQ1IAc0Kg0yLwBviDMBL4rVwCz9F0ZoRdS/6ZB2sRcjz4xXEDhTvUCvaSKeADVRKVCS2Ax4LxJEPgIjwXGg9V8XqQPOAS3Icy25wJJOYNQ3MO3B7eHIAolcnJoGRp3A6QUL5DSZivezuDylwCAQCALQ0TtPEmTuARNB09IQlVpgNL+HvJDXbWCUAlXSZ7EbmL2IlmWdETkT8wr0L6ZAbzUCG3OmiPgtlwRKBHA+wsfmcZECvUEbICstxyq1+SsEtnu9DlSdQPUNTCpeb/SFgPRiNjBqBEKeikAPzmQ8n62U5y/hh4j0WfVy2vMnqAV0WWm7IK9zCfYAX38Ck68DDQaXsxn17wJhM4rfwHgBUZ56ge7ATcJ3lVIgxxf4oKttNPNlVC5mpfWCwE5qGpjXEKi+gZmIZ5/1YNQoozgNjHqBkjylQD4sl/Ccz+WBD0WBTSUaLxa6Vjn4C9iUWpkQGPP6DYwkr4QTmAjwaxaanu5c3qsJ9ChSIEANdgVukN90jVKgt4TnKvai4ST2VBqkj2Cl+YLAsFdqYNQKVN/ALAQ70fS4jlLfwADIUydQkifhMkEC954rlAK9INUTNF7JyFlcU54HY4F2qZaJ6HN9fYEln8BE4P7WMER8TzUNzCsKdJbgp+g8FioFNuGsxjPIbSiKzAFhQIuV9gsCa0Hg8+LvAf47E5hlYF0nRM3oEgjk4ooWCHlKGmRD8GwuT6SxhMcqiFbOXreWCZEcCNSBvN9UBL7BCUwY7m8PRWT3VNPAqBHoXIhATn3AhTWGOA9JoDtw46yUXcTh5euQ+FDR8JQZIHCfuIX0JgSq1r9FeL6+IwSMKm4DAyYUQyA/kCxRH8LdV0gCJRpxVrLf3OeXawSJv4MerKxdkDcKvMYIrfgNTCBebw1H5Hd/tfrHgQRRXj6B9ThjAU+vSyV5wHWlAtljt+W6jSFxGpgHZGVOJgT65JGnRmBTtQILr39TIHtHJwjILIZAlegrXGBdzhjx1XmBUqALcOasYE9dluq0hEDOVKDLyuIFgeUg8GbJRmgln8B4gmv8FDpfjhTWwKgXKMlTCnSUcBgN0bPzCKSGnOXsecMlWp24AIXEMg0Ezv1XJjCcQurfAEg/h/RaZ2DJBNZTI5BTB9SdKskDDZaL1F8GydmyCex9uiDRBQJz3tQEhnMaUpLjIC27cIFOxRRYR6L2KJE6PJKXSQIliU5LGFmhYzbCmVb2vl2Qt//1BRacPqMg+ee+kNEHAtU0MOoFKrEfCSDYaRHgApciikHdxYwsu3ORAt/joLLsvZIJgX6Ql6N+hFbyDnQlJM+KhaCRBQtUlVe0QDsJW+A4VxK4RMRhISOLrpJIYBzInhgHs8rvlUzIkyH6Nr2eQNX06QZ+G4Z63OXVBNrnF5glYgNqT4PMJSIOiyF+HiOzeElkAEQ2Y2QSxnJMmzMj9r5dEGgLgQ/V1L8SNTBpiOITiBSbAYULVI2+QgSOELEGtuO5QEkisEcXbtoWEv15NEJiCN5HQG4r9sK8NavB3scLAhPzC3QBorySd6D7uNAYLk2l/qkVaJNHIMhkZAWsufSFYJGIzSQIbCFGo0kwJIZDYkvxJ7gsotkDixhW/r2UCYkyCPyo4PRZsgamCV7vDoTgbuoFQp4SpUxI5AJFLDMAXu3mQDxk2i0Q3xuHgCCIDIXI5hAZCZGIUstYyI9np9j7fEGiPgSeKcEEBqimz1RE9L5OEDGwaIFSBOI+b3PDn1uNECVacIZD7hRRou0HkJYiSFSNxnYQGQeRnfD5XdlI9r5fkGgEgV9D4Ct3oMshPysacrJAIQIB0ifg91wmFz5aBEIhUxRpDpEWYyF4Pp5Nh8B43uAoo9E8EhIV0dgBErvgc7uzpzY9hJ0RzQWJZhB4Sf0EBhSQPs9DRIt4FYHK+idhKb5CpiixzlgwDmJxb41n5pBpxj9nDu4h17hlngaHzNtAZAxEQrBVZ0hEWrftCZLYMo3FXEBgDQg8AnklamBc8ex2OgR1K1SgMn1KtdAGX1ebp+vxHPHeeiSXCbIhMFGsjyZhENkCz1rzBgcS20NiRyGlEiKRSyS7FHbHPoWZaQzmAxLLQ+I8CJRDXLHqXwJS7FFEiWlaIQKHQ0YuLBQyIa3uJJE62ULnCtHa31l20Z2OaHxWUDRaK6KxFyT2QXSnsmf2/VhLjblCgDwZiIW8O6oCVZcQC5Amx/H0NwwUINBsmIiphDmXCXEOiEinKSIO6KLdp9bctefrTdbPXzzTs2ylE4Ro/LawaEQkUu1+7O/a6ayzxlgxgEQzCFwLgTlKgarRdxGvYTGqAhXyTIaKGAMThUxeg9EB1+dndNDk1JuMbnpy5QtPnv1lRkQVgBY61UroVFMRjV8jGnNsExGNyUI0voDEw9iVcddYKgEQKINAP0TgqYLqnzvk3kyFtK6FCQRDGBmJ4L0o03YsBCIiXWeB2ZA6VUi7Oakb2wcRUUWgpRCATlULIm0gMhgig2v3ZxYaM68BJMogMQwCDyHyXiiiLx0p9pNYRrXSChE4GB+T4O9N8XVWI8W06jwDqXUuIzfQcLq4veU53WwsEVVSyNTwBoFEGSQ2AFMh7uFO1L6eUVyeEqP8KFOssOyw5uM+PjZEVHrMAx9wsaLMutmVdhNRZaCtEfAWcRjKzt8ZhBrWHqIGAy6zUKR6mSF2rY6TCpA5ge9Z6n4jJ7m+RuZbJnU0u3wUXWaNXhA1qAAG58UUQs2HicsSR4hzgUCPuSLO08Xu1naU9q/Pc55rZL5tLoxhn/dvCUnpYKAqJrmBXFNgLv3LkI7ZkDkVImeLOOPegU+CRmpfl8tzNDLfJrSIGfw1iN13bMtl5mNAwZhDpiVk2o0Q576uENh4JmQC58mQOQaM0jujqZlvGZrH4g/GoUvtxsisfyGkKzEfCJFItbbDIWykuEPjDplNuMzpkDmRi8TrWMOlmm72LSMfy/YMcGc3zdKwTEmDrH4iZvkwh1QLRKU1otIO9dIxi1GDsdL5Wkj04jKnigehHfCxyLmNYqWhgUwj4O2kWNsHyeypQxWWYZ7KDgJSIU3EEjJt+B4n0ms9yHIZB3mTxFOBTSHSa7p4/qgBP3mXVe6Hy79dMCGicnK5XCPzbUAz2NjVPuwJbi0s+rIgIAeUH0vItIZM+8EQmYEaCWGNkU69p0mHryHSc4r4b73WQx2NmtMomYgMgI5GwNuJygovhrFfo8zZRsUzi2S2EZBAihIrRKgt6qXDENRIRKU7pHlNhsipEAk8EaEe2eLHPEYbHLj76KYpEZXXpNi3BH3AupyKZDm6WixQ8cyyDzMGNwC9BGKtEZ12iMy6iEznEZA5FgLHgwmI0GyAlNtyARdZ7uqK4zMaEtFbXJJoolJHPpKd71Obnc3/rx5b9mZeVr3Zc7ySQBKj+gMhbjREDhNpjG41EJEZPotRi7mMIvgaM0vn56EfJngTURWgqxHwlqD5LOrr9iynii5rn1+0VRLTtkpkP1tDog1k4p4sEhCVyRA6nJEfRAagZjZDRIagbvrivVPfcmd6Tox2f/jwYWUu8m02PZqoHMW+SHVgX+FtgQ2KdS92vG4/RFsmmhpEYn3US/s+ENudkXk8o+ohjGqEQXKc7J5TT8OsmcsnGf3xxx+8Rmq/XZGaWtn1i3ZCVLYrdO+zF1vuivoYjm41At1qECLQi2938c42ATKbyW7U8is3JayXt/Xdu3f1eNf69ocDmqjUfzGcXe9iw04po1IV2x4swxnRGMZ/DB7NjWcmhPJzuP0RnV1ZTjV3nRhHR8cqT58+1Xp3kahZV075JIg91ZExj6IE2PVgsc5Is01HIMUiGp1SxFpZP1U4hLVDR0/7HTc4mqbH904Se+pajU1Ve1QzsZxb3SQ0PWiA7LqxXx0T2Q13dLSOSeyxbTfmqBHwbtOr0YsMdq1PHfYN3lZUJ8Cum6yabQJ7BpaDGhC6vHYPllO7u+xdn6DTTHrk2ezgMm/2EAMCt+IIgEAZ8Mn1figYoBHwbkWWp0ls494w9sy4PIt9VQEQWVEj4N2KrC4fz3YfCGfPrSqxJI2A0ilRi+ay1i+GsmurfNhD4wqsvUZA6ZFXiRYwR/lM1oKy2YicIez8VzEsJ9GeHSynxeppBPzXI28+c0dTky0fzD79J5k9+gFz1sOh7J/V3uzHvnXYyup6rJligK7hvypxDouWD2fnfohnOUs82U/9HNmC+oasA4YAThBQGZSCaYxGpCkicfdFzFTTHNj+auVYCB6XwimMRqTNi0x2ZaEnu4/lRVzpTZ8akZXlo9n5aW7sFlKpi0ZAKYZmssyDWCdW0mHhGgGlfHqDteJvLc3YRk1jU7qp9GM2C74Ux+RIr2EaAaWXyitWrFj4+eJ2X3wUoPVcR0fHViOglFKjRo0Gu3btenBt32Q6lu5N6enpfLdCc2yxNJGRkVFOT09PJyUlJX3r1q20a+cO+ujD1TRixIhxiiMeGkoBFSpUkH3//fcHjx8/vn/VqlVnt2/fTqdOnaKVK1fSoEGDJmtkliK2bdtmceXKlaeff/45bdiwgf73v//RsWPHaO3atfJOnTpFaQYFpYgvvvgi6aeffqLPPvvsGU+xly5dor1799L8+fMvowGqpRFQijhw4EDTX3/9Vb579+5vDh8+zKUSl5qZmZkNAeU0AkoR+/fvr3727NnkLFxffvml/MSJE/TRRx/91aRJE2fNwKB0Ips0aVKL8+fP30KkyufMmbNT2NbSXKUWXTMzM3OsLVslJSV5aKKy9PF/RWUQ1GVh9WcAAAAASUVORK5CYII=\" width=\"115\" height=\"150\" alt=\"Error Image\" />\r\n                <div>\r\n                    <h1>500 - Internal Server Error</h1>\r\n                    <p>Something went horribly, horribly wrong while servicing your request.</p>\r\n                    <p>We're sorry &#9785;</p>\r\n                </div>\r\n            </div>\r\n\r\n            <div>\r\n                <h2>Error Details</h2>\r\n                <pre>{{ Model.ErrorMessage }}</pre>\r\n            </div>\r\n        </div>\r\n        <footer>\r\n            Powered by <a href=\"http://nancyfx.org\" target=\"_blank\">Nancy</a>. Graphics courtesy of the awesome <a href=\"http://theoatmeal.com/\" target=\"_blank\">Matthew Inman</a>\r\n        </footer>\r\n    </div>\r\n</body>\r\n</html>\r\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Markdown/MarkDownViewEngine.cs",
    "content": "namespace Nancy.ViewEngines.Markdown\r\n{\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Text.RegularExpressions;\r\n\r\n    using HeyRed.MarkdownSharp;\r\n\r\n    using Nancy.Responses;\r\n    using Nancy.ViewEngines.SuperSimpleViewEngine;\r\n\r\n    /// <summary>\r\n    /// Viewengine for rendering Markdown\r\n    /// </summary>\r\n    public class MarkDownViewEngine : IViewEngine\r\n    {\r\n        private readonly SuperSimpleViewEngine engineWrapper;\r\n\r\n        /// <summary>\r\n        /// A regex for removing paragraph tags that the parser inserts on unknown content such as @Section['Content']\r\n        /// </summary>\r\n        /// <remarks>\r\n        ///  &lt;p>\t\t- matches the literal string \"&lt;p>\"\r\n        ///  (\t\t- creates a capture group, so that we can get the text back by backreferencing in our replacement string\r\n        ///  @\t\t- matches the literal string \"@\"\r\n        ///  [^&lt;]*\t- matches any character other than the \"&lt;\" character and does this any amount of times\r\n        ///  )\t\t- ends the capture group\r\n        ///  &lt;/p>\t- matches the literal string \"&lt;/p>\"\r\n        /// </remarks>\r\n        private static readonly Regex ParagraphSubstitution = new Regex(\"<p>(@[^<]*)</p>\", RegexOptions.Compiled | RegexOptions.IgnoreCase);\r\n\r\n        /// <summary>\r\n        /// Gets the extensions file extensions that are supported by the view engine.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> instance containing the extensions.</value>\r\n        /// <remarks>The extensions should not have a leading dot in the name.</remarks>\r\n        public IEnumerable<string> Extensions\r\n        {\r\n            get { return new[] { \"md\", \"markdown\" }; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"MarkDownViewEngine\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"engineWrapper\">The <see cref=\"SuperSimpleViewEngine\"/> that should be used by the engine.</param>\r\n        public MarkDownViewEngine(SuperSimpleViewEngine engineWrapper)\r\n        {\r\n            this.engineWrapper = engineWrapper;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initialise the view engine (if necessary)\r\n        /// </summary>\r\n        /// <param name=\"viewEngineStartupContext\">Startup context</param>\r\n        public void Initialize(ViewEngineStartupContext viewEngineStartupContext)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Renders the view.\r\n        /// </summary>\r\n        /// <param name=\"viewLocationResult\">A <see cref=\"ViewLocationResult\"/> instance, containing information on how to get the view template.</param>\r\n        /// <param name=\"model\">The model that should be passed into the view</param>\r\n        /// <param name=\"renderContext\">The render context.</param>\r\n        /// <returns>A response.</returns>\r\n        public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)\r\n        {\r\n            var response = new HtmlResponse();\r\n\r\n            var html = renderContext.ViewCache.GetOrAdd(viewLocationResult, result =>\r\n                                                                                {\r\n                                                                                    return ConvertMarkdown(viewLocationResult);\r\n                                                                                });\r\n\r\n\r\n\r\n            var renderHtml = this.engineWrapper.Render(html, model, new MarkdownViewEngineHost(new NancyViewEngineHost(renderContext), renderContext, this.Extensions));\r\n\r\n            response.Contents = stream =>\r\n            {\r\n                var writer = new StreamWriter(stream);\r\n                writer.Write(renderHtml);\r\n                writer.Flush();\r\n            };\r\n\r\n            return response;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Converts the markdown.\r\n        /// </summary>\r\n        /// <returns>\r\n        /// HTML converted from markdown\r\n        /// </returns>\r\n        /// <param name='viewLocationResult'>\r\n        /// View location result.\r\n        /// </param>\r\n        public string ConvertMarkdown(ViewLocationResult viewLocationResult)\r\n        {\r\n            string content;\r\n            using (var reader = viewLocationResult.Contents.Invoke())\r\n                content = reader.ReadToEnd();\r\n\r\n            if (content.StartsWith(\"<!DOCTYPE html>\"))\r\n            {\r\n                return MarkdownViewengineRender.RenderMasterPage(content);\r\n            }\r\n\r\n            var parser = new Markdown();\r\n            var html = parser.Transform(content);\r\n            return ParagraphSubstitution.Replace(html, \"$1\");\r\n        }\r\n    }\r\n}\r\n\r\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Markdown/MarkdownViewEngineHost.cs",
    "content": "﻿namespace Nancy.ViewEngines.Markdown\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    using HeyRed.MarkdownSharp;\r\n\r\n    using Nancy.ViewEngines.SuperSimpleViewEngine;\r\n\r\n    public class MarkdownViewEngineHost : IViewEngineHost\r\n    {\r\n        private readonly IViewEngineHost viewEngineHost;\r\n        private readonly IRenderContext renderContext;\r\n        private readonly IEnumerable<string> validExtensions;\r\n        private readonly Markdown parser;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"MarkdownViewEngineHost\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"viewEngineHost\">A decorator <see cref=\"IViewEngineHost\"/></param>\r\n        /// <param name=\"renderContext\">The render context.</param>\r\n        /// <param name=\"viewExtensions\">The allowed extensions</param>\r\n        public MarkdownViewEngineHost(IViewEngineHost viewEngineHost, IRenderContext renderContext, IEnumerable<string> viewExtensions)\r\n        {\r\n            this.viewEngineHost = viewEngineHost;\r\n            this.renderContext = renderContext;\r\n            this.validExtensions = viewExtensions;\r\n            this.Context = this.renderContext.Context;\r\n            this.parser = new Markdown();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Context object of the host application.\r\n        /// </summary>\r\n        /// <value>An instance of the context object from the host.</value>\r\n        public object Context { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Html \"safe\" encode a string\r\n        /// </summary>\r\n        /// <param name=\"input\">Input string</param>\r\n        /// <returns>Encoded string</returns>\r\n        public string HtmlEncode(string input)\r\n        {\r\n            return this.viewEngineHost.HtmlEncode(input);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the contents of a template\r\n        /// </summary>\r\n        /// <param name=\"templateName\">Name/location of the template</param>\r\n        /// <param name=\"model\">Model to use to locate the template via conventions</param>\r\n        /// <returns>Contents of the template, or null if not found</returns>\r\n        public string GetTemplate(string templateName, object model)\r\n        {\r\n            var viewLocationResult = this.renderContext.LocateView(templateName, model);\r\n\r\n            if (viewLocationResult == null)\r\n            {\r\n                return \"[ERR!]\";\r\n            }\r\n\r\n            string templateContent;\r\n            using (var reader = viewLocationResult.Contents.Invoke())\r\n                templateContent = reader.ReadToEnd();\r\n\r\n            if (viewLocationResult.Name.ToLower() == \"master\" && validExtensions.Any(x => x.Equals(viewLocationResult.Extension, StringComparison.OrdinalIgnoreCase)))\r\n            {\r\n                return MarkdownViewengineRender.RenderMasterPage(templateContent);\r\n            }\r\n\r\n            if (!validExtensions.Any(x => x.Equals(viewLocationResult.Extension, StringComparison.OrdinalIgnoreCase)))\r\n            {\r\n                using (var reader = viewLocationResult.Contents.Invoke())\r\n                    return reader.ReadToEnd();\r\n            }\r\n\r\n            return parser.Transform(templateContent);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a uri string for a named route\r\n        /// </summary>\r\n        /// <param name=\"name\">Named route name</param>\r\n        /// <param name=\"parameters\">Parameters to use to expand the uri string</param>\r\n        /// <returns>Expanded uri string, or null if not found</returns>\r\n        public string GetUriString(string name, params string[] parameters)\r\n        {\r\n            return this.viewEngineHost.GetUriString(name, parameters);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Expands a path to include any base paths\r\n        /// </summary>\r\n        /// <param name=\"path\">Path to expand</param>\r\n        /// <returns>Expanded path</returns>\r\n        public string ExpandPath(string path)\r\n        {\r\n            return this.viewEngineHost.ExpandPath(path);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the anti forgery token form element\r\n        /// </summary>\r\n        /// <returns>String containing the form element</returns>\r\n        public string AntiForgeryToken()\r\n        {\r\n            return this.viewEngineHost.AntiForgeryToken();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Markdown/MarkdownViewengineRender.cs",
    "content": "﻿namespace Nancy.ViewEngines.Markdown\r\n{\r\n    using System;\r\n    using System.Text.RegularExpressions;\r\n\r\n    using HeyRed.MarkdownSharp;\r\n\r\n    public static class MarkdownViewengineRender\r\n    {\r\n        /// <summary>\r\n        /// A regex for removing paragraph tags that the parser inserts on unknown content such as @Section['Content']\r\n        /// </summary>\r\n        /// <remarks>\r\n        ///  &lt;p>\t\t- matches the literal string \"&lt;p>\"\r\n        ///  (\t\t- creates a capture group, so that we can get the text back by backreferencing in our replacement string\r\n        ///  @\t\t- matches the literal string \"@\"\r\n        ///  [^&lt;]*\t- matches any character other than the \"&lt;\" character and does this any amount of times\r\n        ///  )\t\t- ends the capture group\r\n        ///  &lt;/p>\t- matches the literal string \"&lt;/p>\"\r\n        /// </remarks>\r\n        private static readonly Regex ParagraphSubstitution = new Regex(\"<p>(@[^<]*)</p>\", RegexOptions.Compiled | RegexOptions.IgnoreCase);\r\n\r\n        /// <summary>\r\n        /// Renders stand alone / master page\r\n        /// </summary>\r\n        /// <param name=\"templateContent\">Template content</param>\r\n        /// <returns>HTML converted to markdown</returns>\r\n        public static string RenderMasterPage(string templateContent)\r\n        {\r\n            var second =\r\n               templateContent.Substring(\r\n                   templateContent.IndexOf(\"<!DOCTYPE html>\", StringComparison.OrdinalIgnoreCase),\r\n                   templateContent.IndexOf(\"<body\", StringComparison.OrdinalIgnoreCase));\r\n\r\n            var third = templateContent.Substring(second.Length);\r\n\r\n            var forth = templateContent.Substring(second.Length, third.IndexOf(\">\", StringComparison.Ordinal) + 1);\r\n\r\n            var header = second + forth;\r\n\r\n            var toConvert = templateContent.Substring(header.Length,\r\n                                                      (templateContent.IndexOf(\"</body>\", StringComparison.Ordinal) -\r\n                                                       (templateContent.IndexOf(forth, StringComparison.Ordinal) + forth.Length)));\r\n\r\n            var footer =\r\n                templateContent.Substring(templateContent.IndexOf(\"</body>\", StringComparison.OrdinalIgnoreCase));\r\n\r\n            var parser = new Markdown();\r\n\r\n            var html = parser.Transform(toConvert.Trim());\r\n\r\n            var serverHtml = ParagraphSubstitution.Replace(html, \"$1\");\r\n\r\n            //TODO: The \"Replace\" is simply for unit testing HTML/MD strings. Probably needs improving\r\n            return string.Concat(header, serverHtml, footer).Replace(\"\\r\\n\", \"\").Replace(\"\\n\", \"\").Replace(\"\\r\", \"\");\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Markdown/Nancy.ViewEngines.Markdown.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <Description>Enables using Markdown with Nancy.</Description>\n    <PackageTags>$(PackageTags);View Engine;Markdown</PackageTags>\n    <TargetFrameworks>netstandard2.0;net452</TargetFrameworks>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <PackageReference Include=\"Markdown\" Version=\"2.2.0\" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Nustache/Nancy.ViewEngines.Nustache.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <Description>Enables using the Nustache view engine with Nancy.</Description>\n    <PackageTags>$(PackageTags);View Engine;Nustache</PackageTags>\n    <TargetFramework>net452</TargetFramework>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <PackageReference Include=\"Nustache\" Version=\"1.13.8.22\" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Nustache/NustacheViewEngine.cs",
    "content": "﻿namespace Nancy.ViewEngines.Nustache\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n\r\n    using global::Nustache.Core;\r\n\r\n    using Nancy.Responses;\r\n\r\n    /// <summary>\r\n    /// View engine for rendering nustache views.\r\n    /// </summary>\r\n    public class NustacheViewEngine : IViewEngine\r\n    {\r\n        /// <summary>\r\n        /// Gets the extensions file extensions that are supported by the view engine.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> instance containing the extensions.</value>\r\n        /// <remarks>The extensions should not have a leading dot in the name.</remarks>\r\n        public IEnumerable<string> Extensions\r\n        {\r\n            get { return new[] { \"nustache\" }; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initialise the view engine (if necessary)\r\n        /// </summary>\r\n        /// <param name=\"viewEngineStartupContext\">Startup context</param>\r\n        public void Initialize(ViewEngineStartupContext viewEngineStartupContext)\r\n        {\r\n        }\r\n\r\n        private Template GetOrCompileTemplate(ViewLocationResult viewLocationResult, IRenderContext renderContext)\r\n        {\r\n            var viewFactory = renderContext.ViewCache.GetOrAdd(\r\n                viewLocationResult,\r\n                x =>\r\n                {\r\n                    using (var reader = x.Contents.Invoke())\r\n                        return this.GetCompiledTemplate<dynamic>(reader);\r\n                });\r\n\r\n            var view = viewFactory.Invoke();\r\n\r\n            return view;\r\n        }\r\n\r\n        private Func<Template> GetCompiledTemplate<TModel>(TextReader reader)\r\n        {\r\n            var template = new Template();\r\n            template.Load(reader);\r\n\r\n            return () =>{\r\n                return template;\r\n            };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Renders the view.\r\n        /// </summary>\r\n        /// <param name=\"viewLocationResult\">A <see cref=\"ViewLocationResult\"/> instance, containing information on how to get the view template.</param>\r\n        /// <param name=\"model\">The model that should be passed into the view</param>\r\n        /// <param name=\"renderContext\"></param>\r\n        /// <returns>A response</returns>\r\n        public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)\r\n        {\r\n            return new HtmlResponse\r\n            {\r\n                Contents = stream =>\r\n                {\r\n                    var template =\r\n                        this.GetOrCompileTemplate(viewLocationResult, renderContext);\r\n\r\n                    var writer =\r\n                        new StreamWriter(stream);\r\n\r\n                    template.Render(model, writer, new TemplateLocator(name => this.GetPartial(renderContext, name, model)));\r\n                }\r\n            };\r\n        }\r\n\r\n        private Template GetPartial(IRenderContext renderContext, string name, dynamic model)\r\n        {\r\n            var view = renderContext.LocateView(name, model);\r\n            return this.GetOrCompileTemplate(view, renderContext);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/AttributeValue.cs",
    "content": "﻿namespace Nancy.ViewEngines.Razor\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// Class to represent attribute values and, more importantly, \r\n    /// decipher them from tuple madness slightly.\r\n    /// </summary>\r\n    public class AttributeValue\r\n    {\r\n        public Tuple<string, int> Prefix { get; private set; }\r\n\r\n        public Tuple<object, int> Value { get; private set; }\r\n\r\n        public bool IsLiteral { get; private set; }\r\n\r\n        public AttributeValue(Tuple<string, int> prefix, Tuple<object, int> value, bool isLiteral)\r\n        {\r\n            this.Prefix = prefix;\r\n            this.Value = value;\r\n            this.IsLiteral = isLiteral;\r\n        }\r\n\r\n        public static implicit operator AttributeValue(Tuple<Tuple<string, int>, Tuple<object, int>, bool> value)\r\n        {\r\n            return new AttributeValue(value.Item1, value.Item2, value.Item3);\r\n        }\r\n\r\n        public static implicit operator AttributeValue(Tuple<Tuple<string, int>, Tuple<string, int>, bool> value)\r\n        {\r\n            return new AttributeValue(\r\n                value.Item1, new Tuple<object, int>(value.Item2.Item1, value.Item2.Item2), value.Item3);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/CSharp/CSharpClrTypeResolver.cs",
    "content": "namespace Nancy.ViewEngines.Razor.CSharp\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Web.Razor.Tokenizer.Symbols;\r\n\r\n    /// <summary>\r\n    /// Resolves C# type name to CLR type\r\n    /// </summary>\r\n    internal class CSharpClrTypeResolver : ClrTypeResolver<CSharpSymbolType, CSharpSymbol>\r\n    {\r\n        public CSharpClrTypeResolver(RazorAssemblyProvider razorAssemblyProvider)\r\n            : base(razorAssemblyProvider, CSharpSymbolType.Identifier, CSharpSymbolType.Keyword, CSharpSymbolType.Dot, CSharpSymbolType.WhiteSpace, CSharpSymbolType.LeftBracket, CSharpSymbolType.RightBracket)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Dequeues symbols '>' representing end of generic arguments\r\n        /// </summary>\r\n        /// <returns>Returns true if move was successful</returns>\r\n        protected override bool MoveOutOfGenericArguments()\r\n        {\r\n            if (this.Symbols.Peek().Type == CSharpSymbolType.GreaterThan)\r\n            {\r\n                this.Symbols.Dequeue();\r\n\r\n                return true;\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Dequeues symbol ',' and whitespace representing separator between generic arguments\r\n        /// </summary>\r\n        protected override void MoveToNextGenericArgument()\r\n        {\r\n            while (this.Symbols.Peek().Type == CSharpSymbolType.WhiteSpace || this.Symbols.Peek().Type == CSharpSymbolType.Comma)\r\n            {\r\n                this.Symbols.Dequeue();\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// equeues symbol '&lt;' representing begin of generic arguments\r\n        /// </summary>\r\n        /// <returns>Returns true if move was successful</returns>\r\n        protected override bool MoveToGenericArguments()\r\n        {\r\n            if (this.Symbols.Peek().Type != CSharpSymbolType.LessThan)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            this.Symbols.Dequeue();\r\n\r\n            return true;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets CLR from name (keyword) used by C#\r\n        /// </summary>\r\n        /// <param name=\"typeName\">Type name to resolve</param>\r\n        /// <returns>CLR type</returns>\r\n        protected override Type ResolvePrimitiveType(string typeName)\r\n        {\r\n            var primitives = new Dictionary<string, Type>\r\n            {\r\n                {\"string\", typeof (string)},\r\n                {\"byte\", typeof (byte)},\r\n                {\"sbyte\", typeof (sbyte)},\r\n                {\"short\", typeof (short)},\r\n                {\"ushort\", typeof (ushort)},\r\n                {\"int\", typeof (int)},\r\n                {\"uint\", typeof (uint)},\r\n                {\"long\", typeof (long)},\r\n                {\"ulong\", typeof (ulong)},\r\n                {\"float\", typeof (float)},\r\n                {\"double\", typeof (double)},\r\n                {\"decimal\", typeof (decimal)},\r\n                {\"char\", typeof (char)},\r\n                {\"bool\", typeof (bool)},\r\n                {\"object\", typeof (object)},\r\n            };\r\n            Type type;\r\n            return primitives.TryGetValue(typeName, out type) ? type : null;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/CSharp/CSharpRazorViewRenderer.cs",
    "content": "﻿namespace Nancy.ViewEngines.Razor.CSharp\r\n{\r\n    using System;\r\n    using System.CodeDom.Compiler;\r\n    using System.Collections.Generic;\r\n    using System.Web.Razor;\r\n    using Microsoft.CSharp.RuntimeBinder;\r\n\r\n    /// <summary>\r\n    /// Renderer for CSharp razor files.\r\n    /// </summary>\r\n    public class CSharpRazorViewRenderer : IRazorViewRenderer, IDisposable\r\n    {\r\n        /// <summary>\r\n        /// Gets the assemblies.\r\n        /// </summary>\r\n        public IEnumerable<string> Assemblies { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the extension this view renderer supports.\r\n        /// </summary>\r\n        public string Extension\r\n        {\r\n            get { return \"cshtml\"; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"SetBaseTypeCodeGenerator\"/> that should be used with the renderer.\r\n        /// </summary>\r\n        public Type ModelCodeGenerator { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the host.\r\n        /// </summary>\r\n        public RazorEngineHost Host { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the provider that is used to generate code.\r\n        /// </summary>\r\n        public CodeDomProvider Provider { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"CSharpRazorViewRenderer\"/> class.\r\n        /// </summary>\r\n        public CSharpRazorViewRenderer(RazorAssemblyProvider razorAssemblyProvider)\r\n        {\r\n            this.Assemblies = new List<string>\r\n            {\r\n                typeof(Binder).Assembly.Location\r\n            };\r\n\r\n            this.ModelCodeGenerator = typeof(ModelCodeGenerator);\r\n\r\n            this.Provider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider();\r\n\r\n            this.Host = new NancyRazorEngineHost(new CSharpRazorCodeLanguage(), razorAssemblyProvider);\r\n\r\n            this.Host.NamespaceImports.Add(\"Microsoft.CSharp.RuntimeBinder\");\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.\r\n        /// </summary>\r\n        public void Dispose()\r\n        {\r\n            if (this.Provider != null)\r\n            {\r\n                this.Provider.Dispose();\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/CSharp/NancyCSharpRazorCodeParser.cs",
    "content": "﻿namespace Nancy.ViewEngines.Razor.CSharp\r\n{\r\n    using System.Globalization;\r\n    using System.Linq;\r\n    using System.Web.Razor.Parser;\r\n    using System.Web.Razor.Text;\r\n    using System.Web.Razor.Tokenizer.Symbols;\r\n\r\n    /// <summary>\r\n    /// Nancy razor parser for csharp files.\r\n    /// </summary>\r\n    public class NancyCSharpRazorCodeParser : CSharpCodeParser\r\n    {\r\n        private readonly RazorAssemblyProvider razorAssemblyProvider;\r\n        private bool modelStatementFound;\r\n        private SourceLocation? endInheritsLocation;\r\n        private readonly ClrTypeResolver<CSharpSymbolType, CSharpSymbol> clrTypeResolver;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancyCSharpRazorCodeParser\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"razorAssemblyProvider\">An <see cref=\"RazorAssemblyProvider\"/> instance.</param>\r\n        public NancyCSharpRazorCodeParser(RazorAssemblyProvider razorAssemblyProvider)\r\n        {\r\n            this.razorAssemblyProvider = razorAssemblyProvider;\r\n            this.MapDirectives(this.ModelDirective, \"model\");\r\n\r\n            this.clrTypeResolver = new CSharpClrTypeResolver(this.razorAssemblyProvider);\r\n        }\r\n\r\n        protected virtual void ModelDirective()\r\n        {\r\n            this.AssertDirective(\"model\");\r\n\r\n            this.AcceptAndMoveNext();\r\n\r\n            var endModelLocation = this.CurrentLocation;\r\n\r\n            this.BaseTypeDirective(\"The 'model' keyword must be followed by a type name on the same line.\", s =>\r\n            {\r\n                var symbols = this.Language.TokenizeString(s);\r\n                var modelType = this.clrTypeResolver.Resolve(symbols.ToList());\r\n\r\n                if (modelType == null)\r\n                {\r\n                    CodeParserHelper.ThrowTypeNotFound(this.razorAssemblyProvider, s);\r\n                }\r\n\r\n                return new ModelCodeGenerator(modelType, modelType.FullName);\r\n            });\r\n\r\n            if (this.modelStatementFound)\r\n            {\r\n                this.Context.OnError(endModelLocation, string.Format(CultureInfo.CurrentCulture, \"Cannot have more than one @model statement.\"));\r\n            }\r\n\r\n            this.modelStatementFound = true;\r\n            this.CheckForInheritsAndModelStatements();\r\n        }\r\n\r\n        protected override void InheritsDirective()\r\n        {\r\n            this.AssertDirective(\"inherits\");\r\n            this.AcceptAndMoveNext();\r\n\r\n            this.endInheritsLocation = this.CurrentLocation;\r\n\r\n            base.InheritsDirective();\r\n\r\n            this.CheckForInheritsAndModelStatements();\r\n        }\r\n\r\n        private void CheckForInheritsAndModelStatements()\r\n        {\r\n            if (this.modelStatementFound && this.endInheritsLocation.HasValue)\r\n            {\r\n                this.Context.OnError(this.endInheritsLocation.Value, string.Format(CultureInfo.CurrentCulture, \"Cannot have both an @inherits statement and an @model statement.\"));\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/ClrTypeResolver.cs",
    "content": "﻿namespace Nancy.ViewEngines.Razor\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Diagnostics;\r\n    using System.Linq;\r\n    using System.Text;\r\n    using System.Web.Razor.Tokenizer.Symbols;\r\n\r\n    using Nancy.Bootstrapper;\r\n\r\n    /// <summary>\r\n    /// Converts language-specific type name into CRL Type\r\n    /// </summary>\r\n    /// <typeparam name=\"TSymbolType\">Symbol type enum</typeparam>\r\n    /// <typeparam name=\"TSymbol\">Symbol class</typeparam>\r\n    internal abstract class ClrTypeResolver<TSymbolType, TSymbol>\r\n        where TSymbol : SymbolBase<TSymbolType>\r\n    {\r\n        private readonly RazorAssemblyProvider razorAssemblyProvider;\r\n\r\n        private readonly TSymbolType identifier;\r\n        private readonly TSymbolType keyword;\r\n        private readonly TSymbolType dot;\r\n        private readonly TSymbolType whiteSpace;\r\n        private readonly TSymbolType arrayBegin;\r\n        private readonly TSymbolType arrayEnd;\r\n\r\n        /// <summary>\r\n        /// Gets remaining symbols that need to be parsed\r\n        /// </summary>\r\n        protected Queue<TSymbol> Symbols { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Initializes new instance of ClrTypeResolver class.\r\n        /// Provided parameters are used to recognized specific symbols in particular language\r\n        /// </summary>\r\n        /// <param name=\"razorAssemblyProvider\">An <see cref=\"RazorAssemblyProvider\"/> used to resolve model types from the available assemblies.</param>\r\n        /// <param name=\"identifier\">Symbol type for identifier</param>\r\n        /// <param name=\"keyword\">Symbol type for keyword</param>\r\n        /// <param name=\"dot\">Symbol type for dot ('.')</param>\r\n        /// <param name=\"whiteSpace\">Symbol type for whitespace</param>\r\n        /// <param name=\"arrayBegin\">Type of symbol that begins array</param>\r\n        /// <param name=\"arrayEnd\">Type of symbol that ends array</param>\r\n        protected ClrTypeResolver(RazorAssemblyProvider razorAssemblyProvider, TSymbolType identifier, TSymbolType keyword, TSymbolType dot, TSymbolType whiteSpace, TSymbolType arrayBegin, TSymbolType arrayEnd)\r\n        {\r\n            this.razorAssemblyProvider = razorAssemblyProvider;\r\n            this.identifier = identifier;\r\n            this.keyword = keyword;\r\n            this.dot = dot;\r\n            this.whiteSpace = whiteSpace;\r\n            this.arrayBegin = arrayBegin;\r\n            this.arrayEnd = arrayEnd;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Parses given list of symbols in order to get CLR type\r\n        /// </summary>\r\n        /// <param name=\"symbols\">List of symbols</param>\r\n        /// <returns>CLR type</returns>\r\n        public Type Resolve(List<TSymbol> symbols)\r\n        {\r\n            this.Symbols = new Queue<TSymbol>(symbols);\r\n\r\n            var type = this.ResolveType();\r\n\r\n            return type.Resolve(ResolveTypeByName);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Dequeues symbols until first symbol of first generic argument\r\n        /// </summary>\r\n        /// <returns>Returns true if move was successful</returns>\r\n        protected abstract bool MoveToGenericArguments();\r\n\r\n        /// <summary>\r\n        /// Dequeues symbols representing separator between generic arguments\r\n        /// </summary>\r\n        protected abstract void MoveToNextGenericArgument();\r\n\r\n        /// <summary>\r\n        /// Dequeues symbols representing end of generic arguments\r\n        /// </summary>\r\n        /// <returns>Returns true if move was successful</returns>\r\n        protected abstract bool MoveOutOfGenericArguments();\r\n\r\n        /// <summary>\r\n        /// Gets CLR from name (keyword) used by specific language\r\n        /// </summary>\r\n        /// <param name=\"typeName\">Type name to resolve</param>\r\n        /// <returns>CLR type</returns>\r\n        protected abstract Type ResolvePrimitiveType(string typeName);\r\n\r\n        private TypeNameParserStep ResolveType()\r\n        {\r\n            var identifier = this.PopFullIdentifier();\r\n\r\n            var step = new TypeNameParserStep(identifier);\r\n\r\n            if (!this.Symbols.Any())\r\n            {\r\n                return step;\r\n            }\r\n\r\n            step.GenericArguments.AddRange(this.ReadGenericArguments());\r\n\r\n            step.ArrayExpression = this.ReadArrayExpression();\r\n\r\n            return step;\r\n        }\r\n\r\n        private List<TypeNameParserStep> ReadGenericArguments()\r\n        {\r\n            var genericArgs = new List<TypeNameParserStep>();\r\n\r\n            if (this.MoveToGenericArguments())\r\n            {\r\n                while (!MoveOutOfGenericArguments())\r\n                {\r\n                    genericArgs.Add(this.ResolveType());\r\n\r\n                    this.MoveToNextGenericArgument();\r\n                }\r\n            }\r\n\r\n            return genericArgs;\r\n        }\r\n\r\n        private string PopFullIdentifier()\r\n        {\r\n            var builder = new StringBuilder();\r\n\r\n            while (this.Symbols.Any())\r\n            {\r\n                var peekType = this.Symbols.Peek().Type;\r\n\r\n                if (peekType.Equals(this.keyword))\r\n                {\r\n                    return this.Symbols.Dequeue().Content;\r\n                }\r\n                else if (peekType.Equals(this.identifier))\r\n                {\r\n                    builder.Append(this.Symbols.Dequeue().Content);\r\n                }\r\n                else if (peekType.Equals(this.dot))\r\n                {\r\n                    this.Symbols.Dequeue();\r\n                    builder.Append(\".\");\r\n                }\r\n                else if (peekType.Equals(this.whiteSpace))\r\n                {\r\n                    this.Symbols.Dequeue();\r\n                }\r\n                else\r\n                {\r\n                    return builder.ToString();\r\n                }\r\n            }\r\n\r\n            return builder.ToString();\r\n        }\r\n\r\n        private string ReadArrayExpression()\r\n        {\r\n            var arrayExpr = \"\";\r\n\r\n            while (this.Symbols.Any() && this.Symbols.Peek().Type.Equals(this.arrayBegin))\r\n            {\r\n                this.Symbols.Dequeue();\r\n\r\n                arrayExpr += \"[\";\r\n\r\n                while (!(this.Symbols.Peek().Type.Equals(this.arrayEnd)))\r\n                {\r\n                    arrayExpr += this.Symbols.Dequeue().Content;\r\n                }\r\n\r\n                arrayExpr += \"]\";\r\n                this.Symbols.Dequeue();\r\n            }\r\n\r\n            return arrayExpr;\r\n        }\r\n\r\n        private Type ResolveTypeByName(string typeName)\r\n        {\r\n            return Type.GetType(typeName)\r\n                   ?? this.ResolvePrimitiveType(typeName)\r\n                   ?? this.ResolveTypeFromAssemblyCatalog(typeName);\r\n        }\r\n\r\n        private Type ResolveTypeFromAssemblyCatalog(string typeName)\r\n        {\r\n            return this.razorAssemblyProvider.GetAssemblies().Select(assembly => assembly.GetType(typeName)).FirstOrDefault(type => type != null);\r\n        }\r\n\r\n        [DebuggerDisplay(\"{GenericTypeName}`{GenericArguments.Count}\")]\r\n        private class TypeNameParserStep\r\n        {\r\n            public string GenericTypeName { get; set; }\r\n            public List<TypeNameParserStep> GenericArguments { get; private set; }\r\n            public string ArrayExpression { get; set; }\r\n\r\n            public TypeNameParserStep(string name)\r\n            {\r\n                this.GenericTypeName = name;\r\n                this.GenericArguments = new List<TypeNameParserStep>();\r\n                this.ArrayExpression = string.Empty;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Resolves CLR type that is represented by this instance\r\n            /// </summary>\r\n            /// <param name=\"resolveType\">Function that allows resolving any simple (like int or MyNamespace.SuperClass) type name to CLR type</param>\r\n            /// <returns>Resolved CLR type</returns>\r\n            public Type Resolve(Func<string, Type> resolveType)\r\n            {\r\n                var effectiveArguments = this.GenericArguments.Where(x => x.GenericTypeName != string.Empty).ToArray();\r\n\r\n                Type resultType = null;\r\n\r\n                if (effectiveArguments.Length == 0)\r\n                {\r\n                    resultType = resolveType(this.GenericTypeName);\r\n                }\r\n                else\r\n                {\r\n                    var genericArguments = effectiveArguments.Select(x => x.Resolve(resolveType)).ToArray();\r\n\r\n                    var genericType = resolveType(string.Format(\"{0}`{1}\", this.GenericTypeName, effectiveArguments.Length));\r\n\r\n                    resultType = genericType.MakeGenericType(genericArguments);\r\n                }\r\n\r\n                if (this.ArrayExpression != \"\")\r\n                {\r\n                    resultType = resolveType(resultType.FullName + this.ArrayExpression);\r\n                }\r\n\r\n                return resultType;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/CodeParserHelper.cs",
    "content": "﻿namespace Nancy.ViewEngines.Razor\r\n{\r\n    using System;\r\n    using System.Linq;\r\n\r\n    internal static class CodeParserHelper\r\n    {\r\n        /// <summary>\r\n        /// Throws exception says that given type was not found in any accessible assembly\r\n        /// </summary>\r\n        /// <param name=\"razorAssemblyProvider\">An <see cref=\"RazorAssemblyProvider\"/> instance.</param>\r\n        /// <param name=\"type\">Type that was not found</param>\r\n        public static void ThrowTypeNotFound(RazorAssemblyProvider razorAssemblyProvider, string type)\r\n        {\r\n            throw new NotSupportedException(string.Format(\r\n                \"Unable to discover CLR Type for model by the name of {0}.\\n\\nTry using a fully qualified type name and ensure that the assembly is added to the configuration file.\\n\\nCurrent RazorAssemblyProvider assemblies:\\n\\t{1}.\",\r\n                type,\r\n                razorAssemblyProvider.GetAssemblies().Select(a => a.FullName).Aggregate((n1, n2) => n1 + \"\\n\\t\" + n2)));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/DefaultRazorConfiguration.cs",
    "content": "﻿namespace Nancy.ViewEngines.Razor\r\n{\r\n    using System.Collections.Generic;\r\n    using System.Configuration;\r\n    using System.Linq;\r\n\r\n    /// <summary>\r\n    ///\r\n    /// </summary>\r\n\tpublic class DefaultRazorConfiguration : IRazorConfiguration\r\n    {\r\n        private readonly RazorConfigurationSection razorConfigurationSection;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"DefaultRazorConfiguration\"/> class.\r\n        /// </summary>\r\n        public DefaultRazorConfiguration()\r\n        {\r\n            this.razorConfigurationSection = ConfigurationManager.GetSection(\"razor\") as RazorConfigurationSection;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether to automatically include the model's namespace in the generated code.\r\n        /// </summary>\r\n        /// <value>\r\n        /// \t<c>true</c> if the model's namespace should be automatically included in the generated code; otherwise, <c>false</c>.\r\n        /// </value>\r\n        public bool AutoIncludeModelNamespace\r\n\t\t{\r\n\t\t\tget { return (this.razorConfigurationSection == null || (!this.razorConfigurationSection.DisableAutoIncludeModelNamespace)); }\r\n\t\t}\r\n\r\n        /// <summary>\r\n        /// Gets the assembly names to include in the generated assembly.\r\n        /// </summary>\r\n        public IEnumerable<string> GetAssemblyNames()\r\n        {\r\n            if (this.razorConfigurationSection == null || this.razorConfigurationSection.Assemblies == null)\r\n            {\r\n                return Enumerable.Empty<string>();\r\n            }\r\n\r\n            return this.razorConfigurationSection.Assemblies.Select(a => a.AssemblyName);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the default namespaces to be included in the generated code.\r\n        /// </summary>\r\n        public IEnumerable<string> GetDefaultNamespaces()\r\n        {\r\n            if (this.razorConfigurationSection == null || this.razorConfigurationSection.Namespaces == null)\r\n            {\r\n                return Enumerable.Empty<string>();\r\n            }\r\n\r\n            return this.razorConfigurationSection.Namespaces.Select(n=>n.NamespaceName);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/EncodedHtmlString.cs",
    "content": "namespace Nancy.ViewEngines.Razor\n{\r\n    using Nancy.Helpers;\r\n\r\n    /// <summary>\n    /// An html string that is encoded.\n    /// </summary>\n    public class EncodedHtmlString : IHtmlString\n    {\n        /// <summary>\n        /// Represents the empty <see cref=\"EncodedHtmlString\"/>. This field is readonly.\n        /// </summary>\n        public static readonly EncodedHtmlString Empty = new EncodedHtmlString(string.Empty);\n\n        private readonly string encodedValue;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"EncodedHtmlString\"/> class.\n        /// </summary>\n        /// <param name=\"value\">The encoded value.</param>\n        public EncodedHtmlString(string value)\n        {\n            this.encodedValue = HttpUtility.HtmlEncode(value);\n        }\n\n        /// <summary>\n        /// Returns an HTML-encoded string.\n        /// </summary>\n        /// <returns>An HTML-encoded string.</returns>\n        public string ToHtmlString()\n        {\n            return this.encodedValue;\n        }\n\n        /// <summary>\r\n        /// Implicitly cast a string to an <see cref=\"EncodedHtmlString\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"value\">The string that should be encoded.</param>\r\n        /// <returns>An <see cref=\"EncodedHtmlString\"/> instance</returns>\n        public static implicit operator EncodedHtmlString(string value)\n        {\n            return new EncodedHtmlString(value);\n        }\r\n\r\n        /// <summary>\r\n        /// Implicitly cast an <see cref=\"EncodedHtmlString\"/> instance to a string.\r\n        /// </summary>\r\n        /// <param name=\"encoded\">The <see cref=\"EncodedHtmlString\"/> instance.</param>\r\n        /// <returns>A string containing the encoded value.</returns>\r\n        public static implicit operator string(EncodedHtmlString encoded)\r\n        {\r\n            return encoded.encodedValue;\r\n        }\n    }\n}\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/HelperResult.cs",
    "content": "﻿namespace Nancy.ViewEngines.Razor\r\n{\r\n    using System;\r\n    using System.Globalization;\r\n    using System.IO;\r\n\r\n    /// <summary>\r\n    /// Helped class used by Razor to render generated code.\r\n    /// </summary>\r\n    public class HelperResult : IHtmlString\r\n    {\r\n        private readonly Action<TextWriter> action;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"HelperResult\"/> class,\r\n        /// with the provided <paramref name=\"action\"/>.\r\n        /// </summary>\r\n        /// <param name=\"action\">The action that should be used to produce the result.</param>\r\n        public HelperResult(Action<TextWriter> action)\r\n        {\r\n            if (action == null)\r\n            {\r\n                throw new ArgumentNullException(\"action\", \"The action parameter cannot be null.\");\r\n            }\r\n\r\n            this.action = action;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns a HTML formatted <see cref=\"string\"/> that represents the current <see cref=\"HelperResult\"/>.\r\n        /// </summary>\r\n        /// <returns>A HTML formatted <see cref=\"string\"/> that represents the current <see cref=\"HelperResult\"/>.</returns>\r\n        public string ToHtmlString()\r\n        {\r\n            return this.ToString();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns a <see cref=\"string\"/> that represents the current <see cref=\"HelperResult\"/>.\r\n        /// </summary>\r\n        /// <returns>A <see cref=\"string\"/> that represents the current <see cref=\"HelperResult\"/>.</returns>\r\n        public override string ToString()\r\n        {\r\n            using (var stringWriter = new StringWriter(CultureInfo.InvariantCulture))\r\n            {\r\n                this.action(stringWriter);\r\n                return stringWriter.ToString();\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Writes the output of the <see cref=\"HelperResult\"/> to the provided <paramref name=\"writer\"/>.\r\n        /// </summary>\r\n        /// <param name=\"writer\">A <see cref=\"TextWriter\"/> instance that the output should be written to.</param>\r\n        public void WriteTo(TextWriter writer)\r\n        {\r\n            this.action(writer);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/HtmlHelpers.cs",
    "content": "﻿namespace Nancy.ViewEngines.Razor\r\n{\r\n    using System;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Security.Claims;\r\n\r\n    /// <summary>\r\n    /// Helpers to generate html content.\r\n    /// </summary>\r\n    /// <typeparam name=\"TModel\">The type of the model.</typeparam>\r\n    public class HtmlHelpers<TModel> : HtmlHelpers\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"HtmlHelpers{T}\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"engine\">The razor view engine instance that the helpers are being used by.</param>\r\n        /// <param name=\"renderContext\">The <see cref=\"IRenderContext\"/> that the helper are being used by.</param>\r\n        /// <param name=\"model\">The model that is used by the page where the helpers are invoked.</param>\r\n        public HtmlHelpers(RazorViewEngine engine, IRenderContext renderContext, TModel model) : base(engine, renderContext)\r\n        {\r\n            this.Model = model;\r\n        }\r\n\r\n        /// <summary>\r\n        /// The model that is being used by the current view.\r\n        /// </summary>\r\n        /// <value>An instance of the view model.</value>\r\n        public TModel Model { get; set; }\r\n    }\r\n\r\n    /// <summary>\r\n    /// Base helpers to generate html content.\r\n    /// </summary>\r\n    public abstract class HtmlHelpers\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"HtmlHelpers\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"engine\">The razor view engine instance that the helpers are being used by.</param>\r\n        /// <param name=\"renderContext\">The <see cref=\"IRenderContext\"/> that the helper are being used by.</param>\r\n        protected HtmlHelpers(RazorViewEngine engine, IRenderContext renderContext)\r\n        {\r\n            this.Engine = engine;\r\n            this.RenderContext = renderContext;\r\n        }\r\n\r\n        /// <summary>\r\n        /// The engine that is currently rendering the view.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"RazorViewEngine\"/> instance.</value>\r\n        public RazorViewEngine Engine { get; set; }\r\n\r\n        /// <summary>\r\n        /// The context of the current render operation.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IRenderContext\"/> instance.</value>\r\n        public IRenderContext RenderContext { get; set; }\r\n\r\n        /// <summary>\r\n        /// Renders a partial with the given view name.\r\n        /// </summary>\r\n        /// <param name=\"viewName\">Name of the view.</param>\r\n        /// <returns>An <see cref=\"IHtmlString\"/> representation of the partial.</returns>\r\n        public IHtmlString Partial(string viewName)\r\n        {\r\n            return this.Partial(viewName, null);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Renders a partial with the given view name.\r\n        /// </summary>\r\n        /// <param name=\"viewName\">Name of the partial view.</param>\r\n        /// <param name=\"modelForPartial\">The model that is passed to the partial.</param>\r\n        /// <returns>An <see cref=\"IHtmlString\"/> representation of the partial.</returns>\r\n        public IHtmlString Partial(string viewName, dynamic modelForPartial)\r\n        {\r\n            var view = this.RenderContext.LocateView(viewName, modelForPartial);\r\n            if (view == null)\r\n            {\r\n                throw new ViewNotFoundException(viewName, this.Engine.Extensions.ToArray());\r\n            }\r\n\r\n            var response = this.Engine.RenderView(view, modelForPartial, this.RenderContext, true);\r\n            Action<Stream> action = response.Contents;\r\n            var mem = new MemoryStream();\r\n\r\n            action.Invoke(mem);\r\n            mem.Position = 0;\r\n\r\n            var reader = new StreamReader(mem);\r\n\r\n            return new NonEncodedHtmlString(reader.ReadToEnd());\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an html string composed of raw, non-encoded text.\r\n        /// </summary>\r\n        /// <param name=\"text\">The text.</param>\r\n        /// <returns>An <see cref=\"IHtmlString\"/> representation of the raw text.</returns>\r\n        public IHtmlString Raw(string text)\r\n        {\r\n            return new NonEncodedHtmlString(text);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Creates an anti-forgery token.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IHtmlString\"/> representation of the anti forgery token.</returns>\r\n        public IHtmlString AntiForgeryToken()\r\n        {\r\n            var tokenKeyValue =\r\n                this.RenderContext.GetCsrfToken();\r\n\r\n            return new NonEncodedHtmlString(String.Format(\"<input type=\\\"hidden\\\" name=\\\"{0}\\\" value=\\\"{1}\\\"/>\", tokenKeyValue.Key, tokenKeyValue.Value));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns current culture name\r\n        /// </summary>\r\n        public string CurrentLocale\r\n        {\r\n            get { return this.RenderContext.Context.Culture.Name; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns current authenticated user name\r\n        /// </summary>\r\n        public ClaimsPrincipal CurrentUser\r\n        {\r\n            get { return this.RenderContext.Context.CurrentUser; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Determines if current user is authenticated\r\n        /// </summary>\r\n        public bool IsAuthenticated\r\n        {\r\n            get { return this.RenderContext.Context.CurrentUser != null; }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/HtmlHelpersExtensions.cs",
    "content": "﻿namespace Nancy.ViewEngines.Razor\r\n{\r\n    /// <summary>\r\n    /// Razor HTML Helper Extensions\r\n    /// </summary>\r\n    public static class HtmlHelpersExtensions\r\n    {\r\n        /// <summary>\r\n        /// Create a hidden input field called X-HTTP-Method-Override for the specified <paramref name=\"method\"/>\r\n        /// </summary>\r\n        /// <typeparam name=\"T\">The model type.</typeparam>\r\n        /// <param name=\"helpers\">A reference to the <see cref=\"HtmlHelpers{TModel}\"/> instance.</param>\r\n        /// <param name=\"method\">The HTTP method to use.</param>\r\n        /// <returns>A string representation of the input field.</returns>\r\n        public static IHtmlString HttpMethodOverride<T>(this HtmlHelpers<T> helpers, string method)\r\n        {\r\n            var tag =\r\n                string.Format(\"<input name='X-HTTP-Method-Override' type='hidden' value='{0}' />\", method);\r\n\r\n            return new NonEncodedHtmlString(tag);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/IHtmlString.cs",
    "content": "namespace Nancy.ViewEngines.Razor\r\n{\r\n    public interface IHtmlString\r\n    {\r\n        /// <summary>\r\n        /// Returns an HTML-encoded string.\r\n        /// </summary>\r\n        /// <returns>An HTML-encoded string.</returns>\r\n        string ToHtmlString();\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/INancyRazorView.cs",
    "content": "﻿namespace Nancy.ViewEngines.Razor\r\n{\r\n    public interface INancyRazorView\r\n    {\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/IRazorConfiguration.cs",
    "content": "﻿namespace Nancy.ViewEngines.Razor\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    /// <summary>\r\n    /// Configuration for the razor view engine.\r\n    /// </summary>\r\n    public interface IRazorConfiguration\r\n    {\r\n        /// <summary>\r\n        /// Gets a value indicating whether to automatically include the model's namespace in the generated code.\r\n        /// </summary>\r\n        /// <value>\r\n        ///     <c>true</c> if the model's namespace should be automatically included in the generated code; otherwise, <c>false</c>.\r\n        /// </value>\r\n        bool AutoIncludeModelNamespace { get; }\r\n\r\n        /// <summary>\r\n        /// Gets the assembly names.\r\n        /// </summary>\r\n        IEnumerable<string> GetAssemblyNames();\r\n\r\n        /// <summary>\r\n        /// Gets the default namespaces.\r\n        /// </summary>\r\n        IEnumerable<string> GetDefaultNamespaces();\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/IRazorViewRenderer.cs",
    "content": "﻿namespace Nancy.ViewEngines.Razor\r\n{\r\n    using System;\r\n    using System.CodeDom.Compiler;\r\n    using System.Collections.Generic;\r\n    using System.Web.Razor;\r\n    using System.Web.Razor.Generator;\r\n\r\n    /// <summary>\r\n    /// Renders a view.\r\n    /// </summary>\r\n    public interface IRazorViewRenderer\r\n    {\r\n        /// <summary>\r\n        /// Gets the assemblies.\r\n        /// </summary>\r\n        IEnumerable<string> Assemblies { get; }\r\n\r\n        /// <summary>\r\n        /// Gets the <see cref=\"SetBaseTypeCodeGenerator\"/> that should be used with the renderer.\r\n        /// </summary>\r\n        Type ModelCodeGenerator { get; }\r\n\r\n        /// <summary>\r\n        /// Gets the extension this view renderer supports.\r\n        /// </summary>\r\n        string Extension { get; }\r\n\r\n        /// <summary>\r\n        /// Gets the host.\r\n        /// </summary>\r\n        RazorEngineHost Host { get; }\r\n\r\n        /// <summary>\r\n        /// Gets the provider that is used to generate code.\r\n        /// </summary>\r\n        CodeDomProvider Provider { get; }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/ModelCodeGenerator.cs",
    "content": "namespace Nancy.ViewEngines.Razor\r\n{\r\n    using System;\r\n    using System.CodeDom;\r\n    using System.Web.Razor.Generator;\r\n    using System.Web.Razor.Parser.SyntaxTree;\r\n\r\n    /// <summary>\r\n    /// Adds base type with model type as generic argument for Razor view class\r\n    /// </summary>\r\n    public class ModelCodeGenerator : SetBaseTypeCodeGenerator\r\n    {\r\n        private readonly Type modelType;\r\n\r\n        public ModelCodeGenerator(Type modelType, string typeFullname)\r\n            : base(typeFullname)\r\n        {\r\n            this.modelType = modelType;\r\n        }\r\n\r\n        protected override string ResolveType(CodeGeneratorContext context, string baseType)\r\n        {\r\n            return typeof(object).FullName;\r\n        }\r\n\r\n        public override void GenerateCode(Span target, CodeGeneratorContext context)\r\n        {\r\n            base.GenerateCode(target, context);\r\n\r\n            context.GeneratedClass.UserData.Add(\"ModelType\", this.modelType);\r\n            context.GeneratedClass.BaseTypes.Clear();\r\n            context.GeneratedClass.BaseTypes.Add(new CodeTypeReference(context.Host.DefaultBaseClass, new CodeTypeReference(this.modelType)));\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/Nancy.ViewEngines.Razor.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <Description>Enables using the Razor view engine with Nancy.</Description>\n    <PackageTags>$(PackageTags);View Engine;Razor</PackageTags>\n    <TargetFramework>net452</TargetFramework>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <EmbeddedResource Include=\"Resources\\**\\*.*\" Exclude=\"bin\\**;obj\\**;**\\*.xproj;packages\\**;@(EmbeddedResource)\" />\n    <None Update=\".\\web.config.transform\">\n      <PackagePath>content</PackagePath>\n      <Pack>true</Pack>\n    </None>\n    <None Update=\".\\app.config.transform\">\n      <PackagePath>content</PackagePath>\n      <Pack>true</Pack>\n    </None>\n  </ItemGroup>\n\n  <ItemGroup>\n    <PackageReference Include=\"Microsoft.AspNet.Razor\" Version=\"2.0.30506\" />\n    <PackageReference Include=\"Microsoft.CodeAnalysis.CSharp\" Version=\"1.3.2\" />\n    <PackageReference Include=\"Microsoft.CodeDom.Providers.DotNetCompilerPlatform\" Version=\"1.0.3\" />\n    <PackageReference Include=\"System.Collections.Immutable\" Version=\"1.2.0\" />\n  </ItemGroup>\n\n  <ItemGroup>\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.IO\" />\n    <Reference Include=\"System.Reflection\" />\n    <Reference Include=\"System.Runtime\" />\n    <Reference Include=\"System.Text.Encoding\" />\n    <Reference Include=\"System.Threading.Tasks\" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/NancyRazorEngineHost.cs",
    "content": "﻿namespace Nancy.ViewEngines.Razor\r\n{\r\n    using System.Web.Razor;\r\n    using System.Web.Razor.Generator;\r\n    using System.Web.Razor.Parser;\r\n    using Nancy.ViewEngines.Razor.CSharp;\r\n\r\n    /// <summary>\r\n    /// A custom razor engine host responsible for decorating the existing code generators with nancy versions.\r\n    /// </summary>\r\n    public class NancyRazorEngineHost : RazorEngineHost\r\n    {\r\n        private readonly RazorAssemblyProvider razorAssemblyProvider;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancyRazorEngineHost\"/> class.\r\n        /// </summary>\r\n        public NancyRazorEngineHost(RazorCodeLanguage language, RazorAssemblyProvider razorAssemblyProvider)\r\n            : base(language)\r\n        {\r\n            this.razorAssemblyProvider = razorAssemblyProvider;\r\n            this.DefaultBaseClass = typeof (NancyRazorViewBase).FullName;\r\n            this.DefaultNamespace = \"RazorOutput\";\r\n            this.DefaultClassName = \"RazorView\";\r\n\r\n            var context = new GeneratedClassContext(\"Execute\", \"Write\", \"WriteLiteral\", \"WriteTo\", \"WriteLiteralTo\",\r\n                typeof (HelperResult).FullName, \"DefineSection\");\r\n            context.ResolveUrlMethodName = \"ResolveUrl\";\r\n\r\n            this.GeneratedClassContext = context;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Decorates the code parser.\r\n        /// </summary>\r\n        /// <param name=\"incomingCodeParser\">The incoming code parser.</param>\r\n        /// <returns></returns>\r\n        public override ParserBase DecorateCodeParser(ParserBase incomingCodeParser)\r\n        {\r\n            if (incomingCodeParser is CSharpCodeParser)\r\n            {\r\n                return new NancyCSharpRazorCodeParser(this.razorAssemblyProvider);\r\n            }\r\n\r\n            return base.DecorateCodeParser(incomingCodeParser);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/NancyRazorErrorView.cs",
    "content": "﻿namespace Nancy.ViewEngines.Razor\r\n{\r\n    using System;\r\n    using System.IO;\r\n\r\n    /// <summary>\r\n    /// Razor view used when compilation of the view fails.\r\n    /// </summary>\r\n    public class NancyRazorErrorView : NancyRazorViewBase\r\n    {\r\n        private readonly TraceConfiguration traceConfiguration;\r\n\r\n        private const string DisplayErrorTracesFalseMessage = \"Error details are currently disabled.<br />To enable it, please set <strong>TraceConfiguration.DisplayErrorTraces</strong> to <strong>true</strong>.<br />For example by overriding your Bootstrapper's <strong>Configure</strong> method and calling<br/> <strong>environment.Tracing(enabled: false, displayErrorTraces: true);</strong>.\";\r\n\r\n        private static string template;\r\n\r\n        /// <summary>\r\n        /// Gets or sets the template for rendering errors.\r\n        /// The token \"[DETAILS]\" will be replaced by the HTML for\r\n        /// the actual error.\r\n        /// </summary>\r\n        public static string Template\r\n        {\r\n            get { return template ?? (template = LoadResource(@\"CompilationError.html\")); }\r\n            set { template = value; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancyRazorErrorView\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"message\">The message.</param>\r\n        /// <param name=\"traceConfiguration\">A <see cref=\"TraceConfiguration\"/> instance.</param>\r\n        public NancyRazorErrorView(string message, TraceConfiguration traceConfiguration)\r\n        {\r\n            this.traceConfiguration = traceConfiguration;\r\n            this.Message = message;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the message.\r\n        /// </summary>\r\n        public string Message { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Executes this instance.\r\n        /// </summary>\r\n        public override void Execute()\r\n        {\r\n            base.WriteLiteral(Template.Replace(\"[DETAILS]\", this.traceConfiguration.DisplayErrorTraces ? this.Message : DisplayErrorTracesFalseMessage));\r\n        }\r\n\r\n        private static string LoadResource(string filename)\r\n        {\r\n            var resourceStream = typeof(NancyRazorErrorView).Assembly.GetManifestResourceStream(String.Format(\"Nancy.ViewEngines.Razor.Resources.{0}\", filename));\r\n\r\n            if (resourceStream == null)\r\n            {\r\n                return string.Empty;\r\n            }\r\n\r\n            using (var reader = new StreamReader(resourceStream))\r\n            {\r\n                return reader.ReadToEnd();\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/NancyRazorViewBase.cs",
    "content": "﻿namespace Nancy.ViewEngines.Razor\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Globalization;\r\n    using System.IO;\r\n    using System.Text;\r\n\r\n    using Nancy.Helpers;\r\n\r\n    /// <summary>\r\n    /// Default base class for nancy razor views\r\n    /// </summary>\r\n    public abstract class NancyRazorViewBase : NancyRazorViewBase<dynamic>\r\n    {\r\n    }\r\n\r\n    /// <summary>\r\n    /// Base class for nancy razor views.\r\n    /// </summary>\r\n    /// <typeparam name=\"TModel\">Model type</typeparam>\r\n    public abstract class NancyRazorViewBase<TModel> : INancyRazorView\r\n    {\r\n        private readonly StringBuilder contents;\r\n        private string childBody;\r\n        private IDictionary<string, string> childSections;\r\n\r\n        /// <summary>\r\n        /// Gets the Html helper.\r\n        /// </summary>\r\n        public HtmlHelpers<TModel> Html { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the model.\r\n        /// </summary>\r\n        public TModel Model { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the Url helper.\r\n        /// </summary>\r\n        public UrlHelpers<TModel> Url { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Non-model specific data for rendering in the response\r\n        /// </summary>\r\n        public dynamic ViewBag { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets the body.\r\n        /// </summary>\r\n        public String Body { get; private set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the section contents.\r\n        /// </summary>\r\n        /// <value>\r\n        /// The section contents.\r\n        /// </value>\r\n        public IDictionary<string, string> SectionContents { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the layout.\r\n        /// </summary>\r\n        /// <value>\r\n        /// The layout.\r\n        /// </value>\r\n        public string Layout { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets a value indicating whether this instance has layout.\r\n        /// </summary>\r\n        /// <value>\r\n        /// \t<c>true</c> if this instance has layout; otherwise, <c>false</c>.\r\n        /// </value>\r\n        public bool HasLayout\r\n        {\r\n            get { return !string.IsNullOrEmpty(this.Layout); }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the code.\r\n        /// </summary>\r\n        /// <value>\r\n        /// The code.\r\n        /// </value>\r\n        public string Code { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the path.\r\n        /// </summary>\r\n        /// <value>\r\n        /// The path.\r\n        /// </value>\r\n        public string Path { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets or sets the sections.\r\n        /// </summary>\r\n        /// <value>\r\n        /// The sections.\r\n        /// </value>\r\n        public IDictionary<string, Action> Sections { get; set; }\r\n\r\n        /// <summary>\r\n        /// Used to return text resources\r\n        /// </summary>\r\n        public dynamic Text\r\n        {\r\n            get\r\n            {\r\n                return this.RenderContext.TextResourceFinder;\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Executes the view.\r\n        /// </summary>\r\n        public abstract void Execute();\r\n\r\n        /// <summary>\r\n        /// Initializes the specified engine.\r\n        /// </summary>\r\n        /// <param name=\"engine\">The engine.</param>\r\n        /// <param name=\"renderContext\">The render context.</param>\r\n        /// <param name=\"model\">The model.</param>\r\n        public virtual void Initialize(RazorViewEngine engine, IRenderContext renderContext, object model)\r\n        {\r\n            var castedModel = default(TModel);\r\n\r\n            if (model != null)\r\n            {\r\n                castedModel = (TModel)model;\r\n            }\r\n\r\n            this.RenderContext = renderContext;\r\n            this.Html = new HtmlHelpers<TModel>(engine, renderContext, castedModel);\r\n            this.Model = castedModel;\r\n            this.Url = new UrlHelpers<TModel>(engine, renderContext);\r\n            this.ViewBag = renderContext.Context.ViewBag;\r\n        }\r\n\r\n        protected IRenderContext RenderContext { get; set; }\r\n\r\n        /// <summary>\r\n        /// Gets the current <see cref=\"NancyContext\"/> instance.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"NancyContext\"/> instance.</value>\r\n        public NancyContext Context\r\n        {\r\n            get { return this.RenderContext.Context; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the current <see cref=\"Request\"/> instance.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"Request\"/> instance.</value>\r\n        public Request Request\r\n        {\r\n            get { return this.Context.Request; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancyRazorViewBase\"/> class.\r\n        /// </summary>\r\n        protected NancyRazorViewBase()\r\n        {\r\n            this.Sections = new Dictionary<string, Action>();\r\n            this.contents = new StringBuilder();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Writes the results of expressions like: \"@foo.Bar\"\r\n        /// </summary>\r\n        /// <param name=\"value\">The value.</param>\r\n        public virtual void Write(object value)\r\n        {\r\n            WriteLiteral(HtmlEncode(value));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Writes literals like markup: \"<p>Foo</p>\"\r\n        /// </summary>\r\n        /// <param name=\"value\">The value.</param>\r\n        public virtual void WriteLiteral(object value)\r\n        {\r\n            contents.Append(value);\r\n        }\r\n\r\n        public virtual void WriteAttribute(string name, Tuple<string, int> prefix, Tuple<string, int> suffix, params AttributeValue[] values)\r\n        {\r\n            var attributeValue = this.BuildAttribute(name, prefix, suffix, values);\r\n            this.WriteLiteral(attributeValue);\r\n        }\r\n\r\n        public virtual void WriteAttributeTo(TextWriter writer, string name, Tuple<string, int> prefix, Tuple<string, int> suffix, params AttributeValue[] values)\r\n        {\r\n            var attributeValue = this.BuildAttribute(name, prefix, suffix, values);\r\n            this.WriteLiteralTo(writer, attributeValue);\r\n        }\r\n\r\n        private string BuildAttribute(string name, Tuple<string, int> prefix, Tuple<string, int> suffix,\r\n                                      params AttributeValue[] values)\r\n        {\r\n            var writtenAttribute = false;\r\n            var attributeBuilder = new StringBuilder(prefix.Item1);\r\n\r\n            foreach (var value in values)\r\n            {\r\n                if (this.ShouldWriteValue(value.Value.Item1))\r\n                {\r\n                    var stringValue = this.GetStringValue(value);\r\n                    var valuePrefix = value.Prefix.Item1;\r\n\r\n                    // encode anything that hasn't opted out of it\r\n                    if (!(value.Value.Item1 is IHtmlString))\r\n                    {\r\n                        stringValue = HtmlEncode(stringValue);\r\n                    }\r\n\r\n                    if (!string.IsNullOrEmpty(valuePrefix))\r\n                    {\r\n                        attributeBuilder.Append(valuePrefix);\r\n                    }\r\n\r\n                    attributeBuilder.Append(stringValue);\r\n                    writtenAttribute = true;\r\n                }\r\n            }\r\n\r\n            attributeBuilder.Append(suffix.Item1);\r\n\r\n            var renderAttribute = writtenAttribute || values.Length == 0;\r\n\r\n            if (renderAttribute)\r\n            {\r\n                return attributeBuilder.ToString();\r\n            }\r\n\r\n            return string.Empty;\r\n        }\r\n\r\n        private string GetStringValue(AttributeValue value)\r\n        {\r\n            if (value.IsLiteral)\r\n            {\r\n                return (string)value.Value.Item1;\r\n            }\r\n\r\n            if (value.Value.Item1 is IHtmlString)\r\n            {\r\n                return ((IHtmlString)value.Value.Item1).ToHtmlString();\r\n            }\r\n\r\n            if (value.Value.Item1 is DynamicDictionaryValue)\r\n            {\r\n                var dynamicValue = (DynamicDictionaryValue)value.Value.Item1;\r\n                return dynamicValue.HasValue ? dynamicValue.Value.ToString() : string.Empty;\r\n            }\r\n\r\n            return value.Value.Item1.ToString();\r\n        }\r\n\r\n        private bool ShouldWriteValue(object value)\r\n        {\r\n            if (value == null)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            if (value is bool)\r\n            {\r\n                var boolValue = (bool)value;\r\n\r\n                return boolValue;\r\n            }\r\n\r\n            return true;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Writes the provided <paramref name=\"value\"/> to the provided <paramref name=\"writer\"/>.\r\n        /// </summary>\r\n        /// <param name=\"writer\">The <see cref=\"TextWriter\"/> that should be written to.</param>\r\n        /// <param name=\"value\">The value that should be written.</param>\r\n        public virtual void WriteTo(TextWriter writer, object value)\r\n        {\r\n            writer.Write(HtmlEncode(value));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Writes the provided <paramref name=\"value\"/>, as a literal, to the provided <paramref name=\"writer\"/>.\r\n        /// </summary>\r\n        /// <param name=\"writer\">The <see cref=\"TextWriter\"/> that should be written to.</param>\r\n        /// <param name=\"value\">The value that should be written as a literal.</param>\r\n        public virtual void WriteLiteralTo(TextWriter writer, object value)\r\n        {\r\n            writer.Write(value);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Writes the provided <paramref name=\"value\"/> to the provided <paramref name=\"writer\"/>.\r\n        /// </summary>\r\n        /// <param name=\"writer\">The <see cref=\"TextWriter\"/> that should be written to.</param>\r\n        /// <param name=\"value\">The <see cref=\"HelperResult\"/> that should be written.</param>\r\n        public virtual void WriteTo(TextWriter writer, HelperResult value)\r\n        {\r\n            if (value != null)\r\n            {\r\n                value.WriteTo(writer);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Writes the provided <paramref name=\"value\"/>, as a literal, to the provided <paramref name=\"writer\"/>.\r\n        /// </summary>\r\n        /// <param name=\"writer\">The <see cref=\"TextWriter\"/> that should be written to.</param>\r\n        /// <param name=\"value\">The <see cref=\"HelperResult\"/> that should be written as a literal.</param>\r\n        public virtual void WriteLiteralTo(TextWriter writer, HelperResult value)\r\n        {\r\n            if (value != null)\r\n            {\r\n                value.WriteTo(writer);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Stores sections\r\n        /// </summary>\r\n        /// <param name=\"sectionName\">Name of the section.</param>\r\n        /// <param name=\"action\">The action.</param>\r\n        public virtual void DefineSection(string sectionName, Action action)\r\n        {\r\n            this.Sections.Add(sectionName, action);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Renders the section.\r\n        /// </summary>\r\n        /// <param name=\"sectionName\">Name of the section.</param>\r\n        /// <returns></returns>\r\n        public virtual object RenderSection(string sectionName)\r\n        {\r\n            return this.RenderSection(sectionName, true);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Renders the section.\r\n        /// </summary>\r\n        /// <param name=\"sectionName\">Name of the section.</param>\r\n        /// <param name=\"required\">if set to <c>true</c> [required].</param>\r\n        public virtual object RenderSection(string sectionName, bool required)\r\n        {\r\n            string sectionContent;\r\n\r\n            var exists = this.childSections.TryGetValue(sectionName, out sectionContent);\r\n            if (!exists && required)\r\n            {\r\n                throw new InvalidOperationException(\"Section name \" + sectionName + \" not found and is required.\");\r\n            }\r\n\r\n            this.contents.Append(sectionContent ?? String.Empty);\r\n\r\n            return null;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Renders the body.\r\n        /// </summary>\r\n        /// <returns></returns>\r\n        public virtual object RenderBody()\r\n        {\r\n            this.contents.Append(this.childBody);\r\n\r\n            return null;\r\n        }\r\n\r\n        ///<summary>\r\n        ///Indicates if a section is defined.\r\n        ///</summary>\r\n        public virtual bool IsSectionDefined(string sectionName)\r\n        {\r\n            return this.childSections.ContainsKey(sectionName);\r\n        }\r\n\r\n        public virtual string ResolveUrl(string url)\r\n        {\r\n            return this.RenderContext.ParsePath(url);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Executes the view.\r\n        /// </summary>\r\n        /// <param name=\"body\">The body.</param>\r\n        /// <param name=\"sectionContents\">The section contents.</param>\r\n        public void ExecuteView(string body, IDictionary<string, string> sectionContents)\r\n        {\r\n            this.childBody = body ?? string.Empty;\r\n            this.childSections = sectionContents ?? new Dictionary<string, string>();\r\n\r\n            try\r\n            {\r\n                this.Execute();\r\n            }\r\n            catch (NullReferenceException e)\r\n            {\r\n                throw new ViewRenderException(\"Unable to render the view.  Most likely the Model, or a property on the Model, is null\", e);\r\n            }\r\n\r\n            this.Body = this.contents.ToString();\r\n\r\n            this.SectionContents = new Dictionary<string, string>(this.Sections.Count);\r\n            foreach (var section in this.Sections)\r\n            {\r\n                this.contents.Clear();\r\n                try\r\n                {\r\n                    section.Value.Invoke();\r\n                }\r\n                catch (NullReferenceException e)\r\n                {\r\n                    throw new ViewRenderException(string.Format(\"A null reference was encountered while rendering the section {0}.  Does the section require a model? (maybe it wasn't passed in)\", section.Key), e);\r\n                }\r\n                this.SectionContents.Add(section.Key, this.contents.ToString());\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Html encodes an object if required\r\n        /// </summary>\r\n        /// <param name=\"value\">Object to potentially encode</param>\r\n        /// <returns>String representation, encoded if necessary</returns>\r\n        private string HtmlEncode(object value)\r\n        {\r\n            if (value == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            var str = value as IHtmlString;\r\n\r\n            var currentCulture = this.Context.Culture ?? CultureInfo.CurrentCulture;\r\n\r\n            return str != null ? str.ToHtmlString() : HttpUtility.HtmlEncode(Convert.ToString(value, currentCulture));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/NonEncodedHtmlString.cs",
    "content": "﻿namespace Nancy.ViewEngines.Razor\r\n{\r\n    /// <summary>\r\n    /// An html string that is not encoded.\r\n    /// </summary>\r\n    public class NonEncodedHtmlString : IHtmlString\r\n    {\r\n        /// <summary>\r\n        /// Represents the empty <see cref=\"NonEncodedHtmlString\"/>. This field is readonly.\r\n        /// </summary>\r\n        public static readonly NonEncodedHtmlString Empty = new NonEncodedHtmlString(string.Empty);\r\n\r\n        private readonly string value;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NonEncodedHtmlString\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"value\">The value.</param>\r\n        public NonEncodedHtmlString(string value)\r\n        {\r\n            this.value = value;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns an HTML-encoded string.\r\n        /// </summary>\r\n        /// <returns>An HTML-encoded string.</returns>\r\n        public string ToHtmlString()\r\n        {\r\n            return value;\r\n        }\r\n\r\n        public static implicit operator NonEncodedHtmlString(string value)\r\n        {\r\n            return new NonEncodedHtmlString(value);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/RazorAssemblyProvider.cs",
    "content": "namespace Nancy.ViewEngines.Razor\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n\r\n    /// <summary>\r\n    /// Provides access to the <see cref=\"Assembly\"/> that are available to Razor.\r\n    /// </summary>\r\n    public class RazorAssemblyProvider\r\n    {\r\n        private readonly IRazorConfiguration configuration;\r\n        private readonly IAssemblyCatalog assemblyCatalog;\r\n        private readonly Lazy<IReadOnlyCollection<Assembly>> assemblies;\r\n        private readonly string[] defaultAssemblyDefinitions = {\r\n            \"mscorlib\",\r\n            \"Microsoft.CSharp\",\r\n            \"System\",\r\n            \"System.Collections\",\r\n            \"System.Collections.Generic\",\r\n            \"System.Core\",\r\n            \"System.Runtime\"\r\n        };\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"RazorAssemblyProvider\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"configuration\">An <see cref=\"IRazorConfiguration\"/> instance.</param>\r\n        /// <param name=\"assemblyCatalog\">An <see cref=\"IAssemblyCatalog\"/> instance.</param>\r\n        public RazorAssemblyProvider(IRazorConfiguration configuration, IAssemblyCatalog assemblyCatalog)\r\n        {\r\n            this.configuration = configuration;\r\n            this.assemblyCatalog = assemblyCatalog;\r\n            this.assemblies = new Lazy<IReadOnlyCollection<Assembly>>(this.GetAllAssemblies);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get all <see cref=\"Assembly\"/> instances that are available to the Razor engine.\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IReadOnlyCollection{T}\"/> of <see cref=\"Assembly\"/> instances.</returns>\r\n        public IReadOnlyCollection<Assembly> GetAssemblies()\r\n        {\r\n            return this.assemblies.Value;\r\n        }\r\n\r\n        private IReadOnlyCollection<Assembly> GetAllAssemblies()\r\n        {\r\n            return this.assemblyCatalog.GetAssemblies()\r\n                       .Union(this.LoadAssembliesInConfiguration())\r\n                       .Union(this.GetDefaultAssemblies())\r\n                       .ToArray();\r\n        }\r\n\r\n        private IEnumerable<Assembly> LoadAssembliesInConfiguration()\r\n        {\r\n            var loadedAssemblies = new HashSet<Assembly>();\r\n\r\n            var validAssemblyDefinitions = this.configuration\r\n                .GetAssemblyNames()\r\n                .Where(definition => !string.IsNullOrEmpty(definition));\r\n\r\n            foreach (var assemblyDefinition in validAssemblyDefinitions)\r\n            {\r\n                try\r\n                {\r\n                    loadedAssemblies.Add(Assembly.Load(assemblyDefinition));\r\n                }\r\n                catch\r\n                {\r\n                }\r\n            }\r\n\r\n            return loadedAssemblies;\r\n        }\r\n\r\n        private IEnumerable<Assembly> GetDefaultAssemblies()\r\n        {\r\n            var loadedAssemblies = new HashSet<Assembly>();\r\n\r\n            foreach (var assemblyDefinition in this.defaultAssemblyDefinitions)\r\n            {\r\n                var assembly = AppDomain.CurrentDomain.GetAssemblies().SingleOrDefault(x => x.GetName().Name.Equals(assemblyDefinition, StringComparison.OrdinalIgnoreCase));\r\n\r\n                if (assembly != null)\r\n                {\r\n                    loadedAssemblies.Add(assembly);\r\n                }\r\n            }\r\n\r\n            return loadedAssemblies;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/RazorConfigurationSection.cs",
    "content": "﻿namespace Nancy.ViewEngines.Razor\r\n{\r\n    using System;\r\n    using System.Collections;\r\n    using System.Collections.Generic;\r\n    using System.Configuration;\r\n\r\n    public class RazorConfigurationSection : ConfigurationSection\r\n    {\r\n        [ConfigurationProperty(\"disableAutoIncludeModelNamespace\", DefaultValue = \"false\", IsRequired = false)]\r\n        public Boolean DisableAutoIncludeModelNamespace\r\n        {\r\n            get { return (Boolean)this[\"disableAutoIncludeModelNamespace\"]; }\r\n            set { this[\"disableAutoIncludeModelNamespace\"] = value; }\r\n        }\r\n\r\n        [ConfigurationProperty(\"assemblies\", IsRequired = false)]\r\n        public AssemblyConfigurationCollection Assemblies\r\n        {\r\n            get { return this[\"assemblies\"] as AssemblyConfigurationCollection; }\r\n            set { this[\"assemblies\"] = value; }\r\n        }\r\n\r\n        [ConfigurationProperty(\"namespaces\", IsRequired = false)]\r\n        public NamespaceConfigurationCollection Namespaces\r\n        {\r\n            get { return this[\"namespaces\"] as NamespaceConfigurationCollection; }\r\n            set { this[\"namespaces\"] = value; }\r\n        }\r\n    }\r\n\r\n    public sealed class AssemblyConfigurationItem : ConfigurationElement\r\n    {\r\n        // repeat this pattern for each additional attribute you want in the <add /> tag.\r\n        // Only the assembly=\"foo.dll\" portion is defined in this class, and is accessed\r\n        // via the AssemblyName property.\r\n        public const string AssemblyPropertyName = \"assembly\";\r\n\r\n        [ConfigurationProperty(AssemblyPropertyName, IsRequired = true, IsKey = true)]\r\n        public string AssemblyName\r\n        {\r\n            get { return this[AssemblyPropertyName] as string; }\r\n            set { this[AssemblyPropertyName] = value; }\r\n        }\r\n    }\r\n\r\n    public class AssemblyConfigurationCollection : ConfigurationElementCollection, IEnumerable<AssemblyConfigurationItem>\r\n    {\r\n        public const string PluginsElementName = \"assembly\";\r\n\r\n        protected override string ElementName\r\n        {\r\n            get { return PluginsElementName; }\r\n        }\r\n\r\n        // this is extraneous, but I find it very useful for enumerating over a configuration collection in a type-safe manner.\r\n\r\n        #region IEnumerable<AssemblyConfigurationItem> Members\r\n\r\n        public new IEnumerator<AssemblyConfigurationItem> GetEnumerator()\r\n        {\r\n            foreach (AssemblyConfigurationItem item in (this as IEnumerable))\r\n            {\r\n                yield return item;\r\n            }\r\n        }\r\n\r\n        #endregion\r\n\r\n        protected override ConfigurationElement CreateNewElement()\r\n        {\r\n            return new AssemblyConfigurationItem();\r\n        }\r\n\r\n        protected override object GetElementKey(ConfigurationElement element)\r\n        {\r\n            return ((AssemblyConfigurationItem)element).AssemblyName;\r\n        }\r\n    }\r\n\r\n    public sealed class NamespaceConfigurationItem : ConfigurationElement\r\n    {\r\n        // repeat this pattern for each additional attribute you want in the <add /> tag.\r\n        // Only the assembly=\"foo.dll\" portion is defined in this class, and is accessed\r\n        // via the AssemblyName property.\r\n        public const string NamespacePropertyName = \"namespace\";\r\n\r\n        [ConfigurationProperty(NamespacePropertyName, IsRequired = true, IsKey = true)]\r\n        public string NamespaceName\r\n        {\r\n            get { return this[NamespacePropertyName] as string; }\r\n            set { this[NamespacePropertyName] = value; }\r\n        }\r\n    }\r\n\r\n    public class NamespaceConfigurationCollection : ConfigurationElementCollection, IEnumerable<NamespaceConfigurationItem>\r\n    {\r\n        public const string PluginsElementName = \"namespace\";\r\n\r\n        protected override string ElementName\r\n        {\r\n            get { return PluginsElementName; }\r\n        }\r\n\r\n        // this is extraneous, but I find it very useful for enumerating over a configuration collection in a type-safe manner.\r\n\r\n        #region IEnumerable<NamespaceConfigurationItem> Members\r\n\r\n        public new IEnumerator<NamespaceConfigurationItem> GetEnumerator()\r\n        {\r\n            foreach (NamespaceConfigurationItem item in (this as IEnumerable))\r\n            {\r\n                yield return item;\r\n            }\r\n        }\r\n\r\n        #endregion\r\n\r\n        protected override ConfigurationElement CreateNewElement()\r\n        {\r\n            return new NamespaceConfigurationItem();\r\n        }\r\n\r\n        protected override object GetElementKey(ConfigurationElement element)\r\n        {\r\n            return ((NamespaceConfigurationItem)element).NamespaceName;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/RazorViewEngine.cs",
    "content": "﻿namespace Nancy.ViewEngines.Razor\r\n{\r\n    using System;\r\n    using System.CodeDom;\r\n    using System.CodeDom.Compiler;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using System.Text.RegularExpressions;\r\n    using System.Web.Razor;\r\n    using Microsoft.CodeAnalysis;\r\n    using Microsoft.CodeAnalysis.CSharp;\r\n    using Microsoft.CodeAnalysis.Emit;\r\n    using Nancy.Configuration;\r\n    using Nancy.Helpers;\r\n    using Nancy.Responses;\r\n    using Nancy.ViewEngines.Razor.CSharp;\r\n\r\n    /// <summary>\r\n    /// View engine for rendering razor views.\r\n    /// </summary>\r\n    public class RazorViewEngine : IViewEngine, IDisposable\r\n    {\r\n        private readonly IRazorConfiguration razorConfiguration;\r\n        private readonly IRazorViewRenderer viewRenderer;\r\n        private readonly TraceConfiguration traceConfiguration;\r\n        private readonly RazorAssemblyProvider razorAssemblyProvider;\r\n\r\n        /// <summary>\r\n        /// Gets the extensions file extensions that are supported by the view engine.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> instance containing the extensions.</value>\r\n        /// <remarks>The extensions should not have a leading dot in the name.</remarks>\r\n        public IEnumerable<string> Extensions\r\n        {\r\n            get { yield return \"cshtml\"; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"RazorViewEngine\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"configuration\">The <see cref=\"IRazorConfiguration\"/> that should be used by the engine.</param>\r\n        /// <param name=\"environment\">An <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        /// <param name=\"assemblyCatalog\">An <see cref=\"IAssemblyCatalog\"/> instance.</param>\r\n        public RazorViewEngine(IRazorConfiguration configuration, INancyEnvironment environment, IAssemblyCatalog assemblyCatalog)\r\n        {\r\n            this.razorAssemblyProvider = new RazorAssemblyProvider(configuration, assemblyCatalog);\r\n            this.viewRenderer = new CSharpRazorViewRenderer(this.razorAssemblyProvider);\r\n            this.razorConfiguration = configuration;\r\n            this.traceConfiguration = environment.GetValue<TraceConfiguration>();\r\n            this.AddDefaultNameSpaces(this.viewRenderer.Host);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initialise the view engine (if necessary)\r\n        /// </summary>\r\n        /// <param name=\"viewEngineStartupContext\">Startup context</param>\r\n        public void Initialize(ViewEngineStartupContext viewEngineStartupContext)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Renders the view.\r\n        /// </summary>\r\n        /// <param name=\"viewLocationResult\">A <see cref=\"ViewLocationResult\"/> instance, containing information on how to get the view template.</param>\r\n        /// <param name=\"model\">The model that should be passed into the view</param>\r\n        /// <param name=\"renderContext\">The render context.</param>\r\n        /// <returns>A response.</returns>\r\n        public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)\r\n        {\r\n            return RenderView(viewLocationResult, model, renderContext, false);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Renders the view.\r\n        /// </summary>\r\n        /// <param name=\"viewLocationResult\">A <see cref=\"ViewLocationResult\"/> instance, containing information on how to get the view template.</param>\r\n        /// <param name=\"model\">The model that should be passed into the view</param>\r\n        /// <param name=\"renderContext\">The render context.</param>\r\n        /// <param name=\"isPartial\">Used by HtmlHelpers to declare a view as partial</param>\r\n        /// <returns>A response.</returns>\r\n        public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext, bool isPartial)\r\n        {\r\n            Assembly referencingAssembly = null;\r\n\r\n            var response = new HtmlResponse();\r\n\r\n            response.Contents = stream =>\r\n            {\r\n                var writer =\r\n                    new StreamWriter(stream);\r\n\r\n                var view = this.GetViewInstance(viewLocationResult, renderContext, model);\r\n\r\n                view.ExecuteView(null, null);\r\n\r\n                var body = view.Body;\r\n                var sectionContents = view.SectionContents;\r\n\r\n                var layout = view.HasLayout ? view.Layout : GetViewStartLayout(model, renderContext, referencingAssembly, isPartial);\r\n\r\n                var root = string.IsNullOrWhiteSpace(layout);\r\n\r\n                while (!root)\r\n                {\r\n                    var viewLocation =\r\n                        renderContext.LocateView(layout, model);\r\n\r\n                    if (viewLocation == null)\r\n                    {\r\n                        throw new InvalidOperationException(\"Unable to locate layout: \" + layout);\r\n                    }\r\n\r\n                    view = this.GetViewInstance(viewLocation, renderContext, model);\r\n\r\n                    view.ExecuteView(body, sectionContents);\r\n\r\n                    body = view.Body;\r\n                    sectionContents = view.SectionContents;\r\n\r\n                    layout = view.HasLayout ? view.Layout : GetViewStartLayout(model, renderContext, referencingAssembly, isPartial);\r\n\r\n                    root = !view.HasLayout;\r\n                }\r\n\r\n                writer.Write(body);\r\n                writer.Flush();\r\n            };\r\n\r\n            return response;\r\n        }\r\n\r\n        private string GetViewStartLayout(dynamic model, IRenderContext renderContext, Assembly referencingAssembly, bool isPartial)\r\n        {\r\n            if (isPartial)\r\n            {\r\n                return string.Empty;\r\n            }\r\n\r\n            var view = renderContext.LocateView(\"_ViewStart\", model);\r\n\r\n            if (view == null)\r\n            {\r\n                return string.Empty;\r\n            }\r\n\r\n            if (!this.Extensions.Any(x => x.Equals(view.Extension, StringComparison.OrdinalIgnoreCase)))\r\n            {\r\n                return string.Empty;\r\n            }\r\n\r\n            var viewInstance = GetViewInstance(view, renderContext, model);\r\n\r\n            viewInstance.ExecuteView(null, null);\r\n\r\n            return viewInstance.Layout ?? string.Empty;\r\n        }\r\n\r\n        private void AddDefaultNameSpaces(RazorEngineHost engineHost)\r\n        {\r\n            engineHost.NamespaceImports.Add(\"System\");\r\n            engineHost.NamespaceImports.Add(\"System.IO\");\r\n\r\n            if (this.razorConfiguration == null)\r\n            {\r\n                return;\r\n            }\r\n\r\n            var namespaces = this.razorConfiguration.GetDefaultNamespaces();\r\n\r\n            if (namespaces == null)\r\n            {\r\n                return;\r\n            }\r\n\r\n            foreach (var n in namespaces.Where(n => !string.IsNullOrWhiteSpace(n)))\r\n            {\r\n                engineHost.NamespaceImports.Add(n);\r\n            }\r\n        }\r\n\r\n        private Func<INancyRazorView> GetCompiledViewFactory(TextReader reader, Type passedModelType, ViewLocationResult viewLocationResult)\r\n        {\r\n            var engine = new RazorTemplateEngine(this.viewRenderer.Host);\r\n\r\n            var razorResult = engine.GenerateCode(reader, null, null, \"roo\");\r\n\r\n            var viewFactory = this.GenerateRazorViewFactory(this.viewRenderer, razorResult, passedModelType, viewLocationResult);\r\n\r\n            return viewFactory;\r\n        }\r\n\r\n        private static Type GetModelTypeFromGeneratedCode(GeneratorResults generatorResults, Type passedModelType)\r\n        {\r\n            return (Type)generatorResults.GeneratedCode.Namespaces[0].Types[0].UserData[\"ModelType\"]\r\n                ?? passedModelType\r\n                ?? typeof(object);\r\n        }\r\n\r\n        private Func<INancyRazorView> GenerateRazorViewFactory(IRazorViewRenderer renderer, GeneratorResults generatorResults, Type passedModelType, ViewLocationResult viewLocationResult)\r\n        {\r\n            var modelType = GetModelTypeFromGeneratedCode(generatorResults, passedModelType);\r\n            var sourceCode = string.Empty;\r\n\r\n            if (this.razorConfiguration != null)\r\n            {\r\n                if (this.razorConfiguration.AutoIncludeModelNamespace)\r\n                {\r\n                    AddModelNamespace(generatorResults, modelType);\r\n                }\r\n            }\r\n\r\n            using (var writer = new StringWriter())\r\n            {\r\n                renderer.Provider.GenerateCodeFromCompileUnit(generatorResults.GeneratedCode, writer, new CodeGeneratorOptions());\r\n                sourceCode = writer.ToString();\r\n            }\r\n\r\n            var compilation = CSharpCompilation.Create(\r\n                assemblyName: string.Format(\"Temp_{0}.dll\", Guid.NewGuid().ToString(\"N\")),\r\n                syntaxTrees: new[] { CSharpSyntaxTree.ParseText(sourceCode) },\r\n                references: this.GetMetadataReferences().Value,\r\n                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));\r\n\r\n            using (var ms = new MemoryStream())\r\n            {\r\n                var result = compilation.Emit(ms);\r\n\r\n                if (!result.Success)\r\n                {\r\n                    return () => new NancyRazorErrorView(BuildErrorMessage(result, viewLocationResult, sourceCode), this.traceConfiguration);\r\n                }\r\n\r\n                ms.Seek(0, SeekOrigin.Begin);\r\n                var viewAssembly = Assembly.Load(ms.ToArray());\r\n\r\n                return () => (INancyRazorView) Activator.CreateInstance(viewAssembly.GetType(\"RazorOutput.RazorView\"));\r\n            }\r\n        }\r\n\r\n        private static string BuildErrorMessage(EmitResult result, ViewLocationResult viewLocationResult, string sourceCode)\r\n        {\r\n            var failures = result.Diagnostics\r\n                .Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error)\r\n                .ToArray();\r\n\r\n            var fullTemplateName = viewLocationResult.Location + \"/\" + viewLocationResult.Name + \".\" + viewLocationResult.Extension;\r\n            var templateLines = GetViewBodyLines(viewLocationResult);\r\n            var compilationSource = GetCompilationSource(sourceCode);\r\n            var errorMessages = BuildErrorMessages(failures, templateLines, compilationSource);\r\n\r\n            var lineNumber = 1;\r\n\r\n            var errorDetails = string.Format(\r\n                \"Template: <strong>{0}</strong><br/><br/>Errors:<ul>{1}</ul>Details:<br/><pre>{2}</pre><br/>Compilation Source:<br/><pre><code>{3}</code></pre>\",\r\n                fullTemplateName,\r\n                errorMessages,\r\n                templateLines.Aggregate((s1, s2) => s1 + \"<br/>\" + s2),\r\n                compilationSource.Aggregate((s1, s2) => s1 + \"<br/><span class='lineNumber'>Line \" + lineNumber++ + \":</span>\\t\" + s2.Replace(\"<\", \"&gt;\").Replace(\">\", \"&lt;\")));\r\n\r\n            return errorDetails;\r\n        }\r\n\r\n        private Lazy<IReadOnlyCollection<MetadataReference>> GetMetadataReferences()\r\n        {\r\n            return new Lazy<IReadOnlyCollection<MetadataReference>>(() =>\r\n            {\r\n                return this.razorAssemblyProvider.GetAssemblies()\r\n                    .Where(x => !string.IsNullOrEmpty(x.Location))\r\n                    .Select(x => MetadataReference.CreateFromFile(x.Location))\r\n                    .ToList();\r\n            });\r\n        }\r\n\r\n        private static string[] GetCompilationSource(string code)\r\n        {\r\n            return HttpUtility.HtmlEncode(code).Split(new[] { Environment.NewLine }, StringSplitOptions.None);\r\n        }\r\n\r\n        private static int GetLineNumber(int startLineIndex, IReadOnlyList<string> compilationSource)\r\n        {\r\n\r\n            for (var lineIndex = startLineIndex; lineIndex >= 0; lineIndex--)\r\n            {\r\n                var match = Regex.Match(compilationSource[lineIndex], @\"#line (?<row>[\\d]+)\");\r\n                if (match.Success)\r\n                {\r\n                    return int.Parse(match.Groups[\"row\"].Value);\r\n                }\r\n            }\r\n\r\n            return -1;\r\n        }\r\n\r\n        private static string BuildErrorMessages(IEnumerable<Diagnostic> errors, IList<string> templateLines, IReadOnlyList<string> compilationSource)\r\n        {\r\n            var messages = errors.Select(error =>\r\n            {\r\n                var lineIndex = error.Location.GetLineSpan().StartLinePosition.Line - 1;\r\n                var lineNumber = GetLineNumber(lineIndex, compilationSource);\r\n\r\n                if (lineNumber > 0)\r\n                {\r\n                    templateLines[lineNumber - 1] = string.Format(\"<a name='{0}'><span class='error'>{1}</span></a>\", lineNumber, templateLines[lineNumber - 1]);\r\n\r\n                    return string.Format(\r\n                        \"<li>[{0}] Line: {1} Column: {2} - {3} (<a href='#{1}'>show</a>)</li>\",\r\n                        error.Id,\r\n                        lineNumber,\r\n                        error.Location.GetLineSpan().StartLinePosition.Character,\r\n                        error.GetMessage());\r\n                }\r\n\r\n                return null;\r\n\r\n            }).Where(x => x != null).ToArray();\r\n\r\n            return (messages.Any())\r\n                ? string.Join(string.Empty, messages)\r\n                : string.Empty;\r\n        }\r\n\r\n        private static string[] GetViewBodyLines(ViewLocationResult viewLocationResult)\r\n        {\r\n            var templateLines = new List<string>();\r\n            using (var templateReader = viewLocationResult.Contents.Invoke())\r\n            {\r\n                var currentLine = templateReader.ReadLine();\r\n                while (currentLine != null)\r\n                {\r\n                    templateLines.Add(HttpUtility.HtmlEncode(currentLine));\r\n\r\n                    currentLine = templateReader.ReadLine();\r\n                }\r\n            }\r\n            return templateLines.ToArray();\r\n        }\r\n\r\n        private static void AddModelNamespace(GeneratorResults razorResult, Type modelType)\r\n        {\r\n            if (string.IsNullOrWhiteSpace(modelType.Namespace))\r\n            {\r\n                return;\r\n            }\r\n\r\n            if (razorResult.GeneratedCode.Namespaces[0].Imports.OfType<CodeNamespaceImport>().Any(x => x.Namespace == modelType.Namespace))\r\n            {\r\n                return;\r\n            }\r\n\r\n            razorResult.GeneratedCode.Namespaces[0].Imports.Add(new CodeNamespaceImport(modelType.Namespace));\r\n        }\r\n\r\n        private INancyRazorView GetOrCompileView(ViewLocationResult viewLocationResult, IRenderContext renderContext, Type passedModelType)\r\n        {\r\n            var viewFactory = renderContext.ViewCache.GetOrAdd(\r\n                viewLocationResult,\r\n                x =>\r\n                {\r\n                    using (var reader = x.Contents.Invoke())\r\n                        return this.GetCompiledViewFactory(reader, passedModelType, viewLocationResult);\r\n                });\r\n\r\n            var view = viewFactory.Invoke();\r\n\r\n            return view;\r\n        }\r\n\r\n        private INancyRazorView GetViewInstance(ViewLocationResult viewLocationResult, IRenderContext renderContext, dynamic model)\r\n        {\r\n            var modelType = (model == null) ? typeof(object) : model.GetType();\r\n\r\n            var view = this.GetOrCompileView(viewLocationResult, renderContext, modelType);\r\n\r\n            view.Initialize(this, renderContext, model);\r\n\r\n            return view;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.\r\n        /// </summary>\r\n        public void Dispose()\r\n        {\r\n            if (this.viewRenderer == null)\r\n            {\r\n                return;\r\n            }\r\n\r\n            var disposable = this.viewRenderer as IDisposable;\r\n\r\n            if (disposable != null)\r\n            {\r\n                disposable.Dispose();\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/RazorViewEngineApplicationStartupRegistrations.cs",
    "content": "namespace Nancy.ViewEngines.Razor\r\n{\r\n    using Nancy.Bootstrapper;\r\n\r\n    /// <summary>\r\n    /// Default dependency registrations for the <see cref=\"RazorViewEngine\"/> class.\r\n    /// </summary>\r\n    public class RazorViewEngineRegistrations : Registrations\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"RazorViewEngineRegistrations\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"typeCatalog\">An <see cref=\"ITypeCatalog\"/> instance.</param>\r\n        public RazorViewEngineRegistrations(ITypeCatalog typeCatalog) : base(typeCatalog)\r\n        {\r\n            this.RegisterWithDefault<IRazorConfiguration>(typeof(DefaultRazorConfiguration));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/Resources/CompilationError.html",
    "content": "<!DOCTYPE html>\r\n<html>\r\n<head>\r\n    <title>Nancy - Razor Compilation Error</title>\r\n    <style>\r\n        html {\r\n            height: 100%;\r\n        }\r\n\r\n        body {\r\n            background: linear-gradient(-180deg, #000000, #434343) #000 fixed;\r\n            color: #333;\r\n            display: table;\r\n            font-family: sans-serif;\r\n            height: 100%;\r\n            margin: 0;\r\n            width: 100%;\r\n        }\r\n\r\n        img {\r\n            float: left;\r\n            margin-right: 40px;\r\n        }\r\n\r\n        h1 {\r\n            font-family: sans-serif;\r\n            margin-bottom: 5px;\r\n        }\r\n\r\n        h1, h2 {\r\n            color: #333;\r\n        }\r\n\r\n        .container {\r\n            display: table-cell;\r\n            vertical-align: middle;\r\n            padding: 20px;\r\n        }\r\n\r\n        .box {\r\n            background-color: #f6f8f8;\r\n            border-radius: 4px;\r\n            box-shadow: 0 2px 4px 0 rgba(0, 0, 0, .3);\r\n            margin: 0 auto;\r\n            max-width: 960px;\r\n            padding: 25px;\r\n        }\r\n\r\n        .header {\r\n            border-bottom: #ccc 1px dotted;\r\n            padding-bottom: 20px;\r\n            overflow: hidden;\r\n            vertical-align: middle;\r\n        }\r\n\r\n        .header div {\r\n            float: left;\r\n        }\r\n\r\n        .details span.lineNumber {\r\n            font-weight: bold;\r\n        }\r\n\r\n        .details span {\r\n            font: normal 14px/20px Monaco, Monospace;\r\n        }\r\n\r\n        code {\r\n            display: inline-block;\r\n            font: normal 14px/22px Monaco, Monospace;\r\n        }\r\n\r\n        footer {\r\n            color: #f6f8f8;\r\n            font-size: 12px;\r\n            margin-top: 10px;\r\n            text-align: center;\r\n        }\r\n\r\n        pre {\r\n            background-image: -webkit-repeating-linear-gradient(top, #efefef 0px, #efefef 22px, #e0e0e0 22px, #e0e0e0 44px);\r\n            background-image: -moz-repeating-linear-gradient(top, #efefef 0px, #efefef 22px, #e0e0e0 22px, #e0e0e0 44px);\r\n            background-image: -ms-repeating-linear-gradient(top, #efefef 0px, #efefef 22px, #e0e0e0 22px, #e0e0e0 44px);\r\n            background-image: -o-repeating-linear-gradient(top, #efefef 0px, #efefef 22px, #e0e0e0 22px, #e0e0e0 44px);\r\n            background-image: repeating-linear-gradient(top, #efefef 0px, #efefef 22px, #e0e0e0 22px, #e0e0e0 44px);\r\n            color: #555;\r\n            display:block;\r\n            font: normal 14px/22px Monaco, Monospace;\r\n            margin-bottom: 0;\r\n            overflow: auto;\r\n            padding: 0 1em;\r\n            white-space: pre-wrap;\r\n        }\r\n\r\n        footer a,\r\n        footer a:hover,\r\n        footer a:visited {\r\n            color: #6daf00;\r\n        }\r\n\r\n        a,\r\n        a:hover,\r\n        a:visited {\r\n            color: #e74c3c;\r\n        }\r\n    </style>\r\n\r\n</head>\r\n<body>\r\n    <div class=\"container\">\r\n        <div class=\"box\">\r\n            <div class=\"header\">\r\n                <img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHMAAACWCAYAAADtyrfXAAAwR0lEQVR4Xu2cB1gUVxeG71LEhmCldxQUFRBQQLpUC6IIghUbKAiKXRAr1l5i7SUmlth77/HXmGg0iUlMNJpijUZNTCzs+b87M+sCCyxo1IA7ed5nZ4dieXPKPfci01waNGjQUFJs3No4NG3Va2FYXFqERkAxsbKyqmlra3uidu3aIxwcHHTetUQ7j7b6th5ts12bdb4XHt/vRbN2KTl+UUkZ3i16amlsqcHCwkLP0tLyjI2NDdnb238CqZXfhcTaTdpp2zeJ7lC7SdvrzoEd/w6LT8sJjkkh/6jeBJFyj9CEeS5BnXQ1xtRghsvc3Px7a2trsrOzOwmhNd+myDpeMc51PNsdcvCKka+a4EjzsnxyQmIhsg1EtuxJHmEJ5BLUmer7xW/G51TWGFODiYmJNZxeQZQS0u639rjetETHprHVHb1j50LQU0ABUXHy71eb0j+LGa3p25B8W/WkxuHdCCmXiySIJKTgU5YukbU0xtRgbGxsBamXkXoJafcmorTxm5BYzydOt55P+551m7a/A6EEodSmvx+lrDSg2JQOdHqEHT0dyKh/VCA1ataFGvh3ED4H9ZQsXSPJpH7z72o4hNbWGFODkZGRCaReQNolNEePEKWR/6ZIRJiPk2/cGUAQShBKnpGtqUtWlLzjSl3yHlee/DpH0rBof3IP6UJezXsQF27XuC1ZubYm43qhVN0+gAztmv2mbx3Y5L2UdPLkyYrnz58P/uyzzwacOHFi8r59+8Zs2bKl/dKlSw3yC6hZs2Z1SD1hampKSLtPUUuTXldiw4COxoiwFfX9O7yAUHICXKh/bBQN3VyB2o1rQM1TYsl2aHmq1cGa3CCySXh3Cm/fT4hKq0atycQpnKrZ+lIVS2/St/J/AZkd3huBX3/9tezGjRuev/zyy+qff/750fXr1+nH7y7TV5cu0pkzZ+jQoUO0ffv23z/++OMeAwcOlOUTWhlsR9olpF05hGYj9ZZ4eYAOVM85sNNAdKgPIJQgVIALDWzZlnqnxlHnWY7UbDajeilW5BYdTS6h8eQbmUj884Papgip1rR+BFW386MqVlyknxwi098bkXfu3HH9/fffd//xxx85jx49osfXv6an00MoJ1Wfng63oxs75xGiVBC6bds2+dq1a6fNmjUrj6zq1avrQehyRCkh7fIoXQmp5YsjsVFwFxkalxB0oV9DKEEo6AhBnA7kFtyZLqwxp1srytOg3m2pcT9XMuypT87hscQ/PzQ2jRqHdRNEeiPV1qwTQAZcpKUvQeRkICvzEm/dulXh4cOHk/7888+nf//9Nz179oxycnJIfnAmnYivRq2sGE31ZJTTR49+PLlTiND9+/fT5s2b5atXrx6eXwqEaoEJtWrVkktpdy8wLEqkW0hXO7fgLp9AaA6EEie3ULfQjhSf4UMZg+PowdwK9CBLh4bHhZBLWBx5RnTndVJIsQGte5Otexuq4xFJhtZNIdKHi1wJtMu8yAcPHjj89ddf5//55x96/vy5KFEuJyKQ85x++ukahYSEEPIpfdmO0f0NWfTVV18Raijt3LmT1q9f/ww1VKWpqFq1qqxatWp9a9So8Rxpl0fpFxBqkV8i1oOVwCj30K5/QihBKDXiKIUKJIwKobTNjCLGWFGP7nH0XZ9q1L1lmCC9acteFBzdF8uQWCxNEsnWtYUkElgH7gR6ZV7k48ePQxCJ9/JKlK67V0nez5Cca+kSBFBFHUY3OjB6tHsm/fjjj3Tu3DkhOjdt2kRr1qw53K1btwJTGKRGIUr/5GkXa9JrqKUN+PMmEd21moR3i8aa8AfIJA6EEoRy8gj1bZ1EkQkDqO0YD3KbKCOzxFpIo53JHfKD2/UVainqJJqjeKqNiETDA5HeEBnwKUTql3mRiMa2T58+ffLixQuFxLzIc4hmh9OPcYyyPRidjGQkH25Dj27fIDRHdOnSJTp27BivnYRmSL5o0SIXVshlaGjojSi9hbRLSLu/13Zyi/Ns3n0/hMohlCCU1zpJKEcp1AdNTfOO/SkkNpX4qK5RTz+yjHaDaDFqw9qnCanYIwQTH/84qmrjoxB5GSLL/qDgyZMnYaiL/+SLRlX+fkS0JYNoWgDRh0n04s5VwtcSGiX67rvv6NNPP6Vdu3bxVEsrVqwYw8UVIbQOovSykbEpuQXFCDUOQglCOQUKxQ6IIDK0fSoFtu1DPniPz+WpGO+TCYMERGhPPoclK5eWZFQnULEE+Rki7d4HkXUh8gEXWdKLy+e1FR0vT7VCI7R3717auHEjrVq1ar/aea5VHXNX/zaPvVsKAiShILdQAKGSyHQKjYPI6GQhQj0lkYhEHpHCvSPqpGdYAkQGKETeh0iXMi8S9bEcRJ6VovGVZCI104MH9+nK1W/o6JmNtH7/GFq8oxfN3trizthDbBKYCIaCOFAbCEsXrAG1IWQll8R5KbRFXqFIu2hoxIjEviQFQaRv60QhipF6+TJFnABF9ECzk0RmDZqTab1gSaTfE4gMZO/DBZFdpYgsMX8+vUVf3VpHO7/pQwtPu9DEI5UIotSRA86OOSgL8GudlA2h5MMpRCiEKUXGQ2S7FKH5QQQLaRdLFGGch60vquMZQ03xteZOIYq15HOIjGHvy4Vm50Rx5cnx3+3HF+nY1bG09Kw7ZR/W4XJeicRZTs+xWSyHUMgpXKhHSAcKjEyglp0HUDOIxNcIz1FDhdSKUR4ktiMbtygyb9iSrJ0jIFJYS+ZAZPJ7IxJ1Thsy76uT+Mff1+nkT5No4ZmGNO6QFpfxWqQttULNS+QbxoKcPEIBhArR2CSsC5lb25OFpRX5RsSjc+0LyYp9SYXIGLLBQMDcuSWmO4G515JjVKY7ZXw4IEOa/bGgepkjf0FX7u2idV+2ovFH9F5LXvYhPRq/3p3aj2LUb0UtCo7rSQHoRAOwaewPIFUSChRCEZ1eobFU08iUjIxNyCssnnevgkjXoFz7khBp4dyKajkEcZGKJcgiiCybx0OG7mYyoFVIJ5sNocTBOpPu379Pt27fpNNfr6edZ8fT1k9H0cdH+9PS/R1p9p4AGr+/WolEDlytT+e/30MY8VGFSlXIp2WC0MBgGSEJ7SMKVUYpZPairon9aPPWHeTqGUgOrn7kj8gtYIOZLFwiycgxWLmWtArYApFl71jIsD3MIPswGzD7FPt6+gl2e+R+thVSmyvEXr16tdpvv/02/Pbt2zk3b94kzGMF+P2vv/5K2CmhH374gS5evEinTp0SlhxrNi6noevq05hiiOw4qhIdOrJfWK6cPPUpoqsDNYtJ4bVPFMopQGh42y702dkzdOH4JtqzsD91a+lBPmFxGBiobjAb1w3NJdL/GERWKlMSh+9hlcYfZoPnfMpuLTzLCCJp5klGS88xmnqcybP26R//+daVifdxYZhOGOERBupCZAJ+LzzDTgkfBmAW+5Mg9Pjx47R9x3bqPbcrJa4xKlJoTIYubd26ha5cuUK6uuWoZVwSBcf25XVPKbRdMqRKQqW0GxKTTF1SR9G+TUvp3pDqdDrGkD5rjWF+fGVq5hcubDDbN44WNphN6oXl2pf0uwiR1cuMxFH7K2hPPirrMusku8oFjj7AaNhuRkMlRuxjtPh/9enqrc+EqQ0W+0J6xRz2JWiIFPfCxyGVCxUi9OzZs4TNaBq3LIvaTvOmlM0Fi+wxS0YzZk2l06dP044dO6mRbwthYhPCKVRoMjVpBkk2dhTQqjM179CPhoyYQP6tUCMDO9DiuHq0JLCaEJHYYOb7krlF/gSRlmVG5OSjFf3HH5b9b+xBRohMyFNl0ekg+uPxbUEgpCkG6YWiGAggQoWUe+HCBTp8+DAtWbeQYqc2p8gF5WnUgbwih29llJgWK3z/YcOGUXSn3sJCH+QVCl4KBWGY6ljaOhD2PamOUyNBOtaSL4cCndsG0dHWumTeIBwimys3mC1970KkU9mpjbtlgRC4EMKWgQ3gCLgGnipEzjnhTo/+uidIVMhSd0Eoj1Ah7aK28m0uYZC+ccsG6jg9iiJm16C0rXlltkk2FcTfu3eP4rr2pghEGA4hUxhQCAXikFwSiugU15HRSWTv5IFmpxfvaKWhQCdh3to7pintaq4rNDs17P2loYDPY4j0VRFQRjvYmqBV9iHTTbf++JaKHKI/vEX00znwmXgvyYR8XkeFxuibb74R6ua2bVup+6x4aj7LlLp+pBTZbxWjTZs3EM4JUaeERIrsOhAy+3PyCpWk8qbHwTuGzLDYx0BdEOsnHlYmj9Dca8l2NL+7A41vXFkSKawln2EJEsnepwvRUv7e46urixzZ3bxMdOdHLk6A7l0j+uVioTJx3oeS53YTZMauVMocvSBSSMtLlq+BvFRq0SkdYziOUigQRCLqxCbGqTnVcAijqnbBGMlF8+mOciiAJQgONpO9RxRdTtOnIDtjxVoyByJ7vG8ia88+afW/f549piKvJw+FbhUHrfhxDmEJQr9+RfK/HijSrLBcwcGul/uVaR/0oohZtSh6uShy1C492rt/O3Xu2o1GTl4gpE0gCgUKoYhGYWmB9aEgsiZE4rgjn9hwUA9b8HlrnqFAu4imdLmzFlUxqsdFyrGWzHzfRLYD93d/27dY9ZEf1poxYwbJZDJydnYmykFtRdqFTKGjxbpT2Hw+cuQIlhxbqe/cnhQ+R5/aQeYYNF0J2dVoz74D1KxtDyG9tuoyMI9QRKRwCgByChGppHrtEL78ENeSkL6rjzGlN6xI+uaefC05p0xNd76986HOzJOVWmAIEImlhwPqol4uiTpgEsgB9NXN9UVbvPUd0fN/qFmzZsQYEwgMDBSeyX/+Mk83i/OydPDgQdTFTdRrVgcK/UCb2qNOjtzHyKKuHo2bOp9aJwyCTBGFUESjsEWlXqQSA9sgIUqb+fvQjV5aVLOWLUT6rYNInTIjcsMlF7u1XxoeWXWe0YovGC04w+QzTrCHGBJ8inXk3Kz9bC8i5WUdu/HgVNEyIY2uf0Hff/89RUVFUZs2bYR7unaWcp4+Iex3Kjae+ZFKYZ25buM6ipsRRCHzmNAARQ3RxhqxDbXpNpiiQOuEwYJMdLLCIWQ0MEqR9RUig7m0orH0pe2J1WmoSwWqZOZ1AM8qlBmRC85UbLfyvPbvfKoz+RijaScYYcpD/P2yzxktB5OPMsrcq5R57fcj6tPs/RtEP18Qj4SgftLV/xH9fv1lvcS4j7799ls+0hOOhCz+cAG1muFAwR8w6rSQkVd4CLXpPoQDmUOoNUT6YZbq5BenKtJRvcjKln5UydyLQrzq0dVuMjKpWutjPK9aJiRm7dPWnX1KNmXJOZYzEbKG5RsKDN7FaNBOcViA1JtH5rmfF6mXycl5LqZcgHvhaxQpFqfYhQbp6NGjQvMzatFwCp1dhYJmM/KP8xRFSoTHpQoHk+v5llwk6iEkeiMKm1A1S48X5/tWlA+tx65AQMUyIRKpswrmqjtnneKSlAKHQGDSRkZtlzEKRbprNpcJaa8N3vffppT58flIUj1tpx7FkuTu3bt5RnnrkWI7zgiloDky8updj6dVQWKrzunYtupOzgEdJZExKiKrFibSKoAqWzTlEgVsfes+39rP4OMzUSynii5rVyZEQl4NpM3TYw9KEYjo67eVUbd1jFouZhQ4p2DC5jPKkKIz+7Au3fzjKz4wKPEhLUSlcIQSkx9hfblz5w4atzSLwmeYUZM0S2rdbYAgM7hdH3SqnbGkKLFIpFQfCPQUJNao60rhQ2tQ1gYZPRrC/m5hxnZAgKwsTHDKI23+j6fUvpsZFudiBAZxYWrA5yHlKqNz9blQ+vufJ+oiNM88FssRoVZi14NHpXC4edm6JRQ7vRm59q1FLRNSKSKuL3lGdBGaHIgUpzXS2tBSENlCFGkfXEhdFCXqWzYm93grSvxQm/ptRgeO9D3bmz2AAOuyMo4bz+eecavYi4gF7BcIuoiI+xE8RUotVCT/WPImUSK6WoHR4MC3I4XOVHlSXXWoDtmiSGmnBPudfDkirC3XbfkYI7w4ckm0opBO3ck3MgEjOOFgslKkp3qRlYW66EWBLRMUKZXiZ1fk/8MKbF7J6FIfRn5j2Z8eU1gft8lMq7SLdEVNPJm6hSVCqDlqozZ/DrFaSL1BGXvYUy464WMmTGCaLxSjscUiRikQOfoAkCSOOqBAiw59O1EQBal5tr5wzyUK22LY3xQi8tq1a/Tll18KPz+yftvHlDinEzVIsKPG0S3IK7KzeF4VItVHpGpd5OdZt+zYR55da1DyRpnwe04G01A+7g1i1GOs2Au4T2bkOomtd57ADEqzTBugVcBUxwpcB6RgjCQM60u85hGIzlYki7OPI6ONXyTS7bu/kWJTGgjTH9RHodlBjeSpVdjuOn7iOC3+ZAF1mx1Lfpm2VDWwIjUKiS62yCo2XCSX6CNIrGoNmaaNqXPPAfTT9Z+o83wtQWIfkLGB0Z3RjLIGMuoJqe0RoYhKcpnIqOF4drF+Niv0NLrJUFbXeCgbCzYaD2HZ1fyYoYHdf7jWQlwVcEEpkZNPXgECR0hkcvaKjdG0w/XozLcb6ZdffxHGdBAonCaARN7sCDVy896NNHx5OrWfGUyhM2tS8wWMbAMZaePUgJ1zoDqRUl30fVkXK+P1g4WrSEdPX1irbt27mnojKnt/wigdIq9OYbQ4hVGnVYwS8b7DakaNJjFCVFKD8YzqjWO/OY5lbrkFmCYwe7PhbBVkPodIMh7MqFoQy4HItaDDf1IkpOmALYI8dQJV5EmgIRougREgkNGMQ+605fQYOvn5Tjp77jQdPLGflm9fSENX9KEOHzSlmIXmqNlawhIofTuj1E8YOTWTkba2NtW0dOLryIJFSnUREqWI9CKXxoHCAGLOnDm0Z88e8kuoJHzfFIi7OIvR9t6MYlEmeuF9z/WQ+iFSLI9KyERUUl2kXocx7EHtUczXJJjZmISzHWbJ7LnpMEgcKlK9FSNI5DwBV8F/r95C3uhCBXJ5xRSoXKOKDObs5Mho8PaK1G9TZUrdVJ7StmhhrcoFSuB+wHYtmnioLs087kX9Z/pQfRcHMqhpgZ3/CDJViLRrJtTFKhZefPMYIhtTFWNHWrV6DbVq1Uqoz5+e/pT8OhlSLwhLhrhzaNgOJzGKmStK7LFOpNMaCMxEVEKk0zhGiEqqgzRsl8H+MIlgv1mkMTIfzshEIXMII8OGokyJB6Dcf0ok5DUHzxUCs4onEPKKFjhIYuAOkQGc7XkFQijWtSIj9hrTnJMBOLEgMmFbAIW19SC9igY4HedNhjb+PJWK0xsbH8oYMw0ptQrVrVtX6JLnzZtH5z4/RyGJNQVpfcA5dN/HEhlFzxIFdpfo9jFkIs2adkc0Qmg9MSoJUUlW6HQtOHhuNlwZlUb9INA+j8zHoPx/RiTkmYPbRQrk8tQJ3JlL4I7iC0yTQFdN4w7UESTOPh5AsySmHwkgz1ZGJNPSpvLVagsi+w+fSBZ2zkINjoiIoPbt2xMuQWT0UGuhuekLLs5kdEgUCXkiCZyPOKLMKpEQ1QMSM8WotOcyUwDem2cwyp1iayYItZJy8fA/IxPSdCBw36sIHKxeoFJeEQI5fTmbGWUfqCcInJmbYwGUscOGTOoyYkxGOhVr0HVslQ0YMIAuX74sNFSLFy/GgP4k9ZjgLETfQIi6gmZnC0S2naMQqKQr6LKWUUfIrBrBqGJzRF03RjYQZzeSkTWi0VKMSmWKBTWi2Yt8Mu8Anf/KKC+1yAZGKU+9QC6uJAI3i6QAaQ2IyKz/UmDmbivK2mNPkw970Yjd9tQ8U9wH1dXV5cscYe/z888/J1zY+/yEek12R2rVptFoam4iwhb3hsj5XBxYK74mb4NoZKAB+8RxZYdVLMc8jD00DGFUAVKrd0I0DkBUIiIt8kUlp3pzlci88k6XJ4gILRAGtkDKPyoNjDqBatInKEgenmnToO361H+rXh6BfTifCCAyG9KMowE0Zp+T0IUmcjbIBLpDSAUDRpUrVxZmuriEIf3CxfModpwxUqsuLVjB6N5glIs0RjFLefSJdEVk9tsDkQdEBkBo8nZhafK3ZTPmYxzEvqgeiggNZ6TfBhGItGuUyqhWGu5TQQpEJiOKA5k8n8yj71KkKdgN5P22vW4Do14gQNeqQ6P22tDEgy40ap89vt4gj8DeHEhLAuMPuNG0IwH4miqK5QNQdqAmTozwI+18miQsQUaNy6TYidWpF6JuD6LwpxR8HqIpfiWjzmvBhyKpu7hAkXREZX+QiowTv5r92X4F09O3Z5WM/Fj/msHsW8NQlqMPsQaI1MqgfBgjvRAA0VU8JYlKZr8rkWbgCiAASSoCS9bAFCEQ6RMRWJ4G76gK4ZXxTLcwgVL0cWQ06VBTCPXILRAou0/rJoiSGjWEnysJCPGi9tMMaNAaRt9NZnS4F9LqeNTBNXz9CNaI9z0/UQrsJ5EG+u4RZtK/YwqkrRCgU4lV1LdjnpDbr5ITW1u5MfuqSiD7C1DFAMj0UpEZ/C5E6oGTgABkvJkGJgUM2m5I4w82pAmHXPBMN4/ApHwCe0lwccmfVKQphwNQJ524PKDagZo5M+EwmH5NLWo1kdEHPK2ils3ow6j1XKVAgBQq0neXJFAida9Iym5hl+hG7IoCa54OMAT2uPPVrc0SDbzZ7Gr+7IxUJy+BNCB7FzKng7/BXwDCCmpgwKs3MECGdGqP5sUfC383vNdB9BUqUCX6hqJjnQyZY/e55xKobGC6INr0jZFmrSBrFqMjkPcDJPYYgvq4TCkwXgRRB7kf5RXIozEFJIPekNxuBbtQDAEyoA10ytdkOlVsmeydSJREhoNJoB24D0HFqn9AkldkBwrEyBuy04hmHAtAdHlBpF6xBHYXQVRWoez9nhDZGLXVnxLXVxIFSnQGMQsY2TRllInXn8cw2tSTUeREiFuVW6ASpE/qtjGvwD6c3SK9kHWil7H9rLRckFEONAC+4CGgdHUNjHqBBda/zN22NA2daPrWapJA1QYGSweIq4wGpyY+zwSY0fCdjjThgB+2qaoiErVo5J5GGPvVlhoYZf3rAlnrFzK63Q81PhVpdX4egZAnEstZAfmg5xYuLi+9QRJIQEZps5StKK4AItIF1e79eaecZaae1rsS6gn+ABBW5ARGosDoU9fAoFaaCM2LagTKqP8WI0hyRtT5oskJoEkHRSZKZO12VUQg5rYmNG6fD95rv6x//SHrazQ5p3ohNWZxWYULbAcQcdQWIKKFdB2/Bs9XAi6dDww2gY14v1xnXHFF3v3ztya9P2m+0Hqk7vdGKewXg9osE+k2Esjelsg64BYg8PoCC69/EFYd0emgMv/M2OWoEAjZPjRshwOObZgipXrRBOGZHyLZ8GUE9v3EFCk3gJLW1xBq4GxIuYsmZ2YSoxYzChYIIEYkGkAkok6UmYwITEMWStmKSIXADnjWGqLDkK4jFlT8PGZZ7YSFJ0YaEpGsEJFaJ67udGuxzOpCnfHiRKiquET5B9wE3m9DpD64CEhJMeofkOSVpIFB6qyBpYi1SgeavsWcMnbWo7TNpniu8zJ9dvuoHKRaYmfDQBGBQAuf64bIDKB+G0xoH5qcq30QXQMgZ7FqBCoFKqJREglaL0FNXczfi5GZgCzRi3fUm/GKyOyKzBGDNB2+iJH/HJ1bgXMMJscuc7HML2DF2Sl2AQuqXnJCZjDLYGSUojJsn/E2ZM4HBJ6Bf1ugSgQO3GZBA7Za5O1AJZT1TyLf8gG1D891acj2BjQWIufsbELXJpej3T0YNR8LecuLFthGImopXiUiIbPlIh59/CShSMRC8cRhFARH87QLmdGr8AzvA+cx8pgqe9JoUvn5/jPNBKnp6+MNm0yv+JkrMoJlljjSq5Wksta8BGRvOr1yiUfANYgsoANVKxDiihYIII+/ymj0XneePlUFKuSpCpTQot6IwqzdXjRmbwCt2dyQfs/UpamJEDFTjUBIixJBJIpEqciUzvx+IB5G85vFyAfftykEeQMvznRGTYDbFEYNJjByGi977DhCZ4pVN60dfFvMdrRy4G6UrCLzKajxJmVOAXPAVgCRhdY/IMlTK1BlCwkS9LlA1Epnof712VhdvUBlB4q6aESZu5rQaEgcvSeAdn1kT7f6QW4qo1YLcslTIxDpVKAViFoiycR9i9wykbIDJJlcpOc0Ro0hzxXynFELGwKnbH50RHy1gziLnohI1T1NuYG9yoy22ZsSWRGkgQFSelVtYIonMH/9U0mhSRsMMCjwQBMTACGeWNhrqwhUXf+JJKytwgUKjNntT6dWmNP3vSFvMGQsKZlAgCjkSKIVMpFWw3PLnM3Id6ZSpiuk2faDuHRIHC2KdBwj7mvaDIZIPLfIyC0TDIJIB5Xdk9Q3JbMCqA+eAKTUktc/VYGF1j/ca0FqdQjWK1Kgagcqo/TNTjRqpzedX1iLziAKIrK4uDwCIa5ogS04C0WaA4XMVgqZ88UfqQjKJdN7OqISDY19f4hoI2LaC++RSh1GiacNbDNUtsKUR0dcVCJz+pvc4joAKBVAYkkFlryBKUKgUp5q/YuDtNMzZXQYjU7IWEhQIxDyVAVy+DJDIopL54JxHw6JIZAo/PARJPogGptMYtRoLKQNQsqMZ1QjlJE+qBjBqGp7RGEyonIoGAGZmUqZRojUWuniVpihj0rdXPymZIYCuRiVxWtg1AtUW/+ASvQV2YHGgE+R7g50Rwoc9+oCwzlStxrMT9tzYaMhDCKcIaE+IqnuQKTONERbslgHTTpBThSiLJjdN6jLthr5s3s1ghlVChFPHRjEMKrZAx/vK+5rVucdbGcIx9fohUF+gIrMjDclczcggLT6GgLVNzCQV5TAwhuYaHCID8u5yLG55JVYoMQ8sS4G8hSaLUqsAwnWSJ3mXSCvPcS0AS1xH4FnkGKNX9sujWVCQHVdA+Zc05tNN27GbguRGs4jVRSrj1dDPKsShHt/RpX9xGcGdQSJcnAKVH4TIs3B3wDbUiodqKpApbzXF7ico74D5WlwA5YJXyBCAkcWKlApT41ATgi+XzAQfj5mNqSvFO99URe9xoqR6olXb55iIdtpDNtXP1s4YumRS4AW9jINa/mwSETq+Jp+bGX1JmxllXpsvp4jW6RbFzRgc8u7sYlVm7Ksqo1Zd0hsBHTeVFR2At8DND0FC+ysRmC8AjUNTLviCsyXPmdAytVkyBiSS+DC4glUylMKFCUqCYbctigvbUCURGvOJ4hwlJuG4un1tuAqKOpknTYoByqAShzpXhdovY2pjw/4GiAi/6UGBsQUS6D6BiYN4u4OQiT3FaSpFzhPvcCgOSKBnNmQvTSvwEiJVmgE/ZdwkQLOYMJ/fcsrEMiRYtU2MOo70OKM0IrfgcaB60h1Q3pAzhy19U9V4NzCBQZI+IOINZLAjaLAlqAFaL4BKXaaIPIZqAq8/usy1wAMCP6NBgYUbwID1DcwB9GcrOvKyG/SvywQjZSfBJfZcoNCINggSowAgSteRuXPQAZ0/ssi9cFjwDvYnFcVWPIRmvoGZhokfdubkU9G4QJV658kML+8PAIBOlhfiaBFkKcQKBEOwtYrolJgV2k4VRANCDxENN587QZGTfosbgeaAO4MQ+RDZugH6hoYSV4xBfpwZjBqKhH6YV6BnFDgu0yQeAUQyCwNMpeAi9ji8oTAe+9OoDKFRkDc2SmMZnWBgKlqGhg1An0LEeg9XcR3riRPImSdSDAaQdcpgsQ1IAc0Kg0yLwBviDMBL4rVwCz9F0ZoRdS/6ZB2sRcjz4xXEDhTvUCvaSKeADVRKVCS2Ax4LxJEPgIjwXGg9V8XqQPOAS3Icy25wJJOYNQ3MO3B7eHIAolcnJoGRp3A6QUL5DSZivezuDylwCAQCALQ0TtPEmTuARNB09IQlVpgNL+HvJDXbWCUAlXSZ7EbmL2IlmWdETkT8wr0L6ZAbzUCG3OmiPgtlwRKBHA+wsfmcZECvUEbICstxyq1+SsEtnu9DlSdQPUNTCpeb/SFgPRiNjBqBEKeikAPzmQ8n62U5y/hh4j0WfVy2vMnqAV0WWm7IK9zCfYAX38Ck68DDQaXsxn17wJhM4rfwHgBUZ56ge7ATcJ3lVIgxxf4oKttNPNlVC5mpfWCwE5qGpjXEKi+gZmIZ5/1YNQoozgNjHqBkjylQD4sl/Ccz+WBD0WBTSUaLxa6Vjn4C9iUWpkQGPP6DYwkr4QTmAjwaxaanu5c3qsJ9ChSIEANdgVukN90jVKgt4TnKvai4ST2VBqkj2Cl+YLAsFdqYNQKVN/ALAQ70fS4jlLfwADIUydQkifhMkEC954rlAK9INUTNF7JyFlcU54HY4F2qZaJ6HN9fYEln8BE4P7WMER8TzUNzCsKdJbgp+g8FioFNuGsxjPIbSiKzAFhQIuV9gsCa0Hg8+LvAf47E5hlYF0nRM3oEgjk4ooWCHlKGmRD8GwuT6SxhMcqiFbOXreWCZEcCNSBvN9UBL7BCUwY7m8PRWT3VNPAqBHoXIhATn3AhTWGOA9JoDtw46yUXcTh5euQ+FDR8JQZIHCfuIX0JgSq1r9FeL6+IwSMKm4DAyYUQyA/kCxRH8LdV0gCJRpxVrLf3OeXawSJv4MerKxdkDcKvMYIrfgNTCBebw1H5Hd/tfrHgQRRXj6B9ThjAU+vSyV5wHWlAtljt+W6jSFxGpgHZGVOJgT65JGnRmBTtQILr39TIHtHJwjILIZAlegrXGBdzhjx1XmBUqALcOasYE9dluq0hEDOVKDLyuIFgeUg8GbJRmgln8B4gmv8FDpfjhTWwKgXKMlTCnSUcBgN0bPzCKSGnOXsecMlWp24AIXEMg0Ezv1XJjCcQurfAEg/h/RaZ2DJBNZTI5BTB9SdKskDDZaL1F8GydmyCex9uiDRBQJz3tQEhnMaUpLjIC27cIFOxRRYR6L2KJE6PJKXSQIliU5LGFmhYzbCmVb2vl2Qt//1BRacPqMg+ee+kNEHAtU0MOoFKrEfCSDYaRHgApciikHdxYwsu3ORAt/joLLsvZIJgX6Ql6N+hFbyDnQlJM+KhaCRBQtUlVe0QDsJW+A4VxK4RMRhISOLrpJIYBzInhgHs8rvlUzIkyH6Nr2eQNX06QZ+G4Z63OXVBNrnF5glYgNqT4PMJSIOiyF+HiOzeElkAEQ2Y2QSxnJMmzMj9r5dEGgLgQ/V1L8SNTBpiOITiBSbAYULVI2+QgSOELEGtuO5QEkisEcXbtoWEv15NEJiCN5HQG4r9sK8NavB3scLAhPzC3QBorySd6D7uNAYLk2l/qkVaJNHIMhkZAWsufSFYJGIzSQIbCFGo0kwJIZDYkvxJ7gsotkDixhW/r2UCYkyCPyo4PRZsgamCV7vDoTgbuoFQp4SpUxI5AJFLDMAXu3mQDxk2i0Q3xuHgCCIDIXI5hAZCZGIUstYyI9np9j7fEGiPgSeKcEEBqimz1RE9L5OEDGwaIFSBOI+b3PDn1uNECVacIZD7hRRou0HkJYiSFSNxnYQGQeRnfD5XdlI9r5fkGgEgV9D4Ct3oMshPysacrJAIQIB0ifg91wmFz5aBEIhUxRpDpEWYyF4Pp5Nh8B43uAoo9E8EhIV0dgBErvgc7uzpzY9hJ0RzQWJZhB4Sf0EBhSQPs9DRIt4FYHK+idhKb5CpiixzlgwDmJxb41n5pBpxj9nDu4h17hlngaHzNtAZAxEQrBVZ0hEWrftCZLYMo3FXEBgDQg8AnklamBc8ex2OgR1K1SgMn1KtdAGX1ebp+vxHPHeeiSXCbIhMFGsjyZhENkCz1rzBgcS20NiRyGlEiKRSyS7FHbHPoWZaQzmAxLLQ+I8CJRDXLHqXwJS7FFEiWlaIQKHQ0YuLBQyIa3uJJE62ULnCtHa31l20Z2OaHxWUDRaK6KxFyT2QXSnsmf2/VhLjblCgDwZiIW8O6oCVZcQC5Amx/H0NwwUINBsmIiphDmXCXEOiEinKSIO6KLdp9bctefrTdbPXzzTs2ylE4Ro/LawaEQkUu1+7O/a6ayzxlgxgEQzCFwLgTlKgarRdxGvYTGqAhXyTIaKGAMThUxeg9EB1+dndNDk1JuMbnpy5QtPnv1lRkQVgBY61UroVFMRjV8jGnNsExGNyUI0voDEw9iVcddYKgEQKINAP0TgqYLqnzvk3kyFtK6FCQRDGBmJ4L0o03YsBCIiXWeB2ZA6VUi7Oakb2wcRUUWgpRCATlULIm0gMhgig2v3ZxYaM68BJMogMQwCDyHyXiiiLx0p9pNYRrXSChE4GB+T4O9N8XVWI8W06jwDqXUuIzfQcLq4veU53WwsEVVSyNTwBoFEGSQ2AFMh7uFO1L6eUVyeEqP8KFOssOyw5uM+PjZEVHrMAx9wsaLMutmVdhNRZaCtEfAWcRjKzt8ZhBrWHqIGAy6zUKR6mSF2rY6TCpA5ge9Z6n4jJ7m+RuZbJnU0u3wUXWaNXhA1qAAG58UUQs2HicsSR4hzgUCPuSLO08Xu1naU9q/Pc55rZL5tLoxhn/dvCUnpYKAqJrmBXFNgLv3LkI7ZkDkVImeLOOPegU+CRmpfl8tzNDLfJrSIGfw1iN13bMtl5mNAwZhDpiVk2o0Q576uENh4JmQC58mQOQaM0jujqZlvGZrH4g/GoUvtxsisfyGkKzEfCJFItbbDIWykuEPjDplNuMzpkDmRi8TrWMOlmm72LSMfy/YMcGc3zdKwTEmDrH4iZvkwh1QLRKU1otIO9dIxi1GDsdL5Wkj04jKnigehHfCxyLmNYqWhgUwj4O2kWNsHyeypQxWWYZ7KDgJSIU3EEjJt+B4n0ms9yHIZB3mTxFOBTSHSa7p4/qgBP3mXVe6Hy79dMCGicnK5XCPzbUAz2NjVPuwJbi0s+rIgIAeUH0vItIZM+8EQmYEaCWGNkU69p0mHryHSc4r4b73WQx2NmtMomYgMgI5GwNuJygovhrFfo8zZRsUzi2S2EZBAihIrRKgt6qXDENRIRKU7pHlNhsipEAk8EaEe2eLHPEYbHLj76KYpEZXXpNi3BH3AupyKZDm6WixQ8cyyDzMGNwC9BGKtEZ12iMy6iEznEZA5FgLHgwmI0GyAlNtyARdZ7uqK4zMaEtFbXJJoolJHPpKd71Obnc3/rx5b9mZeVr3Zc7ySQBKj+gMhbjREDhNpjG41EJEZPotRi7mMIvgaM0vn56EfJngTURWgqxHwlqD5LOrr9iynii5rn1+0VRLTtkpkP1tDog1k4p4sEhCVyRA6nJEfRAagZjZDRIagbvrivVPfcmd6Tox2f/jwYWUu8m02PZqoHMW+SHVgX+FtgQ2KdS92vG4/RFsmmhpEYn3US/s+ENudkXk8o+ohjGqEQXKc7J5TT8OsmcsnGf3xxx+8Rmq/XZGaWtn1i3ZCVLYrdO+zF1vuivoYjm41At1qECLQi2938c42ATKbyW7U8is3JayXt/Xdu3f1eNf69ocDmqjUfzGcXe9iw04po1IV2x4swxnRGMZ/DB7NjWcmhPJzuP0RnV1ZTjV3nRhHR8cqT58+1Xp3kahZV075JIg91ZExj6IE2PVgsc5Is01HIMUiGp1SxFpZP1U4hLVDR0/7HTc4mqbH904Se+pajU1Ve1QzsZxb3SQ0PWiA7LqxXx0T2Q13dLSOSeyxbTfmqBHwbtOr0YsMdq1PHfYN3lZUJ8Cum6yabQJ7BpaDGhC6vHYPllO7u+xdn6DTTHrk2ezgMm/2EAMCt+IIgEAZ8Mn1figYoBHwbkWWp0ls494w9sy4PIt9VQEQWVEj4N2KrC4fz3YfCGfPrSqxJI2A0ilRi+ay1i+GsmurfNhD4wqsvUZA6ZFXiRYwR/lM1oKy2YicIez8VzEsJ9GeHSynxeppBPzXI28+c0dTky0fzD79J5k9+gFz1sOh7J/V3uzHvnXYyup6rJligK7hvypxDouWD2fnfohnOUs82U/9HNmC+oasA4YAThBQGZSCaYxGpCkicfdFzFTTHNj+auVYCB6XwimMRqTNi0x2ZaEnu4/lRVzpTZ8akZXlo9n5aW7sFlKpi0ZAKYZmssyDWCdW0mHhGgGlfHqDteJvLc3YRk1jU7qp9GM2C74Ux+RIr2EaAaWXyitWrFj4+eJ2X3wUoPVcR0fHViOglFKjRo0Gu3btenBt32Q6lu5N6enpfLdCc2yxNJGRkVFOT09PJyUlJX3r1q20a+cO+ujD1TRixIhxiiMeGkoBFSpUkH3//fcHjx8/vn/VqlVnt2/fTqdOnaKVK1fSoEGDJmtkliK2bdtmceXKlaeff/45bdiwgf73v//RsWPHaO3atfJOnTpFaQYFpYgvvvgi6aeffqLPPvvsGU+xly5dor1799L8+fMvowGqpRFQijhw4EDTX3/9Vb579+5vDh8+zKUSl5qZmZkNAeU0AkoR+/fvr3727NnkLFxffvml/MSJE/TRRx/91aRJE2fNwKB0Ips0aVKL8+fP30KkyufMmbNT2NbSXKUWXTMzM3OsLVslJSV5aKKy9PF/RWUQ1GVh9WcAAAAASUVORK5CYII=\" width=\"115\" height=\"150\" alt=\"Error Image\" />\r\n                <div class=\"message\">\r\n                    <h1>Razor Compilation Error</h1>\r\n                    <p>We tried, we really did, but we just can't compile your view.</p>\r\n                    <p>We're sorry &#9785;</p>\r\n                </div>\r\n            </div>\r\n\r\n            <div class=\"details\">\r\n                <h2>Error Details</h2>\r\n                <span>[DETAILS]</span>\r\n            </div>\r\n        </div>\r\n        <footer>\r\n            Powered by <a href=\"http://nancyfx.org\" target=\"_blank\">Nancy</a>. Graphics courtesy of the awesome <a href=\"http://theoatmeal.com/\" target=\"_blank\">Matthew Inman</a>\r\n        </footer>\r\n    </div>\r\n</body>\r\n</html>\r\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/UrlHelpers.cs",
    "content": "namespace Nancy.ViewEngines.Razor\r\n{\r\n    /// <summary>\r\n    /// Helpers for url related functions.\r\n    /// </summary>\r\n    /// <typeparam name=\"TModel\">The type of the model.</typeparam>\r\n    public class UrlHelpers<TModel>\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"UrlHelpers&lt;TModel&gt;\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"razorViewEngine\">The razor view engine.</param>\r\n        /// <param name=\"renderContext\">The render context.</param>\r\n        public UrlHelpers(RazorViewEngine razorViewEngine, IRenderContext renderContext)\r\n        {\r\n            this.RazorViewEngine = razorViewEngine;\r\n            this.RenderContext = renderContext;\r\n        }\r\n\r\n        /// <summary>\r\n        /// The engine that is currently rendering the view.\r\n        /// </summary>\r\n        /// <value>A <see cref=\"RazorViewEngine\"/> instance.</value>\r\n        public RazorViewEngine RazorViewEngine { get; set; }\r\n\r\n        /// <summary>\r\n        /// The context of the current render operation.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IRenderContext\"/> instance.</value>\r\n        public IRenderContext RenderContext { get; set; }\r\n\r\n        /// <summary>\r\n        /// Retrieves the absolute url of the specified path.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path.</param>\r\n        public string Content(string path)\r\n        {\r\n            return this.RenderContext.ParsePath(path);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/app.config.transform",
    "content": "<configuration>\r\n  <configSections>\r\n    <sectionGroup name=\"system.web.webPages.razor\" type=\"System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\">\r\n      <section name=\"pages\" type=\"System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\" requirePermission=\"false\" />\r\n    </sectionGroup>\r\n  </configSections>\r\n  <appSettings>\r\n    <add key=\"webPages:Enabled\" value=\"false\" />\r\n  </appSettings>\r\n  <system.web.webPages.razor>\r\n    <pages pageBaseType=\"Nancy.ViewEngines.Razor.NancyRazorViewBase\">\r\n      <namespaces>\r\n        <add namespace=\"Nancy.ViewEngines.Razor\" />\r\n      </namespaces>\r\n    </pages>\r\n  </system.web.webPages.razor>\r\n</configuration>"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/targets/Nancy.ViewEngines.Razor.targets",
    "content": "<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <PropertyGroup>\r\n    <BuildDependsOn>CopyRazorFiles;$(BuildDependsOn)</BuildDependsOn>\r\n  </PropertyGroup>\r\n\r\n  <PropertyGroup>\r\n    <DestinationFolder>$(ProjectDir)\\bin</DestinationFolder>\r\n  </PropertyGroup>\r\n\r\n  <Target Name=\"CopyRazorFiles\" Condition=\"'$(Configuration)'=='DEBUG'\">\r\n     <Copy SourceFiles=\"$(MSBuildThisFileDirectory)..\\BuildProviders\\Nancy.ViewEngines.Razor.BuildProviders.dll\" DestinationFolder=\"$(DestinationFolder)\" ContinueOnError=\"true\" />\r\n     <Copy SourceFiles=\"$(MSBuildThisFileDirectory)..\\lib\\net45\\Nancy.ViewEngines.Razor.dll\" DestinationFolder=\"$(DestinationFolder)\" ContinueOnError=\"true\" />\r\n   </Target>\r\n</Project>\r\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor/web.config.transform",
    "content": "<configuration>\r\n  <configSections>\r\n    <sectionGroup name=\"system.web.webPages.razor\" type=\"System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\">\r\n      <section name=\"pages\" type=\"System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\" requirePermission=\"false\" />\r\n    </sectionGroup>\r\n  </configSections>\r\n  <appSettings>\r\n    <add key=\"webPages:Enabled\" value=\"false\" />\r\n  </appSettings>\r\n  <system.web>\r\n    <compilation>\r\n      <buildProviders>\r\n        <add extension=\".cshtml\" type=\"Nancy.ViewEngines.Razor.BuildProviders.NancyCSharpRazorBuildProvider, Nancy.ViewEngines.Razor.BuildProviders\" />\r\n        <add extension=\".vbhtml\" type=\"Nancy.ViewEngines.Razor.BuildProviders.NancyVisualBasicRazorBuildProvider, Nancy.ViewEngines.Razor.BuildProviders\" />\r\n      </buildProviders>\r\n    </compilation>\r\n  </system.web>\r\n  <system.web.webPages.razor>\r\n    <pages pageBaseType=\"Nancy.ViewEngines.Razor.NancyRazorViewBase\">\r\n      <namespaces>\r\n        <add namespace=\"Nancy.ViewEngines.Razor\" />\r\n      </namespaces>\r\n    </pages>\r\n  </system.web.webPages.razor>\r\n</configuration>"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor.BuildProviders/Nancy.ViewEngines.Razor.BuildProviders.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <TargetFramework>net452</TargetFramework>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <ProjectReference Include=\"../Nancy.ViewEngines.Razor/Nancy.ViewEngines.Razor.csproj\" />\n  </ItemGroup>\n\n  <ItemGroup>\n    <Reference Include=\"System.Web\" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Razor.BuildProviders/NancyCSharpRazorBuildProvider.cs",
    "content": "﻿namespace Nancy.ViewEngines.Razor.BuildProviders\r\n{\r\n    using System;\r\n    using System.CodeDom;\r\n    using System.CodeDom.Compiler;\r\n    using System.Globalization;\r\n    using System.Web.Compilation;\r\n    using System.Web.Razor;\r\n\r\n    [BuildProviderAppliesTo(BuildProviderAppliesTo.Code | BuildProviderAppliesTo.Web)]\r\n    public class NancyCSharpRazorBuildProvider : BuildProvider\r\n    {\r\n        private readonly RazorEngineHost host;\r\n\r\n        private readonly CompilerType compilerType;\r\n\r\n        private CodeCompileUnit generatedCode;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancyCSharpRazorBuildProvider\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"razorAssemblyProvider\">An <see cref=\"RazorAssemblyProvider\"/> instance.</param>\r\n        public NancyCSharpRazorBuildProvider(RazorAssemblyProvider razorAssemblyProvider)\r\n        {\r\n            this.compilerType = this.GetDefaultCompilerTypeForLanguage(\"C#\");\r\n\r\n            this.host = new NancyRazorEngineHost(new CSharpRazorCodeLanguage(), razorAssemblyProvider);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Represents the compiler type used by a build provider to generate source code for a custom file type.\r\n        /// </summary>\r\n        /// <returns>A read-only <see cref=\"T:System.Web.Compilation.CompilerType\"/> representing the code generator, code compiler, and compiler settings used to build source code for the virtual path. The base class returns null.</returns>\r\n        public override CompilerType CodeCompilerType\r\n        {\r\n            get { return this.compilerType; }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Generates source code for the virtual path of the build provider, and adds the source code to a specified assembly builder.\r\n        /// </summary>\r\n        /// <param name=\"assemblyBuilder\">The assembly builder that references the source code generated by the build provider.</param>\r\n        public override void GenerateCode(AssemblyBuilder assemblyBuilder)\r\n        {\r\n            assemblyBuilder.AddCodeCompileUnit(this, this.GetGeneratedCode());\r\n\r\n            assemblyBuilder.GenerateTypeFactory(string.Format(CultureInfo.InvariantCulture, \"{0}.{1}\", new object[] { this.host.DefaultNamespace, this.host.DefaultClassName }));\r\n        }\r\n\r\n        /// <summary>\r\n        /// Returns a type generated by the build provider from the virtual path.\r\n        /// </summary>\r\n        /// <returns>The type that is generated by the build provider for the virtual path. The base class returns null.</returns>\r\n        /// <param name=\"results\">The compilation results for the build provider's virtual path.</param>\r\n        public override Type GetGeneratedType(CompilerResults results)\r\n        {\r\n            return results.CompiledAssembly.GetType(string.Format(CultureInfo.CurrentCulture, \"{0}.{1}\", new object[] { this.host.DefaultNamespace, this.host.DefaultClassName }));\r\n        }\r\n\r\n        private CodeCompileUnit GetGeneratedCode()\r\n        {\r\n            if (this.generatedCode == null)\r\n            {\r\n                var engine = new RazorTemplateEngine(this.host);\r\n                GeneratorResults results;\r\n                using (var reader = this.OpenReader())\r\n                {\r\n                    results = engine.GenerateCode(reader);\r\n                }\r\n\r\n                if (!results.Success)\r\n                {\r\n                    throw new InvalidOperationException(results.ToString());\r\n                }\r\n\r\n                this.generatedCode = results.GeneratedCode;\r\n            }\r\n\r\n            return this.generatedCode;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.ViewEngines.Spark/Descriptors/BuildDescriptorParams.cs",
    "content": "﻿namespace Nancy.ViewEngines.Spark.Descriptors\r\n{\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    public class BuildDescriptorParams\r\n    {\r\n        private static readonly IDictionary<string, object> extraEmpty = new Dictionary<string, object>();\r\n        private readonly IDictionary<string, object> extra;\r\n        private readonly bool findDefaultMaster;\r\n        private readonly int hashCode;\r\n        private readonly string masterName;\r\n        private readonly string viewName;\r\n        private readonly string viewPath;\r\n\r\n        public BuildDescriptorParams(string viewPath, string viewName, string masterName, bool findDefaultMaster, IDictionary<string, object> extra)\r\n        {\r\n            this.viewPath = viewPath;\r\n            this.viewName = viewName;\r\n            this.masterName = masterName;\r\n            this.findDefaultMaster = findDefaultMaster;\r\n            this.extra = extra ?? extraEmpty;\r\n\r\n            // this object is meant to be immutable and used in a dictionary.\r\n            // the hash code will always be used so it isn't calculated just-in-time.\r\n            hashCode = CalculateHashCode();\r\n        }\r\n\r\n        public string ViewPath\r\n        {\r\n            get { return viewPath; }\r\n        }\r\n\r\n        public string ViewName\r\n        {\r\n            get { return viewName; }\r\n        }\r\n\r\n        public string MasterName\r\n        {\r\n            get { return masterName; }\r\n        }\r\n\r\n        public bool FindDefaultMaster\r\n        {\r\n            get { return findDefaultMaster; }\r\n        }\r\n\r\n        public IDictionary<string, object> Extra\r\n        {\r\n            get { return extra; }\r\n        }\r\n\r\n        private static int Hash(object str)\r\n        {\r\n            return str == null ? 0 : str.GetHashCode();\r\n        }\r\n\r\n        public override int GetHashCode()\r\n        {\r\n            return hashCode;\r\n        }\r\n\r\n        private int CalculateHashCode()\r\n        {\r\n            return Hash(viewName) ^\r\n                   Hash(viewPath) ^\r\n                   Hash(masterName) ^\r\n                   findDefaultMaster.GetHashCode() ^\r\n                   extra.Aggregate(0, (hash, kv) => hash ^ Hash(kv.Key) ^ Hash(kv.Value));\r\n        }\r\n\r\n        public override bool Equals(object obj)\r\n        {\r\n            var that = obj as BuildDescriptorParams;\r\n\r\n            if (that == null || that.GetType() != GetType())\r\n            {\r\n                return false;\r\n            }\r\n\r\n            if (!string.Equals(viewName, that.viewName) ||\r\n                !string.Equals(viewPath, that.viewPath) ||\r\n                !string.Equals(masterName, that.masterName) ||\r\n                findDefaultMaster != that.findDefaultMaster ||\r\n                extra.Count != that.extra.Count)\r\n            {\r\n                return false;\r\n            }\r\n\r\n            foreach (var kv in extra)\r\n            {\r\n                object value;\r\n                if (!that.extra.TryGetValue(kv.Key, out value) || !Equals(kv.Value, value))\r\n                {\r\n                    return false;\r\n                }\r\n\r\n            }\r\n\r\n            return true;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.ViewEngines.Spark/Descriptors/DefaultDescriptorBuilder.cs",
    "content": "﻿namespace Nancy.ViewEngines.Spark.Descriptors\r\n{\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n\r\n    using global::Spark;\r\n    using global::Spark.Parser;\r\n    using global::Spark.Parser.Syntax;\r\n\r\n    public class DefaultDescriptorBuilder : IDescriptorBuilder\r\n    {\r\n        private ISparkViewEngine engine;\r\n        private UseMasterGrammar grammar;\r\n\r\n        public DefaultDescriptorBuilder()\r\n            : this((string) null)\r\n        {\r\n        }\r\n\r\n        public DefaultDescriptorBuilder(string prefix)\r\n        {\r\n            Filters = new List<IDescriptorFilter>();\r\n            grammar = new UseMasterGrammar(prefix);\r\n        }\r\n\r\n        public DefaultDescriptorBuilder(ISparkViewEngine engine)\r\n            : this()\r\n        {\r\n            this.engine = engine;\r\n            grammar = new UseMasterGrammar(this.engine.Settings.Prefix);\r\n        }\r\n\r\n        public IList<IDescriptorFilter> Filters { get; set; }\r\n\r\n        public ParseAction<string> ParseUseMaster\r\n        {\r\n            get { return grammar.ParseUseMaster; }\r\n        }\r\n\r\n        public virtual IDictionary<string, object> GetExtraParameters(ViewLocationResult viewLocationResult)\r\n        {\r\n            var extra = new Dictionary<string, object>();\r\n            foreach (var filter in Filters)\r\n            {\r\n                filter.ExtraParameters(viewLocationResult, extra);\r\n            }\r\n\r\n            return extra;\r\n        }\r\n\r\n        public virtual SparkViewDescriptor BuildDescriptor(BuildDescriptorParams buildDescriptorParams, ICollection<string> searchedLocations)\r\n        {\r\n            var descriptor = new SparkViewDescriptor\r\n                                 {\r\n                                     TargetNamespace = GetNamespaceEncodedPathViewPath(buildDescriptorParams.ViewPath)\r\n                                 };\r\n\r\n            if (!LocatePotentialTemplate(\r\n                PotentialViewLocations(buildDescriptorParams.ViewPath,\r\n                                       buildDescriptorParams.ViewName,\r\n                                       buildDescriptorParams.Extra),\r\n                descriptor.Templates,\r\n                searchedLocations))\r\n            {\r\n                return null;\r\n            }\r\n\r\n            if (!string.IsNullOrEmpty(buildDescriptorParams.MasterName))\r\n            {\r\n                if (!LocatePotentialTemplate(\r\n                    PotentialMasterLocations(buildDescriptorParams.MasterName,\r\n                                             buildDescriptorParams.Extra),\r\n                    descriptor.Templates,\r\n                    searchedLocations))\r\n                {\r\n                    return null;\r\n                }\r\n            }\r\n            else if (buildDescriptorParams.FindDefaultMaster && TrailingUseMasterName(descriptor) == null /*empty is a valid value*/)\r\n            {\r\n                LocatePotentialTemplate(\r\n                    PotentialDefaultMasterLocations(buildDescriptorParams.ViewPath,\r\n                                                    buildDescriptorParams.Extra),\r\n                    descriptor.Templates,\r\n                    null);\r\n            }\r\n\r\n            var trailingUseMaster = TrailingUseMasterName(descriptor);\r\n            while (buildDescriptorParams.FindDefaultMaster && !string.IsNullOrEmpty(trailingUseMaster))\r\n            {\r\n                if (!LocatePotentialTemplate(\r\n                    PotentialMasterLocations(trailingUseMaster,\r\n                                             buildDescriptorParams.Extra ),\r\n                    descriptor.Templates,\r\n                    searchedLocations))\r\n                {\r\n                    return null;\r\n                }\r\n                trailingUseMaster = TrailingUseMasterName(descriptor);\r\n            }\r\n\r\n            return descriptor;\r\n        }\r\n\r\n        public virtual void Initialize(ISparkServiceContainer container)\r\n        {\r\n            engine = container.GetService<ISparkViewEngine>();\r\n            grammar = new UseMasterGrammar(engine.Settings.Prefix);\r\n        }\r\n\r\n        public string TrailingUseMasterName(SparkViewDescriptor descriptor)\r\n        {\r\n            var lastTemplate = descriptor.Templates.Last();\r\n            var sourceContext = AbstractSyntaxProvider.CreateSourceContext(lastTemplate, engine.ViewFolder);\r\n\r\n            if (sourceContext == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            var result = ParseUseMaster(new Position(sourceContext));\r\n\r\n            return result == null ? null : result.Value;\r\n        }\r\n\r\n        private bool LocatePotentialTemplate(\r\n            IEnumerable<string> potentialTemplates,\r\n            ICollection<string> descriptorTemplates,\r\n            ICollection<string> searchedLocations)\r\n        {\r\n            var template = potentialTemplates.FirstOrDefault(t => engine.ViewFolder.HasView(t));\r\n            if (template != null)\r\n            {\r\n                descriptorTemplates.Add(template);\r\n                return true;\r\n            }\r\n\r\n            if (searchedLocations != null)\r\n            {\r\n                foreach (var potentialTemplate in potentialTemplates)\r\n                {\r\n                    searchedLocations.Add(potentialTemplate);\r\n                }\r\n            }\r\n\r\n            return false;\r\n        }\r\n\r\n        /// <remarks>Apply all of the filters PotentialLocations in order</remarks>\r\n        private IEnumerable<string> ApplyFilters(IEnumerable<string> locations, IDictionary<string, object> extra)\r\n        {\r\n            return Filters.Aggregate(locations, (aggregate, filter) => filter.PotentialLocations(aggregate, extra));\r\n        }\r\n\r\n        protected virtual IEnumerable<string> PotentialViewLocations(string viewPath, string viewName, IDictionary<string, object> extra)\r\n        {\r\n            return ApplyFilters(new[]\r\n                                    {\r\n                                        Path.Combine(viewPath, viewName + \".spark\"),\r\n                                        Path.Combine(viewPath, viewName + \".shade\"),\r\n                                        Path.Combine(\"Shared\", viewName + \".spark\"),\r\n                                        Path.Combine(\"Shared\", viewName + \".shade\")\r\n                                    }, extra);\r\n        }\r\n\r\n        protected virtual IEnumerable<string> PotentialMasterLocations( string masterName, IDictionary<string, object> extra )\r\n        {\r\n            return ApplyFilters(new[]\r\n                                    {\r\n                                        Path.Combine(\"Layouts\", masterName + \".spark\"),\r\n                                        Path.Combine(\"Layouts\", masterName + \".shade\"),\r\n                                        Path.Combine(\"Shared\", masterName + \".spark\"),\r\n                                        Path.Combine(\"Shared\", masterName + \".shade\"),\r\n                                        Path.Combine(\"Views\", masterName + \".spark\"),\r\n                                        Path.Combine(\"Views\", masterName + \".shade\"),\r\n                                        Path.Combine(\"Views\", \"Layouts\", masterName + \".spark\"),\r\n                                        Path.Combine(\"Views\", \"Layouts\", masterName + \".shade\"),\r\n                                        Path.Combine(\"Views\", \"Shared\", masterName + \".spark\"),\r\n                                        Path.Combine(\"Views\", \"Shared\", masterName + \".shade\")\r\n                                    }, extra);\r\n        }\r\n\r\n        protected virtual IEnumerable<string> PotentialDefaultMasterLocations(string controllerName, IDictionary<string, object> extra)\r\n        {\r\n            return ApplyFilters(new[]\r\n                                    {\r\n                                        Path.Combine(\"Layouts\", \"Application.spark\"),\r\n                                        Path.Combine(\"Layouts\", \"Application.shade\"),\r\n                                        Path.Combine(\"Shared\", \"Application.spark\"),\r\n                                        Path.Combine(\"Shared\", \"Application.shade\"),\r\n                                        Path.Combine(\"Views\", \"Layouts\", \"Application.spark\"),\r\n                                        Path.Combine(\"Views\", \"Layouts\", \"Application.shade\"),\r\n                                        Path.Combine(\"Views\", \"Shared\", \"Application.spark\"),\r\n                                        Path.Combine(\"Views\", \"Shared\", \"Application.shade\"),\r\n                                    }, extra);\r\n        }\r\n\r\n        private static string GetNamespaceEncodedPathViewPath(string viewPath)\r\n        {\r\n            return viewPath.Replace('\\\\', '_').Replace('/', '_');\r\n        }\r\n\r\n        /// <summary>\r\n        /// Simplified parser for &lt;use master=\"\"/&gt; detection.\r\n        /// TODO: Rob G - move somewhere else when I've had some sleep - probably to Spark.Parser in Core\r\n        /// </summary>\r\n        private class UseMasterGrammar : CharGrammar\r\n        {\r\n            public UseMasterGrammar(string prefix)\r\n            {\r\n                var whiteSpace0 = Rep(Ch(char.IsWhiteSpace));\r\n                var whiteSpace1 = Rep1(Ch(char.IsWhiteSpace));\r\n                var startOfElement = !string.IsNullOrEmpty(prefix) ? Ch(\"<\" + prefix + \":use\") : Ch(\"<use\");\r\n                var startOfAttribute = Ch(\"master\").And(whiteSpace0).And(Ch('=')).And(whiteSpace0);\r\n                var attrValue = Ch('\\'').And(Rep(ChNot('\\''))).And(Ch('\\''))\r\n                    .Or(Ch('\\\"').And(Rep(ChNot('\\\"'))).And(Ch('\\\"')));\r\n\r\n                var endOfElement = Ch(\"/>\");\r\n\r\n                var useMaster = startOfElement\r\n                    .And(whiteSpace1)\r\n                    .And(startOfAttribute)\r\n                    .And(attrValue)\r\n                    .And(whiteSpace0)\r\n                    .And(endOfElement)\r\n                    .Build(hit => new string(hit.Left.Left.Down.Left.Down.ToArray()));\r\n\r\n                ParseUseMaster =\r\n                    pos =>\r\n                        {\r\n                            for (Position scan = pos; scan.PotentialLength() != 0; scan = scan.Advance(1))\r\n                            {\r\n                                ParseResult<string> result = useMaster(scan);\r\n                                if (result != null)\r\n                                    return result;\r\n                            }\r\n                            return null;\r\n                        };\r\n            }\r\n\r\n            public ParseAction<string> ParseUseMaster { get; private set; }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.ViewEngines.Spark/Descriptors/DescriptorFilterExtensions.cs",
    "content": "﻿namespace Nancy.ViewEngines.Spark.Descriptors\r\n{\r\n    //public static class DescriptorFilterExtensions\r\n    //{\r\n    //    public static void AddFilter(this ISparkServiceContainer target, IDescriptorFilter filter)\r\n    //    {\r\n    //        target.GetService<IDescriptorBuilder>().AddFilter(filter);\r\n    //    }\r\n\r\n    //    public static void AddFilter(this SparkViewEngine target, IDescriptorFilter filter)\r\n    //    {\r\n    //        target.DescriptorBuilder.AddFilter(filter);\r\n    //    }\r\n\r\n    //    public static void AddFilter(this IDescriptorBuilder target, IDescriptorFilter filter)\r\n    //    {\r\n    //        if (!(target is DefaultDescriptorBuilder))\r\n    //        {\r\n    //            throw new InvalidCastException(\"IDescriptorFilters may only be added to DefaultDescriptorBuilder\");\r\n    //        }\r\n\r\n    //        ((DefaultDescriptorBuilder) target).AddFilter(filter);\r\n    //    }\r\n\r\n    //    public static void AddFilter(this DefaultDescriptorBuilder target, IDescriptorFilter filter)\r\n    //    {\r\n    //        target.Filters.Add(filter);\r\n    //    }\r\n    //}\r\n}"
  },
  {
    "path": "src/Nancy.ViewEngines.Spark/Descriptors/IDescriptorBuilder.cs",
    "content": "﻿namespace Nancy.ViewEngines.Spark.Descriptors\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using global::Spark;\r\n\r\n    public interface IDescriptorBuilder\r\n    {\r\n        /// <summary>\r\n        /// Implemented by custom descriptor builder to quickly extract additional parameters needed\r\n        /// to locate templates, like the theme or language in effect for the request\r\n        /// </summary>\r\n        /// <param name=\"viewLocationResult\">Context information for the current request</param>\r\n        /// <returns>An in-order array of values which are meaningful to BuildDescriptor on the same implementation class</returns>\r\n        IDictionary<string, object> GetExtraParameters(ViewLocationResult viewLocationResult);\r\n        //TODO: RobG: Move to lower in the Nancy stack to allow for multi-lingual support in all views\r\n\r\n        /// <summary>\r\n        /// Given a set of MVC-specific parameters, a descriptor for the target view is created. This can\r\n        /// be a bit more expensive because the existence of files is tested at various candidate locations.\r\n        /// </summary>\r\n        /// <param name=\"buildDescriptorParams\">Contains all of the standard and extra parameters which contribute to a descriptor</param>\r\n        /// <param name=\"searchedLocations\">Candidate locations are added to this collection so an information-rich error may be returned</param>\r\n        /// <returns>The descriptor with all of the detected view locations in order</returns>\r\n        SparkViewDescriptor BuildDescriptor(BuildDescriptorParams buildDescriptorParams, ICollection<string> searchedLocations);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.ViewEngines.Spark/Descriptors/IDescriptorFilter.cs",
    "content": "﻿namespace Nancy.ViewEngines.Spark.Descriptors\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    public interface IDescriptorFilter\r\n    {\r\n        /// <summary>\r\n        /// Called frequently to extract filter-specific parameters from a request viewLocationResult. This call\r\n        /// happens on every request so should be implemented as efficiently as possible.\r\n        /// </summary>\r\n        /// <param name=\"viewLocationResult\">The current request's action viewLocationResult</param>\r\n        /// <param name=\"extra\">Dictionary where additional parameters should be added</param>\r\n        void ExtraParameters(ViewLocationResult viewLocationResult, IDictionary<string, object> extra);\r\n\r\n        /// <summary>\r\n        /// The DefaultDescriptorBuilder calls this method for the filter to return a modified enumerable\r\n        /// ordered list of potential template locations. This is called only when the unique combination of action,\r\n        /// master, view, and extra have not been resolved previously.\r\n        /// </summary>\r\n        /// <param name=\"locations\">incoming ordered list of locations</param>\r\n        /// <param name=\"extra\">extra parameters which have been extracted</param>\r\n        /// <returns>either the original list or a new, augmented, enumerable list</returns>\r\n        IEnumerable<string> PotentialLocations(IEnumerable<string> locations, IDictionary<string, object> extra);\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.ViewEngines.Spark/Nancy.ViewEngines.Spark.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <Description>Enables using the Spark view engine with Nancy.</Description>\n    <PackageTags>$(PackageTags);View Engine;Spark</PackageTags>\n    <TargetFramework>net452</TargetFramework>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <PackageReference Include=\"Spark\" Version=\"1.7.0\" />\n  </ItemGroup>\n\n  <ItemGroup>\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Web\" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Spark/NancyBindingProvider.cs",
    "content": "namespace Nancy.ViewEngines.Spark\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n\r\n    using global::Spark.Bindings;\r\n\r\n    /// <summary>\r\n    /// Loads binding files from the application path as returned by the current <see cref=\"IRootPathProvider\"/>.\r\n    /// </summary>\r\n    /// <remarks>This will scan all sub-folders as well.</remarks>\r\n    public class NancyBindingProvider : BindingProvider\r\n    {\r\n        private readonly IRootPathProvider rootPathProvider;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancyBindingProvider\"/> class, \r\n        /// with the provided <paramref name=\"rootPathProvider\"/>.\r\n        /// </summary>\r\n        /// <param name=\"rootPathProvider\">The root path provider that defines where bindings should be looked for.</param>\r\n        public NancyBindingProvider(IRootPathProvider rootPathProvider)\r\n        {\r\n            this.rootPathProvider = rootPathProvider;\r\n        }\r\n\r\n        public override IEnumerable<Binding> GetBindings(BindingRequest bindingRequest)\r\n        {\r\n            var locatedFiles = \r\n                Directory.GetFiles(this.rootPathProvider.GetRootPath(), \"bindings.xml\", SearchOption.AllDirectories);\r\n\r\n            return locatedFiles.Any() ? \r\n                locatedFiles.SelectMany(this.LoadBindings) :\r\n                Enumerable.Empty<Binding>();\r\n        }\r\n\r\n        private IEnumerable<Binding> LoadBindings(string fileName)\r\n        {\r\n            try\r\n            {\r\n                using (var stream = new FileStream(fileName, FileMode.Open))\r\n                {\r\n                    using (var reader = new StreamReader(stream))\r\n                    {\r\n                        return this.LoadStandardMarkup(reader);\r\n                    }\r\n                }\r\n            }\r\n            catch (Exception)\r\n            {\r\n                return Enumerable.Empty<Binding>();\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.ViewEngines.Spark/NancySparkView.cs",
    "content": "﻿namespace Nancy.ViewEngines.Spark\r\n{\r\n    using System.IO;\r\n    using System.Web;\r\n\r\n    using global::Spark;\r\n\r\n    public abstract class NancySparkView : SparkViewBase\r\n    {\r\n        private readonly NancyViewData viewData;\r\n\r\n        protected NancySparkView()\r\n        {\r\n            this.viewData = new NancyViewData(this);\r\n        }\r\n\r\n        public object Model { get; set; }\r\n\r\n        public TextWriter Writer { get; set; }\r\n\r\n        public IRenderContext RenderContext { get; set; }\r\n\r\n        public void Execute()\r\n        {\r\n            base.RenderView(Writer);\r\n        }\r\n\r\n        public string H(object value)\r\n        {\r\n            return HttpUtility.HtmlEncode(value);\r\n        }\r\n\r\n        public object HTML(object value)\r\n        {\r\n            return value;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Non-model specific data for rendering in the response\r\n        /// </summary>\r\n        public dynamic ViewBag\r\n        {\r\n            get\r\n            {\r\n                if (this.RenderContext == null)\r\n                {\r\n                    return null;\r\n                }\r\n\r\n                return this.RenderContext.Context == null ? null : this.RenderContext.Context.ViewBag;\r\n            }\r\n        }\r\n\r\n        public string AntiForgeryToken()\r\n        {\r\n            var tokenKeyValue = this.RenderContext.GetCsrfToken();\r\n\r\n            return string.Format(\"<input type=\\\"hidden\\\" name=\\\"{0}\\\" value=\\\"{1}\\\"/>\", tokenKeyValue.Key, tokenKeyValue.Value);\r\n        }\r\n\r\n        public virtual void SetModel(object model)\r\n        {\r\n            this.Model = model;\r\n        }\r\n\r\n        public string SiteResource(string path)\r\n        {\r\n            return this.RenderContext.ParsePath(path);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Non-model specific data retrieved using the &lt;viewdata /&gt; tag in Spark views\r\n        /// </summary>\r\n        /// <remarks>See more on http://sparkviewengine.com/documentation/variables#Usingviewdata</remarks>\r\n        public NancyViewData ViewData\r\n        {\r\n            get { return this.viewData; }\r\n        }\r\n    }\r\n\r\n    public abstract class NancySparkView<TModel> : NancySparkView\r\n    {\r\n        public new TModel Model { get; private set; }\r\n\r\n        public override void SetModel(object model)\r\n        {\r\n            Model = (model is TModel) ? (TModel)model : default(TModel);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.ViewEngines.Spark/NancyViewData.cs",
    "content": "﻿namespace Nancy.ViewEngines.Spark\r\n{\r\n    /// <summary>\r\n    /// Wraps <see cref=\"NancySparkView.ViewBag\"/> so that it can be retrieved in view by using Spark's &lt;viewdata /&gt; tag\r\n    /// </summary>\r\n    /// <example> In route add something to ViewBag:\r\n    /// <code>\r\n    /// this.ViewBag[\"foo\"] = \"bar\";\r\n    /// </code>\r\n    /// In view:\r\n    /// <code>\r\n    /// &lt;viewdata foo=\"string\" /&gt;\r\n    /// \r\n    /// The value of foo is: ${foo}\r\n    /// </code>\r\n    /// </example>\r\n    public class NancyViewData\r\n    {\r\n        private readonly NancySparkView view;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of <see cref=\"NancyViewData\"/>\r\n        /// </summary>\r\n        /// <param name=\"view\">view, whose <see cref=\"NancySparkView.ViewBag\"/> will be used to retrieve values</param>\r\n        public NancyViewData(NancySparkView view)\r\n        {\r\n            this.view = view;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a view data value from the <see cref=\"NancySparkView.ViewBag\"/>\r\n        /// </summary>\r\n        /// <param name=\"key\"><see cref=\"NancySparkView.ViewBag\"/> key</param>\r\n        /// <returns>null if the key wasn't present in the <see cref=\"NancySparkView.ViewBag\"/></returns>\r\n        /// <remarks>This method is output to the generated view class when &lt;viewdata /&gt; tag is used</remarks>\r\n        public object Eval(string key)\r\n        {\r\n            object value;\r\n            return TryGetViewData(key, out value) ? value : null;\r\n        }\r\n\r\n        private bool TryGetViewData(string key, out object value)\r\n        {\r\n            if (this.view.ViewBag.ContainsKey(key) && this.view.ViewBag[key].HasValue)\r\n            {\r\n                value = this.view.ViewBag[key].Value;\r\n                return true;\r\n            }\r\n\r\n            value = null;\r\n            return false;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.ViewEngines.Spark/NancyViewFolder.cs",
    "content": "namespace Nancy.ViewEngines.Spark\r\n{\r\n    using System;\r\n    using System.Collections.Concurrent;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Text;\r\n    using System.Threading;\r\n    using Configuration;\r\n    using global::Spark.FileSystem;\r\n\r\n    using Nancy.Responses.Negotiation;\r\n\r\n    /// <summary>\r\n    /// Implementation of the IViewFolder interface to have Spark use views that's been discovered by Nancy's view locator.\r\n    /// </summary>\r\n    public class NancyViewFolder : IViewFolder\r\n    {\r\n        private readonly ViewEngineStartupContext viewEngineStartupContext;\r\n        private readonly List<ViewLocationResult> currentlyLocatedViews;\r\n        private readonly ReaderWriterLockSlim padlock = new ReaderWriterLockSlim();\r\n        private readonly ConcurrentDictionary<string, IViewFile> cachedFiles = new ConcurrentDictionary<string, IViewFile>();\r\n        private readonly ViewConfiguration configuration;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"NancyViewFolder\"/> class, using the provided <see cref=\"viewEngineStartupContext\"/> instance.\r\n        /// </summary>\r\n        /// <param name=\"viewEngineStartupContext\">A <see cref=\"ViewEngineStartupContext\"/> instance.</param>\r\n        /// <param name=\"environment\">An <see cref=\"INancyEnvironment\"/> instance.</param>\r\n        public NancyViewFolder(ViewEngineStartupContext viewEngineStartupContext, INancyEnvironment environment)\r\n        {\r\n            this.viewEngineStartupContext = viewEngineStartupContext;\r\n            this.configuration = environment.GetValue<ViewConfiguration>();\r\n\r\n            // No need to lock here\r\n            this.currentlyLocatedViews =\r\n                new List<ViewLocationResult>(viewEngineStartupContext.ViewLocator.GetAllCurrentlyDiscoveredViews());\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the source of the requested view.\r\n        /// </summary>\r\n        /// <param name=\"path\">The view to get the source for</param>\r\n        /// <returns>A <see cref=\"IViewFile\"/> instance.</returns>\r\n        public IViewFile GetViewSource(string path)\r\n        {\r\n            var searchPath = ConvertPath(path);\r\n\r\n            IViewFile fileResult;\r\n            if (this.cachedFiles.TryGetValue(searchPath, out fileResult))\r\n            {\r\n                return fileResult;\r\n            }\r\n\r\n            ViewLocationResult result = null;\r\n\r\n            this.padlock.EnterUpgradeableReadLock();\r\n            try\r\n            {\r\n                result = this.currentlyLocatedViews\r\n                             .FirstOrDefault(v => CompareViewPaths(GetSafeViewPath(v), searchPath));\r\n\r\n                if (result == null && this.configuration.RuntimeViewDiscovery)\r\n                {\r\n                    result = this.viewEngineStartupContext.ViewLocator.LocateView(searchPath, GetFakeContext());\r\n\r\n                    this.padlock.EnterWriteLock();\r\n                    try\r\n                    {\r\n                        this.currentlyLocatedViews.Add(result);\r\n                    }\r\n                    finally\r\n                    {\r\n                        this.padlock.ExitWriteLock();\r\n                    }\r\n                }\r\n            }\r\n            finally\r\n            {\r\n                this.padlock.ExitUpgradeableReadLock();\r\n            }\r\n\r\n\r\n            if (result == null)\r\n            {\r\n                throw new FileNotFoundException(string.Format(\"Template {0} not found\", path), path);\r\n            }\r\n\r\n            fileResult = new NancyViewFile(result, this.configuration);\r\n            this.cachedFiles.AddOrUpdate(searchPath, s => fileResult, (s, o) => fileResult);\r\n\r\n            return fileResult;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Lists all view for the specified <paramref name=\"path\"/>.\r\n        /// </summary>\r\n        /// <param name=\"path\">The path to return views for.</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> that contains the matched views.</returns>\r\n        public IList<string> ListViews(string path)\r\n        {\r\n            this.padlock.EnterReadLock();\r\n\r\n            try\r\n            {\r\n                return currentlyLocatedViews.\r\n                    Where(v => v.Location.StartsWith(path, StringComparison.OrdinalIgnoreCase)).\r\n                    Select(v =>\r\n                        v.Location.Length == path.Length ?\r\n                            v.Name + \".\" + v.Extension :\r\n                            v.Location.Substring(path.Length) + \"/\" + v.Name + \".\" + v.Extension).\r\n                    ToList();\r\n\r\n            }\r\n            finally\r\n            {\r\n                this.padlock.ExitReadLock();\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a value that indicates whether or not the view folder contains a specific view.\r\n        /// </summary>\r\n        /// <param name=\"path\">The view to check for.</param>\r\n        /// <returns><see langword=\"true\"/> if the view exists in the view folder; otherwise <see langword=\"false\"/>.</returns>\r\n        public bool HasView(string path)\r\n        {\r\n            var searchPath =\r\n                ConvertPath(path);\r\n\r\n            this.padlock.EnterUpgradeableReadLock();\r\n            try\r\n            {\r\n                var hasCached = this.currentlyLocatedViews.Any(v => CompareViewPaths(GetSafeViewPath(v), searchPath));\r\n\r\n                if (hasCached || !this.configuration.RuntimeViewDiscovery)\r\n                {\r\n                    return hasCached;\r\n                }\r\n\r\n                var newView = this.viewEngineStartupContext.ViewLocator.LocateView(searchPath, GetFakeContext());\r\n\r\n                if (newView == null)\r\n                {\r\n                    return false;\r\n                }\r\n\r\n                this.padlock.EnterWriteLock();\r\n                try\r\n                {\r\n                    this.currentlyLocatedViews.Add(newView);\r\n\r\n                    return true;\r\n                }\r\n                finally\r\n                {\r\n                    this.padlock.ExitWriteLock();\r\n                }\r\n            }\r\n            finally\r\n            {\r\n                this.padlock.ExitUpgradeableReadLock();\r\n            }\r\n        }\r\n\r\n        private static bool CompareViewPaths(string storedViewPath, string requestedViewPath)\r\n        {\r\n            return String.Equals(storedViewPath, requestedViewPath, StringComparison.OrdinalIgnoreCase);\r\n        }\r\n\r\n        private static string ConvertPath(string path)\r\n        {\r\n            return path.Replace(@\"\\\", \"/\");\r\n        }\r\n\r\n        private static string GetSafeViewPath(ViewLocationResult result)\r\n        {\r\n            return string.IsNullOrEmpty(result.Location) ?\r\n                string.Concat(result.Name, \".\", result.Extension) :\r\n                string.Concat(result.Location, \"/\", result.Name, \".\", result.Extension);\r\n        }\r\n\r\n        // Horrible hack, but we have no way to get a context\r\n        private static NancyContext GetFakeContext()\r\n        {\r\n            return new NancyContext { Request = new Request(\"GET\", \"/\", \"http\") };\r\n        }\r\n\r\n        public class NancyViewFile : IViewFile\r\n        {\r\n            private readonly object updateLock = new object();\r\n\r\n            private readonly ViewLocationResult viewLocationResult;\r\n\r\n            private readonly ViewConfiguration viewConfiguration;\r\n\r\n            private string contents;\r\n\r\n            private long lastUpdated;\r\n\r\n            public NancyViewFile(ViewLocationResult viewLocationResult, ViewConfiguration viewConfiguration)\r\n            {\r\n                this.viewLocationResult = viewLocationResult;\r\n                this.viewConfiguration = viewConfiguration;\r\n\r\n                this.UpdateContents();\r\n            }\r\n\r\n            public long LastModified\r\n            {\r\n                get\r\n                {\r\n                    if (this.viewConfiguration.RuntimeViewUpdates && this.viewLocationResult.IsStale())\r\n                    {\r\n                        this.UpdateContents();\r\n                    }\r\n\r\n                    return this.lastUpdated;\r\n                }\r\n            }\r\n\r\n            public Stream OpenViewStream()\r\n            {\r\n                if (this.viewConfiguration.RuntimeViewUpdates && this.viewLocationResult.IsStale())\r\n                {\r\n                    this.UpdateContents();\r\n                }\r\n\r\n                return new MemoryStream(Encoding.UTF8.GetBytes(this.contents));\r\n            }\r\n\r\n            private void UpdateContents()\r\n            {\r\n                lock (this.updateLock)\r\n                {\r\n                    using (var reader = this.viewLocationResult.Contents.Invoke())\r\n                    {\r\n                        this.contents = reader.ReadToEnd();\r\n                    }\r\n\r\n                    this.lastUpdated = DateTime.Now.Ticks;\r\n                }\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Spark/SparkRenderContextWrapper.cs",
    "content": "﻿namespace Nancy.ViewEngines.Spark\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using Nancy.Localization;\r\n\r\n    /// <summary>\r\n    /// Wraps <see cref=\"IRenderContext\"/> to replace tilde (~/) path resolution with Spark's native implementation. \r\n    /// </summary>\r\n    /// <remarks>This allows the use of &lt;resources /&gt; configuration section. \r\n    /// Read more on http://sparkviewengine.com/documentation/configuring#Sparksettingsinconfigfile</remarks>\r\n    internal class SparkRenderContextWrapper : IRenderContext\r\n    {\r\n        private readonly IRenderContext innerContext;\r\n        private readonly global::Spark.SparkViewEngine engine;\r\n\r\n        public SparkRenderContextWrapper(IRenderContext innerContext, global::Spark.SparkViewEngine engine)\r\n        {\r\n            this.innerContext = innerContext;\r\n            this.engine = engine;\r\n        }\r\n\r\n        public NancyContext Context\r\n        {\r\n            get { return this.innerContext.Context; }\r\n        }\r\n\r\n        public IViewCache ViewCache\r\n        {\r\n            get { return this.innerContext.ViewCache; }\r\n        }\r\n\r\n        public ITextResource TextResource\r\n        {\r\n            get { return this.innerContext.TextResource; }\r\n        }\r\n\r\n        public dynamic TextResourceFinder\r\n        {\r\n            get { return this.innerContext.TextResourceFinder; }\r\n        }\r\n\r\n        public string ParsePath(string input)\r\n        {\r\n            var siteRoot = this.innerContext.ParsePath(\"~/\");\r\n            return this.engine.ResourcePathManager.GetResourcePath(siteRoot, input);\r\n        }\r\n\r\n        public string HtmlEncode(string input)\r\n        {\r\n            return this.innerContext.HtmlEncode(input);\r\n        }\r\n\r\n        public ViewLocationResult LocateView(string viewName, dynamic model)\r\n        {\r\n            return this.innerContext.LocateView(viewName, model);\r\n        }\r\n\r\n        public KeyValuePair<string, string> GetCsrfToken()\r\n        {\r\n            return this.innerContext.GetCsrfToken();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/Nancy.ViewEngines.Spark/SparkViewEngine.cs",
    "content": "﻿namespace Nancy.ViewEngines.Spark\r\n{\r\n    using System.Collections.Generic;\r\n    using System.Configuration;\r\n    using System.Dynamic;\r\n    using System.IO;\r\n    using Configuration;\r\n    using global::Spark;\r\n    using global::Spark.FileSystem;\r\n\r\n    using Nancy.Responses;\r\n    using Nancy.ViewEngines.Spark.Descriptors;\r\n\r\n    /// <summary>\r\n    /// View engine for rendering spark views.\r\n    /// </summary>\r\n    public class SparkViewEngine : IViewEngine\r\n    {\r\n        private readonly INancyEnvironment environment;\r\n        private readonly IDescriptorBuilder descriptorBuilder;\r\n        private readonly global::Spark.SparkViewEngine engine;\r\n        private readonly ISparkSettings settings;\r\n        private readonly string[] extensions = new[] { \"spark\", \"shade\" };\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"SparkViewEngine\"/> class.\r\n        /// </summary>\r\n        public SparkViewEngine(IRootPathProvider rootPathProvider, INancyEnvironment environment)\r\n        {\r\n            this.environment = environment;\r\n            this.settings = (ISparkSettings) ConfigurationManager.GetSection(\"spark\") ?? new SparkSettings();\r\n\r\n            this.engine =\r\n                new global::Spark.SparkViewEngine(this.settings)\r\n                {\r\n                    DefaultPageBaseType = typeof (NancySparkView).FullName,\r\n                    BindingProvider = new NancyBindingProvider(rootPathProvider),\r\n                };\r\n\r\n            this.descriptorBuilder = new DefaultDescriptorBuilder(this.engine);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the extensions file extensions that are supported by the view engine.\r\n        /// </summary>\r\n        /// <value>An <see cref=\"IEnumerable{T}\"/> instance containing the extensions.</value>\r\n        /// <remarks>The extensions should not have a leading dot in the name.</remarks>\r\n        public IEnumerable<string> Extensions\r\n        {\r\n            get { return this.extensions; }\r\n        }\r\n\r\n        private SparkViewEngineResult CreateView<TModel>(ViewLocationResult viewLocationResult, TModel model, IRenderContext renderContext)\r\n        {\r\n            var result = this.LocateView(\r\n                viewLocationResult.Location,\r\n                viewLocationResult.Name,\r\n                viewLocationResult,\r\n                renderContext);\r\n\r\n            var viewWithModel = result.View;\r\n\r\n            if (viewWithModel != null)\r\n            {\r\n                viewWithModel.SetModel(model);\r\n            }\r\n\r\n            return result;\r\n        }\r\n\r\n        private static IViewFolder GetViewFolder(ViewEngineStartupContext viewLocationResults, INancyEnvironment environment)\r\n        {\r\n            return new NancyViewFolder(viewLocationResults, environment);\r\n        }\r\n\r\n        private SparkViewEngineResult LocateView(string viewPath, string viewName, ViewLocationResult viewLocationResult, IRenderContext renderContext)\r\n        {\r\n            var searchedLocations = new List<string>();\r\n\r\n            var descriptorParams = new BuildDescriptorParams(\r\n                viewPath,\r\n                viewName,\r\n                null,\r\n                true,\r\n                null);\r\n\r\n            var descriptor = this.descriptorBuilder.BuildDescriptor(\r\n                descriptorParams,\r\n                searchedLocations);\r\n\r\n            if (descriptor == null)\r\n            {\r\n                return new SparkViewEngineResult(searchedLocations);\r\n            }\r\n\r\n            var entry = renderContext.ViewCache.GetOrAdd(\r\n                viewLocationResult,\r\n                x => this.engine.CreateEntry(descriptor));\r\n\r\n            var nancySparkView = entry.CreateInstance() as NancySparkView;\r\n            if (nancySparkView != null)\r\n            {\r\n                nancySparkView.RenderContext = renderContext;\r\n            }\r\n\r\n            return new SparkViewEngineResult(nancySparkView);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Initialise the view engine (if necessary)\r\n        /// </summary>\r\n        /// <param name=\"viewEngineStartupContext\">Startup context</param>\r\n        public void Initialize(ViewEngineStartupContext viewEngineStartupContext)\r\n        {\r\n            this.engine.ViewFolder = GetViewFolder(viewEngineStartupContext, this.environment);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Renders the view.\r\n        /// </summary>\r\n        /// <param name=\"viewLocationResult\">A <see cref=\"ViewLocationResult\"/> instance, containing information on how to get the view template.</param>\r\n        /// <param name=\"model\">The model that should be passed into the view</param>\r\n        /// <param name=\"renderContext\"></param>\r\n        /// <returns>A response</returns>\r\n        public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)\r\n        {\r\n            return new HtmlResponse(contents: stream =>\r\n            {\r\n                var sparkRenderConext = new SparkRenderContextWrapper(renderContext, engine);\r\n\r\n                SparkViewEngineResult sparkViewEngineResult =\r\n                    this.CreateView(viewLocationResult, model ?? new ExpandoObject(), sparkRenderConext);\r\n\r\n                var writer =\r\n                    new StreamWriter(stream);\r\n\r\n                sparkViewEngineResult.View.Writer = writer;\r\n                sparkViewEngineResult.View.Model = model;\r\n                sparkViewEngineResult.View.Execute();\r\n\r\n                writer.Flush();\r\n            });\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/Nancy.ViewEngines.Spark/SparkViewEngineResult.cs",
    "content": "﻿namespace Nancy.ViewEngines.Spark\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using global::Spark.Compiler;\r\n\r\n    public class SparkViewEngineResult\r\n    {\r\n        public SparkViewEngineResult(NancySparkView view)\r\n        {\r\n            View = view;\r\n        }\r\n\r\n        public SparkViewEngineResult(List<string> searchedLocations)\r\n        {\r\n            var locations = string.Empty;\r\n            searchedLocations.ForEach(loc => locations += string.Format(\"{0} \", loc));\r\n\r\n            if (!string.IsNullOrEmpty(locations))\r\n            {\r\n                throw new CompilerException(string.Format(\"The view could not be found in any of the following locations: {0}\", locations));\r\n            }\r\n        }\r\n\r\n        public NancySparkView View { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "test/Directory.Build.props",
    "content": "<Project>\r\n  <PropertyGroup>\r\n    <CodeAnalysisRuleSet>..\\..\\Nancy.ruleset</CodeAnalysisRuleSet>\r\n    <Configurations>Debug;Release</Configurations>\r\n    <DisableImplicitFrameworkReferences Condition=\" '$(TargetFramework)' == 'net452' \">true</DisableImplicitFrameworkReferences>\r\n    <Platforms>AnyCPU</Platforms>\r\n  </PropertyGroup>\r\n\r\n  <PropertyGroup Condition=\" '$(TargetFramework)' == 'netcoreapp2.0' \">\r\n    <DefineConstants>$(DefineConstants);CORE</DefineConstants>\r\n    <RuntimeFrameworkVersion>2.0.5</RuntimeFrameworkVersion>\r\n  </PropertyGroup>\r\n\r\n  <PropertyGroup Condition=\" '$(Configuration)' == 'MonoRelease' \">\r\n    <DefineConstants>$(DefineConstants);MONO</DefineConstants>\r\n  </PropertyGroup>\r\n\r\n  <PropertyGroup>\r\n    <ProjectUnderTest>$(MSBuildProjectName.Substring(0, $(MSBuildProjectName.IndexOf(\".Tests\"))))</ProjectUnderTest>\r\n  </PropertyGroup>\r\n\r\n  <ItemGroup>\r\n    <ProjectReference Include=\"../../src/Nancy/Nancy.csproj\" />\r\n  </ItemGroup>\r\n\r\n  <ItemGroup Condition=\" '$(MSBuildProjectName)' != 'Nancy.Tests' and '$(MSBuildProjectName)' != 'Nancy.Tests.Functional' \">\r\n    <ProjectReference Include=\"../../src/$(ProjectUnderTest)/$(ProjectUnderTest).csproj\" />\r\n  </ItemGroup>\r\n\r\n  <ItemGroup Condition=\" '$(MSBuildProjectName)' != 'Nancy.Testing.Tests' \">\r\n    <ProjectReference Include=\"../../src/Nancy.Testing/Nancy.Testing.csproj\" />\r\n  </ItemGroup>\r\n\r\n  <ItemGroup Condition=\" '$(MSBuildProjectName)' != 'Nancy.Tests' and '$(MSBuildProjectName)' != 'Nancy.ViewEngines.Razor.Tests.Models' \">\r\n    <Compile Include=\"..\\Nancy.Tests\\Fakes\\*.cs;..\\Nancy.Tests\\ShouldExtensions.cs;..\\Nancy.Tests\\xUnitExtensions\\*.cs\" Exclude=\"bin\\**;obj\\**;packages\\**\" />\r\n  </ItemGroup>\r\n\r\n  <ItemGroup>\r\n    <PackageReference Include=\"FakeItEasy\" Version=\"4.6.0\" />\r\n    <PackageReference Include=\"FakeItEasy.Analyzer.CSharp\" Version=\"4.6.0\" />\r\n    <PackageReference Include=\"Microsoft.NET.Test.Sdk\" Version=\"15.5.0\" />\r\n    <PackageReference Include=\"xunit\" Version=\"2.4.0-beta.1.build3958\" />\r\n    <PackageReference Include=\"xunit.runner.visualstudio\" Version=\"2.4.0-beta.1.build3958\" />\r\n  </ItemGroup>\r\n\r\n  <ItemGroup Condition=\" '$(TargetFramework)' == 'net452' \">\r\n    <Reference Include=\"Microsoft.CSharp\" />\r\n    <Reference Include=\"System.Dynamic.Runtime\" />\r\n    <Reference Include=\"System.Threading.Tasks\" />\r\n    <Reference Include=\"System.Runtime\" />\r\n    <Reference Include=\"System.Core\" />\r\n    <Reference Include=\"System\" />\r\n  </ItemGroup>\r\n\r\n  <ItemGroup>\r\n    <DotNetCliToolReference Include=\"dotnet-xunit\" Version=\"2.4.0-beta.1.build3958\" />\r\n  </ItemGroup>\r\n</Project>\r\n"
  },
  {
    "path": "test/Nancy.Authentication.Basic.Tests/BasicAuthenticationConfigurationFixture.cs",
    "content": "﻿namespace Nancy.Authentication.Basic.Tests\r\n{\r\n    using System;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Tests;\r\n\r\n    using Xunit;\r\n\r\n    public class BasicAuthenticationConfigurationFixture\r\n\t{\r\n\t\t[Fact]\r\n\t\tpublic void Should_throw_with_null_user_validator()\r\n\t\t{\r\n\t\t\tvar result = Record.Exception(() => new BasicAuthenticationConfiguration(null, \"realm\"));\r\n\r\n\t\t\tresult.ShouldBeOfType(typeof(ArgumentNullException));\r\n\t\t}\r\n\r\n\t\t[Fact]\r\n\t\tpublic void Should_throw_with_null_realm()\r\n\t\t{\r\n\t\t\tvar result = Record.Exception(() => new BasicAuthenticationConfiguration(A.Fake<IUserValidator>(), null));\r\n\r\n\t\t\tresult.ShouldBeOfType(typeof(ArgumentException));\r\n\t\t}\r\n\r\n\r\n\t}\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Authentication.Basic.Tests/BasicAuthenticationFixture.cs",
    "content": "﻿namespace Nancy.Authentication.Basic.Tests\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Security.Claims;\r\n    using System.Text;\r\n    using System.Threading;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Tests;\r\n    using Nancy.Tests.Fakes;\r\n\r\n    using Xunit;\r\n\r\n    public class BasicAuthenticationFixture\r\n    {\r\n        private readonly BasicAuthenticationConfiguration config;\r\n        const string ajaxRequestHeaderKey = \"X-Requested-With\";\r\n        const string ajaxRequestHeaderValue = \"XMLHttpRequest\";\r\n        private readonly IPipelines hooks;\r\n\r\n        public BasicAuthenticationFixture()\r\n        {\r\n            this.config = new BasicAuthenticationConfiguration(A.Fake<IUserValidator>(), \"realm\", UserPromptBehaviour.Always);\r\n            this.hooks = new Pipelines();\r\n            BasicAuthentication.Enable(this.hooks, this.config);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_a_pre_and_post_hook_in_application_when_enabled()\r\n        {\r\n            // Given\r\n            var pipelines = A.Fake<IPipelines>();\r\n\r\n            // When\r\n            BasicAuthentication.Enable(pipelines, this.config);\r\n\r\n            // Then\r\n            A.CallTo(() => pipelines.BeforeRequest.AddItemToStartOfPipeline(A<Func<NancyContext, Response>>.Ignored))\r\n                .MustHaveHappenedOnceExactly();\r\n            A.CallTo(() => pipelines.AfterRequest.AddItemToEndOfPipeline(A<Action<NancyContext>>.Ignored))\r\n                .MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_both_basic_and_requires_auth_pre_and_post_hooks_in_module_when_enabled()\r\n        {\r\n            // Given\r\n            var module = new FakeModule();\r\n\r\n            // When\r\n            BasicAuthentication.Enable(module, this.config);\r\n            \r\n            // Then\r\n            module.Before.PipelineDelegates.ShouldHaveCount(2);\r\n            module.After.PipelineDelegates.ShouldHaveCount(1);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_with_null_config_passed_to_enable_with_application()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => BasicAuthentication.Enable(A.Fake<IPipelines>(), null));\r\n\r\n            // Then\r\n            result.ShouldBeOfType(typeof(ArgumentNullException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_with_null_config_passed_to_enable_with_module()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => BasicAuthentication.Enable(new FakeModule(), null));\r\n\r\n            // Then\r\n            result.ShouldBeOfType(typeof(ArgumentNullException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_with_null_pipeline_passed_to_enable_with_config()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => BasicAuthentication.Enable((IPipelines)null, this.config));\r\n\r\n            // Then\r\n            result.ShouldBeOfType(typeof(ArgumentNullException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_with_null_module_passed_to_enable_with_config()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => BasicAuthentication.Enable((INancyModule)null, this.config));\r\n\r\n            // Then\r\n            result.ShouldBeOfType(typeof(ArgumentNullException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Pre_request_hook_should_not_set_auth_details_with_no_auth_headers()\r\n        {\r\n            // Given\r\n            var context = new NancyContext()\r\n            {\r\n                Request = new FakeRequest(\"GET\", \"/\")\r\n            };\r\n\r\n            // When\r\n            var result = this.hooks.BeforeRequest.Invoke(context, new CancellationToken());\r\n\r\n            // Then\r\n            result.Result.ShouldBeNull();\r\n            context.CurrentUser.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Post_request_hook_should_return_challenge_when_unauthorized_returned_from_route()\r\n        {\r\n            // Given\r\n            var context = new NancyContext()\r\n            {\r\n                Request = new FakeRequest(\"GET\", \"/\")\r\n            };\r\n\r\n            string wwwAuthenticate;\r\n            context.Response = new Response { StatusCode = HttpStatusCode.Unauthorized };\r\n\r\n            // When\r\n            this.hooks.AfterRequest.Invoke(context, new CancellationToken());\r\n\r\n            // Then\r\n            context.Response.Headers.TryGetValue(\"WWW-Authenticate\", out wwwAuthenticate);\r\n            context.Response.StatusCode.ShouldEqual(HttpStatusCode.Unauthorized);\r\n            context.Response.Headers.ContainsKey(\"WWW-Authenticate\").ShouldBeTrue();\r\n            context.Response.Headers[\"WWW-Authenticate\"].ShouldContain(\"Basic\");\r\n            context.Response.Headers[\"WWW-Authenticate\"].ShouldContain(\"realm=\\\"\" + this.config.Realm + \"\\\"\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Post_request_hook_should_not_return_a_challenge_when_set_to_never()\r\n        {\r\n            // Given\r\n            var config = new BasicAuthenticationConfiguration(A.Fake<IUserValidator>(), \"realm\", UserPromptBehaviour.Never);\r\n            var hooks = new Pipelines();\r\n            BasicAuthentication.Enable(hooks, config);\r\n\r\n            var context = new NancyContext()\r\n            {\r\n                Request = new FakeRequest(\"GET\", \"/\")\r\n            };\r\n\r\n            context.Response = new Response { StatusCode = HttpStatusCode.Unauthorized };\r\n\r\n            // When\r\n            hooks.AfterRequest.Invoke(context, new CancellationToken());\r\n\r\n            // Then\r\n            context.Response.Headers.ContainsKey(\"WWW-Authenticate\").ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Post_request_hook_should_not_return_a_challenge_on_an_ajax_request_when_set_to_nonajax()\r\n        {\r\n            // Given\r\n            var config = new BasicAuthenticationConfiguration(A.Fake<IUserValidator>(), \"realm\", UserPromptBehaviour.NonAjax);\r\n            var hooks = new Pipelines();\r\n            BasicAuthentication.Enable(hooks, config);\r\n            var headers = new Dictionary<string,IEnumerable<string>>();\r\n            headers.Add(ajaxRequestHeaderKey, new [] { ajaxRequestHeaderValue });\r\n\r\n            var context = new NancyContext()\r\n            {\r\n                Request = new FakeRequest(\"GET\", \"/\", headers)\r\n            };\r\n\r\n            context.Response = new Response { StatusCode = HttpStatusCode.Unauthorized };\r\n\r\n            // When\r\n            hooks.AfterRequest.Invoke(context, new CancellationToken());\r\n\r\n            // Then\r\n            context.Response.Headers.ContainsKey(\"WWW-Authenticate\").ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Post_request_hook_should_return_a_challenge_on_a_nonajax_request_when_set_to_nonajax()\r\n        {\r\n            // Given\r\n            var config = new BasicAuthenticationConfiguration(A.Fake<IUserValidator>(), \"realm\", UserPromptBehaviour.NonAjax);\r\n            var hooks = new Pipelines();\r\n            BasicAuthentication.Enable(hooks, config);\r\n\r\n            var context = new NancyContext()\r\n            {\r\n                Request = new FakeRequest(\"GET\", \"/\")\r\n            };\r\n\r\n            context.Response = new Response { StatusCode = HttpStatusCode.Unauthorized };\r\n\r\n            // When\r\n            hooks.AfterRequest.Invoke(context, new CancellationToken());\r\n\r\n            // Then\r\n            context.Response.Headers.ContainsKey(\"WWW-Authenticate\").ShouldBeTrue();\r\n        }\r\n\r\n\r\n        [Fact]\r\n        public void Pre_request_hook_should_not_set_auth_details_when_invalid_scheme_in_auth_header()\r\n        {\r\n            // Given\r\n            var context = CreateContextWithHeader(\r\n                \"Authorization\", new[] { \"FooScheme\" + \" \" + EncodeCredentials(\"foo\", \"bar\") });\r\n\r\n            // When\r\n            var result = this.hooks.BeforeRequest.Invoke(context, new CancellationToken());\r\n\r\n            // Then\r\n            result.Result.ShouldBeNull();\r\n            context.CurrentUser.ShouldBeNull();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"Basic\")]\r\n        [InlineData(\"BASIC\")]\r\n        [InlineData(\"basic\")]\r\n        public void Pre_request_hook_should_call_user_validator_when_valid_scheme_in_auth_header(string scheme)\r\n        {\r\n            // Given\r\n            var context = CreateContextWithHeader(\r\n                \"Authorization\", new[] { scheme + \" \" + EncodeCredentials(\"foo\", \"bar\") });\r\n\r\n            // When\r\n            var result = this.hooks.BeforeRequest.Invoke(context, new CancellationToken());\r\n\r\n            // Then\r\n            A.CallTo(() => config.UserValidator.Validate(\"foo\", \"bar\")).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Pre_request_hook_should_not_authenticate_when_invalid_encoded_username_in_auth_header()\r\n        {\r\n            // Given\r\n            var context = CreateContextWithHeader(\r\n               \"Authorization\", new[] { \"Basic\" + \" \" + \"some credentials\" });\r\n\r\n            // When\r\n            var result = this.hooks.BeforeRequest.Invoke(context, new CancellationToken());\r\n\r\n            // Then\r\n            result.Result.ShouldBeNull();\r\n            context.CurrentUser.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Pre_request_hook_should_call_user_validator_with_username_in_auth_header()\r\n        {\r\n            // Given\r\n            var context = CreateContextWithHeader(\r\n               \"Authorization\", new[] { \"Basic\" + \" \" + EncodeCredentials(\"foo\", \"bar\") });\r\n\r\n            // When\r\n            this.hooks.BeforeRequest.Invoke(context, new CancellationToken());\r\n\r\n            // Then\r\n            A.CallTo(() => config.UserValidator.Validate(\"foo\", \"bar\")).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Pre_request_hook_should_call_user_validator_with_password_in_auth_header_containing_colon()\r\n        {\r\n            // Given\r\n            var context = CreateContextWithHeader(\r\n                \"Authorization\", new[] {\"Basic\" + \" \" + EncodeCredentials(\"foo\", \"bar:baz\")});\r\n\r\n            // When\r\n            this.hooks.BeforeRequest.Invoke(context, new CancellationToken());\r\n\r\n            // Then\r\n            A.CallTo(() => config.UserValidator.Validate(\"foo\", \"bar:baz\")).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_user_in_context_with_valid_username_in_auth_header()\r\n        {\r\n            // Given\r\n            var fakePipelines = new Pipelines();\r\n\r\n            var validator = A.Fake<IUserValidator>();\r\n            var fakeUser = A.Fake<ClaimsPrincipal>();\r\n            A.CallTo(() => validator.Validate(\"foo\", \"bar\")).Returns(fakeUser);\r\n\r\n            var cfg = new BasicAuthenticationConfiguration(validator, \"realm\");\r\n\r\n            var context = CreateContextWithHeader(\r\n               \"Authorization\", new [] { \"Basic\" + \" \" + EncodeCredentials(\"foo\", \"bar\") });\r\n\r\n            BasicAuthentication.Enable(fakePipelines, cfg);\r\n\r\n            // When\r\n            fakePipelines.BeforeRequest.Invoke(context, new CancellationToken());\r\n\r\n            // Then\r\n            context.CurrentUser.ShouldBeSameAs(fakeUser);\r\n        }\r\n\r\n        private static NancyContext CreateContextWithHeader(string name, IEnumerable<string> values)\r\n        {\r\n            var header = new Dictionary<string, IEnumerable<string>>\r\n            {\r\n                { name, values }\r\n            };\r\n\r\n            return new NancyContext()\r\n            {\r\n                Request = new FakeRequest(\"GET\", \"/\", header)\r\n            };\r\n        }\r\n\r\n        private static string EncodeCredentials(string username, string password)\r\n        {\r\n            var credentials = string.Format(\"{0}:{1}\", username, password);\r\n\r\n            var encodedCredentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials));\r\n\r\n            return encodedCredentials;\r\n        }\r\n\r\n        class FakeModule : NancyModule\r\n        {\r\n            public FakeModule()\r\n            {\r\n                this.After = new AfterPipeline();\r\n                this.Before = new BeforePipeline();\r\n                this.OnError = new ErrorPipeline();\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Authentication.Basic.Tests/Nancy.Authentication.Basic.Tests.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <TargetFrameworks>netcoreapp2.0;net452</TargetFrameworks>\n  </PropertyGroup>\n</Project>\n"
  },
  {
    "path": "test/Nancy.Authentication.Forms.Tests/FormsAuthenticationConfigurationFixture.cs",
    "content": "namespace Nancy.Authentication.Forms.Tests\r\n{\r\n    using System;\r\n    using FakeItEasy;\r\n    using Cryptography;\r\n    using Nancy.Tests;\r\n    using Xunit;\r\n\r\n    public class FormsAuthenticationConfigurationFixture\r\n    {\r\n        private FormsAuthenticationConfiguration config;\r\n\r\n        public FormsAuthenticationConfigurationFixture()\r\n        {\r\n            var cryptographyConfiguration = new CryptographyConfiguration(\r\n                new AesEncryptionProvider(new PassphraseKeyGenerator(\"SuperSecretPass\", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 })),\r\n                new DefaultHmacProvider(new PassphraseKeyGenerator(\"UberSuperSecure\", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 })));\r\n\r\n            this.config = new FormsAuthenticationConfiguration()\r\n                              {\r\n                                  CryptographyConfiguration = cryptographyConfiguration,\r\n                                  RedirectUrl = \"/login\",\r\n                                  UserMapper = A.Fake<IUserMapper>(),\r\n                              };\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_valid_with_all_properties_set()\r\n        {\r\n            // Given, When, Then\r\n            config.EnsureConfigurationIsValid();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_valid_with_empty_redirect_url_when_redirect_is_disabled()\r\n        {\r\n            // Given\r\n            config.RedirectUrl = \"\";\r\n            config.DisableRedirect = true;\r\n\r\n            // When, Then\r\n            config.EnsureConfigurationIsValid();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_be_valid_with_empty_redirect_url()\r\n        {\r\n            // Given\r\n            config.RedirectUrl = \"\";\r\n\r\n            // When\r\n            var result = Record.Exception(() => config.EnsureConfigurationIsValid());\r\n\r\n            // Then\r\n            result.ShouldBeOfType<InvalidOperationException>();\r\n            result.Message.ShouldEqual(\"When DisableRedirect is false RedirectUrl cannot be null.\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_be_valid_with_null_username_mapper()\r\n        {\r\n            // Given\r\n            config.UserMapper = null;\r\n\r\n            // When\r\n            var result = Record.Exception(() => config.EnsureConfigurationIsValid());\r\n\r\n            // Then\r\n            result.ShouldBeOfType<InvalidOperationException>();\r\n            result.Message.ShouldEqual(\"UserMapper cannot be null.\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_be_valid_with_null_cryptography_configuration()\r\n        {\r\n            // Given\r\n            config.CryptographyConfiguration = null;\r\n\r\n            // When\r\n            var result = Record.Exception(() => config.EnsureConfigurationIsValid());\r\n\r\n            // Then\r\n            result.ShouldBeOfType<InvalidOperationException>();\r\n            result.Message.ShouldEqual(\"CryptographyConfiguration cannot be null.\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_be_valid_with_null_encryption_provider()\r\n        {\r\n            // Given\r\n            config.CryptographyConfiguration = new CryptographyConfiguration(null, config.CryptographyConfiguration.HmacProvider);\r\n\r\n            // When\r\n            var result = Record.Exception(() => config.EnsureConfigurationIsValid());\r\n\r\n            // Then\r\n            result.ShouldBeOfType<InvalidOperationException>();\r\n            result.Message.ShouldEqual(\"CryptographyConfiguration EncryptionProvider cannot be null.\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_be_valid_with_null_hmac_provider()\r\n        {\r\n            // Given\r\n            config.CryptographyConfiguration = new CryptographyConfiguration(config.CryptographyConfiguration.EncryptionProvider, null);\r\n\r\n            // When\r\n            var result = Record.Exception(() => config.EnsureConfigurationIsValid());\r\n\r\n            // Then\r\n            result.ShouldBeOfType<InvalidOperationException>();\r\n            result.Message.ShouldEqual(\"CryptographyConfiguration HmacProvider cannot be null.\");\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Authentication.Forms.Tests/FormsAuthenticationFixture.cs",
    "content": "namespace Nancy.Authentication.Forms.Tests\r\n{\r\n    using System;\r\n    using System.Linq;\r\n    using System.Security.Claims;\r\n    using System.Security.Principal;\r\n    using System.Threading;\r\n    using FakeItEasy;\r\n    using Bootstrapper;\r\n    using Cryptography;\r\n    using Nancy.Tests;\r\n    using Nancy.Tests.Fakes;\r\n    using Xunit;\r\n\r\n    public class FormsAuthenticationFixture\r\n    {\r\n        private FormsAuthenticationConfiguration config;\r\n        private FormsAuthenticationConfiguration secureConfig;\r\n        private FormsAuthenticationConfiguration domainPathConfig;\r\n        private NancyContext context;\r\n        private Guid userGuid;\r\n\r\n        private string validCookieValue =\r\n            \"C+QzBqI2qSE6Qk60fmCsoMsQNLbQtCAFd5cpcy1xhu4=k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9\";\r\n\r\n        private string cookieWithNoHmac =\r\n            \"k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9\";\r\n\r\n        private string cookieWithEmptyHmac =\r\n            \"k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9\";\r\n\r\n        private string cookieWithInvalidHmac =\r\n            \"C+QzbqI2qSE6Qk60fmCsoMsQNLbQtCAFd5cpcy1xhu4=k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3sZwI0jB0KeVY9\";\r\n\r\n        private string cookieWithBrokenEncryptedData =\r\n            \"C+QzBqI2qSE6Qk60fmCsoMsQNLbQtCAFd5cpcy1xhu4=k+1IvvzkgKgfOK2/EgIr7Ut15f47a0fnlgH9W+Lzjv/a2Zkfxg3spwI0jB0KeVY9\";\r\n\r\n        private CryptographyConfiguration cryptographyConfiguration;\r\n\r\n        private string domain = \".nancyfx.org\";\r\n\r\n        private string path = \"/\";\r\n\r\n        public FormsAuthenticationFixture()\r\n        {\r\n            this.cryptographyConfiguration = new CryptographyConfiguration(\r\n                new AesEncryptionProvider(new PassphraseKeyGenerator(\"SuperSecretPass\", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000)),\r\n                new DefaultHmacProvider(new PassphraseKeyGenerator(\"UberSuperSecure\", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000)));\r\n\r\n            this.config = new FormsAuthenticationConfiguration()\r\n            {\r\n                CryptographyConfiguration = this.cryptographyConfiguration,\r\n                RedirectUrl = \"/login\",\r\n                UserMapper = A.Fake<IUserMapper>(),\r\n                RequiresSSL = false\r\n            };\r\n\r\n            this.secureConfig = new FormsAuthenticationConfiguration()\r\n            {\r\n                CryptographyConfiguration = this.cryptographyConfiguration,\r\n                RedirectUrl = \"/login\",\r\n                UserMapper = A.Fake<IUserMapper>(),\r\n                RequiresSSL = true\r\n            };\r\n\r\n            this.domainPathConfig = new FormsAuthenticationConfiguration()\r\n            {\r\n                CryptographyConfiguration = this.cryptographyConfiguration,\r\n                RedirectUrl = \"/login\",\r\n                UserMapper = A.Fake<IUserMapper>(),\r\n                RequiresSSL = false,\r\n                Domain = domain,\r\n                Path = path\r\n            };\r\n\r\n            this.context = new NancyContext\r\n                               {\r\n                                    Request = new Request(\r\n                                                    \"GET\",\r\n                                                    new Url { Scheme = \"http\", BasePath = \"/testing\", HostName = \"test.com\", Path = \"test\" })\r\n                               };\r\n\r\n            this.userGuid = new Guid(\"3D97EB33-824A-4173-A2C1-633AC16C1010\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_with_null_application_pipelines_passed_to_enable()\r\n        {\r\n            var result = Record.Exception(() => FormsAuthentication.Enable((IPipelines)null, this.config));\r\n\r\n            result.ShouldBeOfType(typeof(ArgumentNullException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_with_null_config_passed_to_enable()\r\n        {\r\n            var result = Record.Exception(() => FormsAuthentication.Enable(A.Fake<IPipelines>(), null));\r\n\r\n            result.ShouldBeOfType(typeof(ArgumentNullException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_with_invalid_config_passed_to_enable()\r\n        {\r\n            var fakeConfig = A.Fake<FormsAuthenticationConfiguration>();\r\n            A.CallTo(() => fakeConfig.EnsureConfigurationIsValid()).Throws<InvalidOperationException>();\r\n            var result = Record.Exception(() => FormsAuthentication.Enable(A.Fake<IPipelines>(), fakeConfig));\r\n\r\n            result.ShouldBeOfType(typeof(InvalidOperationException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_a_pre_and_post_hook_when_enabled()\r\n        {\r\n            var pipelines = A.Fake<IPipelines>();\r\n\r\n            FormsAuthentication.Enable(pipelines, this.config);\r\n\r\n            A.CallTo(() => pipelines.BeforeRequest.AddItemToStartOfPipeline(A<Func<NancyContext, Response>>.Ignored))\r\n                .MustHaveHappenedOnceExactly();\r\n            A.CallTo(() => pipelines.AfterRequest.AddItemToEndOfPipeline(A<Action<NancyContext>>.Ignored))\r\n                .MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_a_pre_hook_but_not_a_post_hook_when_DisableRedirect_is_true()\r\n        {\r\n            var pipelines = A.Fake<IPipelines>();\r\n\r\n            this.config.DisableRedirect = true;\r\n            FormsAuthentication.Enable(pipelines, this.config);\r\n\r\n            A.CallTo(() => pipelines.BeforeRequest.AddItemToStartOfPipeline(A<Func<NancyContext, Response>>.Ignored))\r\n                .MustHaveHappenedOnceExactly();\r\n            A.CallTo(() => pipelines.AfterRequest.AddItemToEndOfPipeline(A<Action<NancyContext>>.Ignored))\r\n                .MustNotHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_redirect_response_when_user_logs_in_with_redirect()\r\n        {\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);\r\n\r\n            var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);\r\n\r\n            result.ShouldBeOfType(typeof(Response));\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_ok_response_when_user_logs_in_without_redirect()\r\n        {\r\n            // Given\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);\r\n\r\n            // When\r\n            var result = FormsAuthentication.UserLoggedInResponse(userGuid);\r\n\r\n            // Then\r\n            result.ShouldBeOfType(typeof(Response));\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.OK);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_have_authentication_cookie_in_login_response_when_logging_in_with_redirect()\r\n        {\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);\r\n\r\n            var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);\r\n\r\n            result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).Any().ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_have_authentication_cookie_in_login_response_when_logging_in_without_redirect()\r\n        {\r\n            // Given\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);\r\n\r\n            // When\r\n            var result = FormsAuthentication.UserLoggedInResponse(userGuid);\r\n\r\n            // Then\r\n            result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).Any().ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_authentication_cookie_to_httponly_when_logging_in_with_redirect()\r\n        {\r\n            //Given\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);\r\n\r\n            //When\r\n            var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);\r\n\r\n            //Then\r\n            result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First()\r\n                .HttpOnly.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_authentication_cookie_to_httponly_when_logging_in_without_redirect()\r\n        {\r\n            // Given\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);\r\n\r\n            // When\r\n            var result = FormsAuthentication.UserLoggedInResponse(userGuid);\r\n\r\n            // Then\r\n            result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First()\r\n                .HttpOnly.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_set_expiry_date_if_one_not_specified_when_logging_in_with_redirect()\r\n        {\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);\r\n\r\n            var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);\r\n\r\n            result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First()\r\n                .Expires.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_set_expiry_date_if_one_not_specified_when_logging_in_without_redirect()\r\n        {\r\n            // Given\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);\r\n\r\n            // When\r\n            var result = FormsAuthentication.UserLoggedInResponse(userGuid);\r\n\r\n            // Then\r\n            result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First()\r\n                .Expires.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_expiry_date_if_one_specified_when_logging_in_with_redirect()\r\n        {\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);\r\n\r\n            var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, DateTime.Now.AddDays(1));\r\n\r\n            result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First()\r\n                .Expires.ShouldNotBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_expiry_date_if_one_specified_when_logging_in_without_redirect()\r\n        {\r\n            // Given\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);\r\n\r\n            // When\r\n            var result = FormsAuthentication.UserLoggedInResponse(userGuid, DateTime.Now.AddDays(1));\r\n\r\n            // Then\r\n            result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First()\r\n                .Expires.ShouldNotBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_encrypt_cookie_when_logging_in_with_redirect()\r\n        {\r\n            var mockEncrypter = A.Fake<IEncryptionProvider>();\r\n            this.config.CryptographyConfiguration = new CryptographyConfiguration(mockEncrypter, this.cryptographyConfiguration.HmacProvider);\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);\r\n\r\n            FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, DateTime.Now.AddDays(1));\r\n\r\n            A.CallTo(() => mockEncrypter.Encrypt(A<string>.Ignored))\r\n                .MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_encrypt_cookie_when_logging_in_without_redirect()\r\n        {\r\n            // Given\r\n            var mockEncrypter = A.Fake<IEncryptionProvider>();\r\n            this.config.CryptographyConfiguration = new CryptographyConfiguration(mockEncrypter, this.cryptographyConfiguration.HmacProvider);\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);\r\n\r\n            // When\r\n            FormsAuthentication.UserLoggedInResponse(userGuid, DateTime.Now.AddDays(1));\r\n\r\n            // Then\r\n            A.CallTo(() => mockEncrypter.Encrypt(A<string>.Ignored))\r\n                .MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_generate_hmac_for_cookie_from_encrypted_cookie_when_logging_in_with_redirect()\r\n        {\r\n            var fakeEncrypter = A.Fake<IEncryptionProvider>();\r\n            var fakeCryptoText = \"FakeText\";\r\n            A.CallTo(() => fakeEncrypter.Encrypt(A<string>.Ignored))\r\n                .Returns(fakeCryptoText);\r\n            var mockHmac = A.Fake<IHmacProvider>();\r\n            this.config.CryptographyConfiguration = new CryptographyConfiguration(fakeEncrypter, mockHmac);\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);\r\n\r\n            FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, DateTime.Now.AddDays(1));\r\n\r\n            A.CallTo(() => mockHmac.GenerateHmac(fakeCryptoText))\r\n                .MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_generate_hmac_for_cookie_from_encrypted_cookie_when_logging_in_without_redirect()\r\n        {\r\n            // Given\r\n            var fakeEncrypter = A.Fake<IEncryptionProvider>();\r\n            var fakeCryptoText = \"FakeText\";\r\n            A.CallTo(() => fakeEncrypter.Encrypt(A<string>.Ignored))\r\n                .Returns(fakeCryptoText);\r\n            var mockHmac = A.Fake<IHmacProvider>();\r\n            this.config.CryptographyConfiguration = new CryptographyConfiguration(fakeEncrypter, mockHmac);\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);\r\n\r\n            // When\r\n            FormsAuthentication.UserLoggedInResponse(userGuid, DateTime.Now.AddDays(1));\r\n\r\n            // Then\r\n            A.CallTo(() => mockHmac.GenerateHmac(fakeCryptoText))\r\n                .MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_redirect_response_when_user_logs_out_with_redirect()\r\n        {\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);\r\n\r\n            var result = FormsAuthentication.LogOutAndRedirectResponse(context, \"/\");\r\n\r\n            result.ShouldBeOfType(typeof(Response));\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_ok_response_when_user_logs_out_without_redirect()\r\n        {\r\n            // Given\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);\r\n\r\n            // When\r\n            var result = FormsAuthentication.LogOutResponse();\r\n\r\n            // Then\r\n            result.ShouldBeOfType(typeof(Response));\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.OK);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_have_expired_empty_authentication_cookie_in_logout_response_when_user_logs_out_with_redirect()\r\n        {\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);\r\n\r\n            var result = FormsAuthentication.LogOutAndRedirectResponse(context, \"/\");\r\n\r\n            var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First();\r\n            cookie.Value.ShouldBeEmpty();\r\n            cookie.Expires.ShouldNotBeNull();\r\n            (cookie.Expires < DateTime.Now).ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_have_expired_empty_authentication_cookie_in_logout_response_when_user_logs_out_without_redirect()\r\n        {\r\n            // Given\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);\r\n\r\n            // When\r\n            var result = FormsAuthentication.LogOutResponse();\r\n\r\n            // Then\r\n            var cookie = result.Cookies.First(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName);\r\n            cookie.Value.ShouldBeEmpty();\r\n            cookie.Expires.ShouldNotBeNull();\r\n            (cookie.Expires < DateTime.Now).ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_get_username_from_mapping_service_with_valid_cookie()\r\n        {\r\n            var fakePipelines = new Pipelines();\r\n            var mockMapper = A.Fake<IUserMapper>();\r\n            this.config.UserMapper = mockMapper;\r\n            FormsAuthentication.Enable(fakePipelines, this.config);\r\n            this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.validCookieValue);\r\n\r\n            fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());\r\n\r\n            A.CallTo(() => mockMapper.GetUserFromIdentifier(this.userGuid, this.context))\r\n                .MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_user_in_context_with_valid_cookie()\r\n        {\r\n            var fakePipelines = new Pipelines();\r\n            var fakeMapper = A.Fake<IUserMapper>();\r\n            var fakeUser = new ClaimsPrincipal(new GenericIdentity(\"Bob\"));\r\n            A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser);\r\n            this.config.UserMapper = fakeMapper;\r\n            FormsAuthentication.Enable(fakePipelines, this.config);\r\n            this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.validCookieValue);\r\n\r\n            var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());\r\n\r\n            context.CurrentUser.ShouldBeSameAs(fakeUser);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_set_user_in_context_with_empty_cookie()\r\n        {\r\n            var fakePipelines = new Pipelines();\r\n            var fakeMapper = A.Fake<IUserMapper>();\r\n            var fakeUser = new ClaimsPrincipal(new GenericIdentity(\"Bob\"));\r\n            A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser);\r\n            this.config.UserMapper = fakeMapper;\r\n            FormsAuthentication.Enable(fakePipelines, this.config);\r\n            this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, string.Empty);\r\n\r\n            var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());\r\n\r\n            context.CurrentUser.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_set_user_in_context_with_invalid_hmac()\r\n        {\r\n            var fakePipelines = new Pipelines();\r\n            var fakeMapper = A.Fake<IUserMapper>();\r\n            var fakeUser = new ClaimsPrincipal(new GenericIdentity(\"Bob\"));\r\n            A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser);\r\n            this.config.UserMapper = fakeMapper;\r\n            FormsAuthentication.Enable(fakePipelines, this.config);\r\n            this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithInvalidHmac);\r\n\r\n            var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());\r\n\r\n            context.CurrentUser.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_set_user_in_context_with_empty_hmac()\r\n        {\r\n            var fakePipelines = new Pipelines();\r\n            var fakeMapper = A.Fake<IUserMapper>();\r\n            var fakeUser = new ClaimsPrincipal(new GenericIdentity(\"Bob\"));\r\n            A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser);\r\n            this.config.UserMapper = fakeMapper;\r\n            FormsAuthentication.Enable(fakePipelines, this.config);\r\n            this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithEmptyHmac);\r\n\r\n            var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());\r\n\r\n            context.CurrentUser.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_set_user_in_context_with_no_hmac()\r\n        {\r\n            var fakePipelines = new Pipelines();\r\n            var fakeMapper = A.Fake<IUserMapper>();\r\n            var fakeUser = new ClaimsPrincipal(new GenericIdentity(\"Bob\"));\r\n            A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser);\r\n            this.config.UserMapper = fakeMapper;\r\n            FormsAuthentication.Enable(fakePipelines, this.config);\r\n            this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithNoHmac);\r\n\r\n            var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());\r\n\r\n            context.CurrentUser.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_set_username_in_context_with_broken_encryption_data()\r\n        {\r\n            var fakePipelines = new Pipelines();\r\n            var fakeMapper = A.Fake<IUserMapper>();\r\n            var fakeUser = new ClaimsPrincipal(new GenericIdentity(\"Bob\"));\r\n            A.CallTo(() => fakeMapper.GetUserFromIdentifier(this.userGuid, this.context)).Returns(fakeUser);\r\n            this.config.UserMapper = fakeMapper;\r\n            FormsAuthentication.Enable(fakePipelines, this.config);\r\n            this.context.Request.Cookies.Add(FormsAuthentication.FormsAuthenticationCookieName, this.cookieWithBrokenEncryptedData);\r\n\r\n            var result = fakePipelines.BeforeRequest.Invoke(this.context, new CancellationToken());\r\n\r\n            context.CurrentUser.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_retain_querystring_when_redirecting_to_login_page()\r\n        {\r\n            // Given\r\n            var fakePipelines = new Pipelines();\r\n\r\n            FormsAuthentication.Enable(fakePipelines, this.config);\r\n\r\n            var queryContext = new NancyContext()\r\n            {\r\n                Request = new FakeRequest(\"GET\", \"/secure\", \"?foo=bar\"),\r\n                Response = HttpStatusCode.Unauthorized\r\n            };\r\n\r\n            // When\r\n            fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken());\r\n\r\n            // Then\r\n            queryContext.Response.Headers[\"Location\"].ShouldEqual(\"/login?returnUrl=/secure%3ffoo%3dbar\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_change_the_forms_authentication_redirect_uri_querystring_key()\r\n        {\r\n            // Given\r\n            var fakePipelines = new Pipelines();\r\n\r\n            this.config.RedirectQuerystringKey = \"next\";\r\n            FormsAuthentication.Enable(fakePipelines, this.config);\r\n\r\n            var queryContext = new NancyContext()\r\n            {\r\n                Request = new FakeRequest(\"GET\", \"/secure\", \"?foo=bar\"),\r\n                Response = HttpStatusCode.Unauthorized\r\n            };\r\n\r\n            // When\r\n            fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken());\r\n\r\n            // Then\r\n            queryContext.Response.Headers[\"Location\"].ShouldEqual(\"/login?next=/secure%3ffoo%3dbar\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_change_the_forms_authentication_redirect_uri_querystring_key_returnUrl_if_config_redirectQuerystringKey_is_null()\r\n        {\r\n            // Given\r\n            var fakePipelines = new Pipelines();\r\n\r\n            this.config.RedirectQuerystringKey = null;\r\n            FormsAuthentication.Enable(fakePipelines, this.config);\r\n\r\n            var queryContext = new NancyContext()\r\n            {\r\n                Request = new FakeRequest(\"GET\", \"/secure\", \"?foo=bar\"),\r\n                Response = HttpStatusCode.Unauthorized\r\n            };\r\n\r\n            // When\r\n            fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken());\r\n\r\n            // Then\r\n            queryContext.Response.Headers[\"Location\"].ShouldEqual(\"/login?returnUrl=/secure%3ffoo%3dbar\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_change_the_forms_authentication_redirect_uri_querystring_key_returnUrl_if_config_redirectQuerystringKey_is_empty()\r\n        {\r\n            // Given\r\n            var fakePipelines = new Pipelines();\r\n\r\n            this.config.RedirectQuerystringKey = string.Empty;\r\n            FormsAuthentication.Enable(fakePipelines, this.config);\r\n\r\n            var queryContext = new NancyContext()\r\n            {\r\n                Request = new FakeRequest(\"GET\", \"/secure\", \"?foo=bar\"),\r\n                Response = HttpStatusCode.Unauthorized\r\n            };\r\n\r\n            // When\r\n            fakePipelines.AfterRequest.Invoke(queryContext, new CancellationToken());\r\n\r\n            // Then\r\n            queryContext.Response.Headers[\"Location\"].ShouldEqual(\"/login?returnUrl=/secure%3ffoo%3dbar\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_retain_querystring_when_redirecting_after_successfull_login()\r\n        {\r\n            // Given\r\n            var queryContext = new NancyContext()\r\n            {\r\n                Request = new FakeRequest(\"GET\", \"/secure\", \"returnUrl=/secure%3Ffoo%3Dbar\")\r\n            };\r\n\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);\r\n\r\n            // When\r\n            var result = FormsAuthentication.UserLoggedInRedirectResponse(queryContext, userGuid, DateTime.Now.AddDays(1));\r\n\r\n            // Then\r\n            result.Headers[\"Location\"].ShouldEqual(\"/secure?foo=bar\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_logging_in_with_redirect()\r\n        {\r\n            //Given\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig);\r\n\r\n            //When\r\n            var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);\r\n\r\n            //Then\r\n            result.Cookies\r\n                    .Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName)\r\n                    .First()\r\n                    .Secure.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_logging_in_without_redirect()\r\n        {\r\n            // Given\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig);\r\n\r\n            // When\r\n            var result = FormsAuthentication.UserLoggedInResponse(userGuid);\r\n\r\n            // Then\r\n            result.Cookies\r\n                    .Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName)\r\n                    .First()\r\n                    .Secure.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_user_logs_out_with_redirect()\r\n        {\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig);\r\n\r\n            var result = FormsAuthentication.LogOutAndRedirectResponse(context, \"/\");\r\n\r\n            var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First();\r\n            cookie.Secure.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_authentication_cookie_to_secure_when_config_requires_ssl_and_user_logs_out_without_redirect()\r\n        {\r\n            // Given\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.secureConfig);\r\n\r\n            // When\r\n            var result = FormsAuthentication.LogOutResponse();\r\n\r\n            // Then\r\n            var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First();\r\n            cookie.Secure.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_redirect_to_base_path_if_non_local_url_and_no_fallback()\r\n        {\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);\r\n            context.Request.Query[config.RedirectQuerystringKey] = \"http://moo.com/\";\r\n\r\n            var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);\r\n\r\n            result.ShouldBeOfType(typeof(Response));\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther);\r\n            result.Headers[\"Location\"].ShouldEqual(\"/testing\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_redirect_to_fallback_if_non_local_url_and_fallback_set()\r\n        {\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);\r\n            context.Request.Query[config.RedirectQuerystringKey] = \"http://moo.com/\";\r\n\r\n            var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid, fallbackRedirectUrl:\"/moo\");\r\n\r\n            result.ShouldBeOfType(typeof(Response));\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther);\r\n            result.Headers[\"Location\"].ShouldEqual(\"/moo\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_redirect_to_given_url_if_local()\r\n        {\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.config);\r\n            context.Request.Query[config.RedirectQuerystringKey] = \"~/login\";\r\n\r\n            var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);\r\n\r\n            result.ShouldBeOfType(typeof(Response));\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.SeeOther);\r\n            result.Headers[\"Location\"].ShouldEqual(\"/testing/login\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_Domain_when_config_provides_domain_value()\r\n        {\r\n            //Given\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.domainPathConfig);\r\n\r\n            //When\r\n            var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);\r\n\r\n            //Then\r\n            var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First();\r\n            cookie.Domain.ShouldEqual(domain);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_Path_when_config_provides_path_value()\r\n        {\r\n            //Given\r\n            FormsAuthentication.Enable(A.Fake<IPipelines>(), this.domainPathConfig);\r\n\r\n            //When\r\n            var result = FormsAuthentication.UserLoggedInRedirectResponse(context, userGuid);\r\n\r\n            //Then\r\n            var cookie = result.Cookies.Where(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName).First();\r\n            cookie.Path.ShouldEqual(path);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_with_null_module_passed_to_enable()\r\n        {\r\n            var result = Record.Exception(() => FormsAuthentication.Enable((INancyModule)null, this.config));\r\n\r\n            result.ShouldBeOfType(typeof(ArgumentNullException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_with_null_config_passed_to_enable_with_module()\r\n        {\r\n            var result = Record.Exception(() => FormsAuthentication.Enable(new FakeModule(), null));\r\n\r\n            result.ShouldBeOfType(typeof(ArgumentNullException));\r\n        }\r\n\r\n        class FakeModule : NancyModule\r\n        {\r\n            public FakeModule()\r\n            {\r\n                this.After = new AfterPipeline();\r\n                this.Before = new BeforePipeline();\r\n                this.OnError = new ErrorPipeline();\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Authentication.Forms.Tests/Nancy.Authentication.Forms.Tests.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <TargetFrameworks>netcoreapp2.0;net452</TargetFrameworks>\n  </PropertyGroup>\n</Project>\n"
  },
  {
    "path": "test/Nancy.Embedded.Tests/Nancy.Embedded.Tests.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <TargetFrameworks>netcoreapp2.0;net452</TargetFrameworks>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <EmbeddedResource Include=\"Resources\\**\\*.*\" Exclude=\"bin\\**;obj\\**;**\\*.xproj;packages\\**;@(EmbeddedResource)\" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "test/Nancy.Embedded.Tests/Resources/Subfolder/embedded2.txt",
    "content": "Embedded2 Text"
  },
  {
    "path": "test/Nancy.Embedded.Tests/Resources/Subfolder-with-hyphen/embedded3.txt",
    "content": "Embedded3 Text"
  },
  {
    "path": "test/Nancy.Embedded.Tests/Resources/embedded.txt",
    "content": "Embedded Text"
  },
  {
    "path": "test/Nancy.Embedded.Tests/Unit/EmbeddedStaticContentConventionBuilderFixture.cs",
    "content": "﻿namespace Nancy.Embedded.Tests.Unit\r\n{\r\n    using System.IO;\r\n    using System.Text;\r\n\r\n    using Nancy.Diagnostics;\r\n    using Nancy.Embedded.Conventions;\r\n    using Nancy.Extensions;\r\n    using Nancy.Responses;\r\n    using Nancy.Tests;\r\n\r\n    using Xunit;\r\n\r\n    public class EmbeddedStaticContentConventionBuilderFixture\r\n    {\r\n        [Fact]\r\n        public void Should_retrieve_static_content_with_urlencoded_dot()\r\n        {\r\n            // Given\r\n            // When\r\n            var result = GetEmbeddedStaticContent(\"Foo\", \"embedded%2etxt\");\r\n\r\n            // Then\r\n            result.ShouldEqual(\"Embedded Text\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_retrieve_static_content_in_subfolder()\r\n        {\r\n            // Given\r\n            // When\r\n            var result = GetEmbeddedStaticContent(\"Foo\", \"Subfolder/embedded2.txt\");\r\n\r\n            // Then\r\n            result.ShouldEqual(\"Embedded2 Text\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_retrieve_static_content_with_hyphens_in_subfolder()\r\n        {\r\n            // Given\r\n            // When\r\n            var result = GetEmbeddedStaticContent(\"Foo\", \"Subfolder-with-hyphen/embedded3.txt\");\r\n\r\n            // Then\r\n            result.ShouldEqual(\"Embedded3 Text\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_retrieve_static_content_with_relative_path()\r\n        {\r\n            // Given\r\n            // When\r\n            var result = GetEmbeddedStaticContent(\"Foo\", \"Subfolder/../embedded.txt\");\r\n\r\n            // Then\r\n            result.ShouldEqual(\"Embedded Text\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_retrieve_static_content_ignoring_casing()\r\n        {\r\n            // Given\r\n            // When\r\n            var result = GetEmbeddedStaticContent(\"Foo\", \"Subfolder/embedded2.txt\", \"resources\");\r\n\r\n            // Then\r\n            result.ShouldEqual(\"Embedded2 Text\");\r\n        }\r\n\r\n        private static string GetEmbeddedStaticContent(string virtualDirectory, string requestedFilename, string contentPath = null)\r\n        {\r\n            var resource =\r\n                string.Format(\"/{0}/{1}\", virtualDirectory, requestedFilename);\r\n\r\n            var context =\r\n                new NancyContext\r\n                {\r\n                    Request = new Request(\"GET\", resource, \"http\"),\r\n                    Trace = new DefaultRequestTrace\r\n                    {\r\n                        TraceLog = new DefaultTraceLog()\r\n                    }\r\n                };\r\n\r\n            var assembly =\r\n                typeof(EmbeddedStaticContentConventionBuilderFixture).GetAssembly();\r\n\r\n            var resolver =\r\n                EmbeddedStaticContentConventionBuilder.AddDirectory(virtualDirectory, assembly, contentPath ?? \"Resources\");\r\n\r\n            var response =\r\n                resolver.Invoke(context, null) as EmbeddedFileResponse;\r\n\r\n            if (response != null)\r\n            {\r\n                using (var stream = new MemoryStream())\r\n                {\r\n                    response.Contents(stream);\r\n                    return Encoding.UTF8.GetString(stream.ToArray());\r\n                }\r\n            }\r\n\r\n            return null;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Encryption.MachineKey.Tests/MachineConfigEncryptionProviderFixture.cs",
    "content": "﻿namespace Nancy.Encryption.MachineKey.Tests\r\n{\r\n    using Nancy.Cryptography;\r\n    using Nancy.Tests;\r\n\r\n    using Xunit;\r\n\r\n    public class MachineConfigEncryptionProviderFixture\r\n    {\r\n        private readonly IEncryptionProvider provider = new MachineKeyEncryptionProvider();\r\n\r\n        [Fact]\r\n        public void Should_encrypt_data()\r\n        {\r\n            const string input = \"This is some input\";\r\n\r\n            var output = provider.Encrypt(input);\r\n\r\n            output.ShouldNotEqual(input);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_decrypt_valid_data()\r\n        {\r\n            const string clear = \"This is some input\";\r\n            var input = provider.Encrypt(clear);\r\n\r\n            var output = provider.Decrypt(input);\r\n\r\n            output.ShouldEqual(clear);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_emptystring_for_invalid_data_when_decrypting()\r\n        {\r\n            const string clear = \"This is some input\";\r\n            var input = provider.Encrypt(clear);\r\n            input = input.Substring(0, input.Length - 3);\r\n\r\n            var output = provider.Decrypt(input);\r\n\r\n            output.ShouldEqual(string.Empty);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Encryption.MachineKey.Tests/MachineKeyHmacProviderFixture.cs",
    "content": "﻿namespace Nancy.Encryption.MachineKey.Tests\r\n{\r\n    using Nancy.Cryptography;\r\n    using Nancy.Tests;\r\n\r\n    using Xunit;\r\n    using Xunit.Extensions;\r\n\r\n    public class MachineKeyHmacProviderFixture\r\n    {\r\n        private readonly IHmacProvider provider = new MachineKeyHmacProvider();\r\n\r\n        [Fact]\r\n        public void Should_sign_string_data()\r\n        {\r\n            const string input = \"this is some data\";\r\n\r\n            var output = provider.GenerateHmac(input);\r\n\r\n            output.Length.ShouldNotEqual(0);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"this is some data\", \"this is some data\", true)]\r\n        [InlineData(\"this is some data\", \"this is some dat\", false)]\r\n        [InlineData(\"this is some data  \", \"this is some data\", false)]\r\n        [InlineData(\"this 1s some data\", \"this is some data\", false)]\r\n        public void Should_validate(string input1, string input2, bool expected)\r\n        {\r\n            var hmac1 = provider.GenerateHmac(input1);\r\n            var hmac2 = provider.GenerateHmac(input2);\r\n\r\n            var result = HmacComparer.Compare(hmac1, hmac2, provider.HmacLength);\r\n\r\n            result.ShouldEqual(expected);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Encryption.MachineKey.Tests/Nancy.Encryption.MachineKey.Tests.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <TargetFramework>net452</TargetFramework>\n  </PropertyGroup>\n</Project>\n"
  },
  {
    "path": "test/Nancy.Hosting.Aspnet.Tests/Nancy.Hosting.Aspnet.Tests.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <TargetFramework>net452</TargetFramework>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <Reference Include=\"System.Web\" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "test/Nancy.Hosting.Aspnet.Tests/NancyHandlerFixture.cs",
    "content": "namespace Nancy.Hosting.Aspnet.Tests\r\n{\r\n    using System;\r\n    using System.Collections.Specialized;\r\n    using System.IO;\r\n    using System.Text;\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n    using System.Web;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Cookies;\r\n    using Nancy.Helpers;\r\n\r\n    using Xunit;\r\n\r\n    public class NancyHandlerFixture\r\n    {\r\n        private readonly NancyHandler handler;\r\n        private readonly HttpContextBase context;\r\n        private readonly HttpRequestBase request;\r\n        private readonly HttpResponseBase response;\r\n        private readonly INancyEngine engine;\r\n        private readonly NameValueCollection formData;\r\n\r\n        public NancyHandlerFixture()\r\n        {\r\n            this.context = A.Fake<HttpContextBase>();\r\n            this.request = A.Fake<HttpRequestBase>();\r\n            this.response = A.Fake<HttpResponseBase>();\r\n            this.engine = A.Fake<INancyEngine>();\r\n            this.handler = new NancyHandler(engine);\r\n            this.formData = new NameValueCollection();\r\n\r\n            A.CallTo(() => this.request.Form).ReturnsLazily(() => this.formData);\r\n            A.CallTo(() => this.request.Url).Returns(new Uri(\"http://www.foo.com\"));\r\n            A.CallTo(() => this.request.InputStream).Returns(new MemoryStream());\r\n            A.CallTo(() => this.request.Headers).Returns(new NameValueCollection());\r\n            A.CallTo(() => this.request.AppRelativeCurrentExecutionFilePath).Returns(\"~/foo\");\r\n\r\n            A.CallTo(() => this.context.Request).Returns(this.request);\r\n            A.CallTo(() => this.context.Response).Returns(this.response);\r\n            A.CallTo(() => this.response.OutputStream).Returns(new MemoryStream());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_invoke_engine_with_requested_method()\r\n        {\r\n            // Given\r\n            var nancyContext = new NancyContext {Response = new Response()};\r\n            A.CallTo(() => this.request.HttpMethod).Returns(\"POST\");\r\n            A.CallTo(() => this.engine.HandleRequest(\r\n                                        A<Request>.Ignored,\r\n                                        A<Func<NancyContext, NancyContext>>.Ignored,\r\n                                        A<CancellationToken>.Ignored))\r\n                                      .Returns(Task.FromResult(nancyContext));\r\n\r\n            // When\r\n            await this.handler.ProcessRequest(this.context);\r\n\r\n            // Then\r\n            A.CallTo(() => this.engine.HandleRequest(A<Request>\r\n                .That\r\n                .Matches(x => x.Method.Equals(\"POST\")), A<Func<NancyContext, NancyContext>>.Ignored, A<CancellationToken>.Ignored))\r\n                .MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_output_the_responses_cookies()\r\n        {\r\n            // Given\r\n            var cookie1 = A.Fake<INancyCookie>();\r\n            var cookie2 = A.Fake<INancyCookie>();\r\n            var r = new Response();\r\n            r.WithCookie(cookie1).WithCookie(cookie2);\r\n            var nancyContext = new NancyContext { Response = r };\r\n\r\n            A.CallTo(() => cookie1.ToString()).Returns(\"the first cookie\");\r\n            A.CallTo(() => cookie2.ToString()).Returns(\"the second cookie\");\r\n\r\n            SetupRequestProcess(nancyContext);\r\n\r\n            // When\r\n            await this.handler.ProcessRequest(context);\r\n\r\n            // Then\r\n            A.CallTo(() => this.response.AddHeader(\"Set-Cookie\", \"the first cookie\")).MustHaveHappened();\r\n            A.CallTo(() => this.response.AddHeader(\"Set-Cookie\", \"the second cookie\")).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_dispose_the_context()\r\n        {\r\n            // Given\r\n            var disposable = A.Fake<IDisposable>();\r\n            var nancyContext = new NancyContext() { Response = new Response() };\r\n            nancyContext.Items.Add(\"Disposable\", disposable);\r\n            A.CallTo(() => this.request.HttpMethod).Returns(\"GET\");\r\n            A.CallTo(() => this.engine.HandleRequest(\r\n                                        A<Request>.Ignored,\r\n                                        A<Func<NancyContext, NancyContext>>.Ignored,\r\n                                        A<CancellationToken>.Ignored))\r\n                                      .Returns(Task.FromResult(nancyContext));\r\n\r\n            // When\r\n            await this.handler.ProcessRequest(this.context);\r\n\r\n            // Then\r\n            A.CallTo(() => disposable.Dispose()).MustHaveHappenedOnceExactly();\r\n        }\r\n        [Fact]\r\n        public async Task Should_create_request_body_when_content_length_specified()\r\n        {\r\n            var bodyString = \"This is a sample body\";\r\n            var nancyContext = new NancyContext() { Response = new Response() };\r\n            A.CallTo(() => this.request.HttpMethod).Returns(\"POST\");\r\n            A.CallTo(() => this.request.Headers).Returns(new NameValueCollection { { \"Content-Length\", bodyString.Length.ToString() } });\r\n            A.CallTo(() => this.request.InputStream).Returns(new MemoryStream(Encoding.UTF8.GetBytes(bodyString)));\r\n            A.CallTo(() => this.request.Url).Returns(new Uri(\"http://ihatedummydata.com/about\"));\r\n            A.CallTo(() => this.engine.HandleRequest(\r\n                                        A<Request>.Ignored,\r\n                                        A<Func<NancyContext, NancyContext>>.Ignored,\r\n                                        A<CancellationToken>.Ignored))\r\n                                      .Returns(Task.FromResult(nancyContext));\r\n \r\n            await this.handler.ProcessRequest(this.context);\r\n \r\n            A.CallTo(() => this.engine.HandleRequest(A<Request>\r\n                .That\r\n                .Matches(x => x.Body.Length == bodyString.Length), A<Func<NancyContext, NancyContext>>.Ignored, A<CancellationToken>.Ignored))\r\n                .MustHaveHappened();\r\n        }\r\n \r\n        [Fact]\r\n        public async Task Should_not_create_request_body_when_content_length__not_specified_and_not_chunked()\r\n        {\r\n            var bodyString = \"This is a sample body\";\r\n            var nancyContext = new NancyContext() { Response = new Response() };\r\n            A.CallTo(() => this.request.HttpMethod).Returns(\"GET\");\r\n            A.CallTo(() => this.request.InputStream).Returns(new MemoryStream(Encoding.UTF8.GetBytes(bodyString)));\r\n            A.CallTo(() => this.request.Url).Returns(new Uri(\"http://ihatedummydata.com/about\"));\r\n            A.CallTo(() => this.engine.HandleRequest(\r\n                                        A<Request>.Ignored,\r\n                                        A<Func<NancyContext, NancyContext>>.Ignored,\r\n                                        A<CancellationToken>.Ignored))\r\n                                      .Returns(Task.FromResult(nancyContext));\r\n \r\n            await this.handler.ProcessRequest(this.context);\r\n \r\n            A.CallTo(() => this.engine.HandleRequest(A<Request>\r\n                .That\r\n                .Matches(x => x.Body.Length == 0), A<Func<NancyContext, NancyContext>>.Ignored, A<CancellationToken>.Ignored))\r\n                .MustHaveHappened();\r\n        }\r\n \r\n        [Fact]\r\n        public async Task Should_create_request_body_when_content_length_not_specified_but_transfer_encoding_is_chunked()\r\n        {\r\n            var bodyString = \"This is a sample body\";\r\n            var nancyContext = new NancyContext() { Response = new Response() };\r\n            A.CallTo(() => this.request.HttpMethod).Returns(\"POST\");\r\n            A.CallTo(() => this.request.Headers).Returns(new NameValueCollection { { \"Transfer-Encoding\", \"chunked\" } });\r\n            A.CallTo(() => this.request.InputStream).Returns(new MemoryStream(Encoding.UTF8.GetBytes(bodyString)));\r\n            A.CallTo(() => this.request.Url).Returns(new Uri(\"http://ihatedummydata.com/about\"));\r\n            A.CallTo(() => this.engine.HandleRequest(\r\n                                        A<Request>.Ignored,\r\n                                        A<Func<NancyContext, NancyContext>>.Ignored,\r\n                                        A<CancellationToken>.Ignored))\r\n                                      .Returns(Task.FromResult(nancyContext));\r\n \r\n            await this.handler.ProcessRequest(this.context);\r\n \r\n            A.CallTo(() => this.engine.HandleRequest(A<Request>\r\n                .That\r\n                .Matches(x => x.Body.Length == bodyString.Length), A<Func<NancyContext, NancyContext>>.Ignored, A<CancellationToken>.Ignored))\r\n                .MustHaveHappened();\r\n        }\r\n\r\n        private void SetupRequestProcess(NancyContext nancyContext)\r\n        {\r\n            A.CallTo(() => this.request.AppRelativeCurrentExecutionFilePath).Returns(\"~/about\");\r\n            A.CallTo(() => this.request.Url).Returns(new Uri(\"http://ihatedummydata.com/about\"));\r\n            A.CallTo(() => this.request.HttpMethod).Returns(\"GET\");\r\n            A.CallTo(() => this.engine.HandleRequest(\r\n                                        A<Request>.Ignored,\r\n                                        A<Func<NancyContext, NancyContext>>.Ignored,\r\n                                        A<CancellationToken>.Ignored))\r\n                                      .Returns(Task.FromResult(nancyContext));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Hosting.Self.Tests/IsCaseInstensitiveBaseOfFixture.cs",
    "content": "namespace Nancy.Hosting.Self.Tests\r\n{\r\n    using System;\r\n\r\n    using Nancy.Tests;\r\n\r\n    using Xunit;\r\n\r\n    public class IsCaseInstensitiveBaseOfFixture\r\n    {\r\n        private readonly Uri baseUri = new Uri(\"http://host/path/path/file\");\r\n        private readonly Uri baseSlashUri = new Uri(\"http://host/path/path/\");\r\n        private readonly Uri baseLocalHostUri = new Uri(\"http://localhost/path/path/\");\r\n\r\n        [Fact]\r\n        public void url_should_be_base_of_sub_directory()\r\n        {\r\n            // Given, When\r\n            var isBaseOf = baseUri.IsCaseInsensitiveBaseOf(new Uri(\"http://host/path/path/file/\"));\r\n\r\n            // Then\r\n            isBaseOf.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void url_should_be_base_of_sub_path_with_fragment()\r\n        {\r\n            // Given, When\r\n            var isBaseOf = baseUri.IsCaseInsensitiveBaseOf(new Uri(\"http://host/path/path/file#fragment\"));\r\n\r\n            // Then\r\n            isBaseOf.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void url_should_be_base_of_path_with_more_dirs()\r\n        {\r\n            // Given, When\r\n            var isBaseOf = baseUri.IsCaseInsensitiveBaseOf(new Uri(\"http://host/path/path/file/MoreDir/\"));\r\n\r\n            // Then\r\n            isBaseOf.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void url_should_be_base_of_sub_path_with_file_and_query()\r\n        {\r\n            // Given, When\r\n            var isBaseOf = baseUri.IsCaseInsensitiveBaseOf(new Uri(\"http://host/path/path/file/OtherFile?Query\"));\r\n\r\n            // Then\r\n            isBaseOf.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void url_should_be_base_of_path_with_extra_slash()\r\n        {\r\n            // Given, When\r\n            var isBaseOf = baseUri.IsCaseInsensitiveBaseOf(new Uri(\"http://host/path/path/file/\"));\r\n\r\n            // Then\r\n            isBaseOf.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void url_should_be_base_of_sub_file()\r\n        {\r\n            // Given, When\r\n            var isBaseOf = baseUri.IsCaseInsensitiveBaseOf(new Uri(\"http://host/path/path/file\"));\r\n\r\n            // Then\r\n            isBaseOf.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void url_should_not_be_base_of_other_scheme()\r\n        {\r\n            // Given, When\r\n            var isBaseOf = baseUri.IsCaseInsensitiveBaseOf(new Uri(\"https://host/path/path/file\"));\r\n\r\n            // Then\r\n            isBaseOf.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void url_should_not_be_base_of_other_host()\r\n        {\r\n            // Given, When\r\n            var isBaseOf = baseUri.IsCaseInsensitiveBaseOf(new Uri(\"http://otherhost/path/path/file\"));\r\n\r\n            // Then\r\n            isBaseOf.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void url_should_not_be_base_of_other_port()\r\n        {\r\n            // Given, When\r\n            var isBaseOf = baseUri.IsCaseInsensitiveBaseOf(new Uri(\"http://otherhost:8080/path/path/file\"));\r\n\r\n            // Then\r\n            isBaseOf.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void url_should_be_base_of_host_with_different_casing()\r\n        {\r\n            // Given, When\r\n            var isBaseOf = baseUri.IsCaseInsensitiveBaseOf(new Uri(\"http://Host/path/path/file\"));\r\n\r\n            // Then\r\n            isBaseOf.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void url_should_be_base_of_exact_path_without_trailing_slash()\r\n        {\r\n            // Given, When\r\n            var isBaseOf = baseSlashUri.IsCaseInsensitiveBaseOf(new Uri(\"http://host/path/path\"));\r\n\r\n            // Then\r\n            isBaseOf.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void url_should_be_base_of_exact_path_without_trailing_slash_with_query()\r\n        {\r\n            // Given, When\r\n            var isBaseOf = baseSlashUri.IsCaseInsensitiveBaseOf(new Uri(\"http://host/path/path?query\"));\r\n\r\n            // Then\r\n            isBaseOf.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void url_should_be_base_of_exact_path_without_trailing_slash_with_fragment()\r\n        {\r\n            // Given, When\r\n            var isBaseOf = baseSlashUri.IsCaseInsensitiveBaseOf(new Uri(\"http://host/path/path#Fragment\"));\r\n\r\n            // Then\r\n            isBaseOf.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void url_should_not_be_base_of_other_path()\r\n        {\r\n            // Given, When\r\n            var isBaseOf = baseSlashUri.IsCaseInsensitiveBaseOf(new Uri(\"http://host/path/path2/\"));\r\n\r\n            // Then\r\n            isBaseOf.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void url_should_be_base_of_same_path_with_different_host_casing()\r\n        {\r\n            // Given, When\r\n            var isBaseOf = baseSlashUri.IsCaseInsensitiveBaseOf(new Uri(\"http://Host/path/path/\"));\r\n\r\n            // Then\r\n            isBaseOf.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void url_should_be_base_of_same_path_with_different_path_casing()\r\n        {\r\n            // Given, When\r\n            var isBaseOf = baseSlashUri.IsCaseInsensitiveBaseOf(new Uri(\"http://host/Path/PATH/\"));\r\n\r\n            // Then\r\n            isBaseOf.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void url_should_be_base_of_same_path_with_different_host_using_localhost_wildcard()\r\n        {\r\n            // Given, When\r\n            var isBaseOf = baseLocalHostUri.IsCaseInsensitiveBaseOf(new Uri(\"http://OtherHost/path/path/file\"));\r\n\r\n            // Then\r\n            isBaseOf.ShouldBeTrue();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Hosting.Self.Tests/MakeAppLocalPathFixture.cs",
    "content": "namespace Nancy.Hosting.Self.Tests\r\n{\r\n    using System;\r\n\r\n    using Nancy.Tests;\r\n\r\n    using Xunit;\r\n\r\n    public class MakeAppLocalPathFixture\r\n    {\r\n        [Fact]\r\n        public void Should_return_path_as_local_path()\r\n        {\r\n            // Given\r\n            var uri = new Uri(\"http://host/base/\");\r\n\r\n            // When\r\n            string result = uri.MakeAppLocalPath(new Uri(\"http://host/base/rel\"));\r\n\r\n            // Then\r\n            result.ShouldEqual(\"/rel\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_root_path_with_trailing_slash_as_slash()\r\n        {\r\n            // Given\r\n            var uri = new Uri(\"http://host/base/\");\r\n\r\n            // When\r\n            string result = uri.MakeAppLocalPath(new Uri(\"http://host/base/\"));\r\n\r\n            // Then\r\n            result.ShouldEqual(\"/\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_root_path_without_trailing_slash_as_slash()\r\n        {\r\n            // Given\r\n            var uri = new Uri(\"http://host/base/\");\r\n\r\n            // When\r\n            string result = uri.MakeAppLocalPath(new Uri(\"http://host/base\"));\r\n\r\n            // Then\r\n            result.ShouldEqual(\"/\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_path_with_same_casing_as_full_uri()\r\n        {\r\n            // Given\r\n            var uri = new Uri(\"http://host/base/\");\r\n\r\n            // When\r\n            string result = uri.MakeAppLocalPath(new Uri(\"http://host/base/ReL\"));\r\n\r\n            // Then\r\n            result.ShouldEqual(\"/ReL\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_support_extended_site_root()\r\n        {\r\n            // Given\r\n            var uri = new Uri(\"http://host/\");\r\n\r\n            // When\r\n            string result = uri.MakeAppLocalPath(new Uri(\"http://host/rel/file\"));\r\n\r\n            // Then\r\n            result.ShouldEqual(\"/rel/file\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_support_site_root_without_trailing_slash()\r\n        {\r\n            // Given\r\n            var uri = new Uri(\"http://host/\");\r\n\r\n            // When\r\n            string result = uri.MakeAppLocalPath(new Uri(\"http://host\"));\r\n\r\n            // Then\r\n            result.ShouldEqual(\"/\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_path_with_case_insensitive_base_uri_comparison()\r\n        {\r\n            // Given\r\n            var uri = new Uri(\"http://host/base/\");\r\n\r\n            // When\r\n            string result = uri.MakeAppLocalPath(new Uri(\"http://host/Base/rel\"));\r\n\r\n            // Then\r\n            result.ShouldEqual(\"/rel\");\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Hosting.Self.Tests/Nancy.Hosting.Self.Tests.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <TargetFrameworks>netcoreapp2.0;net452</TargetFrameworks>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <Compile Remove=\"..\\Nancy.Tests\\Fakes\\FakeDefaultNancyBootstrapper.cs\" />\n  </ItemGroup>\n\n  <PropertyGroup Condition=\" '$(Configuration)' == 'MonoRelease' \">\n    <DefineConstants>$(DefineConstants);MONO</DefineConstants>\n  </PropertyGroup>\n</Project>\n"
  },
  {
    "path": "test/Nancy.Hosting.Self.Tests/NancySelfHostFixture.cs",
    "content": "﻿#if !MONO\r\nnamespace Nancy.Hosting.Self.Tests\r\n{\r\n    using System;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Net;\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Tests;\r\n    using Nancy.Tests.xUnitExtensions;\r\n\r\n    using Xunit;\r\n\r\n    /// <remarks>\r\n    /// These tests attempt to listen on port 1234, and so require either administrative\r\n    /// privileges or that a command similar to the following has been run with\r\n    /// administrative privileges:\r\n    /// <code>netsh http add urlacl url=http://+:1234/base user=DOMAIN\\user</code>\r\n    /// See http://msdn.microsoft.com/en-us/library/ms733768.aspx for more information.\r\n    /// </remarks>\r\n    public class NancySelfHostFixture\r\n    {\r\n        private static readonly Uri BaseUri = new Uri(\"http://localhost:1234/base/\");\r\n\r\n        [SkippableFact]\r\n        public void Should_be_get_an_exception_indicating_a_conflict_when_trying_to_listen_on_a_used_prefix()\r\n        {\r\n            Exception ex;\r\n\r\n            // Given\r\n            using (CreateAndOpenSelfHost())\r\n            {\r\n                // When\r\n                ex = Record.Exception(() =>\r\n                    {\r\n                        using (var host = new NancyHost(BaseUri))\r\n                        {\r\n                            host.Start();\r\n                        }\r\n                    });\r\n            }\r\n\r\n            // Then\r\n            ex.Message.ShouldContain(\"conflict\");\r\n        }\r\n\r\n        [SkippableFact]\r\n        public void Should_be_able_to_get_any_header_from_selfhost()\r\n        {\r\n            // Given\r\n            using (CreateAndOpenSelfHost())\r\n            {\r\n                // When\r\n                var request = WebRequest.Create(new Uri(BaseUri, \"rel/header/?query=value\"));\r\n                request.Method = \"GET\";\r\n\r\n                // Then\r\n                request.GetResponse().Headers[\"X-Some-Header\"].ShouldEqual(\"Some value\");\r\n            }\r\n        }\r\n\r\n        [SkippableFact]\r\n        public void Should_set_query_string_and_uri_correctly()\r\n        {\r\n            // Given\r\n            Request nancyRequest = null;\r\n            var fakeEngine = A.Fake<INancyEngine>();\r\n            A.CallTo(() => fakeEngine.HandleRequest(A<Request>.Ignored, A<Func<NancyContext, NancyContext>>.Ignored,A<CancellationToken>.Ignored))\r\n                .Invokes(f => nancyRequest = (Request)f.Arguments[0])\r\n                .ReturnsLazily(c => Task.FromResult(new NancyContext { Request = (Request)c.Arguments[0], Response = new Response() }));\r\n\r\n            var fakeBootstrapper = A.Fake<INancyBootstrapper>();\r\n            A.CallTo(() => fakeBootstrapper.GetEngine()).Returns(fakeEngine);\r\n\r\n            // When\r\n            using (CreateAndOpenSelfHost(fakeBootstrapper))\r\n            {\r\n                var request = WebRequest.Create(new Uri(BaseUri, \"test/stuff?query=value&query2=value2\"));\r\n                request.Method = \"GET\";\r\n\r\n                try\r\n                {\r\n                    request.GetResponse();\r\n                }\r\n                catch (WebException)\r\n                {\r\n                    // Will throw because it returns 404 - don't care.\r\n                }\r\n            }\r\n\r\n            // Then\r\n            nancyRequest.Path.ShouldEqual(\"/test/stuff\");\r\n            Assert.True(nancyRequest.Query.query.HasValue);\r\n            Assert.True(nancyRequest.Query.query2.HasValue);\r\n        }\r\n\r\n        [SkippableFact]\r\n        public void Should_be_able_to_get_from_selfhost()\r\n        {\r\n            using (CreateAndOpenSelfHost())\r\n            {\r\n                var reader =\r\n                    new StreamReader(WebRequest.Create(new Uri(BaseUri, \"rel\")).GetResponse().GetResponseStream());\r\n\r\n                var response = reader.ReadToEnd();\r\n\r\n                response.ShouldEqual(\"This is the site route\");\r\n            }\r\n        }\r\n\r\n        [SkippableFact]\r\n        public void Should_be_able_to_get_from_chunked_selfhost()\r\n        {\r\n            using (CreateAndOpenSelfHost())\r\n            {\r\n                var response = WebRequest.Create(new Uri(BaseUri, \"rel\")).GetResponse();\r\n\r\n                Assert.Equal(\"chunked\", response.Headers[\"Transfer-Encoding\"]);\r\n                Assert.Null(response.Headers[\"Content-Length\"]);\r\n\r\n                using (var reader = new StreamReader(response.GetResponseStream()))\r\n                {\r\n                    var contents = reader.ReadToEnd();\r\n                    contents.ShouldEqual(\"This is the site route\");\r\n                }\r\n            }\r\n        }\r\n\r\n        [SkippableFact]\r\n        public void Should_be_able_to_get_from_contentlength_selfhost()\r\n        {\r\n            HostConfiguration configuration = new HostConfiguration()\r\n            {\r\n                AllowChunkedEncoding = false\r\n            };\r\n            using (CreateAndOpenSelfHost(null, configuration))\r\n            {\r\n                var response = WebRequest.Create(new Uri(BaseUri, \"rel\")).GetResponse();\r\n\r\n                Assert.Null(response.Headers[\"Transfer-Encoding\"]);\r\n                Assert.Equal(22, Convert.ToInt32(response.Headers[\"Content-Length\"]));\r\n\r\n                using (var reader = new StreamReader(response.GetResponseStream()))\r\n                {\r\n                    var contents = reader.ReadToEnd();\r\n                    contents.ShouldEqual(\"This is the site route\");\r\n                }\r\n            }\r\n        }\r\n\r\n        [SkippableFact]\r\n        public void Should_be_able_to_post_body_to_selfhost()\r\n        {\r\n            using (CreateAndOpenSelfHost())\r\n            {\r\n                const string testBody = \"This is the body of the request\";\r\n\r\n                var request =\r\n                    WebRequest.Create(new Uri(BaseUri, \"rel\"));\r\n                request.Method = \"POST\";\r\n\r\n                var writer =\r\n                    new StreamWriter(request.GetRequestStream()) { AutoFlush = true };\r\n                writer.Write(testBody);\r\n\r\n                var responseBody =\r\n                    new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd();\r\n\r\n                responseBody.ShouldEqual(testBody);\r\n            }\r\n        }\r\n\r\n        [SkippableFact]\r\n        public void Should_be_able_to_get_from_selfhost_with_slashless_uri()\r\n        {\r\n            using (CreateAndOpenSelfHost())\r\n            {\r\n                var reader =\r\n                    new StreamReader(WebRequest.Create(BaseUri.ToString().TrimEnd('/')).GetResponse().GetResponseStream());\r\n\r\n                var response = reader.ReadToEnd();\r\n\r\n                response.ShouldEqual(\"This is the site home\");\r\n            }\r\n        }\r\n\r\n        private static NancyHostWrapper CreateAndOpenSelfHost(INancyBootstrapper nancyBootstrapper = null, HostConfiguration configuration = null)\r\n        {\r\n            if (nancyBootstrapper == null)\r\n            {\r\n                nancyBootstrapper = new DefaultNancyBootstrapper();\r\n            }\r\n\r\n            var host = new NancyHost(\r\n                nancyBootstrapper,\r\n                configuration,\r\n                BaseUri);\r\n\r\n            try\r\n            {\r\n                host.Start();\r\n            }\r\n            catch\r\n            {\r\n                throw new SkipException(\"Skipped due to no Administrator access - please see test fixture for more information.\");\r\n            }\r\n\r\n            return new NancyHostWrapper(host);\r\n        }\r\n\r\n\r\n        [SkippableFact]\r\n        public void Should_be_able_to_recover_from_rendering_exception()\r\n        {\r\n            using (CreateAndOpenSelfHost())\r\n            {\r\n\r\n                var reader =\r\n                    new StreamReader(WebRequest.Create(new Uri(BaseUri, \"exception\")).GetResponse().GetResponseStream());\r\n\r\n                var response = reader.ReadToEnd();\r\n\r\n                response.ShouldEqual(\"Content\");\r\n            }\r\n        }\r\n\r\n        [SkippableFact]\r\n        public void Should_be_serializable()\r\n        {\r\n            var type = typeof(NancyHost);\r\n            Assert.True(type.Attributes.ToString().Contains(\"Serializable\"));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_include_default_port_in_uri_prefixes()\r\n        {\r\n            // Given\r\n            var host = new NancyHost(new Uri(\"http://localhost/\"));\r\n\r\n            // When\r\n            var prefix = host.GetPrefixes().Single();\r\n\r\n            // Then\r\n            prefix.ShouldEqual(\"http://+:80/\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_throw_when_disposed_without_starting()\r\n        {\r\n            // Given\r\n            var bootstrapperMock = A.Fake<INancyBootstrapper>();\r\n            var host = new NancyHost(new Uri(\"http://localhost/\"), bootstrapperMock);\r\n\r\n            // When\r\n            host.Dispose();\r\n\r\n            // Then\r\n            A.CallTo(() => bootstrapperMock.Dispose()).MustHaveHappened();\r\n        }\r\n\r\n        private class NancyHostWrapper : IDisposable\r\n        {\r\n            private readonly NancyHost host;\r\n\r\n            public NancyHostWrapper(NancyHost host)\r\n            {\r\n                this.host = host;\r\n            }\r\n\r\n            public void Dispose()\r\n            {\r\n                host.Stop();\r\n            }\r\n        }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "test/Nancy.Hosting.Self.Tests/TestModule.cs",
    "content": "﻿namespace Nancy.Hosting.Self.Tests\r\n{\r\n    using System;\r\n    using System.IO;\r\n\r\n    public class TestModule : NancyModule\r\n    {\r\n        public TestModule()\r\n        {\r\n        \tGet(\"/\", args => \"This is the site home\");\r\n\r\n            Get(\"/rel\", args => \"This is the site route\");\r\n\r\n            Get(\"/rel/header\", args =>\r\n            {\r\n                var response = new Response();\r\n                response.Headers[\"X-Some-Header\"] = \"Some value\";\r\n\r\n                return response;\r\n            });\r\n\r\n            Post(\"/rel\", args => new StreamReader(this.Request.Body).ReadToEnd());\r\n\r\n        \tGet(\"/exception\", args =>\r\n        \t{\r\n        \t    return new Response\r\n        \t    {\r\n        \t        Contents = s =>\r\n        \t        {\r\n        \t            var writer = new StreamWriter(s);\r\n        \t            writer.Write(\"Content\");\r\n        \t            writer.Flush();\r\n        \t            throw new Exception(\"An error occured during content rendering\");\r\n        \t        }\r\n        \t    };\r\n        \t});\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Metadata.Modules.Tests/DefaultMetadataModuleConventionsFixture.cs",
    "content": "﻿namespace Nancy.Metadata.Modules.Tests\r\n{\r\n    using System.Linq;\r\n    using Nancy.Tests;\r\n    using Xunit;\r\n\r\n    public class DefaultMetadataModuleConventionsFixture\r\n    {\r\n        private readonly DefaultMetadataModuleConventions conventions;\r\n\r\n        public DefaultMetadataModuleConventionsFixture()\r\n        {\r\n            this.conventions = new DefaultMetadataModuleConventions();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_define_convention_that_returns_metadata_module_type_alongside_module()\r\n        {\r\n            // Given\r\n            var convention = this.conventions.ElementAt(0);\r\n            var module = new FakeNancyModule();\r\n            var metadataModules = new[] { new FakeNancyMetadataModule() };\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                module,\r\n                metadataModules);\r\n\r\n            // Then\r\n            result.ShouldEqual(metadataModules[0]);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_define_convention_that_returns_metadata_module_type_in_metadata_subfolder()\r\n        {\r\n            // Given\r\n            var convention = this.conventions.ElementAt(1);\r\n            var module = new FakeNancyModule();\r\n            var metadataModules = new[] { new Metadata.FakeNancyMetadataModule() };\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                module,\r\n                metadataModules);\r\n\r\n            // Then\r\n            result.ShouldEqual(metadataModules[0]);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_define_convention_that_returns_metadata_module_type_in_peer_metadata_folder()\r\n        {\r\n            // Given\r\n            var convention = this.conventions.ElementAt(2);\r\n            var module = new Modules.FakeNancyModule();\r\n            var metadataModules = new[] { new Metadata.FakeNancyMetadataModule() };\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                module,\r\n                metadataModules);\r\n\r\n            // Then\r\n            result.ShouldEqual(metadataModules[0]);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Metadata.Modules.Tests/FakeNancyMetadataModule.cs",
    "content": "﻿namespace Nancy.Metadata.Modules.Tests\r\n{\r\n    public class FakeNancyMetadataModule : MetadataModule<string>\r\n    {\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Metadata.Modules.Tests/FakeNancyModule.cs",
    "content": "﻿namespace Nancy.Metadata.Modules.Tests\r\n{\r\n    using System;\r\n\r\n    public class FakeNancyModule : NancyModule\r\n    {\r\n        public FakeNancyModule()\r\n        {\r\n        }\r\n\r\n        public FakeNancyModule(Action<FakeNancyModuleConfigurator> closure)\r\n        {\r\n            var configurator =\r\n                new FakeNancyModuleConfigurator(this);\r\n\r\n            closure.Invoke(configurator);\r\n        }\r\n\r\n        public class FakeNancyModuleConfigurator\r\n        {\r\n            private readonly NancyModule module;\r\n\r\n            public FakeNancyModuleConfigurator(NancyModule module)\r\n            {\r\n                this.module = module;\r\n            }\r\n\r\n            public FakeNancyModuleConfigurator AddDeleteRoute(string path)\r\n            {\r\n                this.module.Delete(path, args => {\r\n                    return HttpStatusCode.OK;\r\n                });\r\n\r\n                return this;\r\n            }\r\n\r\n            public FakeNancyModuleConfigurator AddGetRoute(string path)\r\n            {\r\n                return this.AddGetRoute(path, x => HttpStatusCode.OK);\r\n            }\r\n\r\n            public FakeNancyModuleConfigurator AddGetRoute(string path, Func<object, Response> action)\r\n            {\r\n                this.module.Get(path, args =>\r\n                {\r\n                    return action.Invoke(args);\r\n                });\r\n\r\n                return this;\r\n            }\r\n\r\n            public FakeNancyModuleConfigurator AddPostRoute(string path)\r\n            {\r\n                this.module.Post(path, args => {\r\n                    return HttpStatusCode.OK;\r\n                });\r\n\r\n                return this;\r\n            }\r\n\r\n            public FakeNancyModuleConfigurator AddPutRoute(string path)\r\n            {\r\n                this.module.Put(path, args => {\r\n                    return HttpStatusCode.OK;\r\n                });\r\n\r\n                return this;\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Metadata.Modules.Tests/Metadata/FakeNancyMetadataModule.cs",
    "content": "﻿namespace Nancy.Metadata.Modules.Tests.Metadata\r\n{\r\n    public class FakeNancyMetadataModule : MetadataModule<string>\r\n    {\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Metadata.Modules.Tests/MetadataModuleFixture.cs",
    "content": "﻿namespace Nancy.Metadata.Modules.Tests\r\n{\r\n    using Nancy.Routing;\r\n    using Nancy.Tests;\r\n\r\n    using Xunit;\r\n\r\n    public class MetadataModuleFixture\r\n    {\r\n        private readonly MetadataModule<string> metadataModule;\r\n\r\n        private readonly RouteDescription route;\r\n\r\n        public MetadataModuleFixture()\r\n        {\r\n            this.route = new RouteDescription(\"NamedDescription\", \"GET\", \"/things\", ctx => true, typeof(object));\r\n            this.metadataModule = new FakeNancyMetadataModule();\r\n        }\r\n\r\n        [Fact]\r\n        public void Adds_metadata_when_describe_invoked()\r\n        {\r\n            // Given\r\n            const string Metadata = \"metadata\";\r\n\r\n            // When\r\n            this.metadataModule.Describe[this.route.Name] = desc => { return Metadata; };\r\n\r\n            // Then\r\n            this.metadataModule.GetMetadata(this.route).ShouldEqual(Metadata);\r\n        }\r\n\r\n        [Fact]\r\n        public void Returns_null_if_no_metadata_found()\r\n        {\r\n            // Then\r\n            this.metadataModule.GetMetadata(this.route).ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Returns_correct_metadata_type()\r\n        {\r\n            this.metadataModule.MetadataType.ShouldEqual(typeof(string));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Metadata.Modules.Tests/MetadataModuleRouteMetadataProviderFixture.cs",
    "content": "﻿namespace Nancy.Metadata.Modules.Tests\r\n{\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Routing;\r\n    using Nancy.Tests;\r\n\r\n    using Xunit;\r\n\r\n    public class MetadataModuleRouteMetadataProviderFixture\r\n    {\r\n        private readonly MetadataModuleRouteMetadataProvider provider;\r\n        private readonly INancyModule module;\r\n        private readonly FakeNancyMetadataModule metadataModule;\r\n        private readonly RouteDescription route;\r\n        private readonly IMetadataModuleResolver resolver;\r\n        private const string Metadata = \"metadata\";\r\n\r\n        public MetadataModuleRouteMetadataProviderFixture()\r\n        {\r\n            this.resolver = A.Fake<IMetadataModuleResolver>();\r\n            this.module = A.Fake<INancyModule>();\r\n            this.route = new RouteDescription(\"NamedDescription\", \"GET\", \"/things\", ctx => true, typeof(object));\r\n            this.metadataModule = new FakeNancyMetadataModule();\r\n            this.metadataModule.Describe[this.route.Name] = desc => { return Metadata; };\r\n\r\n            this.provider = new MetadataModuleRouteMetadataProvider(this.resolver);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_for_metadata_type_where_no_metadata_module_registered()\r\n        {\r\n            // Given\r\n            A.CallTo(() => this.resolver.GetMetadataModule(null)).WithAnyArguments().Returns(null);\r\n\r\n            // Then\r\n            this.provider.GetMetadataType(this.module, this.route).ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_for_metadata_where_no_metadata_module_registered()\r\n        {\r\n            // Given\r\n            A.CallTo(() => this.resolver.GetMetadataModule(null)).WithAnyArguments().Returns(null);\r\n\r\n            // Then\r\n            this.provider.GetMetadata(this.module, this.route).ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_metadata_type_from_metadata_module()\r\n        {\r\n            // Given\r\n            A.CallTo(() => this.resolver.GetMetadataModule(null)).WithAnyArguments().Returns(this.metadataModule);\r\n\r\n            // Then\r\n            this.provider.GetMetadataType(this.module, this.route).ShouldEqual(typeof(string));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_metadata_from_metadata_module()\r\n        {\r\n            // Given\r\n            A.CallTo(() => this.resolver.GetMetadataModule(null)).WithAnyArguments().Returns(this.metadataModule);\r\n\r\n            // Then\r\n            this.provider.GetMetadata(this.module, this.route).ShouldEqual(Metadata);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Metadata.Modules.Tests/Modules/FakeNancyModule.cs",
    "content": "﻿namespace Nancy.Metadata.Modules.Tests.Modules\r\n{\r\n    public class FakeNancyModule : NancyModule\r\n    {\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Metadata.Modules.Tests/Nancy.Metadata.Modules.Tests.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <TargetFrameworks>netcoreapp2.0;net452</TargetFrameworks>\n  </PropertyGroup>\n</Project>\n"
  },
  {
    "path": "test/Nancy.Owin.Tests/AppBuilderExtensionsFixture.cs",
    "content": "﻿namespace Nancy.Owin.Tests\r\n{\r\n    using System;\r\n    using System.Security.Cryptography.X509Certificates;\r\n    using System.Text;\r\n    using global::Owin;\r\n    using Nancy.Testing;\r\n    using Xunit;\r\n    using HttpStatusCode = Nancy.HttpStatusCode;\r\n    using Microsoft.Owin.Builder;\r\n    using System.Net.Http;\r\n    using System.Threading.Tasks;\r\n    using AppFunc = System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>;\r\n    public class AppBuilderExtensionsFixture\r\n    {\r\n#if !MONO\r\n        [Fact]\r\n        public async Task When_host_Nancy_via_IAppBuilder_then_should_handle_requests()\r\n        {\r\n            // Given\r\n            var app = new AppBuilder();\r\n            var bootstrapper = new ConfigurableBootstrapper(config => config.Module<TestModule>());\r\n            app.UseNancy(opts => opts.Bootstrapper = bootstrapper);\r\n            var appFunc = app.Build();\r\n\r\n            var handler = new OwinHttpMessageHandler(appFunc);\r\n\r\n            using (var httpClient = new HttpClient(handler)\r\n            {\r\n                BaseAddress = new Uri(\"http://localhost\")\r\n            })\r\n            {\r\n                // When\r\n                var response = await httpClient.GetAsync(new Uri(\"http://localhost/\"));\r\n\r\n                // Then\r\n                Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode);\r\n            }\r\n        }\r\n\r\n        [Fact]\r\n        public async Task When_host_Nancy_via_IAppBuilder_should_read_X509Certificate2()\r\n        {\r\n            // Given\r\n            var app = new AppBuilder();\r\n            var bootstrapper = new ConfigurableBootstrapper(config => config.Module<TestModule>());\r\n\r\n            var cert = @\"-----BEGIN CERTIFICATE-----\r\n                            MIICNTCCAZ4CCQC21XwOAYG32zANBgkqhkiG9w0BAQUFADBfMQswCQYDVQQGEwJH\r\n                            QjETMBEGA1UECBMKU29tZS1TdGF0ZTEOMAwGA1UEChMFTmFuY3kxDjAMBgNVBAsT\r\n                            BU5hbmN5MRswGQYDVQQDExJodHRwOi8vbmFuY3lmeC5vcmcwHhcNMTYwMjIyMTE1\r\n                            NzQ3WhcNMTcwMjIxMTE1NzQ3WjBfMQswCQYDVQQGEwJHQjETMBEGA1UECBMKU29t\r\n                            ZS1TdGF0ZTEOMAwGA1UEChMFTmFuY3kxDjAMBgNVBAsTBU5hbmN5MRswGQYDVQQD\r\n                            ExJodHRwOi8vbmFuY3lmeC5vcmcwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGB\r\n                            AMT4vOtIH9Fzad+8KCGjMPkkVpCtn+L5H97bnI3x+y3x5lY0WRsK8FyxVshY/7fv\r\n                            TDeeVKUWanmbMkQjgFRYffA3ep3/AIguswYdANiNVHrx0L7DXNDcgsjRwaa6JVgQ\r\n                            9iavlli0a80AF67FN1wfidlHCX53u3/fAjiSTwf7D+NBAgMBAAEwDQYJKoZIhvcN\r\n                            AQEFBQADgYEAh12A4NntHHdVMGaw+2umXkWqCOyAPuNhyBGUHK5vGON+VG0HPFaf\r\n                            8P8eMtdF4deBHkrfoWxRuGGn2tJzNpZLiEf23BAivEf36IqwfkVP7/zDwI+bjVXC\r\n                            k64Un2uN8ALR/wLwfJzHfOLPtsca7ySWhlv8oZo2nk0vR34asQiGJDQ=\r\n                            -----END CERTIFICATE-----\r\n                            \";\r\n\r\n            var embeddedCert = Encoding.UTF8.GetBytes(cert);\r\n\r\n            app.Use(new Func<AppFunc, AppFunc>(next => (async env =>\r\n            {\r\n                env.Add(\"ssl.ClientCertificate\", new X509Certificate(embeddedCert));\r\n                await next.Invoke(env);\r\n            })));\r\n\r\n            app.UseNancy(opts =>\r\n            {\r\n                opts.Bootstrapper = bootstrapper;\r\n                opts.EnableClientCertificates = true;\r\n            });\r\n\r\n            var appFunc = app.Build();\r\n\r\n            var handler = new OwinHttpMessageHandler(appFunc);\r\n\r\n            using (var httpClient = new HttpClient(handler)\r\n            {\r\n                BaseAddress = new Uri(\"http://localhost\")\r\n            })\r\n            {\r\n                // When\r\n                var response = await httpClient.GetAsync(new Uri(\"http://localhost/ssl\"));\r\n\r\n                // Then\r\n                Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode);\r\n            }\r\n        }\r\n#endif\r\n        public class TestModule : NancyModule\r\n        {\r\n            public TestModule()\r\n            {\r\n                Get(\"/\", args => HttpStatusCode.OK);\r\n\r\n                Get(\"/ssl\", args => this.Request.ClientCertificate != null ? 200 : 500);\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Owin.Tests/Nancy.Owin.Tests.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <TargetFramework>net452</TargetFramework>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <PackageReference Include=\"Microsoft.Owin\" Version=\"3.0.1\" />\n    <PackageReference Include=\"OwinHttpMessageHandler\" Version=\"1.3.5\" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "test/Nancy.Testing.Tests/AndConnectorTests.cs",
    "content": "namespace Nancy.Testing.Tests\r\n{\r\n    using System.Text;\r\n\r\n    using Xunit;\r\n\r\n    public class AndConnectorTests\r\n    {\r\n        [Fact]\r\n        public void Should_allow_chaining_of_asserts_and_still_pass()\r\n        {\r\n            // Given\r\n            const string input = @\"<html><head></head><body><div id='testId' class='myClass'>Test</div></body></html>\";\r\n\r\n            var buffer =\r\n                Encoding.UTF8.GetBytes(input);\r\n\r\n            // When\r\n            var document = new DocumentWrapper(buffer);\r\n\r\n            // Then\r\n            document[\"#testId\"].ShouldExist().And.ShouldBeOfClass(\"myClass\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_chaining_of_asserts_and_fail_where_appropriate()\r\n        {\r\n            // Given\r\n            // When\r\n            var result = Record.Exception(\r\n                () =>\r\n                    {\r\n                        const string input =\r\n                            @\"<html><head></head><body><div id='testId' class='myOtherClass'>Test</div></body></html>\";\r\n\r\n                    var buffer =\r\n                        Encoding.UTF8.GetBytes(input);\r\n\r\n                    var document = \r\n                        new DocumentWrapper(buffer);\r\n\r\n                        document[\"#testId\"].ShouldExist().And.ShouldBeOfClass(\"myClass\");\r\n                    });\r\n\r\n            Assert.IsType<AssertException>(result);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Testing.Tests/AssertEqualityComparerFixture.cs",
    "content": "namespace Nancy.Testing.Tests\r\n{\r\n    using System;\r\n\r\n    using Nancy.Tests;\r\n\r\n    using Xunit;\r\n    using Xunit.Extensions;\r\n\r\n    public class AssertEqualityComparerFixture\r\n    {\r\n        [Fact]\r\n        public void Should_return_false_if_actual_is_null_when_comparing_equality()\r\n        {\r\n            // Given\r\n            var comparer = new AssertEqualityComparer<object>();\r\n\r\n            // When\r\n            var results = comparer.Equals(new object(), null);\r\n\r\n            // Then\r\n            results.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_if_expected_is_null_when_comparing_equality()\r\n        {\r\n            // Given\r\n            var comparer = new AssertEqualityComparer<object>();\r\n\r\n            // When\r\n            var results = comparer.Equals(null, new object());\r\n\r\n            // Then\r\n            results.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_equals_with_expected_value_when_actual_is_equatable()\r\n        {\r\n            // Given\r\n            var comparer = new AssertEqualityComparer<EquatableModel>();\r\n            var actual = new EquatableModel();\r\n            var expected = new EquatableModel();\r\n\r\n            // When\r\n            comparer.Equals(expected, actual);\r\n\r\n            // Then\r\n            actual.ExpectedValueThatWasPassedIn.ShouldBeSameAs(expected);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(false)]\r\n        [InlineData(true)]\r\n        public void Should_return_result_from_comparing_equatables(bool expectedReturnValue)\r\n        {\r\n            // Given\r\n            var comparer = new AssertEqualityComparer<EquatableModel>();\r\n            var actual = new EquatableModel(expectedReturnValue);\r\n            var expected = new EquatableModel();\r\n\r\n            // When\r\n            var result = comparer.Equals(expected, actual);\r\n\r\n            // Then\r\n            result.ShouldEqual(expectedReturnValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_compareto_with_expected_value_when_actual_is_generic_comparable()\r\n        {\r\n            // Given\r\n            var comparer = new AssertEqualityComparer<GenericCompareableModel>();\r\n            var actual = new GenericCompareableModel();\r\n            var expected = new GenericCompareableModel();\r\n\r\n            // When\r\n            comparer.Equals(expected, actual);\r\n\r\n            // Then\r\n            actual.ExpectedValueThatWasPassedIn.ShouldBeSameAs(expected);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(-1, false)]\r\n        [InlineData(0, true)]\r\n        [InlineData(1, false)]\r\n        public void Should_return_result_from_comparing_generic_comparables(int compareResult, bool expectedResult)\r\n        {\r\n            // Given\r\n            var comparer = new AssertEqualityComparer<GenericCompareableModel>();\r\n            var actual = new GenericCompareableModel(compareResult);\r\n            var expected = new GenericCompareableModel();\r\n\r\n            // When\r\n            var result = comparer.Equals(expected, actual);\r\n\r\n            // Then\r\n            result.ShouldEqual(expectedResult);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_compareto_with_expected_value_when_actual_is_comparable()\r\n        {\r\n            // Given\r\n            var comparer = new AssertEqualityComparer<CompareableModel>();\r\n            var actual = new CompareableModel();\r\n            var expected = new CompareableModel();\r\n\r\n            // When\r\n            comparer.Equals(expected, actual);\r\n\r\n            // Then\r\n            actual.ExpectedValueThatWasPassedIn.ShouldBeSameAs(expected);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(-1, false)]\r\n        [InlineData(0, true)]\r\n        [InlineData(1, false)]\r\n        public void Should_return_result_from_comparing_comparables(int compareResult, bool expectedResult)\r\n        {\r\n            // Given\r\n            var comparer = new AssertEqualityComparer<CompareableModel>();\r\n            var actual = new CompareableModel(compareResult);\r\n            var expected = new CompareableModel();\r\n\r\n            // When\r\n            var result = comparer.Equals(expected, actual);\r\n\r\n            // Then\r\n            result.ShouldEqual(expectedResult);\r\n        }\r\n\r\n        public class EquatableModel : IEquatable<EquatableModel>\r\n        {\r\n            private readonly bool returnValue;\r\n\r\n            public EquatableModel()\r\n                : this(true)\r\n            {\r\n            }\r\n\r\n            public EquatableModel(bool returnValue)\r\n            {\r\n                this.returnValue = returnValue;\r\n            }\r\n\r\n            public EquatableModel ExpectedValueThatWasPassedIn { get; private set; }\r\n\r\n            public bool Equals(EquatableModel expected)\r\n            {\r\n                this.ExpectedValueThatWasPassedIn = expected;\r\n                return this.returnValue;\r\n            }\r\n        }\r\n\r\n        public class GenericCompareableModel : IComparable<GenericCompareableModel>\r\n        {\r\n            private readonly int returnValue;\r\n\r\n            public GenericCompareableModel()\r\n                : this(0)\r\n            {\r\n            }\r\n\r\n            public GenericCompareableModel(int returnValue)\r\n            {\r\n                this.returnValue = returnValue;\r\n            }\r\n\r\n            public GenericCompareableModel ExpectedValueThatWasPassedIn { get; private set; }\r\n\r\n            public int CompareTo(GenericCompareableModel comparable)\r\n            {\r\n                this.ExpectedValueThatWasPassedIn = comparable;\r\n                return this.returnValue;\r\n            }\r\n        }\r\n\r\n        public class CompareableModel : IComparable\r\n        {\r\n            private readonly int returnValue;\r\n\r\n            public CompareableModel()\r\n                : this(0)\r\n            {\r\n            }\r\n\r\n            public CompareableModel(int returnValue)\r\n            {\r\n                this.returnValue = returnValue;\r\n            }\r\n\r\n            public object ExpectedValueThatWasPassedIn { get; private set; }\r\n\r\n            public int CompareTo(object comparable)\r\n            {\r\n                this.ExpectedValueThatWasPassedIn = comparable;\r\n                return this.returnValue;\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Testing.Tests/AssertExtensionsTests.cs",
    "content": "namespace Nancy.Testing.Tests\r\n{\r\n    using System;\r\n    using System.Linq;\r\n    using AngleSharp.Parser.Html;\r\n    using Xunit;\r\n\r\n    public class AssertExtensionsTests\r\n    {\r\n        private readonly QueryWrapper query;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"T:System.Object\"/> class.\r\n        /// </summary>\r\n        public AssertExtensionsTests()\r\n        {\r\n            var parser = new HtmlParser();\r\n\r\n            var document =\r\n                parser.Parse(@\"<html><head></head><body><div id='testId' class='myClass' attribute1 attribute2='value2'>Test</div><div class='anotherClass'>Tes</div><span class='class'>some contents</span><span class='class'>This has contents</span></body></html>\");\r\n\r\n            this.query =\r\n                new QueryWrapper(new[] { document.DocumentElement });\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_assertexception_when_id_does_not_exist()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => this.query[\"#notThere\"].ShouldExist());\r\n\r\n            // Then\r\n            Assert.IsAssignableFrom<AssertException>(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_throw_exception_when_id_does_exist()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => this.query[\"#testId\"].ShouldExist());\r\n\r\n            // Then\r\n            Assert.Null(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_detect_nonexistence()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => this.query[\"#jamesIsAwesome\"].ShouldNotExist());\r\n\r\n            // Then\r\n            Assert.Null(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_throw_exception_when_id_that_should_only_exists_once_only_exists_once()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => this.query[\"#testId\"].ShouldExistOnce());\r\n\r\n            // Then\r\n            Assert.Null(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void ShouldExistOnce_ExistsOnce_ReturnsSingleItemAndConnector()\r\n        {\r\n            // Given, When\r\n            var result = this.query[\"#testId\"].ShouldExistOnce();\r\n\r\n            // Then\r\n            Assert.IsType<AndConnector<NodeWrapper>>(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void ShouldExistsExactly2_Exists2_ReturnsResultAndConnector()\r\n        {\r\n            // Given, when\r\n            var result = this.query[\".class\"].ShouldExistExactly(2);\r\n\r\n            // Then\r\n            Assert.IsType<AndConnector<QueryWrapper>>(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void ShouldExistsExactly3_Exists2_ReturnsResultAndConnector()\r\n        {\r\n            // When\r\n            var result = Record.Exception(() => this.query[\".class\"].ShouldExistExactly(3));\r\n\r\n            // Then\r\n            Assert.IsAssignableFrom<AssertException>(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void ShouldExistOnce_DoesNotExist_ShouldThrowAssert()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => this.query[\"#notHere\"].ShouldExistOnce());\r\n\r\n            // Then\r\n            Assert.IsAssignableFrom<AssertException>(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void ShouldExistOnce_ExistsMoreThanOnce_ShouldThrowAssert()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => this.query[\"div\"].ShouldExistOnce());\r\n\r\n            // Then\r\n            Assert.IsAssignableFrom<AssertException>(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void ShouldBeClass_ZeroElements_ShouldThrowAssert()\r\n        {\r\n            // Given\r\n            var queryWrapper = this.query[\"#missing\"];\r\n\r\n            // When\r\n            var result = Record.Exception(() => queryWrapper.ShouldBeOfClass(\"nope\"));\r\n\r\n            // Then\r\n            Assert.IsAssignableFrom<AssertException>(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void ShouldBeClass_SingleElementNotThatClass_ShouldThrowAssert()\r\n        {\r\n            // Given\r\n            var htmlNode = this.query[\"#testId\"].First();\r\n\r\n            // When\r\n            var result = Record.Exception(() => htmlNode.ShouldBeOfClass(\"nope\"));\r\n\r\n            // Then\r\n            Assert.IsAssignableFrom<AssertException>(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void ShouldBeClass_SingleElementWithThatClass_ShouldNotThrowAssert()\r\n        {\r\n            // Given\r\n            var htmlNode = this.query[\"#testId\"].First();\r\n\r\n            // When\r\n            var result = Record.Exception(() => htmlNode.ShouldBeOfClass(\"myClass\"));\r\n\r\n            // Then\r\n            Assert.Null(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void ShouldBeClass_MultipleElementsOneNotThatClass_ShouldThrowAssert()\r\n        {\r\n            // Given\r\n            var htmlNodes = this.query[\"div\"];\r\n\r\n            // When\r\n            var result = Record.Exception(() => htmlNodes.ShouldBeOfClass(\"myClass\"));\r\n\r\n            // Then\r\n            Assert.IsAssignableFrom<AssertException>(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void ShouldBeClass_MultipleElementsAllThatClass_ShouldNotThrowAssert()\r\n        {\r\n            // Given\r\n            var htmlNodes = this.query[\"span\"];\r\n\r\n            // When\r\n            var result = Record.Exception(() => htmlNodes.ShouldBeOfClass(\"class\"));\r\n\r\n            // Then\r\n            Assert.Null(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void AllShouldContain_ZeroElements_ShouldThrowAssert()\r\n        {\r\n            // Given\r\n            var queryWrapper = this.query[\"#missing\"];\r\n\r\n            // When\r\n            var result = Record.Exception(() => queryWrapper.AllShouldContain(\"Anything\"));\r\n\r\n            // Then\r\n            Assert.IsAssignableFrom<AssertException>(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void AnyShouldContain_ZeroElements_ShouldThrowAssert()\r\n        {\r\n            // Given\r\n            var queryWrapper = this.query[\"#missing\"];\r\n\r\n            // When\r\n            var result = Record.Exception(() => queryWrapper.AnyShouldContain(\"Anything\"));\r\n\r\n            // Then\r\n            Assert.IsAssignableFrom<AssertException>(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void ShouldContain_SingleElementThatContainsText_ShouldNotThrowAssert()\r\n        {\r\n            // Given\r\n            var htmlNode = this.query[\"#testId\"].First();\r\n\r\n            // When\r\n            var result = Record.Exception(() => htmlNode.ShouldContain(\"Test\"));\r\n\r\n            // Then\r\n            Assert.Null(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void ShouldContain_SingleElementWithTextInDifferentCase_ShouldHonorCompareType()\r\n        {\r\n            // Given\r\n            var htmlNode = this.query[\"#testId\"].First();\r\n\r\n            // When\r\n            var result = Record.Exception(() => htmlNode.ShouldContain(\"test\", StringComparison.OrdinalIgnoreCase));\r\n\r\n            // Then\r\n            Assert.Null(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void ShouldContain_SingleElementDoesntContainText_ShouldThrowAssert()\r\n        {\r\n            // Given\r\n            var htmlNode = this.query[\"#testId\"].First();\r\n\r\n            // When\r\n            var result = Record.Exception(() => htmlNode.ShouldContain(\"nope\"));\r\n\r\n            // Then\r\n            Assert.IsAssignableFrom<AssertException>(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void AllShouldContain_MultipleElementsAllContainingText_ShouldntThrowAssert()\r\n        {\r\n            // Given\r\n            var htmlNodes = this.query[\"span\"];\r\n\r\n            // When\r\n            var result = Record.Exception(() => htmlNodes.AllShouldContain(\"contents\"));\r\n\r\n            // Then\r\n            Assert.Null(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void AnyShouldContain_MultipleElementsAllContainingText_ShouldntThrowAssert()\r\n        {\r\n            // Given\r\n            var htmlNodes = this.query[\"span\"];\r\n\r\n            // When\r\n            var result = Record.Exception(() => htmlNodes.AnyShouldContain(\"contents\"));\r\n\r\n            // Then\r\n            Assert.Null(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void AllShouldContain_MultipleElementsOneNotContainingText_ShouldThrowAssert()\r\n        {\r\n            // Given\r\n            var htmlNodes = this.query[\"div\"];\r\n\r\n            // When\r\n            var result = Record.Exception(() => htmlNodes.AllShouldContain(\"Test\"));\r\n\r\n            // Then\r\n            Assert.IsAssignableFrom<AssertException>(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void AnyShouldContain_MultipleElementsOneNotContainingText_ShouldntThrowAssert()\r\n        {\r\n            // Given\r\n            var htmlNodes = this.query[\"div\"];\r\n\r\n            // When\r\n            var result = Record.Exception(() => htmlNodes.AnyShouldContain(\"Test\"));\r\n\r\n            // Then\r\n            Assert.Null(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void ShouldContainAttribute_ZeroElements_ShouldThrowAssert()\r\n        {\r\n            // Given\r\n            var queryWrapper = this.query[\"#missing\"];\r\n\r\n            // When\r\n            var result = Record.Exception(() => queryWrapper.ShouldContainAttribute(\"nope\"));\r\n\r\n            // Then\r\n            Assert.IsAssignableFrom<AssertException>(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void ShouldContainAttribute_ZeroElementsNameAndValue_ShouldThrowAssert()\r\n        {\r\n            // Given\r\n            var queryWrapper = this.query[\"#missing\"];\r\n\r\n            // When\r\n            var result = Record.Exception(() => queryWrapper.ShouldContainAttribute(\"nope\", \"nope\"));\r\n\r\n            // Then\r\n            Assert.IsAssignableFrom<AssertException>(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void ShouldContainAttribute_SingleElementNotContainingAttribute_ShouldThrowAssert()\r\n        {\r\n            // Given\r\n            var htmlNode = this.query[\"#testId\"].First();\r\n\r\n            // When\r\n            var result = Record.Exception(() => htmlNode.ShouldContainAttribute(\"nope\"));\r\n\r\n            // Then\r\n            Assert.IsAssignableFrom<AssertException>(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void ShouldContainAttribute_SingleElementNotContainingAttributeAndValue_ShouldThrowAssert()\r\n        {\r\n            // Given\r\n            var htmlNode = this.query[\"#testId\"].First();\r\n\r\n            // When\r\n            var result = Record.Exception(() => htmlNode.ShouldContainAttribute(\"nope\", \"nope\"));\r\n\r\n            // Then\r\n            Assert.IsAssignableFrom<AssertException>(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void ShouldContainAttribute_SingleElementContainingAttributeWithoutValueButShouldContainValue_ShouldThrowAssert()\r\n        {\r\n            // Given\r\n            var htmlNode = this.query[\"#testId\"].First();\r\n\r\n            // When\r\n            var result = Record.Exception(() => htmlNode.ShouldContainAttribute(\"attribute1\", \"nope\"));\r\n\r\n            // Then\r\n            Assert.IsAssignableFrom<AssertException>(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void ShouldContainAttribute_SingleElementContainingAttributeWithDifferentValue_ShouldThrowAssert()\r\n        {\r\n            // Given\r\n            var htmlNode = this.query[\"#testId\"].First();\r\n\r\n            // When\r\n            var result = Record.Exception(() => htmlNode.ShouldContainAttribute(\"attribute2\", \"nope\"));\r\n\r\n            // Then\r\n            Assert.IsAssignableFrom<AssertException>(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void ShouldContainAttribute_SingleElementContainingAttribute_ShouldNotThrowAssert()\r\n        {\r\n            // Given\r\n            var htmlNode = this.query[\"#testId\"].First();\r\n\r\n            // When\r\n            var result = Record.Exception(() => htmlNode.ShouldContainAttribute(\"attribute1\"));\r\n\r\n            // Then\r\n            Assert.Null(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void ShouldContainAttribute_SingleElementContainingAttributeAndValueButIngoringValue_ShouldNotThrowAssert()\r\n        {\r\n            // Given\r\n            var htmlNode = this.query[\"#testId\"].First();\r\n\r\n            // When\r\n            var result = Record.Exception(() => htmlNode.ShouldContainAttribute(\"attribute2\"));\r\n\r\n            // Then\r\n            Assert.Null(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void ShouldContainAttribute_SingleElementContainingAttributeAndValue_ShouldNotThrowAssert()\r\n        {\r\n            // Given\r\n            var htmlNode = this.query[\"#testId\"].First();\r\n\r\n            // When\r\n            var result = Record.Exception(() => htmlNode.ShouldContainAttribute(\"attribute2\", \"value2\"));\r\n\r\n            // Then\r\n            Assert.Null(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void ShouldContainAttribute_MultipleElementsOneNotContainingAttribute_ShouldThrowAssert()\r\n        {\r\n            // Given\r\n            var htmlNode = this.query[\"div\"];\r\n\r\n            // When\r\n            var result = Record.Exception(() => htmlNode.ShouldContainAttribute(\"attribute1\"));\r\n\r\n            // Then\r\n            Assert.IsAssignableFrom<AssertException>(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void ShouldContainAttribute_MultipleElementsOneNotContainingAttributeAndValue_ShouldThrowAssert()\r\n        {\r\n            // Given\r\n            var htmlNode = this.query[\"div\"];\r\n\r\n            // When\r\n            var result = Record.Exception(() => htmlNode.ShouldContainAttribute(\"class\", \"myClass\"));\r\n\r\n            // Then\r\n            Assert.IsAssignableFrom<AssertException>(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void ShouldContainAttribute_MultipleElementsContainingAttribute_ShouldNotThrowAssert()\r\n        {\r\n            // Given\r\n            var htmlNode = this.query[\"div\"];\r\n\r\n            // When\r\n            var result = Record.Exception(() => htmlNode.ShouldContainAttribute(\"class\"));\r\n\r\n            // Then\r\n            Assert.Null(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void ShouldContainAttribute_MultipleElementsContainingAttributeAndValue_ShouldNotThrowAssert()\r\n        {\r\n            // Given\r\n            var htmlNode = this.query[\"span\"];\r\n\r\n            // When\r\n            var result = Record.Exception(() => htmlNode.ShouldContainAttribute(\"class\", \"class\"));\r\n\r\n            // Then\r\n            Assert.Null(result);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Testing.Tests/BrowserContextExtensionsFixture.cs",
    "content": "﻿namespace Nancy.Testing.Tests\r\n{\r\n    using System.Linq;\r\n    using FakeItEasy;\r\n    using Nancy.Configuration;\r\n    using Nancy.Tests;\r\n\r\n    using Xunit;\r\n\r\n    public class BrowserContextExtensionsFixture\r\n    {\r\n        [Fact]\r\n        public void Should_remove_default_accept_header_when_accept_is_invoked_without_quality_parameter()\r\n        {\r\n            // Given\r\n            var context = new BrowserContext(A.Fake<INancyEnvironment>());\r\n\r\n            // When\r\n            context.Accept(\"application/json\");\r\n\r\n            // Then\r\n            ((IBrowserContextValues)context).Headers.Count.ShouldEqual(1);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_remove_default_accept_header_once_when_accept_is_invoked_without_quality_parameter()\r\n        {\r\n            // Given\r\n            var context = new BrowserContext(A.Fake<INancyEnvironment>());\r\n\r\n            // When\r\n            context.Accept(\"application/json\");\r\n            context.Accept(\"*/*\");\r\n            context.Accept(\"application/xml\");\r\n\r\n            // Then\r\n            ((IBrowserContextValues)context).Headers[\"accept\"].Count().ShouldEqual(3);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_remove_default_accept_header_when_accept_is_invoked_with_quality_parameter()\r\n        {\r\n            // Given\r\n            var context = new BrowserContext(A.Fake<INancyEnvironment>());\r\n\r\n            // When\r\n            context.Accept(\"application/json\", 0.8m);\r\n\r\n            // Then\r\n            ((IBrowserContextValues)context).Headers.Count.ShouldEqual(1);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_remove_default_accept_header_once_when_accept_is_invoked_with_quality_parameter()\r\n        {\r\n            // Given\r\n            var context = new BrowserContext(A.Fake<INancyEnvironment>());\r\n\r\n            // When\r\n            context.Accept(\"application/json\", 0.8m);\r\n            context.Accept(\"*/*\", 1.0m);\r\n            context.Accept(\"application/xml\", 0.5m);\r\n\r\n            // Then\r\n            ((IBrowserContextValues)context).Headers[\"accept\"].Count().ShouldEqual(3);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_mediarange_as_accept_header_with_default_quality_when_accept_is_invoked_without_quality_parameter()\r\n        {\r\n            // Given\r\n            var context = new BrowserContext(A.Fake<INancyEnvironment>());\r\n\r\n            // When\r\n            context.Accept(\"application/json\");\r\n\r\n            // Then\r\n            ((IBrowserContextValues) context).Headers[\"accept\"].First().ShouldEqual(\"application/json;q=1.0\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_mediarange_with_supplied_quality_as_accept_header_with_default_quality_when_accept_is_invoked_with_quality_parameter()\r\n        {\r\n            // Given\r\n            var context = new BrowserContext(A.Fake<INancyEnvironment>());\r\n\r\n            // When\r\n            context.Accept(\"application/json\", 0.8m);\r\n\r\n            // Then\r\n            ((IBrowserContextValues)context).Headers[\"accept\"].First().ShouldEqual(\"application/json;q=0.8\");\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Testing.Tests/BrowserDefaultsFixture.cs",
    "content": "﻿namespace Nancy.Testing.Tests\r\n{\r\n    using System.Linq;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Tests;\r\n\r\n    using Xunit;\r\n\r\n    public class BrowserDefaultsFixture\r\n    {\r\n        private readonly string expected;\r\n        private readonly CaptureRequestModule captureRequestModule;\r\n\r\n        public BrowserDefaultsFixture()\r\n        {\r\n            // Given\r\n            this.expected = \"application/json\";\r\n            this.captureRequestModule = new CaptureRequestModule();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_pass_default_headers_in_get_request_when_using_configurable_bootstrapper_ctor()\r\n        {\r\n            // Given\r\n            var sut = new Browser(with => with.Module(this.captureRequestModule), defaults: to => to.Accept(this.expected));\r\n\r\n            // When\r\n            await sut.Get(\"/\");\r\n\r\n            // Then\r\n            this.captureRequestModule.CapturedRequest.Headers.Accept.First().Item1.ShouldEqual(this.expected);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_pass_default_headers_in_post_request_when_using_configurable_bootstrapper_ctor()\r\n        {\r\n            // Given\r\n            var sut = new Browser(with => with.Module(this.captureRequestModule), defaults: to => to.Accept(this.expected));\r\n\r\n            // When\r\n            await sut.Post(\"/\");\r\n\r\n            // Then\r\n            this.captureRequestModule.CapturedRequest.Headers.Accept.First().Item1.ShouldEqual(this.expected);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_pass_default_headers_in_put_request_when_using_configurable_bootstrapper_ctor()\r\n        {\r\n            // Given\r\n            var sut = new Browser(with => with.Module(this.captureRequestModule), defaults: to => to.Accept(this.expected));\r\n\r\n            // When\r\n            await sut.Put(\"/\");\r\n\r\n            // Then\r\n            this.captureRequestModule.CapturedRequest.Headers.Accept.First().Item1.ShouldEqual(this.expected);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_pass_default_headers_in_patch_request_when_using_configurable_bootstrapper_ctor()\r\n        {\r\n            // Given\r\n            var sut = new Browser(with => with.Module(this.captureRequestModule), defaults: to => to.Accept(this.expected));\r\n\r\n            // When\r\n            await sut.Patch(\"/\");\r\n\r\n            // Then\r\n            this.captureRequestModule.CapturedRequest.Headers.Accept.First().Item1.ShouldEqual(this.expected);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_pass_default_headers_in_delete_request_when_using_configurable_bootstrapper_ctor()\r\n        {\r\n            // Given\r\n            var sut = new Browser(with => with.Module(this.captureRequestModule), defaults: to => to.Accept(this.expected));\r\n\r\n            // When\r\n            await sut.Delete(\"/\");\r\n\r\n            // Then\r\n            this.captureRequestModule.CapturedRequest.Headers.Accept.First().Item1.ShouldEqual(this.expected);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_pass_default_headers_in_get_request_when_using_inancybootstrapper_ctor()\r\n        {\r\n            // Given\r\n            var bootstrapper = new ConfigurableBootstrapper(with => with.Module(this.captureRequestModule));\r\n            var sut = new Browser(bootstrapper, defaults: to => to.Accept(this.expected));\r\n\r\n            // When\r\n            await sut.Get(\"/\");\r\n\r\n            // Then\r\n            this.captureRequestModule.CapturedRequest.Headers.Accept.First().Item1.ShouldEqual(this.expected);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_pass_default_headers_in_post_request_when_using_inancybootstrapper_ctor()\r\n        {\r\n            // Given\r\n            var bootstrapper = new ConfigurableBootstrapper(with => with.Module(this.captureRequestModule));\r\n            var sut = new Browser(bootstrapper, defaults: to => to.Accept(this.expected));\r\n\r\n            // When\r\n            await sut.Post(\"/\");\r\n\r\n            // Then\r\n            this.captureRequestModule.CapturedRequest.Headers.Accept.First().Item1.ShouldEqual(this.expected);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_pass_default_headers_in_put_request_when_using_inancybootstrapper_ctor()\r\n        {\r\n            // Given\r\n            var bootstrapper = new ConfigurableBootstrapper(with => with.Module(this.captureRequestModule));\r\n            var sut = new Browser(bootstrapper, defaults: to => to.Accept(this.expected));\r\n\r\n            // When\r\n            await sut.Put(\"/\");\r\n\r\n            // Then\r\n            this.captureRequestModule.CapturedRequest.Headers.Accept.First().Item1.ShouldEqual(this.expected);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_pass_default_headers_in_patch_request_when_using_inancybootstrapper_ctor()\r\n        {\r\n            // Given\r\n            var bootstrapper = new ConfigurableBootstrapper(with => with.Module(this.captureRequestModule));\r\n            var sut = new Browser(bootstrapper, defaults: to => to.Accept(this.expected));\r\n\r\n            // When\r\n            await sut.Patch(\"/\");\r\n\r\n            // Then\r\n            this.captureRequestModule.CapturedRequest.Headers.Accept.First().Item1.ShouldEqual(this.expected);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_pass_default_headers_in_delete_request_when_using_inancybootstrapper_ctor()\r\n        {\r\n            // Given\r\n            var bootstrapper = new ConfigurableBootstrapper(with => with.Module(this.captureRequestModule));\r\n            var sut = new Browser(bootstrapper, defaults: to => to.Accept(this.expected));\r\n\r\n            // When\r\n            await sut.Delete(\"/\");\r\n\r\n            // Then\r\n            this.captureRequestModule.CapturedRequest.Headers.Accept.First().Item1.ShouldEqual(this.expected);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_pass_both_defaults_and_request_specific_context_through()\r\n        {\r\n            // Given\r\n            var sut = new Browser(with => with.Module(this.captureRequestModule), defaults: to => to.Accept(this.expected));\r\n\r\n            // When\r\n            await sut.Get(\"/\", with => with.Query(\"testKey\", \"testValue\"));\r\n\r\n            // Then\r\n            this.captureRequestModule.CapturedRequest.Headers.Accept.First().Item1.ShouldEqual(this.expected);\r\n            Assert.Equal(this.captureRequestModule.CapturedRequest.Query.testKey.Value, \"testValue\");\r\n        }\r\n\r\n        public class CaptureRequestModule : NancyModule\r\n        {\r\n            public Request CapturedRequest;\r\n\r\n            public CaptureRequestModule()\r\n            {\r\n                Get(\"/\", args => this.CaptureRequest());\r\n                Post(\"/\", args => this.CaptureRequest());\r\n                Put(\"/\", args => this.CaptureRequest());\r\n                Delete(\"/\", args => this.CaptureRequest());\r\n                Patch(\"/\", args => this.CaptureRequest());\r\n            }\r\n\r\n            private dynamic CaptureRequest()\r\n            {\r\n                this.CapturedRequest = this.Request;\r\n                return HttpStatusCode.OK;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Testing.Tests/BrowserFixture.cs",
    "content": "namespace Nancy.Testing.Tests\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Security.Cryptography.X509Certificates;\r\n    using System.Text;\r\n    using System.Collections.ObjectModel;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Extensions;\r\n    using Nancy.Helpers;\r\n    using Nancy.Session;\r\n    using Nancy.Tests;\r\n    using Nancy.Authentication.Forms;\r\n    using Nancy.Configuration;\r\n    using Nancy.Tests.xUnitExtensions;\r\n    using Xunit;\r\n    using FakeItEasy;\r\n\r\n    public class BrowserFixture\r\n    {\r\n        private readonly Browser browser;\r\n\r\n        public BrowserFixture()\r\n        {\r\n            var bootstrapper =\r\n                new ConfigurableBootstrapper(config => config.Modules(typeof(EchoModule)));\r\n\r\n            CookieBasedSessions.Enable(bootstrapper);\r\n\r\n            this.browser = new Browser(bootstrapper);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_be_able_to_send_string_in_body()\r\n        {\r\n            // Given\r\n            const string thisIsMyRequestBody = \"This is my request body\";\r\n\r\n            // When\r\n            var result = await browser.Post(\"/\", with =>\r\n                {\r\n                    with.HttpRequest();\r\n                    with.Body(thisIsMyRequestBody);\r\n                });\r\n\r\n            // Then\r\n            result.Body.AsString().ShouldEqual(thisIsMyRequestBody);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_be_able_to_set_user_host_address()\r\n        {\r\n            // Given\r\n            const string userHostAddress = \"127.0.0.1\";\r\n\r\n            // When\r\n            var result = await browser.Get(\"/userHostAddress\", with =>\r\n                {\r\n                    with.HttpRequest();\r\n                    with.UserHostAddress(userHostAddress);\r\n                });\r\n\r\n            // Then\r\n            result.Body.AsString().ShouldEqual(userHostAddress);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_be_able_check_is_local_ipV4()\r\n        {\r\n            // Given\r\n            const string userHostAddress = \"127.0.0.1\";\r\n\r\n            // When\r\n            var result = await browser.Get(\"/isLocal\", with =>\r\n                {\r\n                    with.HttpRequest();\r\n                    with.HostName(\"localhost\");\r\n                    with.UserHostAddress(userHostAddress);\r\n                });\r\n\r\n            // Then\r\n            result.Body.AsString().ShouldEqual(\"local\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_be_able_check_is_local_ipV6()\r\n        {\r\n            // Given\r\n            const string userHostAddress = \"::1\";\r\n\r\n            // When\r\n            var result = await browser.Get(\"/isLocal\", with =>\r\n                {\r\n                    with.HttpRequest();\r\n                    with.HostName(\"localhost\");\r\n                    with.UserHostAddress(userHostAddress);\r\n                });\r\n\r\n            // Then\r\n            result.Body.AsString().ShouldEqual(\"local\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_be_able_check_is_not_local()\r\n        {\r\n            // Given\r\n            const string userHostAddress = \"84.12.65.72\";\r\n\r\n            // When\r\n            var result = await browser.Get(\"/isLocal\", with =>\r\n                {\r\n                    with.HttpRequest();\r\n                    with.HostName(\"anotherhost\");\r\n                    with.UserHostAddress(userHostAddress);\r\n                });\r\n\r\n            // Then\r\n            result.Body.AsString().ShouldEqual(\"not-local\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_be_able_to_send_stream_in_body()\r\n        {\r\n            // Given\r\n            const string thisIsMyRequestBody = \"This is my request body\";\r\n            var stream = new MemoryStream();\r\n            var writer = new StreamWriter(stream);\r\n            writer.Write(thisIsMyRequestBody);\r\n            writer.Flush();\r\n\r\n            // When\r\n            var result = await browser.Post(\"/\", with =>\r\n                {\r\n                    with.HttpRequest();\r\n                    with.Body(stream, \"text/plain\");\r\n                });\r\n\r\n            // Then\r\n            result.Body.AsString().ShouldEqual(thisIsMyRequestBody);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_be_able_to_send_json_in_body()\r\n        {\r\n            // Given\r\n            var model = new EchoModel { SomeString = \"Some String\", SomeInt = 29, SomeBoolean = true };\r\n\r\n            // When\r\n            var result = await browser.Post(\"/\", with =>\r\n                {\r\n                    with.JsonBody(model);\r\n                });\r\n\r\n            // Then\r\n            var actualModel = result.Body.DeserializeJson<EchoModel>();\r\n\r\n            actualModel.ShouldNotBeNull();\r\n            actualModel.SomeString.ShouldEqual(model.SomeString);\r\n            actualModel.SomeInt.ShouldEqual(model.SomeInt);\r\n            actualModel.SomeBoolean.ShouldEqual(model.SomeBoolean);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_be_able_to_send_xml_in_body()\r\n        {\r\n            // Given\r\n            var model = new EchoModel { SomeString = \"Some String\", SomeInt = 29, SomeBoolean = true };\r\n\r\n            // When\r\n            var result = await browser.Post(\"/\", with =>\r\n                {\r\n                    with.XMLBody(model);\r\n                });\r\n\r\n            // Then\r\n            var actualModel = result.Body.DeserializeXml<EchoModel>();\r\n\r\n            actualModel.ShouldNotBeNull();\r\n            actualModel.SomeString.ShouldEqual(model.SomeString);\r\n            actualModel.SomeInt.ShouldEqual(model.SomeInt);\r\n            actualModel.SomeBoolean.ShouldEqual(model.SomeBoolean);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_basic_authentication_credentials_to_the_headers_of_the_request()\r\n        {\r\n            // Given\r\n            var context = new BrowserContext(A.Fake<INancyEnvironment>());\r\n\r\n            // When\r\n            context.BasicAuth(\"username\", \"password\");\r\n\r\n            // Then\r\n            IBrowserContextValues values = context;\r\n\r\n            var credentials = string.Format(\"{0}:{1}\", \"username\", \"password\");\r\n            var encodedCredentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials));\r\n\r\n            values.Headers[\"Authorization\"].ShouldHaveCount(1);\r\n            values.Headers[\"Authorization\"].First().ShouldEqual(\"Basic \" + encodedCredentials);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_cookies_to_the_request()\r\n        {\r\n            // Given\r\n            var context = new BrowserContext(A.Fake<INancyEnvironment>());\r\n\r\n            var cookies =\r\n                new Dictionary<string, string>\r\n                {\r\n                    { \"CookieName\", \"CookieValue\" },\r\n                    { \"SomeCookieName\", \"SomeCookieValue\" }\r\n                };\r\n\r\n            // When\r\n            context.Cookie(cookies);\r\n\r\n            // Then\r\n            IBrowserContextValues values = context;\r\n\r\n            var cookieString = cookies.Aggregate(string.Empty, (current, cookie) => current + string.Format(\"{0}={1};\", HttpUtility.UrlEncode(cookie.Key), HttpUtility.UrlEncode(cookie.Value)));\r\n\r\n            values.Headers[\"Cookie\"].ShouldHaveCount(1);\r\n            values.Headers[\"Cookie\"].First().ShouldEqual(cookieString);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_cookie_to_the_request()\r\n        {\r\n            // Given\r\n            var context = new BrowserContext(A.Fake<INancyEnvironment>());\r\n\r\n            var cookies =\r\n                new Dictionary<string, string>\r\n                {\r\n                    { \"CookieName\", \"CookieValue\" },\r\n                    { \"SomeCookieName\", \"SomeCookieValue\" }\r\n                };\r\n\r\n            // When\r\n            foreach (var cookie in cookies)\r\n            {\r\n                context.Cookie(cookie.Key, cookie.Value);\r\n            }\r\n\r\n            // Then\r\n            IBrowserContextValues values = context;\r\n\r\n            var cookieString = cookies.Aggregate(string.Empty, (current, cookie) => current + string.Format(\"{0}={1};\", HttpUtility.UrlEncode(cookie.Key), HttpUtility.UrlEncode(cookie.Value)));\r\n\r\n            values.Headers[\"Cookie\"].ShouldHaveCount(1);\r\n            values.Headers[\"Cookie\"].First().ShouldEqual(cookieString);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_add_cookies_to_the_request_and_get_cookies_in_response()\r\n        {\r\n            // Given\r\n            var cookies =\r\n                new Dictionary<string, string>\r\n                {\r\n                    { \"CookieName\", \"CookieValue\" },\r\n                    { \"SomeCookieName\", \"SomeCookieValue\" }\r\n                };\r\n\r\n            // When\r\n            var result = await browser.Get(\"/cookie\", with =>\r\n                {\r\n                    with.Cookie(cookies);\r\n                });\r\n\r\n            // Then\r\n            result.Cookies.Single(x => x.Name == \"CookieName\").Value.ShouldEqual(\"CookieValue\");\r\n            result.Cookies.Single(x => x.Name == \"SomeCookieName\").Value.ShouldEqual(\"SomeCookieValue\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_add_a_cookie_to_the_request_and_get_a_cookie_in_response()\r\n        {\r\n            // Given, When\r\n            var result = await browser.Get(\"/cookie\", with => with.Cookie(\"CookieName\", \"CookieValue\"));\r\n\r\n            // Then\r\n            result.Cookies.Single(x => x.Name == \"CookieName\").Value.ShouldEqual(\"CookieValue\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_be_able_to_continue_with_another_request()\r\n        {\r\n            // Given\r\n            const string FirstRequestBody = \"This is my first request body\";\r\n            const string SecondRequestBody = \"This is my second request body\";\r\n            var firstRequestStream = new MemoryStream();\r\n            var firstRequestWriter = new StreamWriter(firstRequestStream);\r\n            firstRequestWriter.Write(FirstRequestBody);\r\n            firstRequestWriter.Flush();\r\n            var secondRequestStream = new MemoryStream();\r\n            var secondRequestWriter = new StreamWriter(secondRequestStream);\r\n            secondRequestWriter.Write(SecondRequestBody);\r\n            secondRequestWriter.Flush();\r\n\r\n            // When\r\n            await browser.Post(\"/\", with =>\r\n                {\r\n                    with.HttpRequest();\r\n                    with.Body(firstRequestStream, \"text/plain\");\r\n                });\r\n\r\n            var result = await browser.Post(\"/\", with =>\r\n                {\r\n                    with.HttpRequest();\r\n                    with.Body(secondRequestStream, \"text/plain\");\r\n                });\r\n\r\n            // Then\r\n            result.Body.AsString().ShouldEqual(SecondRequestBody);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_maintain_cookies_when_chaining_requests()\r\n        {\r\n            // Given\r\n            // When\r\n            await browser.Get(\"/session\", with => with.HttpRequest());\r\n\r\n            var result = await this.browser.Get(\r\n                             \"/session\",\r\n                             with => with.HttpRequest());\r\n\r\n            //Then\r\n            result.Body.AsString().ShouldEqual(\"Current session value is: I've created a session!\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_maintain_cookies_even_if_not_set_on_directly_preceding_request()\r\n        {\r\n            // Given\r\n            // When\r\n            await browser.Get(\"/session\", with => with.HttpRequest());\r\n\r\n            await browser.Get(\"/nothing\", with => with.HttpRequest());\r\n\r\n            var result = await browser.Get(\"/session\", with => with.HttpRequest());\r\n\r\n            //Then\r\n            result.Body.AsString().ShouldEqual(\"Current session value is: I've created a session!\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_be_able_to_not_specify_delegate_for_basic_http_request()\r\n        {\r\n            //Given, When\r\n            var result = await browser.Get(\"/type\");\r\n\r\n            //Then\r\n            result.Body.AsString().ShouldEqual(\"http\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_add_ajax_header()\r\n        {\r\n            //Given, When\r\n            var result = await browser.Get(\"/ajax\", with => with.AjaxRequest());\r\n\r\n            //Then\r\n            result.Body.AsString().ShouldEqual(\"ajax\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_throw_an_exception_when_the_cert_couldnt_be_found()\r\n        {\r\n            //Given, When\r\n            var exception = await RecordAsync.Exception(() =>\r\n                {\r\n                    return browser.Get(\"/ajax\", with =>\r\n                                         with.Certificate(\r\n                                             StoreLocation.CurrentUser,\r\n                                             StoreName.My,\r\n                                             X509FindType.FindByThumbprint,\r\n                                             \"aa aa aa\"));\r\n                });\r\n\r\n            //Then\r\n            exception.ShouldBeOfType<InvalidOperationException>();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_add_certificate()\r\n        {\r\n            //Given, When\r\n            var result = await browser.Get(\"/cert\", with => with.Certificate());\r\n\r\n            //Then\r\n            result.Context.Request.ClientCertificate.ShouldNotBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_change_scheme_to_https_when_HttpsRequest_is_called_on_the_context()\r\n        {\r\n            //Given, When\r\n            var result = await browser.Get(\"/\", with => with.HttpsRequest());\r\n\r\n            //Then\r\n            result.Context.Request.Url.Scheme.ShouldEqual(\"https\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_add_forms_authentication_cookie_to_the_request()\r\n        {\r\n            //Given\r\n            var userId = A.Dummy<Guid>();\r\n\r\n            var formsAuthConfig = new FormsAuthenticationConfiguration()\r\n            {\r\n                RedirectUrl = \"/login\",\r\n                UserMapper = A.Fake<IUserMapper>(),\r\n            };\r\n\r\n            var encryptedId = formsAuthConfig.CryptographyConfiguration.EncryptionProvider.Encrypt(userId.ToString());\r\n            var hmacBytes = formsAuthConfig.CryptographyConfiguration.HmacProvider.GenerateHmac(encryptedId);\r\n            var hmacString = Convert.ToBase64String(hmacBytes);\r\n            var cookieContents = String.Format(\"{1}{0}\", encryptedId, hmacString);\r\n\r\n            //When\r\n            var response = await browser.Get(\"/cookie\", (with) =>\r\n                {\r\n                    with.HttpRequest();\r\n                    with.FormsAuth(userId, formsAuthConfig);\r\n                });\r\n\r\n            var cookie = response.Cookies.Single(c => c.Name == FormsAuthentication.FormsAuthenticationCookieName);\r\n            var cookieValue = cookie.Value;\r\n\r\n            //Then\r\n            cookieValue.ShouldEqual(cookieContents);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_JSON_serialized_form()\r\n        {\r\n            // Given\r\n            var response = await browser.Post(\"/serializedform\", (with) =>\r\n                {\r\n                    with.HttpRequest();\r\n                    with.Accept(\"application/json\");\r\n                    with.FormValue(\"SomeString\", \"Hi\");\r\n                    with.FormValue(\"SomeInt\", \"1\");\r\n                    with.FormValue(\"SomeNullableInt1\", \"2\");\r\n                    with.FormValue(\"SomeNullableInt2\", string.Empty);\r\n                    with.FormValue(\"SomeNullableInt3\", null);\r\n                    with.FormValue(\"SomeBoolean\", \"true\");\r\n                });\r\n\r\n            // When\r\n            var actualModel = response.Body.DeserializeJson<EchoModel>();\r\n\r\n            // Then\r\n            Assert.Equal(\"Hi\", actualModel.SomeString);\r\n            Assert.Equal(1, actualModel.SomeInt);\r\n            actualModel.SomeNullableInt1.ShouldEqual(2);\r\n            actualModel.SomeNullableInt2.ShouldBeNull();\r\n            actualModel.SomeNullableInt3.ShouldBeNull();\r\n            Assert.True(actualModel.SomeBoolean);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_JSON_serialized_querystring()\r\n        {\r\n            // Given\r\n            var response = await browser.Get(\"/serializedquerystring\", (with) =>\r\n                {\r\n                    with.HttpRequest();\r\n                    with.Accept(\"application/json\");\r\n                    with.Query(\"SomeString\", \"Hi\");\r\n                    with.Query(\"SomeInt\", \"1\");\r\n                    with.Query(\"SomeNullableInt1\", \"2\");\r\n                    with.Query(\"SomeNullableInt2\", string.Empty);\r\n                    with.Query(\"SomeNullableInt3\", null);\r\n                    with.Query(\"SomeBoolean\", \"true\");\r\n                });\r\n\r\n            // When\r\n            var actualModel = response.Body.DeserializeJson<EchoModel>();\r\n\r\n            // Then\r\n            Assert.Equal(\"Hi\", actualModel.SomeString);\r\n            Assert.Equal(1, actualModel.SomeInt);\r\n            actualModel.SomeNullableInt1.ShouldEqual(2);\r\n            actualModel.SomeNullableInt2.ShouldBeNull();\r\n            actualModel.SomeNullableInt3.ShouldBeNull();\r\n            Assert.True(actualModel.SomeBoolean);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_encode_form()\r\n        {\r\n            //Given, When\r\n            var result = await browser.Post(\"/encoded\", with =>\r\n                {\r\n                    with.HttpRequest();\r\n                    with.FormValue(\"name\", \"john++\");\r\n                });\r\n\r\n            //Then\r\n            result.Body.AsString().ShouldEqual(\"john++\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_encode_querystring()\r\n        {\r\n            //Given, When\r\n            var result = await browser.Post(\"/encodedquerystring\", with =>\r\n                {\r\n                    with.HttpRequest();\r\n                    with.Query(\"name\", \"john++\");\r\n                });\r\n\r\n            //Then\r\n            result.Body.AsString().ShouldEqual(\"john++\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_add_nancy_testing_browser_header_as_default_user_agent()\r\n        {\r\n            // Given\r\n            const string expectedHeaderValue = \"Nancy.Testing.Browser\";\r\n\r\n            // When\r\n            var result = (await browser.Get(\"/useragent\")).Body.AsString();\r\n\r\n            // Then\r\n            result.ShouldEqual(expectedHeaderValue);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_override_default_user_agent_when_explicitly_defined()\r\n        {\r\n            // Given\r\n            const string expectedHeaderValue = \"Custom.User.Agent\";\r\n\r\n            // When\r\n            var result = await browser.Get(\"/useragent\", with =>\r\n                {\r\n                    with.Header(\"User-Agent\", expectedHeaderValue);\r\n                });\r\n\r\n            var header = result.Body.AsString();\r\n\r\n            // Then\r\n            header.ShouldEqual(expectedHeaderValue);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"application/xml\")]\r\n        public async Task Should_return_error_message_on_cyclical_exception(string accept)\r\n        {\r\n            //Given\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.Modules(typeof(EchoModule));\r\n                with.Configure(env =>\r\n                {\r\n                    env.Tracing(\r\n                        enabled: true,\r\n                        displayErrorTraces: true);\r\n                });\r\n            });\r\n\r\n            // When\r\n            var result = await browser.Get(\"/cyclical\", with => with.Accept(accept));\r\n\r\n            //Then\r\n            var resultBody = result.Body.AsString();\r\n            resultBody.ShouldNotBeEmpty();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"application/xml\")]\r\n        public async Task Should_return_no_error_message_on_cyclical_exception_when_disabled_error_trace(string accept)\r\n        {\r\n            //Given\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.Modules(typeof(EchoModule));\r\n                with.Configure(env =>\r\n                {\r\n                    env.Tracing(\r\n                        enabled: true,\r\n                        displayErrorTraces: false);\r\n                });\r\n            });\r\n\r\n            // When\r\n            var result = await browser.Get(\"/cyclical\", with => with.Accept(accept));\r\n\r\n            //Then\r\n            result.Body.AsString().ShouldBeEmpty();\r\n        }\r\n\r\n        public class EchoModel\r\n        {\r\n            public string SomeString { get; set; }\r\n\r\n            public int SomeInt { get; set; }\r\n\r\n            public int? SomeNullableInt1 { get; set; }\r\n\r\n            public int? SomeNullableInt2 { get; set; }\r\n\r\n            public int? SomeNullableInt3 { get; set; }\r\n\r\n            public bool SomeBoolean { get; set; }\r\n        }\r\n\r\n        public class Category\r\n        {\r\n            public string Name { get; set; }\r\n\r\n            public ICollection<Product> Products { get; set; }\r\n        }\r\n\r\n        public class Product\r\n        {\r\n            public string Name { get; set; }\r\n\r\n            public Category Category { get; set; }\r\n        }\r\n\r\n        public class EchoModule : NancyModule\r\n        {\r\n            public EchoModule()\r\n            {\r\n                Get(\"/cyclical\", args =>\r\n                {\r\n                    var category = new Category();\r\n                    category.Name = \"Electronics\";\r\n\r\n                    var product = new Product();\r\n                    product.Name = \"iPad\";\r\n                    product.Category = category;\r\n\r\n                    category.Products = new Collection<Product>(new List<Product>(new[] { product }));\r\n\r\n                    return product;\r\n                });\r\n\r\n                Post(\"/\", args =>\r\n                {\r\n                    var body = new StreamReader(this.Context.Request.Body).ReadToEnd();\r\n                    return new Response\r\n                    {\r\n                        Contents = stream =>\r\n                        {\r\n                            var writer = new StreamWriter(stream);\r\n                            writer.Write(body);\r\n                            writer.Flush();\r\n                        }\r\n                    };\r\n                });\r\n\r\n                Get(\"/cookie\", args =>\r\n                {\r\n                    var response = (Response)\"Cookies\";\r\n\r\n                    foreach (var cookie in this.Request.Cookies)\r\n                    {\r\n                        response.WithCookie(cookie.Key, cookie.Value);\r\n                    }\r\n\r\n                    return response;\r\n                });\r\n\r\n                Get(\"/nothing\", args => string.Empty);\r\n\r\n                Get(\"/userHostAddress\", args => this.Request.UserHostAddress);\r\n\r\n                Get(\"/isLocal\", args => this.Request.IsLocal() ? \"local\" : \"not-local\");\r\n\r\n                Get(\"/session\", args =>\r\n                {\r\n                    var value = Session[\"moo\"] ?? \"\";\r\n\r\n                    var output = \"Current session value is: \" + value;\r\n\r\n                    if (string.IsNullOrEmpty(value.ToString()))\r\n                    {\r\n                        Session[\"moo\"] = \"I've created a session!\";\r\n                    }\r\n\r\n                    var response = (Response)output;\r\n\r\n                    return response;\r\n                });\r\n\r\n                Get(\"/useragent\", args => this.Request.Headers.UserAgent);\r\n\r\n                Get(\"/type\", args => this.Request.Url.Scheme.ToLower());\r\n\r\n                Get(\"/ajax\", args => this.Request.IsAjaxRequest() ? \"ajax\" : \"not-ajax\");\r\n\r\n                Post(\"/encoded\", args => (string)this.Request.Form.name);\r\n\r\n                Post(\"/encodedquerystring\", args => (string)this.Request.Query.name);\r\n\r\n                Post(\"/serializedform\", args =>\r\n                {\r\n                    IDictionary<string, object> data = Request.Form.ToDictionary();\r\n\r\n                    return data;\r\n                });\r\n\r\n                Get(\"/serializedquerystring\", args =>\r\n                {\r\n                    IDictionary<string, object> data = Request.Query.ToDictionary();\r\n\r\n                    return data;\r\n                });\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Testing.Tests/BrowserResponseBodyWrapperExtensionsFixture.cs",
    "content": "namespace Nancy.Testing.Tests\r\n{\r\n    using System.IO;\r\n    using FakeItEasy;\r\n    using Nancy.Tests;\r\n\r\n    using Xunit;\r\n\r\n    public class BrowserResponseBodyWrapperExtensionsFixture\r\n    {\r\n        [Fact]\r\n        public void Should_convert_to_string()\r\n        {\r\n            // Given\r\n            var body = new BrowserResponseBodyWrapper(new Response\r\n            {\r\n                Contents = stream =>\r\n                {\r\n                    var writer = new StreamWriter(stream);\r\n                    writer.Write(\"This is the content\");\r\n                    writer.Flush();\r\n                }\r\n            }, A.Dummy<BrowserContext>());\r\n\r\n            // When\r\n            var result = body.AsString();\r\n\r\n            // Then\r\n            result.ShouldEqual(\"This is the content\");\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Testing.Tests/BrowserResponseBodyWrapperFixture.cs",
    "content": "﻿namespace Nancy.Testing.Tests\r\n{\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Text;\r\n    using FakeItEasy;\r\n    using Nancy.Tests;\r\n\r\n    using Xunit;\r\n\r\n    public class BrowserResponseBodyWrapperFixture\r\n    {\r\n        [Fact]\r\n        public void Should_contain_response_body()\r\n        {\r\n            // Given\r\n            var body = new BrowserResponseBodyWrapper(new Response\r\n            {\r\n                Contents = stream =>\r\n                {\r\n                    var writer = new StreamWriter(stream);\r\n                    writer.Write(\"This is the content\");\r\n                    writer.Flush();\r\n                }\r\n            }, A.Dummy<BrowserContext>());\r\n\r\n            var content = Encoding.ASCII.GetBytes(\"This is the content\");\r\n\r\n            // When\r\n            var result = body.SequenceEqual(content);\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_querywrapper_for_css_selector_match()\r\n        {\r\n            // Given\r\n            var body = new BrowserResponseBodyWrapper(new Response\r\n            {\r\n                Contents = stream =>\r\n                {\r\n                    var writer = new StreamWriter(stream);\r\n                    writer.Write(\"<div>Outer and <div id='bar'>inner</div></div>\");\r\n                    writer.Flush();\r\n                }\r\n            }, A.Dummy<BrowserContext>());\r\n\r\n            // When\r\n            var result = body[\"#bar\"];\r\n\r\n            // Then\r\n#if MONO\r\n            AssertExtensions.AllShouldContain(result, \"inner\", System.StringComparison.OrdinalIgnoreCase);\r\n#else\r\n            result.AllShouldContain(\"inner\");\r\n#endif\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Testing.Tests/BrowserResponseExtensionsTests.cs",
    "content": "﻿namespace Nancy.Testing.Tests\r\n{\r\n    using System.Xml;\r\n    using FakeItEasy;\r\n    using Xunit;\r\n\r\n    public class BrowserResponseExtensionsTests\r\n\t{\r\n\t\tprivate BrowserResponse sut;\r\n\r\n\t\t[Fact]\r\n\t\tpublic void Should_create_xdocument_from_xml_body()\r\n\t\t{\r\n            // Given\r\n\t\t\tvar context = new NancyContext() { Response = \"<tag />\" };\r\n            sut = new BrowserResponse(context, A.Fake<Browser>(), A.Dummy<BrowserContext>());\r\n\r\n            // When\r\n            var bodyAsXml = sut.BodyAsXml();\r\n\r\n            // Then\r\n\t\t\tAssert.NotNull(bodyAsXml.Element(\"tag\"));\r\n\t\t}\r\n\r\n\t\t[Fact]\r\n\t\tpublic void Should_fail_to_create_xdocument_from_non_xml_body()\r\n\t\t{\r\n            // Given\r\n\t\t\tvar context = new NancyContext() { Response = \"hello\" };\r\n\r\n            // When\r\n\t\t    sut = new BrowserResponse(context, A.Fake<Browser>(), A.Dummy<BrowserContext>());\r\n\r\n            // Then\r\n\t\t\tAssert.Throws<XmlException>(() => sut.BodyAsXml());\r\n\t\t}\r\n\t}\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Testing.Tests/CaseSensitivityFixture.cs",
    "content": "﻿namespace Nancy.Testing.Tests\r\n{\r\n    using System.Threading.Tasks;\r\n    using Nancy.ModelBinding;\r\n    using Nancy.Tests;\r\n    using Xunit;\r\n\r\n    public class CaseSensitivityFixture\r\n    {\r\n        private readonly Browser browser;\r\n\r\n        public CaseSensitivityFixture()\r\n        {\r\n            var bootstrapper = new ConfigurableBootstrapper(with =>\r\n            {\r\n                with.Module<MainModule>();\r\n            });\r\n\r\n            this.browser = new Browser(bootstrapper);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_pull_query_parameter_with_different_case()\r\n        {\r\n            // Given\r\n            const string animal = \"dog\";\r\n\r\n            using (new StaticConfigurationContext(x => x.CaseSensitive = false))\r\n            {\r\n                // When\r\n                var response = await browser.Get(\"/\", with =>\r\n                {\r\n                    with.Query(\"ANIMAL\", animal);\r\n                });\r\n\r\n                // Then\r\n                response.Body.AsString().ShouldEqual(animal);\r\n            }\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_pull_query_parameter_with_different_case_when_sensitivity_is_on()\r\n        {\r\n            // Given\r\n            const string animal = \"dog\";\r\n\r\n            using (new StaticConfigurationContext(x => x.CaseSensitive = true))\r\n            {\r\n\r\n                // When\r\n                var response = await browser.Get(\"/\", with =>\r\n                {\r\n                    with.Query(\"ANIMAL\", animal);\r\n                });\r\n\r\n                // Then\r\n                response.Body.AsString().ShouldEqual(string.Empty);\r\n            }\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_pull_parameter_with_different_case()\r\n        {\r\n            // Given\r\n            const string animal = \"dog\";\r\n\r\n            using (new StaticConfigurationContext(x => x.CaseSensitive = false))\r\n            {\r\n                // When\r\n                var response = await browser.Get(\"/dog\", with =>\r\n                {\r\n                });\r\n\r\n                // Then\r\n                response.Body.AsString().ShouldEqual(animal);\r\n            }\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_pull_parameter_with_different_case_when_sensitivity_is_on()\r\n        {\r\n            // Given\r\n            using (new StaticConfigurationContext(x => x.CaseSensitive = true))\r\n            {\r\n                // When\r\n                var response = await browser.Get(\"/dog\");\r\n\r\n                // Then\r\n                response.Body.AsString().ShouldEqual(string.Empty);\r\n            }\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_bind_query_with_different_case_when_sensitivity_is_off()\r\n        {\r\n            // Given\r\n            const string animal = \"dog\";\r\n\r\n            using (new StaticConfigurationContext(x => x.CaseSensitive = false))\r\n            {\r\n                // When\r\n                var response = await browser.Get(\"/animal\", with =>\r\n                {\r\n                    with.Query(\"TYPE\", animal);\r\n                });\r\n\r\n                // Then\r\n                response.StatusCode.ShouldEqual(HttpStatusCode.Accepted);\r\n            }\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_bind_query_with_different_case_when_sensitivity_is_on()\r\n        {\r\n            // Given\r\n            const string animal = \"dog\";\r\n\r\n            using (new StaticConfigurationContext(x => x.CaseSensitive = true))\r\n            {\r\n                // When\r\n                var response = await browser.Get(\"/animal\", with =>\r\n                {\r\n                    with.Query(\"TYPE\", animal);\r\n                });\r\n\r\n                // Then\r\n                response.StatusCode.ShouldEqual(HttpStatusCode.NoContent);\r\n            }\r\n        }\r\n\r\n        public class MainModule : NancyModule\r\n        {\r\n            public MainModule()\r\n            {\r\n                Get(\"/\", args =>\r\n                {\r\n                    var name = this.Request.Query.animal.HasValue ? this.Request.Query.animal : \"\";\r\n                    return name;\r\n                });\r\n\r\n                Get(\"/{ANIMAL}\", args =>\r\n                {\r\n                    var name = args.animal.HasValue ? args.animal : \"\";\r\n                    return name;\r\n                });\r\n\r\n                Get(\"/animal\", args =>\r\n                {\r\n                    var animal = this.Bind<Animal>();\r\n                    return (animal.Type == null) ? HttpStatusCode.NoContent : HttpStatusCode.Accepted;\r\n                });\r\n            }\r\n        }\r\n\r\n        public class Animal\r\n        {\r\n            public string Type { get; set; }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Testing.Tests/ConfigurableBootstrapperDependenciesTests.cs",
    "content": "﻿namespace Nancy.Testing.Tests\r\n{\r\n    using System;\r\n    using System.Threading.Tasks;\r\n    using FakeItEasy;\r\n\r\n    using Xunit;\r\n\r\n    public class ConfigurableBootstrapperDependenciesTests\r\n    {\r\n        private const string _dataFromFake = \"Faked version ITestDependency\";\r\n        private const string _dataFromFake2 = \"Faked version ITestDependency2\";\r\n\r\n        private static ITestDependency GetFakeDependency()\r\n        {\r\n            var fakeRep = A.Fake<ITestDependency>();\r\n            A.CallTo(() => fakeRep.GetData()).Returns(_dataFromFake);\r\n            return fakeRep;\r\n        }\r\n\r\n        private static ITestDependency2 GetFakeDependency2()\r\n        {\r\n            var fakeRep = A.Fake<ITestDependency2>();\r\n            A.CallTo(() => fakeRep.GetData()).Returns(_dataFromFake2);\r\n            return fakeRep;\r\n        }\r\n\r\n        [Fact]\r\n        public async Task should_be_able_to_configure_dependency_typeparam()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.Module<ModuleWithOneDependency>();\r\n                with.Dependency<ImplementedTestDependency>();\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/1dependency\");\r\n\r\n            // Assert\r\n            Assert.Contains(\"Implemented ITestDependency\", response.Body.AsString());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task should_be_able_to_configure_dependency_typeparam_and_instance()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with =>\r\n                    {\r\n                        with.Module<ModuleWithOneDependency>();\r\n                        with.Dependency<ITestDependency>(GetFakeDependency());\r\n                    });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/1dependency\");\r\n\r\n            // Assert\r\n            Assert.Contains(_dataFromFake, response.Body.AsString());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task should_be_able_to_configure_dependency_instance()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.Module<ModuleWithOneDependency>();\r\n                with.Dependency(GetFakeDependency());\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/1dependency\");\r\n\r\n            // Assert\r\n            Assert.Contains(_dataFromFake, response.Body.AsString());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task should_be_able_to_configure_dependency_type()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.Module<ModuleWithOneDependency>();\r\n                with.Dependency<ITestDependency>(typeof(ImplementedTestDependency));\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/1dependency\");\r\n\r\n            // Assert\r\n            Assert.Contains(\"Implemented ITestDependency\", response.Body.AsString());\r\n        }\r\n\r\n        interface IIinterface { }\r\n        class DisposableDependency : IIinterface, IDisposable\r\n        {\r\n            public bool Disposed { get; private set; }\r\n\r\n            public void Dispose()\r\n            {\r\n                this.Disposed = true;\r\n            }\r\n        }\r\n\r\n        [Fact]\r\n        public void should_be_able_to_configure_disposbale_dependency_implementing_interface_by_interface()\r\n        {\r\n            // Given\r\n            var disposableDependency = new DisposableDependency();\r\n\r\n            // When\r\n            new Browser(with =>\r\n              with.Dependency<IIinterface>(disposableDependency)\r\n            );\r\n\r\n            // Then\r\n            Assert.False(disposableDependency.Disposed);\r\n        }\r\n\r\n\r\n        [Fact]\r\n        public async Task should_be_able_to_configure_dependencies_by_instances()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.Module<ModuleWithTwoDependencies>();\r\n                with.Dependencies<object>(GetFakeDependency(), GetFakeDependency2());\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/2dependencies\");\r\n\r\n            // Assert\r\n            var bodyAsString = response.Body.AsString();\r\n            Assert.Contains(_dataFromFake, bodyAsString);\r\n            Assert.Contains(_dataFromFake2, bodyAsString);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task should_be_able_to_configure_dependencies_by_a_map_with_interface_and_instance()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.Module<ModuleWithTwoDependencies>();\r\n                with.MappedDependencies(new[] {\r\n                                       new Tuple<Type, object>(typeof(ITestDependency), GetFakeDependency()),\r\n                                       new Tuple<Type, object>(typeof(ITestDependency2), GetFakeDependency2())\r\n                                   });\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/2dependencies\");\r\n\r\n            // Assert\r\n            var bodyAsString = response.Body.AsString();\r\n            Assert.Contains(_dataFromFake, bodyAsString);\r\n            Assert.Contains(_dataFromFake2, bodyAsString);\r\n        }\r\n\r\n        public class ModuleWithOneDependency : NancyModule\r\n        {\r\n            public ModuleWithOneDependency(ITestDependency dependency)\r\n                : base(\"/1dependency\")\r\n            {\r\n                Get(\"/\", args =>\r\n                {\r\n                    return string.Format(\"Data of dependency: {0}\", dependency.GetData());\r\n                });\r\n            }\r\n        }\r\n\r\n        public class ModuleWithTwoDependencies : NancyModule\r\n        {\r\n            public ModuleWithTwoDependencies(ITestDependency dependency, ITestDependency2 dependency2)\r\n                : base(\"/2dependencies\")\r\n            {\r\n                Get(\"/\", args =>\r\n                {\r\n                    return string.Format(\"Data of dependencies: {0}, {1}\", dependency.GetData(), dependency2.GetData());\r\n                });\r\n            }\r\n        }\r\n\r\n        public interface ITestDependency\r\n        {\r\n            string GetData();\r\n        }\r\n\r\n        public class ImplementedTestDependency : ITestDependency\r\n        {\r\n            public string GetData()\r\n            {\r\n                return \"Implemented ITestDependency\";\r\n            }\r\n        }\r\n\r\n        public interface ITestDependency2\r\n        {\r\n            string GetData();\r\n        }\r\n\r\n        public class ImplementedTestDependency2 : ITestDependency2\r\n        {\r\n            public string GetData()\r\n            {\r\n                return \"Implemented ITestDependency2\";\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Testing.Tests/ConfigurableBootstrapperFixture.cs",
    "content": "﻿namespace Nancy.Testing.Tests\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Tests;\r\n\r\n    using Xunit;\r\n    using Xunit.Sdk;\r\n\r\n    public class ConfigurableBootstrapperFixture\r\n    {\r\n        [Fact]\r\n        public void Should_use_default_type_when_no_type_or_instance_overrides_have_been_configured()\r\n        {\r\n            // Given\r\n            var bootstrapper = new ConfigurableBootstrapper();\r\n            bootstrapper.Initialise();\r\n\r\n            // When\r\n            var engine = bootstrapper.GetEngine();\r\n\r\n            // Then\r\n            engine.ShouldBeOfType<NancyEngine>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_type_override_when_it_has_been_configured()\r\n        {\r\n            // Given\r\n            var bootstrapper = new ConfigurableBootstrapper(with =>\r\n            {\r\n                with.NancyEngine<FakeNancyEngine>();\r\n            });\r\n\r\n            bootstrapper.Initialise();\r\n\r\n            // When\r\n            var engine = bootstrapper.GetEngine();\r\n\r\n            // Then\r\n            engine.ShouldBeOfType<FakeNancyEngine>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_instance_override_when_it_has_been_configured()\r\n        {\r\n            // Given\r\n            var fakeEngine = A.Fake<INancyEngine>();\r\n\r\n            var bootstrapper = new ConfigurableBootstrapper(with =>\r\n            {\r\n                with.NancyEngine(fakeEngine);\r\n            });\r\n\r\n            bootstrapper.Initialise();\r\n\r\n            // When\r\n            var engine = bootstrapper.GetEngine();\r\n\r\n            // Then\r\n            engine.ShouldBeSameAs(fakeEngine);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_instance_override_when_both_type_and_instance_overrides_have_been_configured()\r\n        {\r\n            // Given\r\n            var fakeEngine = A.Fake<INancyEngine>();\r\n\r\n            var bootstrapper = new ConfigurableBootstrapper(with =>\r\n            {\r\n                with.NancyEngine<FakeNancyEngine>();\r\n                with.NancyEngine(fakeEngine);\r\n            });\r\n\r\n            bootstrapper.Initialise();\r\n\r\n            // When\r\n            var engine = bootstrapper.GetEngine();\r\n\r\n            // Then\r\n            engine.ShouldBeSameAs(fakeEngine);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_provide_configuration_for_all_base_properties()\r\n        {\r\n            // Given\r\n            var availableMembers =\r\n                typeof(ConfigurableBootstrapper.ConfigurableBootstrapperConfigurator)\r\n                .GetMethods(BindingFlags.Public | BindingFlags.Instance)\r\n                .Select(x => x.Name)\r\n                .Distinct();\r\n\r\n            var expectedConfigurableMembers =\r\n                this.GetConfigurableBootstrapperMembers();\r\n\r\n            // When\r\n            var result = expectedConfigurableMembers.Where(x => !availableMembers.Contains(x, StringComparer.OrdinalIgnoreCase)).ToArray();\r\n\r\n            // Then\r\n            if (result.Any())\r\n            {\r\n                throw new AssertException(string.Format(\"Types missing from configurable versions: {0} \", result.Aggregate((t1, t2) => t1 + \", \" + t2)));\r\n            }\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_throw_exceptions_if_any_occur_in_route()\r\n        {\r\n            var bootstrapper = new ConfigurableBootstrapper(with =>\r\n                {\r\n                    with.Module<BlowUpModule>();\r\n                });\r\n            bootstrapper.Initialise();\r\n            var engine = bootstrapper.GetEngine();\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n\r\n            var result = await Record.Exception(() => engine.HandleRequest(request));\r\n\r\n            result.ShouldNotBeNull();\r\n            result.ShouldBeOfType<Exception>();\r\n            result.ToString().ShouldContain(\"Oh noes!\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_run_application_startup_closure()\r\n        {\r\n            var date = new DateTime(2112,10,31);\r\n\r\n            var bootstrapper = new ConfigurableBootstrapper(with =>\r\n            {\r\n                with.ApplicationStartup((container, pipelines) =>\r\n                {\r\n                    pipelines.BeforeRequest += ctx =>\r\n                        {\r\n                            ctx.Items.Add(\"date\", date);\r\n                            return null;\r\n                        };\r\n                });\r\n            });\r\n\r\n            bootstrapper.Initialise();\r\n\r\n            var engine = bootstrapper.GetEngine();\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n            var result = await engine.HandleRequest(request);\r\n\r\n            result.Items[\"date\"].ShouldEqual(date);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_run_request_startup_closure()\r\n        {\r\n            var date = new DateTime(2112, 10, 31);\r\n            var bootstrapper =\r\n                new ConfigurableBootstrapper(\r\n                    with => with.RequestStartup((container, pipelines, context) =>\r\n                        context.Items.Add(\"date\", date)));\r\n\r\n            bootstrapper.Initialise();\r\n\r\n            var engine = bootstrapper.GetEngine();\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n            var result = await engine.HandleRequest(request);\r\n\r\n            result.Items[\"date\"].ShouldEqual(date);\r\n        }\r\n\r\n        private IEnumerable<string> GetConfigurableBootstrapperMembers()\r\n        {\r\n            var ignoreList = new[]\r\n            {\r\n                \"AfterRequest\", \"BeforeRequest\", \"IsValid\", \"ModuleKeyGenerator\",\r\n                \"BindingDefaults\", \"OnError\", \"InteractiveDiagnosticProviders\", \"RequestTracing\", \"IgnoredAssemblies\"\r\n            };\r\n\r\n            var typesToReflect =\r\n                new[] { typeof(NancyBootstrapperBase<>), typeof(NancyInternalConfiguration) };\r\n\r\n            return typesToReflect\r\n                .SelectMany(x => x.GetProperties(BindingFlags.Public | BindingFlags.Instance))\r\n                .Select(x => x.Name)\r\n                .Where(x => !ignoreList.Contains(x, StringComparer.OrdinalIgnoreCase));\r\n        }\r\n\r\n        private class FakeNancyEngine : INancyEngine\r\n        {\r\n            public Func<NancyContext, Response> PreRequestHook { get; set; }\r\n\r\n            public Action<NancyContext> PostRequestHook { get; set; }\r\n\r\n            public Func<NancyContext, Exception, dynamic> OnErrorHook { get; set; }\r\n\r\n            public Func<NancyContext, IPipelines> RequestPipelinesFactory { get; set; }\r\n\r\n            public Task<NancyContext> HandleRequest(Request request, Func<NancyContext, NancyContext> preRequest, CancellationToken cancellationToken)\r\n            {\r\n                throw new NotImplementedException();\r\n            }\r\n\r\n            public void Dispose()\r\n            {\r\n            }\r\n        }\r\n\r\n        private class BlowUpModule : NancyModule\r\n        {\r\n            public BlowUpModule()\r\n            {\r\n                Get(\"/\", args =>\r\n                {\r\n                    throw new InvalidOperationException(\"Oh noes!\");\r\n                    return 500;\r\n                });\r\n            }\r\n        }\r\n\r\n        private static class Record\r\n        {\r\n            internal static async Task<Exception> Exception(Func<Task> code)\r\n            {\r\n                try\r\n                {\r\n                    await code();\r\n                    return null;\r\n                }\r\n                catch (Exception ex)\r\n                {\r\n                    return ex;\r\n                }\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Testing.Tests/ContextExtensionsTests.cs",
    "content": "namespace Nancy.Testing.Tests\r\n{\r\n    using System;\r\n    using System.IO;\r\n    using System.Text;\r\n    using Nancy.Configuration;\r\n    using Nancy.Json;\r\n    using Nancy.Responses;\r\n    using Nancy.Tests;\r\n    using Nancy.Xml;\r\n    using Xunit;\r\n\r\n    public class ContextExtensionsTests\r\n    {\r\n        [Fact]\r\n        public void Should_use_documentwrapper_from_context_if_it_is_present()\r\n        {\r\n            // Given\r\n            var buffer =\r\n                Encoding.UTF8.GetBytes(\"<html></html>\");\r\n\r\n            var wrapper = new DocumentWrapper(buffer);\r\n            var context = new NancyContext();\r\n            context.Items[\"@@@@DOCUMENT_WRAPPER@@@@\"] = wrapper; // Yucky hardcoded stringyness\r\n\r\n            // When\r\n            var result = context.DocumentBody();\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(wrapper);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_create_new_wrapper_from_html_response_if_not_already_present()\r\n        {\r\n            // Given\r\n            var called = false;\r\n            var bodyBytes = Encoding.ASCII.GetBytes(\"<html></html>\");\r\n            Action<Stream> bodyDelegate = (s) =>\r\n            {\r\n                s.Write(bodyBytes, 0, bodyBytes.Length);\r\n                called = true;\r\n            };\r\n            var response = new Response { Contents = bodyDelegate };\r\n            var context = new NancyContext() { Response = response };\r\n\r\n            // When\r\n            var result = context.DocumentBody();\r\n\r\n            // Then\r\n            result.ShouldBeOfType(typeof(DocumentWrapper));\r\n            called.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_jsonresponse_from_context_if_it_is_present()\r\n        {\r\n            // Given\r\n            var model = new Model() { Dummy = \"Data\" };\r\n            var context = new NancyContext();\r\n            context.Items[\"@@@@JSONRESPONSE@@@@\"] = model; // Yucky hardcoded stringyness\r\n\r\n            // When\r\n            var result = context.JsonBody<Model>();\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(model);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_create_new_wrapper_from_json_response_if_not_already_present()\r\n        {\r\n            // Given\r\n            var environment = GetTestingEnvironment();\r\n            var response = new JsonResponse<Model>(new Model() { Dummy = \"Data\" }, new DefaultJsonSerializer(environment), environment);\r\n            var context = new NancyContext() { Response = response };\r\n\r\n            // When\r\n            var result = context.JsonBody<Model>();\r\n\r\n            // Then\r\n            result.Dummy.ShouldEqual(\"Data\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_xmlresponse_from_context_if_it_is_present()\r\n        {\r\n            // Given\r\n            var model = new Model() { Dummy = \"Data\" };\r\n            var context = new NancyContext();\r\n            context.Items[\"@@@@XMLRESPONSE@@@@\"] = model; // Yucky hardcoded stringyness\r\n\r\n            var result = context.XmlBody<Model>();\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(model);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_create_new_wrapper_from_xml_response_if_not_already_present()\r\n        {\r\n            // Given\r\n            var environment = new DefaultNancyEnvironment();\r\n            environment.AddValue(XmlConfiguration.Default);\r\n            environment.Tracing(\r\n                enabled: true,\r\n                displayErrorTraces: true);\r\n\r\n            var response = new XmlResponse<Model>(new Model() { Dummy = \"Data\" }, new DefaultXmlSerializer(environment), environment);\r\n            var context = new NancyContext() { Response = response };\r\n\r\n            // When\r\n            var result = context.XmlBody<Model>();\r\n\r\n            // Then\r\n            result.Dummy.ShouldEqual(\"Data\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_fail_to_return_xml_body_on_non_xml_response()\r\n        {\r\n            // Given\r\n            var environment = GetTestingEnvironment();\r\n            var response = new JsonResponse<Model>(new Model() { Dummy = \"Data\" }, new DefaultJsonSerializer(environment), environment);\r\n            var context = new NancyContext() { Response = response };\r\n\r\n            // When\r\n            var result = Record.Exception(() => context.XmlBody<Model>());\r\n\r\n            // Then\r\n            result.ShouldNotBeNull();\r\n        }\r\n\r\n        private static INancyEnvironment GetTestingEnvironment()\r\n        {\r\n            var environment =\r\n                new DefaultNancyEnvironment();\r\n\r\n            environment.Tracing(\r\n                enabled: true,\r\n                displayErrorTraces: true);\r\n\r\n            environment.Json();\r\n            environment.Globalization(new []{\"en-US\"});\r\n\r\n            return environment;\r\n        }\r\n\r\n        public class Model\r\n        {\r\n            public string Dummy { get; set; }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Testing.Tests/DocumentWrapperTests.cs",
    "content": "namespace Nancy.Testing.Tests\r\n{\r\n    using System.Text;\r\n\r\n    using Xunit;\r\n\r\n    public class DocumentWrapperTests\r\n    {\r\n        [Fact]\r\n        public void Should_allow_byte_array_input()\r\n        {\r\n            // Given\r\n            const string input = @\"<html><head></head><body><div id='testId' class='myClass'>Test</div></body></html>\";\r\n            var buffer = Encoding.UTF8.GetBytes(input);\r\n\r\n            // When\r\n            var document = new DocumentWrapper(buffer);\r\n\r\n            // Then\r\n            Assert.NotNull(document[\"#testId\"]);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_querywrapper_when_indexer_accessed()\r\n        {\r\n            // Given\r\n            const string input = @\"<html><head></head><body><div id='testId' class='myClass'>Test</div></body></html>\";\r\n            var buffer = Encoding.UTF8.GetBytes(input);\r\n            var document = new DocumentWrapper(buffer);\r\n\r\n            // When\r\n            var result = document[\"#testId\"];\r\n\r\n            // Then\r\n            Assert.IsType<QueryWrapper>(result);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Testing.Tests/Nancy.Testing.Tests.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <TargetFrameworks>netcoreapp2.0;net452</TargetFrameworks>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <None Update=\"TestingViewExtensions\\ViewFactoryTest.sshtml\">\n      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>\n    </None>\n  </ItemGroup>\n\n  <ItemGroup>\n    <PackageReference Include=\"AngleSharp\" Version=\"0.9.8.1\" />\n  </ItemGroup>\n\n  <ItemGroup Condition=\" '$(TargetFramework)' == 'net452' \">\n    <Reference Include=\"System.Xml.Linq\" />\n    <Reference Include=\"System.Xml\" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "test/Nancy.Testing.Tests/PathHelperTests.cs",
    "content": "namespace Nancy.Testing.Tests\r\n{\r\n    using System;\r\n    using System.IO;\r\n\r\n    using Nancy.Tests;\r\n\r\n    using Xunit;\r\n\r\n    public class PathHelperTests\r\n    {\r\n        [Fact]\r\n        public void Should_return_same_path_for_zero_levels()\r\n        {\r\n            // Given\r\n            var path = Path.Combine(\"c:\", \"this\", \"this\", \"the\", \"other\", \"path\");\r\n\r\n            // When\r\n            var result = PathHelper.GetParent(path, 0);\r\n\r\n            // Then\r\n            result.ShouldEqual(path);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_go_up_correct_path_levels()\r\n        {\r\n            // Given\r\n            var path = Path.Combine(\"c:\", \"this\", \"this\", \"the\", \"other\", \"path\");\r\n            var expectedPath = Path.Combine(\"c:\", \"this\", \"this\", \"the\");\r\n            \r\n            // When\r\n            var result = PathHelper.GetParent(path, 2);\r\n\r\n            // Then\r\n            result.ShouldEqual(expectedPath);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_invalidoperationexception_if_attempting_to_go_up_beyond_root()\r\n        {\r\n            // Given\r\n            var path = Path.Combine(\"c:\", \"this\", \"this\", \"the\", \"other\", \"path\");\r\n\r\n            // When\r\n            var exception = Record.Exception(() => PathHelper.GetParent(path, 28));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<InvalidOperationException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_argumentexception_when_path_is_null()\r\n        {\r\n            // Given\r\n            string path = null;            \r\n\r\n            // When\r\n            var exception = Record.Exception(() => PathHelper.GetParent(path, 28));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ArgumentException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_argumentexception_when_path_is_empty()\r\n        {\r\n            // Given\r\n            var path = string.Empty;\r\n\r\n            // When\r\n            var exception = Record.Exception(() => PathHelper.GetParent(path, 28));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ArgumentException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_argumentexception_when_levels_is_less_than_zero()\r\n        {\r\n            // Given\r\n            var path = Path.Combine(\"c:\", \"this\", \"this\", \"the\", \"other\", \"path\");\r\n\r\n            // When\r\n            var exception = Record.Exception(() => PathHelper.GetParent(path, -10));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ArgumentException>();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Testing.Tests/QueryWrapperTests.cs",
    "content": "namespace Nancy.Testing.Tests\r\n{\r\n    using System.Linq;\r\n    using AngleSharp.Dom;\r\n    using AngleSharp.Parser.Html;\r\n    using Xunit;\r\n\r\n    public class QueryWrapperTests\r\n    {\r\n        private readonly HtmlParser parser;\r\n\r\n        public QueryWrapperTests()\r\n        {\r\n            this.parser = new HtmlParser();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_cq_find_when_indexer_invoked()\r\n        {\r\n            // Given\r\n            var document =\r\n                this.parser.Parse(@\"<html><head></head><body><div id='testId' class='myClass'>Test</div></body></html>\");\r\n\r\n            var queryResult =\r\n                document.QuerySelectorAll(\"#testId\").FirstOrDefault();\r\n\r\n            var wrapper =\r\n                new QueryWrapper(new[] { document.DocumentElement });\r\n\r\n            // When\r\n            var result = wrapper[\"#testId\"].FirstOrDefault();\r\n\r\n            // Then\r\n            Assert.NotNull(result);\r\n            Assert.Equal(queryResult.InnerHtml, result.InnerText);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_filter_selection_when_second_indexer_invoked()\r\n        {\r\n            // Given\r\n            var document =\r\n                this.parser.Parse(@\"<html><head></head><body><table><tr><td></td><td></td></tr><tr><td></td><td></td></tr></table></body></html>\");\r\n\r\n            var wrapper = new QueryWrapper(new[] { document.DocumentElement });\r\n\r\n            var row = wrapper[\"tr:first-child\"];\r\n\r\n            // When\r\n            var cells = row[\"td\"];\r\n\r\n            // Then\r\n            Assert.NotNull(cells);\r\n            Assert.Equal(2, cells.Count());\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Testing.Tests/TestingViewExtensions/GetModelExtententionsTests.cs",
    "content": "namespace Nancy.Testing.Tests.TestingViewExtensions\r\n{\r\n    using System.Threading.Tasks;\r\n    using Xunit;\r\n\r\n    public class GetModelExtententionsTests\r\n    {\r\n        private readonly Browser _browser;\r\n\r\n        public GetModelExtententionsTests()\r\n        {\r\n            this._browser = new Browser(with =>\r\n            {\r\n                with.Module<TestingViewFactoryTestModule>();\r\n                with.ViewFactory<TestingViewFactory>();\r\n            });\r\n\r\n        }\r\n        [Fact]\r\n        public async Task should_return_null_when_model_is_not_set()\r\n        {\r\n            var response = await this._browser.Get(\"/testingViewFactoryNoModel\");\r\n            Assert.Null(response.GetModel<ViewFactoryTestModel>());\r\n        }\r\n        \r\n        [Fact]\r\n        public async Task should_not_return_null_when_model_is_set()\r\n        {\r\n            var response = await this._browser.Get(\"/testingViewFactory\");\r\n            Assert.NotNull(response.GetModel<ViewFactoryTestModel>());\r\n        }\r\n        \r\n        [Fact]\r\n        public async Task should_return_model_of_correct_type()\r\n        {\r\n            var response = await this._browser.Get(\"/testingViewFactory\");            \r\n            Assert.IsType<ViewFactoryTestModel>(response.GetModel<ViewFactoryTestModel>());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task should_set_values_correct_on_the_model()\r\n        {\r\n            var response = await this._browser.Get(\"/testingViewFactory\");\r\n            var model = response.GetModel<ViewFactoryTestModel>();\r\n            Assert.Equal(\"A value\", model.AString);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task should_set_values_correct_on_a_complex_model()\r\n        {\r\n            var response = await this._browser.Get(\"/testingViewFactory\");\r\n            var model = response.GetModel<ViewFactoryTestModel>();\r\n            Assert.Equal(\"Another value\", model.ComplexModel.AnotherString);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Testing.Tests/TestingViewExtensions/GetModuleNameExtensionTests.cs",
    "content": "﻿namespace Nancy.Testing.Tests.TestingViewExtensions\r\n{\r\n    using System.Threading.Tasks;\r\n    using Xunit;\r\n\r\n    public class GetModuleNameExtensionTests\r\n    {\r\n        private readonly Browser browser;\r\n\r\n        public GetModuleNameExtensionTests()\r\n        {\r\n            this.browser = new Browser(with =>\r\n            {\r\n                with.Module<TestingViewFactoryTestModule>();\r\n                with.ViewFactory<TestingViewFactory>();\r\n            });\r\n        }\r\n\r\n        [Fact]\r\n        public async Task should_return_name_of_the_module()\r\n        {\r\n            var response = await this.browser.Get(\"/testingViewFactory\");\r\n            Assert.Equal(\"TestingViewFactoryTest\", response.GetModuleName());\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Testing.Tests/TestingViewExtensions/GetModulePathExtensionMethodTests.cs",
    "content": "namespace Nancy.Testing.Tests.TestingViewExtensions\r\n{\r\n    using System.Threading.Tasks;\r\n    using Xunit;\r\n\r\n    public class GetModulePathExtensionMethodTests\r\n    {\r\n        [Fact]\r\n        public async Task should_get_the_module_path_for_modules_with_module_path()\r\n        {\r\n            // Arrange\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.Module<TestModuleWithLongModulePath>();\r\n                with.ViewFactory<TestingViewFactory>();\r\n            });\r\n\r\n            // Act\r\n            var response = await browser.Get(\"/a/long/path/getModulePath\");\r\n\r\n            // Assert\r\n            Assert.Equal(\"/a/long/path\", response.GetModulePath());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task GetModule_should_get_empty_string_for_module_with_no_module_path_set()\r\n        {\r\n            // Arrange\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.Module<TestModuleWithLongModulePath>();\r\n                with.ViewFactory<TestingViewFactory>();\r\n            });\r\n\r\n            // Act\r\n            var response = await browser.Get(\"/getModulePath\");\r\n\r\n            // Assert\r\n            Assert.Equal(\"\", response.GetModulePath());\r\n        }\r\n\r\n        internal class TestModuleWithLongModulePath : NancyModule\r\n        {\r\n            public TestModuleWithLongModulePath()\r\n                : base(\"/a/long/path\")\r\n            {\r\n                Get(\"/getModulePath\", args => this.View[\"TestingViewExtensions/ViewFactoryTest.sshtml\"]);\r\n            }\r\n        }\r\n\r\n        internal class ModuleWithoutModulePath : NancyModule\r\n        {\r\n            public ModuleWithoutModulePath()\r\n            {\r\n                Get(\"/getModulePath\", args => this.View[\"TestingViewExtensions/ViewFactoryTest.sshtml\"]);\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Testing.Tests/TestingViewExtensions/GetViewNameExtensionTests.cs",
    "content": "﻿namespace Nancy.Testing.Tests.TestingViewExtensions\r\n{\r\n    using System.Threading.Tasks;\r\n    using Xunit;\r\n\r\n    public class GetViewNameExtensionTests\r\n    {\r\n        private readonly Browser browser;\r\n\r\n        public GetViewNameExtensionTests()\r\n        {\r\n            this.browser = new Browser(with =>\r\n            {\r\n                with.Module<TestingViewFactoryTestModule>();\r\n                with.ViewFactory<TestingViewFactory>();\r\n            });\r\n        }\r\n\r\n        [Fact]\r\n        public async Task should_return_name_of_the_view_for_routes_with_view()\r\n        {\r\n            var response = await this.browser.Get(\"/testingViewFactory\");\r\n            Assert.Equal(\"TestingViewExtensions/ViewFactoryTest.sshtml\", response.GetViewName());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task should_return_empty_string_for_routes_without_view()\r\n        {\r\n            var response = await this.browser.Get(\"/testingViewFactoryNoViewName\", \r\n                with => with.Accept(\"application/json\"));\r\n            Assert.Equal(string.Empty, response.GetViewName());\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Testing.Tests/TestingViewExtensions/TestingViewFactoryTestModule.cs",
    "content": "﻿namespace Nancy.Testing.Tests.TestingViewExtensions\r\n{\r\n    public class TestingViewFactoryTestModule : NancyModule\r\n    {\r\n        private const string VIEW_PATH = \"TestingViewExtensions/ViewFactoryTest.sshtml\";\r\n\r\n        public TestingViewFactoryTestModule()\r\n        {\r\n            Get(\"/testingViewFactoryNoModel\", args => this.View[VIEW_PATH]);\r\n            Get(\"/testingViewFactory\", args => this.View[VIEW_PATH, GetModel()]);\r\n            Get(\"/testingViewFactoryNoViewName\", args => { return GetModel(); });\r\n        }\r\n\r\n        private static ViewFactoryTestModel GetModel()\r\n        {\r\n            return new ViewFactoryTestModel\r\n            {\r\n                AString = \"A value\",\r\n                ComplexModel = new CompositeTestModel { AnotherString = \"Another value\" }\r\n            };\r\n        }\r\n    }\r\n\r\n    public class ViewFactoryTestModel\r\n    {\r\n        public string AString { get; set; }\r\n        public CompositeTestModel ComplexModel { get; set; }\r\n    }\r\n\r\n    public class CompositeTestModel\r\n    {\r\n        public string AnotherString { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Testing.Tests/TestingViewExtensions/ViewFactoryTest.sshtml",
    "content": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n    <title>Super Simple View Engine</title>\r\n</head>\r\n<body>\r\n<h1>Super Simple View Engine</h1>\r\n<p>Hello @Model.AString!<p>\r\n</body>\r\n</html>\r\n"
  },
  {
    "path": "test/Nancy.Tests/Extensions/ResponseExtensions.cs",
    "content": "namespace Nancy.Tests.Extensions\r\n{\r\n    using System.IO;\r\n\r\n    public static class ResponseExtensions\r\n    {\r\n        public static string GetStringContentsFromResponse(this Response response)\r\n        {\r\n            var memory = new MemoryStream();\r\n            response.Contents.Invoke(memory);\r\n            memory.Position = 0;\r\n            using (var reader = new StreamReader(memory))\r\n            {\r\n                return reader.ReadToEnd();\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Fakes/FakeDefaultNancyBootstrapper.cs",
    "content": "﻿namespace Nancy.Tests.Fakes\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.ErrorHandling;\r\n    using Nancy.TinyIoc;\r\n\r\n    public class FakeDefaultNancyBootstrapper : DefaultNancyBootstrapper\r\n    {\r\n        public IEnumerable<Type> OverriddenRegistrationTasks { get; set; }\r\n\r\n        private Func<ITypeCatalog, NancyInternalConfiguration> configuration;\r\n\r\n        protected override IEnumerable<ModuleRegistration> Modules\r\n        {\r\n            get\r\n            {\r\n                return new[] { new ModuleRegistration(typeof(FakeNancyModuleWithoutBasePath)) };\r\n            }\r\n        }\r\n        public FakeDefaultNancyBootstrapper()\r\n            : this(NancyInternalConfiguration.WithOverrides(b => b.StatusCodeHandlers = new List<Type>(new[] { typeof(DefaultStatusCodeHandler) })))\r\n        {\r\n\r\n        }\r\n\r\n        protected override IEnumerable<Type> RegistrationTasks\r\n        {\r\n            get\r\n            {\r\n                return this.OverriddenRegistrationTasks ?? base.RegistrationTasks;\r\n            }\r\n        }\r\n\r\n        protected override IEnumerable<Func<Assembly, bool>> AutoRegisterIgnoredAssemblies\r\n        {\r\n            get\r\n            {\r\n                return base.AutoRegisterIgnoredAssemblies.Union(new Func<Assembly, bool>[] { asm => asm.FullName.StartsWith(\"TestAssembly\") });\r\n            }\r\n        }\r\n        public FakeDefaultNancyBootstrapper(Func<ITypeCatalog, NancyInternalConfiguration> configuration)\r\n        {\r\n            this.configuration = configuration;\r\n            this.RequestContainerInitialisations = new Dictionary<NancyContext, int>();\r\n        }\r\n\r\n        protected override Func<ITypeCatalog, NancyInternalConfiguration> InternalConfiguration\r\n        {\r\n            get { return configuration; }\r\n        }\r\n\r\n        public IDictionary<NancyContext, int> RequestContainerInitialisations { get; private set; }\r\n\r\n        public bool ApplicationContainerConfigured { get; set; }\r\n\r\n        public TinyIoCContainer Container { get { return this.ApplicationContainer; } }\r\n\r\n        public Request ConfigureRequestContainerLastRequest { get; set; }\r\n\r\n        public Request RequestStartupLastRequest { get; set; }\r\n\r\n        protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)\r\n        {\r\n            base.RequestStartup(container, pipelines, context);\r\n\r\n            this.RequestStartupLastRequest = context.Request;\r\n        }\r\n\r\n        protected override void ConfigureRequestContainer(TinyIoCContainer existingContainer, NancyContext context)\r\n        {\r\n            base.ConfigureRequestContainer(existingContainer, context);\r\n\r\n            this.ConfigureRequestContainerLastRequest = context.Request;\r\n\r\n            this.AddRequestContainerInitialisation(context);\r\n\r\n            existingContainer.Register<IFoo, Foo>().AsSingleton();\r\n            existingContainer.Register<IDependency, Dependency>().AsSingleton();\r\n        }\r\n\r\n        private void AddRequestContainerInitialisation(NancyContext context)\r\n        {\r\n            if (!this.RequestContainerInitialisations.ContainsKey(context))\r\n            {\r\n                this.RequestContainerInitialisations.Add(context, 1);\r\n                return;\r\n            }\r\n\r\n            this.RequestContainerInitialisations[context] = this.RequestContainerInitialisations[context] + 1;\r\n        }\r\n\r\n        protected override void ConfigureApplicationContainer(TinyIoCContainer existingContainer)\r\n        {\r\n            ApplicationContainerConfigured = true;\r\n            base.ConfigureApplicationContainer(existingContainer);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Fakes/FakeHookedModule.cs",
    "content": "namespace Nancy.Tests.Fakes\r\n{\r\n    public class FakeHookedModule : NancyModule\r\n    {\r\n        public FakeHookedModule(BeforePipeline before = null, AfterPipeline after = null)\r\n        {\r\n            this.Before = before;\r\n            this.After = after;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Fakes/FakeModuleCatalog.cs",
    "content": "namespace Nancy.Tests.Fakes\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    public class FakeModuleCatalog : INancyModuleCatalog\r\n    {\r\n        private Dictionary<Type, INancyModule> modules;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the FakeModuleCatalog class.\r\n        /// </summary>\r\n        public FakeModuleCatalog()\r\n        {\r\n            this.modules = new Dictionary<Type, INancyModule>() { { typeof(FakeNancyModuleWithBasePath), new FakeNancyModuleWithBasePath() }, { typeof(FakeNancyModuleWithoutBasePath), new FakeNancyModuleWithoutBasePath() } };\r\n        }\r\n\r\n        public IEnumerable<INancyModule> GetAllModules(NancyContext context)\r\n        {\r\n            return this.modules.Values.AsEnumerable();\r\n        }\r\n\r\n        public INancyModule GetModule(Type moduleType, NancyContext context)\r\n        {\r\n            return this.modules[moduleType];\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Fakes/FakeNancyModule.cs",
    "content": "﻿namespace Nancy.Tests.Fakes\r\n{\r\n    using System;\r\n\r\n    public class FakeNancyModule : NancyModule\r\n    {\r\n        public FakeNancyModule()\r\n        {\r\n        }\r\n\r\n        public FakeNancyModule(Action<FakeNancyModuleConfigurator> closure)\r\n        {\r\n            var configurator =\r\n                new FakeNancyModuleConfigurator(this);\r\n\r\n            closure.Invoke(configurator);\r\n        }\r\n\r\n        public class FakeNancyModuleConfigurator\r\n        {\r\n            private readonly NancyModule module;\r\n\r\n            public FakeNancyModuleConfigurator(NancyModule module)\r\n            {\r\n                this.module = module;\r\n            }\r\n\r\n            public FakeNancyModuleConfigurator AddDeleteRoute(string path)\r\n            {\r\n                this.module.Delete(path, args => {\r\n                    return HttpStatusCode.OK;\r\n                });\r\n\r\n                return this;\r\n            }\r\n\r\n            public FakeNancyModuleConfigurator AddGetRoute(string path)\r\n            {\r\n                return this.AddGetRoute(path, x => HttpStatusCode.OK);\r\n            }\r\n\r\n            public FakeNancyModuleConfigurator AddGetRoute(string path, Func<object, Response> action)\r\n            {\r\n                this.module.Get(path, args =>\r\n                {\r\n                    return action.Invoke(args);\r\n                });\r\n\r\n                return this;\r\n            }\r\n\r\n            public FakeNancyModuleConfigurator AddPostRoute(string path)\r\n            {\r\n                this.module.Post(path, args => {\r\n                    return HttpStatusCode.OK;\r\n                });\r\n\r\n                return this;\r\n            }\r\n\r\n            public FakeNancyModuleConfigurator AddPutRoute(string path)\r\n            {\r\n                this.module.Put(path, args => {\r\n                    return HttpStatusCode.OK;\r\n                });\r\n\r\n                return this;\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Fakes/FakeNancyModuleNoRoutes.cs",
    "content": "﻿namespace Nancy.Tests.Fakes\r\n{\r\n    public class FakeNancyModuleNoRoutes : NancyModule\r\n    {\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Fakes/FakeNancyModuleWithBasePath.cs",
    "content": "namespace Nancy.Tests.Fakes\r\n{\r\n    using System;\r\n\r\n    public class FakeNancyModuleWithBasePath : NancyModule\r\n    {\r\n        public FakeNancyModuleWithBasePath() : base(\"/fake\")\r\n        {\r\n            Delete(\"/\", args => {\r\n                throw new NotImplementedException();\r\n                return 500;\r\n            });\r\n\r\n            Get(\"/route/with/some/parts\", args => {\r\n                return \"FakeNancyModuleWithBasePath\";\r\n            });\r\n\r\n            Get(\"/should/have/conflicting/route/defined\", args => {\r\n                return \"FakeNancyModuleWithBasePath\";\r\n            });\r\n\r\n            Get<object>(\"/child/{value}\", args => {\r\n                throw new NotImplementedException();\r\n                return 500;\r\n            });\r\n\r\n            Get(\"/child/route/{value}\", args => {\r\n                return \"test\";\r\n                return 500;\r\n            });\r\n\r\n            Get(\"/\", args => {\r\n                throw new NotImplementedException();\r\n                return 500;\r\n            });\r\n\r\n            Get(\"/foo/{value}/bar/{capture}\", args => {\r\n                return string.Concat(args.value, \" \", args.capture);\r\n            });\r\n\r\n            Post(\"/\", args => {\r\n                return \"Action result\";\r\n            });\r\n\r\n            Put(\"/\", args => {\r\n                throw new NotImplementedException();\r\n                return 500;\r\n            });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Fakes/FakeNancyModuleWithDependency.cs",
    "content": "﻿namespace Nancy.Tests.Fakes\r\n{\r\n    public interface IFoo\r\n    {\r\n    }\r\n\r\n    public class Foo : IFoo\r\n    {\r\n    }\r\n\r\n    public interface IDependency\r\n    {\r\n        IFoo FooDependency { get; set; }\r\n    }\r\n\r\n    public class Dependency : IDependency\r\n    {\r\n        public IFoo FooDependency { get; set; }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the Dependency class.\r\n        /// </summary>\r\n        public Dependency(IFoo fooDependency)\r\n        {\r\n            FooDependency = fooDependency;\r\n        }\r\n    }\r\n\r\n    public class FakeNancyModuleWithDependency : NancyModule\r\n    {\r\n        public IDependency Dependency { get; set; }\r\n        public IFoo FooDependency { get; set; }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the FakeNancyModuleWithDependency class.\r\n        /// </summary>\r\n        public FakeNancyModuleWithDependency(IDependency dependency, IFoo foo)\r\n        {\r\n            Dependency = dependency;\r\n            FooDependency = foo;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Fakes/FakeNancyModuleWithPreAndPostHooks.cs",
    "content": "﻿namespace Nancy.Tests.Fakes\r\n{\r\n    public class FakeNancyModuleWithPreAndPostHooks : NancyModule\r\n    {\r\n        public FakeNancyModuleWithPreAndPostHooks()\r\n        {\r\n            this.Before += (c) => null;\r\n            this.After += (c) => { };\r\n\r\n            Get(\"/PrePost\", args =>\r\n            {\r\n                return new Response();\r\n            });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Fakes/FakeNancyModuleWithoutBasePath.cs",
    "content": "﻿namespace Nancy.Tests.Fakes\r\n{\r\n    public class FakeNancyModuleWithoutBasePath : NancyModule\r\n    {\r\n        public FakeNancyModuleWithoutBasePath()\r\n        {\r\n            Delete(\"/\", args => {\r\n                return \"Default delete root\";\r\n            });\r\n\r\n            Get(\"/\", args => {\r\n                return \"Default get root\";\r\n            });\r\n\r\n            Get(\"/fake/should/have/conflicting/route/defined\", args => {\r\n                return \"FakeNancyModuleWithoutBasePath\";\r\n            });\r\n\r\n            Get(\"/greet/{name}\", args =>\r\n            {\r\n                return string.Concat(\"Hello \", args.name);\r\n            });\r\n\r\n            Get(\"/filtered\",\r\n                condition: req => false,\r\n                action: args =>\r\n                {\r\n                    return \"I should never be run because I am filtered\";\r\n                });\r\n\r\n            Get(\"/notfiltered\",\r\n                condition: req => true,\r\n                action: args =>\r\n                {\r\n                    return \"I should always be fine because my filter returns true\";\r\n                });\r\n\r\n            Post(\"/\", args => {\r\n                return \"Default post root\";\r\n            });\r\n\r\n            Put(\"/\", args => {\r\n                return \"Default put root\";\r\n            });\r\n\r\n            Get(\"/filt\",\r\n                condition: req => false,\r\n                action: args =>\r\n                {\r\n                    return \"false\";\r\n                });\r\n\r\n            Get(\"/filt\",\r\n                condition: req => true,\r\n                action: args =>\r\n                {\r\n                    return \"true\";\r\n                });\r\n\r\n            Get(\"/filt\",\r\n                condition: req => false,\r\n                action: args =>\r\n                {\r\n                    return \"false\";\r\n                });\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Fakes/FakeObjectSerializer.cs",
    "content": "namespace Nancy.Tests.Fakes\r\n{\r\n    public class FakeObjectSerializer : IObjectSerializer\r\n    {\r\n        /// <summary>\r\n        /// Serialize an object\r\n        /// </summary>\r\n        /// <param name=\"sourceObject\">Source object</param>\r\n        /// <returns>Serialised object string</returns>\r\n        public string Serialize(object sourceObject)\r\n        {\r\n            return sourceObject.ToString();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Deserialize an object string\r\n        /// </summary>\r\n        /// <param name=\"sourceString\">Source object string</param>\r\n        /// <returns>Deserialized object</returns>\r\n        public object Deserialize(string sourceString)\r\n        {\r\n            return sourceString;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Fakes/FakeRequest.cs",
    "content": "﻿namespace Nancy.Tests.Fakes\r\n{\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n\r\n    using Nancy.IO;\r\n\r\n    public class FakeRequest : Request\r\n    {\r\n        public FakeRequest(string method, string path)\r\n            : this(method, path, new Dictionary<string, IEnumerable<string>>(), RequestStream.FromStream(new MemoryStream()), \"http\", string.Empty)\r\n        {\r\n        }\r\n\r\n        public FakeRequest(string method, string path, IDictionary<string, IEnumerable<string>> headers)\r\n            : this(method, path, headers, RequestStream.FromStream(new MemoryStream()), \"http\", string.Empty)\r\n        {\r\n        }\r\n\r\n        public FakeRequest(string method, string path, string query, string userHostAddress = null)\r\n            : this(method, path, new Dictionary<string, IEnumerable<string>>(), RequestStream.FromStream(new MemoryStream()), \"http\", query, userHostAddress)\r\n        {\r\n        }\r\n\r\n        public FakeRequest(string method, string path, IDictionary<string, IEnumerable<string>> headers, RequestStream body, string protocol, string query, string userHostAddress = null)\r\n            : base(method, new Url { Path = path, Query = query, Scheme = protocol }, body, headers, ip: userHostAddress)\r\n        {\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Fakes/FakeRoute.cs",
    "content": "namespace Nancy.Tests.Fakes\r\n{\r\n    using System;\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Routing;\r\n\r\n    public class FakeRoute : Route<object>\r\n    {\r\n        public bool ActionWasInvoked;\r\n        public DynamicDictionary ParametersUsedToInvokeAction;\r\n\r\n        public FakeRoute()\r\n            : this(new Response())\r\n        {\r\n        }\r\n\r\n        public FakeRoute(object response)\r\n            : base(\"GET\", \"/\", null, (args, ct) => null)\r\n        {\r\n            this.Action = (parameters, token) =>\r\n            {\r\n                this.ActionWasInvoked = true;\r\n                this.ParametersUsedToInvokeAction = (DynamicDictionary)parameters;\r\n                return Task.FromResult(response);\r\n            };\r\n        }\r\n\r\n        public FakeRoute(Func<object, CancellationToken, Task<object>> action)\r\n            : base(\"GET\", \"/\", null, (args, ct) => null)\r\n        {\r\n            this.Action = (parameters, token) =>\r\n            {\r\n                this.ActionWasInvoked = true;\r\n                this.ParametersUsedToInvokeAction = (DynamicDictionary)parameters;\r\n                return action.Invoke(parameters, token);\r\n            };\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Fakes/FakeRouteCache.cs",
    "content": "﻿namespace Nancy.Tests.Fakes\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    using Nancy.Routing;\r\n\r\n    public class FakeRouteCache : Dictionary<Type, List<Tuple<int, RouteDescription>>>, IRouteCache\r\n    {\r\n        public static FakeRouteCache Empty = new FakeRouteCache();\r\n\r\n        public FakeRouteCache()\r\n        {\r\n        }\r\n\r\n        public FakeRouteCache(Action<FakeRouteCacheConfigurator> closure)\r\n        {\r\n            var configurator =\r\n                new FakeRouteCacheConfigurator(this);\r\n\r\n            closure.Invoke(configurator);\r\n        }\r\n\r\n        public bool IsEmpty()\r\n        {\r\n            return false;\r\n        }\r\n\r\n        public class FakeRouteCacheConfigurator\r\n        {\r\n            private readonly FakeRouteCache routeCache;\r\n\r\n            public FakeRouteCacheConfigurator(FakeRouteCache routeCache)\r\n            {\r\n                this.routeCache = routeCache;\r\n            }\r\n\r\n            private void AddRoutesToCache(IEnumerable<RouteDescription> routes, Type moduleType)\r\n            {\r\n                if (!this.routeCache.ContainsKey(moduleType))\r\n                {\r\n                    this.routeCache[moduleType] = new List<Tuple<int, RouteDescription>>();\r\n                }\r\n\r\n                this.routeCache[moduleType].AddRange(routes.Select((r, i) => new Tuple<int, RouteDescription>(i, r)));\r\n            }\r\n\r\n            public FakeRouteCacheConfigurator AddGetRoute(string path, Type moduleType)\r\n            {\r\n                this.AddRoutesToCache(new[] { new RouteDescription(string.Empty, \"GET\", path, null, typeof(object)) }, moduleType);\r\n\r\n                return this;\r\n            }\r\n\r\n            public FakeRouteCacheConfigurator AddGetRoute(string path, Type moduleType, Func<NancyContext, bool> condition)\r\n            {\r\n                this.AddRoutesToCache(new[] { new RouteDescription(string.Empty, \"GET\", path, condition, typeof(object)) }, moduleType);\r\n\r\n                return this;\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Fakes/FakeRouteResolver.cs",
    "content": "namespace Nancy.Tests.Fakes\r\n{\r\n    using Nancy.Routing;\r\n\r\n    public class FakeRouteResolver : IRouteResolver\r\n    {\r\n        public string Path { get; private set; }\r\n\r\n        public string ModulePath { get; private set; }\r\n\r\n        ResolveResult IRouteResolver.Resolve(NancyContext context)\r\n        {\r\n            return new ResolveResult\r\n            {\r\n                Route = new FakeRoute(), \r\n                Parameters = new DynamicDictionary(), \r\n                Before = null, \r\n                After = null, \r\n                OnError = null\r\n            };\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Fakes/FakeViewEngine.cs",
    "content": "﻿namespace Nancy.Tests.Fakes\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using Nancy.Responses;\r\n    using Nancy.ViewEngines;\r\n\r\n    public class FakeViewEngine : IViewEngine\r\n    {\r\n        public FakeViewEngine()\r\n        {\r\n            this.Extensions = new[] { \"html \" };\r\n        }\r\n\r\n        public IEnumerable<string> Extensions { get; set; }\r\n\r\n        public dynamic Model { get; set; }\r\n\r\n        public void Initialize(ViewEngineStartupContext viewEngineStartupContext)\r\n        {\r\n        }\r\n\r\n        public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)\r\n        {\r\n            this.Model = model;\r\n            return new HtmlResponse();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Fakes/FakeViewEngineHost.cs",
    "content": "namespace Nancy.Tests.Fakes\r\n{\r\n    using System;\r\n\r\n    using Nancy.ViewEngines.SuperSimpleViewEngine;\r\n\r\n    public class FakeViewEngineHost : IViewEngineHost\r\n    {\r\n        public Func<string, object, string> GetTemplateCallback { get; set; }\r\n        public Func<string, string> ExpandPathCallBack { get; set; }\r\n\r\n        public FakeViewEngineHost()\r\n        {\r\n            this.Context = new FakeContext {Name = \"Frank\" };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Html \"safe\" encode a string\r\n        /// </summary>\r\n        /// <param name=\"input\">Input string</param>\r\n        /// <returns>Encoded string</returns>\r\n        public string HtmlEncode(string input)\r\n        {\r\n            return input.Replace(\"&\", \"&amp;\").\r\n                Replace(\"<\", \"&lt;\").\r\n                Replace(\">\", \"&gt;\").\r\n                Replace(\"\\\"\", \"&quot;\");\r\n        }\r\n\r\n        public class FakeContext\r\n        {\r\n            public dynamic ViewBag { get; private set; }\r\n\r\n            public FakeContext()\r\n            {\r\n                ViewBag = new DynamicDictionary();\r\n                this.User = new FakeUser { Username = \"Frank123\" };\r\n            }\r\n\r\n            public string Name { get; set; }\r\n\r\n            public FakeUser User { get; set; }\r\n\r\n            public class FakeUser\r\n            {\r\n                public string Username { get; set; }\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Context object of the host application.\r\n        /// </summary>\r\n        /// <value>An instance of the context object from the host.</value>\r\n        public object Context { get; set; }\r\n\r\n        /// <summary>\r\n        /// Get the contenst of a template\r\n        /// </summary>\r\n        /// <param name=\"templateName\">Name/location of the template</param>\r\n        /// <param name=\"model\">Model to use to locate the template via conventions</param>\r\n        /// <returns>Contents of the template, or null if not found</returns>\r\n        public string GetTemplate(string templateName, object model)\r\n        {\r\n            return this.GetTemplateCallback != null ? this.GetTemplateCallback.Invoke(templateName, model) : string.Empty;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets a uri string for a named route\r\n        /// </summary>\r\n        /// <param name=\"name\">Named route name</param>\r\n        /// <param name=\"parameters\">Parameters to use to expand the uri string</param>\r\n        /// <returns>Expanded uri string, or null if not found</returns>\r\n        public string GetUriString(string name, params string[] parameters)\r\n        {\r\n            throw new NotImplementedException();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Expands a path to include any base paths\r\n        /// </summary>\r\n        /// <param name=\"path\">Path to expand</param>\r\n        /// <returns>Expanded path</returns>\r\n        public string ExpandPath(string path)\r\n        {\r\n            return this.ExpandPathCallBack != null ? this.ExpandPathCallBack.Invoke(path) : path;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get the anti forgery token form element\r\n        /// </summary>\r\n        /// <returns>String containin the form element</returns>\r\n        public string AntiForgeryToken()\r\n        {\r\n            return \"CSRF\";\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Fakes/MockPipelines.cs",
    "content": "﻿namespace Nancy.Tests.Fakes\r\n{\r\n    using Nancy.Bootstrapper;\r\n\r\n    public class MockPipelines : IPipelines\r\n    {\r\n        public BeforePipeline BeforeRequest { get; set; }\r\n\r\n        public AfterPipeline AfterRequest { get; set; }\r\n\r\n        public ErrorPipeline OnError { get; set; }\r\n\r\n        public MockPipelines()\r\n        {\r\n            this.BeforeRequest = new BeforePipeline();\r\n            this.AfterRequest = new AfterPipeline();\r\n            this.OnError = new ErrorPipeline();\r\n        }\r\n    }\r\n\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Fakes/Person.cs",
    "content": "﻿namespace Nancy.Tests.Fakes\r\n{\r\n    public class Person\r\n    {\r\n        public string FirstName { get; set; }\r\n        public string LastName { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Fakes/PersonWithAgeField.cs",
    "content": "﻿namespace Nancy.Tests.Fakes\r\n{\r\n    public class PersonWithAgeField : Person\r\n    {\r\n        public int Age;\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Fakes/StructModel.cs",
    "content": "﻿namespace Nancy.Tests.Fakes\r\n{\r\n    public struct StructModel\r\n    {\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Fakes/ViewModel.cs",
    "content": "namespace Nancy.Tests.Fakes\r\n{\r\n    public class ViewModel\r\n    {\r\n        \r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Helpers/AssemblyHelpers.cs",
    "content": "﻿namespace Nancy.Tests.Helpers\r\n{\r\n    using System.IO;\r\n    using System.Reflection;\r\n\r\n#if CORE\r\n    using System.Runtime.Loader;\r\n#endif\r\n\r\n    /// <summary>\r\n    /// Convenience class with helper methods for <see cref=\"Assembly\"/>.\r\n    /// </summary>\r\n    public static class AssemblyHelpers\r\n    {\r\n        /// <summary>\r\n        /// Loads an assembly from the emitted image contained in <paramref name=\"stream\"/>.\r\n        /// </summary>\r\n        /// <param name=\"stream\">The steam that contains the emitted assembly.</param>\r\n        /// <returns>The loaded assembly.</returns>\r\n        public static Assembly Load(MemoryStream stream)\r\n        {\r\n#if CORE\r\n            stream.Position = 0;\r\n            return AssemblyLoadContext.Default.LoadFromStream(stream);\r\n#else\r\n            return Assembly.Load(stream.ToArray());\r\n#endif\r\n\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Helpers/CacheHelpersFixture.cs",
    "content": "﻿namespace Nancy.Tests.Helpers\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Globalization;\r\n\r\n    using Nancy.Helpers;\r\n\r\n    using Xunit;\r\n\r\n    public class CacheHelpersFixture\r\n    {\r\n        private string etag;\r\n\r\n        private DateTime lastModified;\r\n\r\n        public CacheHelpersFixture()\r\n        {\r\n            this.etag = \"etag\";\r\n            this.lastModified = DateTime.Now;\r\n        }\r\n        \r\n        [Fact]\r\n        public void Should_return_modified_false_if_no_etag_and_no_ifmodifiedsince_sent()\r\n        {\r\n            var context = this.GetContext(null, null);\r\n\r\n            var result = CacheHelpers.ReturnNotModified(this.etag, this.lastModified, context);\r\n\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_with_differe_etag()\r\n        {\r\n            var context = this.GetContext(\"moo\", null);\r\n\r\n            var result = CacheHelpers.ReturnNotModified(this.etag, this.lastModified, context);\r\n\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_with_same_etag()\r\n        {\r\n            var context = this.GetContext(this.etag, null);\r\n\r\n            var result = CacheHelpers.ReturnNotModified(this.etag, this.lastModified, context);\r\n\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_with_date_in_the_past()\r\n        {\r\n            var context = this.GetContext(null, this.lastModified.AddMinutes(-1));\r\n\r\n            var result = CacheHelpers.ReturnNotModified(this.etag, this.lastModified, context);\r\n\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_with_date_in_future()\r\n        {\r\n            var context = this.GetContext(null, this.lastModified.AddHours(1));\r\n\r\n            var result = CacheHelpers.ReturnNotModified(this.etag, this.lastModified, context);\r\n\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        private NancyContext GetContext(string etag, DateTime? lastModified)\r\n        {\r\n            var headers = new Dictionary<string, IEnumerable<string>>();\r\n            if (!string.IsNullOrEmpty(etag))\r\n            {\r\n                headers[\"If-None-Match\"] = new[] { etag };\r\n            }\r\n            if (lastModified.HasValue)\r\n            {\r\n                headers[\"If-Modified-Since\"] = new[] { lastModified.Value.ToString(\"R\", CultureInfo.InvariantCulture) };\r\n            }\r\n\r\n            var request = new Request(\"GET\", new Url { Path = \"/\", Scheme = \"http\" }, headers: headers);\r\n\r\n            var context = new NancyContext { Request = request };\r\n\r\n            return context;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Helpers/ExceptionExtensionsFixture.cs",
    "content": "﻿namespace Nancy.Tests.Helpers\r\n{\r\n    using System;\r\n    using Nancy.Helpers;\r\n    using Xunit;\r\n\r\n    public class ExceptionExtensionsFixture\r\n    {\r\n        [Fact]\r\n        public void Should_return_exception_if_not_aggregate_exception()\r\n        {\r\n            var exception = new Exception(\"Not an aggregate exception.\", new Exception(\"Inner exception.\"));\r\n            var result = exception.FlattenInnerExceptions();\r\n\r\n            Assert.Equal(exception, result);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_flatten_aggregate_exceptions()\r\n        {\r\n            var exception1 = new Exception(\"Exception 1\", new Exception(\"Inner exception of exception 1\"));\r\n            var exception2 = new Exception(\"Exception 2\", new Exception(\"Inner exception of exception 2\"));\r\n            var exception3 = new Exception(\"Exception 3\", new Exception(\"Inner exception of exception 3\"));\r\n            \r\n            // Aggregate exceptions nested three levels deep.\r\n            var aggregate3 = new AggregateException(exception3);\r\n            var aggregate2 = new AggregateException(aggregate3, exception2);\r\n            var aggregate1 = new AggregateException(aggregate2, exception1);\r\n\r\n            var result = aggregate1.FlattenInnerExceptions();\r\n\r\n            Assert.IsType<AggregateException>(result);\r\n\r\n            // Only the inner exceptions of any aggregates should be returned. The inner exception\r\n            // of a non-aggregate should not be flattened.\r\n            var innerExceptions = ((AggregateException)result).InnerExceptions;\r\n            var expectedExceptions = new[] { exception1, exception2, exception3 };\r\n\r\n            Assert.Equal(3, innerExceptions.Count);\r\n\r\n            foreach (var exception in expectedExceptions)\r\n                Assert.True(innerExceptions.Contains(exception));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Nancy.Tests.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <TargetFrameworks>netcoreapp2.0;net452</TargetFrameworks>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <EmbeddedResource Include=\"Resources\\Views\\staticviewresource.html\" Exclude=\"bin\\**;obj\\**;packages\\**;@(EmbeddedResource)\" />\n    <None Update=\"Resources\\**\\*\">\n      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>\n    </None>\n  </ItemGroup>\n\n  <ItemGroup Condition=\" '$(TargetFramework)' == 'netcoreapp2.0' \">\n    <PackageReference Include=\"Microsoft.CodeAnalysis.CSharp\" Version=\"1.3.2\" />\n    <PackageReference Include=\"System.Data.Common\" Version=\"4.3.0\" />\n    <PackageReference Include=\"System.Xml.XmlSerializer\" Version=\"4.3.0\" />\n  </ItemGroup>\n\n  <ItemGroup Condition=\" '$(TargetFramework)' == 'net452' \">\n    <PackageReference Include=\"Microsoft.CodeAnalysis.CSharp\" Version=\"1.3.2\" />\n    <PackageReference Include=\"System.Collections.Immutable\" Version=\"1.2.0\" />\n  </ItemGroup>\n\n  <ItemGroup Condition=\" '$(TargetFramework)' == 'net452' \">\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"System.Xml\" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "test/Nancy.Tests/NoAppStartupsFixture.cs",
    "content": "﻿namespace Nancy.Tests\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Diagnostics;\r\n    using System.Linq;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Testing;\r\n    using Nancy.Tests.xUnitExtensions;\r\n    using Xunit;\r\n\r\n    public class AutoThingsRegistrations : IRegistrations\r\n    {\r\n        public IEnumerable<TypeRegistration> TypeRegistrations\r\n        {\r\n            get\r\n            {\r\n                ThrowWhenNoAppStartupsFixtureRuns();\r\n\r\n                return Enumerable.Empty<TypeRegistration>();\r\n            }\r\n        }\r\n\r\n        public IEnumerable<CollectionTypeRegistration> CollectionTypeRegistrations\r\n        {\r\n            get\r\n            {\r\n                ThrowWhenNoAppStartupsFixtureRuns();\r\n\r\n                return Enumerable.Empty<CollectionTypeRegistration>();\r\n            }\r\n        }\r\n\r\n        public IEnumerable<InstanceRegistration> InstanceRegistrations\r\n        {\r\n            get\r\n            {\r\n                ThrowWhenNoAppStartupsFixtureRuns();\r\n\r\n                return Enumerable.Empty<InstanceRegistration>();\r\n            }\r\n        }\r\n\r\n        private static void ThrowWhenNoAppStartupsFixtureRuns()\r\n        {\r\n            if ( Environment.StackTrace.Contains(typeof(NoAppStartupsFixture).FullName))\r\n            {\r\n                throw new Exception();\r\n            }\r\n        }\r\n    }\r\n\r\n    public class NoAppStartupsFixture\r\n    {\r\n        [Fact]\r\n        public async Task When_AutoRegistration_Is_Enabled_Should_Throw()\r\n        {\r\n            var ex = await RecordAsync.Exception(async () =>\r\n            {\r\n                // Given\r\n                var bootstrapper = new ConfigurableBootstrapper(config =>\r\n                {\r\n                    config.Module<NoAppStartupsModule>();\r\n                    config.Dependency<INoAppStartupsTestDependency>(typeof(AutoDependency));\r\n                });\r\n                var browser = new Browser(bootstrapper);\r\n\r\n                // When\r\n                await browser.Get(\"/\");\r\n            });\r\n\r\n            //Then\r\n            ex.ShouldNotBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task When_AutoRegistration_Is_Disabled_Should_Not_Throw()\r\n        {\r\n            // Given\r\n            var bootstrapper = new ConfigurableBootstrapper(config =>\r\n            {\r\n                config.DisableAutoRegistrations();\r\n                config.Module<NoAppStartupsModule>();\r\n                config.Dependency<INoAppStartupsTestDependency>(typeof(AutoDependency));\r\n            });\r\n            var browser = new Browser(bootstrapper);\r\n\r\n            // When\r\n            var result = await browser.Get(\"/\");\r\n\r\n            // Then\r\n            result.Body.AsString().ShouldEqual(\"disabled auto registration works\");\r\n        }\r\n\r\n        public interface INoAppStartupsTestDependency\r\n        {\r\n            string GetStuff();\r\n        }\r\n\r\n        public class AutoDependency : INoAppStartupsTestDependency\r\n        {\r\n            public string GetStuff()\r\n            {\r\n                return \"disabled auto registration works\";\r\n            }\r\n        }\r\n\r\n        public class NoAppStartupsModule : NancyModule\r\n        {\r\n            public NoAppStartupsModule(INoAppStartupsTestDependency dependency)\r\n            {\r\n                Get(\"/\", args => dependency.GetStuff());\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Properties/AssemblyInfo.cs",
    "content": "﻿using Xunit;\r\n\r\n[assembly: CollectionBehavior(DisableTestParallelization = true)]"
  },
  {
    "path": "test/Nancy.Tests/Resources/Assets/Styles/Sub/styles.css",
    "content": "body {\r\n\tbackground-color: white;\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Resources/Assets/Styles/Sub.folder/styles.css",
    "content": "body {\r\n\tbackground-color: white;\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Resources/Assets/Styles/css/styles.css",
    "content": "body {\r\n\tbackground-color: white;\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Resources/Assets/Styles/dotted.filename.css",
    "content": "body {\r\n\tbackground-color: white;\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Resources/Assets/Styles/space in name.css",
    "content": "body {\r\n\tbackground-color: white;\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Resources/Assets/Styles/strange-css-filename.css",
    "content": "body {\r\n\tbackground-color: white;\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Resources/Assets/Styles/styles.css",
    "content": "body {\r\n\tbackground-color: white;\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Resources/Link.Texts.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\r\n// <auto-generated>\r\n//     This code was generated by a tool.\r\n//     Runtime Version:4.0.30319.42000\r\n//\r\n//     Changes to this file may cause incorrect behavior and will be lost if\r\n//     the code is regenerated.\r\n// </auto-generated>\r\n//------------------------------------------------------------------------------\r\n\r\nnamespace Nancy.Tests.Resources {\r\n    using System;\r\n    using Nancy.Extensions;\r\n\r\n    /// <summary>\r\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\r\n    /// </summary>\r\n    // This class was auto-generated by the StronglyTypedResourceBuilder\r\n    // class via a tool like ResGen or Visual Studio.\r\n    // To add or remove a member, edit your .ResX file then rerun ResGen\r\n    // with the /str option, or rebuild your VS project.\r\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\r\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\r\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\r\n    internal class Link_Texts {\r\n        \r\n        private static global::System.Resources.ResourceManager resourceMan;\r\n        \r\n        private static global::System.Globalization.CultureInfo resourceCulture;\r\n        \r\n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\r\n        internal Link_Texts() {\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Returns the cached ResourceManager instance used by this class.\r\n        /// </summary>\r\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\r\n        internal static global::System.Resources.ResourceManager ResourceManager {\r\n            get {\r\n                if (object.ReferenceEquals(resourceMan, null)) {\r\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"Nancy.Tests.Resources.Link.Texts\", typeof(Link_Texts).GetAssembly());\r\n                    resourceMan = temp;\r\n                }\r\n                return resourceMan;\r\n            }\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Overrides the current thread's CurrentUICulture property for all\r\n        ///   resource lookups using this strongly typed resource class.\r\n        /// </summary>\r\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\r\n        internal static global::System.Globalization.CultureInfo Culture {\r\n            get {\r\n                return resourceCulture;\r\n            }\r\n            set {\r\n                resourceCulture = value;\r\n            }\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Looks up a localized string similar to This is the home link.\r\n        /// </summary>\r\n        internal static string Home {\r\n            get {\r\n                return ResourceManager.GetString(\"Home\", resourceCulture);\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Resources/Link.Texts.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<root>\r\n  <!-- \r\n    Microsoft ResX Schema \r\n    \r\n    Version 2.0\r\n    \r\n    The primary goals of this format is to allow a simple XML format \r\n    that is mostly human readable. The generation and parsing of the \r\n    various data types are done through the TypeConverter classes \r\n    associated with the data types.\r\n    \r\n    Example:\r\n    \r\n    ... ado.net/XML headers & schema ...\r\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\r\n    <resheader name=\"version\">2.0</resheader>\r\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\r\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\r\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\r\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\r\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\r\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\r\n    </data>\r\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\r\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\r\n        <comment>This is a comment</comment>\r\n    </data>\r\n                \r\n    There are any number of \"resheader\" rows that contain simple \r\n    name/value pairs.\r\n    \r\n    Each data row contains a name, and value. The row also contains a \r\n    type or mimetype. Type corresponds to a .NET class that support \r\n    text/value conversion through the TypeConverter architecture. \r\n    Classes that don't support this are serialized and stored with the \r\n    mimetype set.\r\n    \r\n    The mimetype is used for serialized objects, and tells the \r\n    ResXResourceReader how to depersist the object. This is currently not \r\n    extensible. For a given mimetype the value must be set accordingly:\r\n    \r\n    Note - application/x-microsoft.net.object.binary.base64 is the format \r\n    that the ResXResourceWriter will generate, however the reader can \r\n    read any of the formats listed below.\r\n    \r\n    mimetype: application/x-microsoft.net.object.binary.base64\r\n    value   : The object must be serialized with \r\n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\r\n            : and then encoded with base64 encoding.\r\n    \r\n    mimetype: application/x-microsoft.net.object.soap.base64\r\n    value   : The object must be serialized with \r\n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\r\n            : and then encoded with base64 encoding.\r\n\r\n    mimetype: application/x-microsoft.net.object.bytearray.base64\r\n    value   : The object must be serialized into a byte array \r\n            : using a System.ComponentModel.TypeConverter\r\n            : and then encoded with base64 encoding.\r\n    -->\r\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\r\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\r\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\r\n      <xsd:complexType>\r\n        <xsd:choice maxOccurs=\"unbounded\">\r\n          <xsd:element name=\"metadata\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\r\n              <xsd:attribute ref=\"xml:space\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"assembly\">\r\n            <xsd:complexType>\r\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"data\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\r\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\r\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\r\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\r\n              <xsd:attribute ref=\"xml:space\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"resheader\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n        </xsd:choice>\r\n      </xsd:complexType>\r\n    </xsd:element>\r\n  </xsd:schema>\r\n  <resheader name=\"resmimetype\">\r\n    <value>text/microsoft-resx</value>\r\n  </resheader>\r\n  <resheader name=\"version\">\r\n    <value>2.0</value>\r\n  </resheader>\r\n  <resheader name=\"reader\">\r\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\r\n  </resheader>\r\n  <resheader name=\"writer\">\r\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\r\n  </resheader>\r\n  <data name=\"Home\" xml:space=\"preserve\">\r\n    <value>This is the home link</value>\r\n  </data>\r\n</root>"
  },
  {
    "path": "test/Nancy.Tests/Resources/Menu.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\r\n// <auto-generated>\r\n//     This code was generated by a tool.\r\n//     Runtime Version:4.0.30319.34011\r\n//\r\n//     Changes to this file may cause incorrect behavior and will be lost if\r\n//     the code is regenerated.\r\n// </auto-generated>\r\n//------------------------------------------------------------------------------\r\n\r\nnamespace Nancy.Demo.Hosting.Aspnet.Resources {\r\n    using System;\r\n    using Nancy.Extensions;\r\n\r\n\r\n    /// <summary>\r\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\r\n    /// </summary>\r\n    // This class was auto-generated by the StronglyTypedResourceBuilder\r\n    // class via a tool like ResGen or Visual Studio.\r\n    // To add or remove a member, edit your .ResX file then rerun ResGen\r\n    // with the /str option, or rebuild your VS project.\r\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\r\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\r\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\r\n    internal class Menu {\r\n        \r\n        private static global::System.Resources.ResourceManager resourceMan;\r\n        \r\n        private static global::System.Globalization.CultureInfo resourceCulture;\r\n        \r\n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\r\n        internal Menu() {\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Returns the cached ResourceManager instance used by this class.\r\n        /// </summary>\r\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\r\n        internal static global::System.Resources.ResourceManager ResourceManager {\r\n            get {\r\n                if (object.ReferenceEquals(resourceMan, null)) {\r\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"Nancy.Demo.Hosting.Aspnet.Resources.Menu\", typeof(Menu).GetAssembly());\r\n                    resourceMan = temp;\r\n                }\r\n                return resourceMan;\r\n            }\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Overrides the current thread's CurrentUICulture property for all\r\n        ///   resource lookups using this strongly typed resource class.\r\n        /// </summary>\r\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\r\n        internal static global::System.Globalization.CultureInfo Culture {\r\n            get {\r\n                return resourceCulture;\r\n            }\r\n            set {\r\n                resourceCulture = value;\r\n            }\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Looks up a localized string similar to This is the home link.\r\n        /// </summary>\r\n        internal static string Home {\r\n            get {\r\n                return ResourceManager.GetString(\"Home\", resourceCulture);\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Resources/Menu.Texts.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\r\n// <auto-generated>\r\n//     This code was generated by a tool.\r\n//     Runtime Version:4.0.30319.42000\r\n//\r\n//     Changes to this file may cause incorrect behavior and will be lost if\r\n//     the code is regenerated.\r\n// </auto-generated>\r\n//------------------------------------------------------------------------------\r\n\r\nnamespace Nancy.Tests.Resources {\r\n    using System;\r\n    using Nancy.Extensions;\r\n\r\n    /// <summary>\r\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\r\n    /// </summary>\r\n    // This class was auto-generated by the StronglyTypedResourceBuilder\r\n    // class via a tool like ResGen or Visual Studio.\r\n    // To add or remove a member, edit your .ResX file then rerun ResGen\r\n    // with the /str option, or rebuild your VS project.\r\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\r\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\r\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\r\n    internal class Menu_Texts {\r\n        \r\n        private static global::System.Resources.ResourceManager resourceMan;\r\n        \r\n        private static global::System.Globalization.CultureInfo resourceCulture;\r\n        \r\n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\r\n        internal Menu_Texts() {\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Returns the cached ResourceManager instance used by this class.\r\n        /// </summary>\r\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\r\n        internal static global::System.Resources.ResourceManager ResourceManager {\r\n            get {\r\n                if (object.ReferenceEquals(resourceMan, null)) {\r\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"Nancy.Tests.Resources.Menu.Texts\", typeof(Menu_Texts).GetAssembly());\r\n                    resourceMan = temp;\r\n                }\r\n                return resourceMan;\r\n            }\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Overrides the current thread's CurrentUICulture property for all\r\n        ///   resource lookups using this strongly typed resource class.\r\n        /// </summary>\r\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\r\n        internal static global::System.Globalization.CultureInfo Culture {\r\n            get {\r\n                return resourceCulture;\r\n            }\r\n            set {\r\n                resourceCulture = value;\r\n            }\r\n        }\r\n        \r\n        /// <summary>\r\n        ///   Looks up a localized string similar to This is the home link.\r\n        /// </summary>\r\n        internal static string Home {\r\n            get {\r\n                return ResourceManager.GetString(\"Home\", resourceCulture);\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Resources/Menu.Texts.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<root>\r\n  <!-- \r\n    Microsoft ResX Schema \r\n    \r\n    Version 2.0\r\n    \r\n    The primary goals of this format is to allow a simple XML format \r\n    that is mostly human readable. The generation and parsing of the \r\n    various data types are done through the TypeConverter classes \r\n    associated with the data types.\r\n    \r\n    Example:\r\n    \r\n    ... ado.net/XML headers & schema ...\r\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\r\n    <resheader name=\"version\">2.0</resheader>\r\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\r\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\r\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\r\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\r\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\r\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\r\n    </data>\r\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\r\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\r\n        <comment>This is a comment</comment>\r\n    </data>\r\n                \r\n    There are any number of \"resheader\" rows that contain simple \r\n    name/value pairs.\r\n    \r\n    Each data row contains a name, and value. The row also contains a \r\n    type or mimetype. Type corresponds to a .NET class that support \r\n    text/value conversion through the TypeConverter architecture. \r\n    Classes that don't support this are serialized and stored with the \r\n    mimetype set.\r\n    \r\n    The mimetype is used for serialized objects, and tells the \r\n    ResXResourceReader how to depersist the object. This is currently not \r\n    extensible. For a given mimetype the value must be set accordingly:\r\n    \r\n    Note - application/x-microsoft.net.object.binary.base64 is the format \r\n    that the ResXResourceWriter will generate, however the reader can \r\n    read any of the formats listed below.\r\n    \r\n    mimetype: application/x-microsoft.net.object.binary.base64\r\n    value   : The object must be serialized with \r\n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\r\n            : and then encoded with base64 encoding.\r\n    \r\n    mimetype: application/x-microsoft.net.object.soap.base64\r\n    value   : The object must be serialized with \r\n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\r\n            : and then encoded with base64 encoding.\r\n\r\n    mimetype: application/x-microsoft.net.object.bytearray.base64\r\n    value   : The object must be serialized into a byte array \r\n            : using a System.ComponentModel.TypeConverter\r\n            : and then encoded with base64 encoding.\r\n    -->\r\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\r\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\r\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\r\n      <xsd:complexType>\r\n        <xsd:choice maxOccurs=\"unbounded\">\r\n          <xsd:element name=\"metadata\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\r\n              <xsd:attribute ref=\"xml:space\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"assembly\">\r\n            <xsd:complexType>\r\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"data\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\r\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\r\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\r\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\r\n              <xsd:attribute ref=\"xml:space\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"resheader\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n        </xsd:choice>\r\n      </xsd:complexType>\r\n    </xsd:element>\r\n  </xsd:schema>\r\n  <resheader name=\"resmimetype\">\r\n    <value>text/microsoft-resx</value>\r\n  </resheader>\r\n  <resheader name=\"version\">\r\n    <value>2.0</value>\r\n  </resheader>\r\n  <resheader name=\"reader\">\r\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\r\n  </resheader>\r\n  <resheader name=\"writer\">\r\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\r\n  </resheader>\r\n  <data name=\"Home\" xml:space=\"preserve\">\r\n    <value>This is the home link</value>\r\n  </data>\r\n</root>"
  },
  {
    "path": "test/Nancy.Tests/Resources/Menu.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<root>\r\n  <!-- \r\n    Microsoft ResX Schema \r\n    \r\n    Version 2.0\r\n    \r\n    The primary goals of this format is to allow a simple XML format \r\n    that is mostly human readable. The generation and parsing of the \r\n    various data types are done through the TypeConverter classes \r\n    associated with the data types.\r\n    \r\n    Example:\r\n    \r\n    ... ado.net/XML headers & schema ...\r\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\r\n    <resheader name=\"version\">2.0</resheader>\r\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\r\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\r\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\r\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\r\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\r\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\r\n    </data>\r\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\r\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\r\n        <comment>This is a comment</comment>\r\n    </data>\r\n                \r\n    There are any number of \"resheader\" rows that contain simple \r\n    name/value pairs.\r\n    \r\n    Each data row contains a name, and value. The row also contains a \r\n    type or mimetype. Type corresponds to a .NET class that support \r\n    text/value conversion through the TypeConverter architecture. \r\n    Classes that don't support this are serialized and stored with the \r\n    mimetype set.\r\n    \r\n    The mimetype is used for serialized objects, and tells the \r\n    ResXResourceReader how to depersist the object. This is currently not \r\n    extensible. For a given mimetype the value must be set accordingly:\r\n    \r\n    Note - application/x-microsoft.net.object.binary.base64 is the format \r\n    that the ResXResourceWriter will generate, however the reader can \r\n    read any of the formats listed below.\r\n    \r\n    mimetype: application/x-microsoft.net.object.binary.base64\r\n    value   : The object must be serialized with \r\n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\r\n            : and then encoded with base64 encoding.\r\n    \r\n    mimetype: application/x-microsoft.net.object.soap.base64\r\n    value   : The object must be serialized with \r\n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\r\n            : and then encoded with base64 encoding.\r\n\r\n    mimetype: application/x-microsoft.net.object.bytearray.base64\r\n    value   : The object must be serialized into a byte array \r\n            : using a System.ComponentModel.TypeConverter\r\n            : and then encoded with base64 encoding.\r\n    -->\r\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\r\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\r\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\r\n      <xsd:complexType>\r\n        <xsd:choice maxOccurs=\"unbounded\">\r\n          <xsd:element name=\"metadata\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\r\n              <xsd:attribute ref=\"xml:space\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"assembly\">\r\n            <xsd:complexType>\r\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"data\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\r\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\r\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\r\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\r\n              <xsd:attribute ref=\"xml:space\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n          <xsd:element name=\"resheader\">\r\n            <xsd:complexType>\r\n              <xsd:sequence>\r\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\r\n              </xsd:sequence>\r\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\r\n            </xsd:complexType>\r\n          </xsd:element>\r\n        </xsd:choice>\r\n      </xsd:complexType>\r\n    </xsd:element>\r\n  </xsd:schema>\r\n  <resheader name=\"resmimetype\">\r\n    <value>text/microsoft-resx</value>\r\n  </resheader>\r\n  <resheader name=\"version\">\r\n    <value>2.0</value>\r\n  </resheader>\r\n  <resheader name=\"reader\">\r\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\r\n  </resheader>\r\n  <resheader name=\"writer\">\r\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\r\n  </resheader>\r\n  <data name=\"Home\" xml:space=\"preserve\">\r\n    <value>This is the home link</value>\r\n  </data>\r\n</root>"
  },
  {
    "path": "test/Nancy.Tests/Resources/Views/SuperSimpleViewEngineSampleContent.cs",
    "content": "﻿namespace Nancy.Tests.Resources.Views\r\n{\r\n    public static class SuperSimpleViewEngineSampleContent\r\n    {\r\n        public static string testFileInput = @\"<!DOCTYPE html PUBLIC \"\"-//W3C//DTD XHTML 1.0 Transitional//EN\"\" \"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"\">\r\n<html xmlns=\"\"http://www.w3.org/1999/xhtml\"\">\r\n<head>\r\n    <title>@Model.Title</title>\r\n</head>\r\n<body>\r\n\t<h1>@Model.Title</h1>\r\n\r\n\t<p>Hello there @Model.Name!</p>\r\n\r\n\t<p>@Model.Complex.Item1;. @Model.Complex.Item2;.</p>\r\n\r\n\t<h2>Users:</h2>\r\n\t@IfNot.HasUsers\r\n\t<p>No users found</p>\r\n\t@EndIf\r\n\r\n\t@If.HasUsers\r\n\t<ul id=\"\"users\"\">\r\n\t\t@Each.Users\r\n\t\t<li>@Current.Name - @Current.Age</li>\r\n\t\t@EndEach\r\n\t</ul>\r\n\t@EndIf\r\n\r\n\t<h2>Admins:</h2>\r\n\t@IfNot.HasAdmins\r\n\t<p>No admin users found</p>\r\n\t@EndIf\r\n\r\n\t@If.HasAdmins\r\n\t<ul id=\"\"admins\"\">\r\n\t\t@Each.Admins\r\n\t\t<li>@Current</li>\r\n\t\t@EndEach\r\n\t</ul>\r\n\t@EndIf\r\n</body>\r\n</html>\r\n\";\r\n\r\n        public static string ExpectedOutput = @\"<!DOCTYPE html PUBLIC \"\"-//W3C//DTD XHTML 1.0 Transitional//EN\"\" \"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"\">\r\n<html xmlns=\"\"http://www.w3.org/1999/xhtml\"\">\r\n<head>\r\n    <title>Demonstration of Nancy's SuperSimple ViewEngine</title>\r\n</head>\r\n<body>\r\n\t<h1>Demonstration of Nancy's SuperSimple ViewEngine</h1>\r\n\r\n\t<p>Hello there Frankie!</p>\r\n\r\n\t<p>This is a nested property. Oh yes it is.</p>\r\n\r\n\t<h2>Users:</h2>\r\n\t\r\n\r\n\t\r\n\t<ul id=\"\"users\"\">\r\n\t\t\r\n\t\t<li>Bob Smith - 27</li>\r\n\t\t\r\n\t\t<li>Jim Jones - 42</li>\r\n\t\t\r\n\t\t<li>Bill Bobson - 78</li>\r\n\t\t\r\n\t</ul>\r\n\t\r\n\r\n\t<h2>Admins:</h2>\r\n\t\r\n\t<p>No admin users found</p>\r\n\t\r\n\r\n\t\r\n</body>\r\n</html>\r\n\";\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Resources/Views/staticviewresource.html",
    "content": "﻿<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\r\n<html>\r\n\t<head>\r\n\t\t<title></title>\r\n\t</head>\r\n\t<body>\r\n\t\r\n\t</body>\r\n</html>"
  },
  {
    "path": "test/Nancy.Tests/Resources/test.txt",
    "content": "﻿Testing Text"
  },
  {
    "path": "test/Nancy.Tests/Responses/MaterialisingResponseFixture.cs",
    "content": "﻿namespace Nancy.Tests.Responses\r\n{\r\n    using System.IO;\r\n    using Nancy.Responses;\r\n    using Xunit;\r\n\r\n    public class MaterialisingResponseFixture\r\n    {\r\n        [Fact]\r\n        public void Should_call_inner_response_on_preinit()\r\n        {\r\n            // Given\r\n            var sourceResponse = new FakeResponse();\r\n            var response = new MaterialisingResponse(sourceResponse);\r\n            var context = this.GetContext();\r\n\r\n            // When\r\n            response.PreExecute(context);\r\n\r\n            // Then\r\n            sourceResponse.ContentsCalled.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_call_inner_response_again_if_alread_inited()\r\n        {\r\n            // Given\r\n            var sourceResponse = new FakeResponse();\r\n            var response = new MaterialisingResponse(sourceResponse);\r\n            var context = this.GetContext();\r\n            response.PreExecute(context);\r\n            sourceResponse.ContentsCalled = false;\r\n\r\n            // When\r\n            response.Contents.Invoke(new MemoryStream());\r\n\r\n            // Then\r\n            sourceResponse.ContentsCalled.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_call_inner_response_again_if_executed_and_not_already_inited()\r\n        {\r\n            // Given\r\n            var sourceResponse = new FakeResponse();\r\n            var response = new MaterialisingResponse(sourceResponse);\r\n\r\n            // When\r\n            response.Contents.Invoke(new MemoryStream());\r\n\r\n            // Then\r\n            sourceResponse.ContentsCalled.ShouldBeTrue();\r\n        }\r\n\r\n        private NancyContext GetContext()\r\n        {\r\n            return new NancyContext();\r\n        }\r\n    }\r\n\r\n    public class FakeResponse : Response\r\n    {\r\n        public bool ContentsCalled { get; set; }\r\n\r\n        public Stream PassedStream { get; set; }\r\n\r\n        public FakeResponse()\r\n        {\r\n            this.Contents = stream =>\r\n            {\r\n                this.PassedStream = stream;\r\n                this.ContentsCalled = true;\r\n            };\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/ShouldExtensions.cs",
    "content": "﻿namespace Nancy.Tests\r\n{\r\n    using System;\r\n    using System.Collections;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using Xunit;\r\n\r\n    public static class ShouldAssertExtensions\r\n    {\r\n        public static void ShouldStartWith(this string actual, string expected)\r\n        {\r\n            Assert.True(actual.StartsWith(expected), String.Format(\"Expected to start with {0} but ended with {1}\", expected, actual));\r\n        }\r\n\r\n        public static void ShouldEndWith(this string actual, string expected)\r\n        {\r\n            Assert.True(actual.EndsWith(expected), String.Format(\"Expected to end with {0} but ended with {1}\", expected, actual));\r\n        }\r\n\r\n        public static void ShouldMatch<T>(this T actual, Func<T, bool> condition)\r\n        {\r\n            Assert.True(condition.Invoke(actual));\r\n        }\r\n\r\n        public static void ShouldBeEmpty(this string actual)\r\n        {\r\n            Assert.True(string.IsNullOrEmpty(actual));\r\n        }\r\n\r\n        public static void ShouldNotBeEmpty(this string actual)\r\n        {\r\n            Assert.False(string.IsNullOrEmpty(actual));\r\n        }\r\n\r\n        public static void ShouldImplementInterface<T>(this Type actual)\r\n        {\r\n            var found =\r\n                actual.GetInterfaces().Contains(typeof(T));\r\n\r\n            Assert.True(found);\r\n        }\r\n\r\n        public static void ShouldContainType<T>(this IEnumerable collection)\r\n        {\r\n            var selection =\r\n                from c in collection.Cast<object>()\r\n                where c.GetType().IsAssignableFrom(typeof(T))\r\n                select c;\r\n\r\n            Assert.True(selection.Any());\r\n        }\r\n\r\n        public static void ShouldNotContainType<T>(this IEnumerable collection)\r\n        {\r\n            var selection =\r\n                from c in collection.Cast<object>()\r\n                where c.GetType().IsAssignableFrom(typeof(T))\r\n                select c;\r\n\r\n            Assert.False(selection.Any());\r\n        }\r\n\r\n        public static void ShouldContainInOrder(this string actual, params string[] values)\r\n        {\r\n            int index = 0;\r\n            foreach (string value in values)\r\n            {\r\n                int nextIndex = actual.IndexOf(value, index);\r\n                Assert.True(nextIndex >= 0, string.Format(\"Looking for {0}\", value));\r\n                index = nextIndex + value.Length;\r\n            }\r\n        }\r\n\r\n        public static void ShouldContain(this string actual, string expected)\r\n        {\r\n            Assert.True(actual.Contains(expected), string.Format(\"'{0}' does not contain '{1}'\", actual, expected));\r\n        }\r\n\r\n        public static void ShouldNotContain(this string actual, string expected)\r\n        {\r\n            Assert.False(actual.Contains(expected), string.Format(\"'{0}' does contain '{1}'\", actual, expected));\r\n        }\r\n\r\n        public static void ShouldHave<T>(this IEnumerable<T> list, Func<T, bool> predicate)\r\n        {\r\n            Assert.True(list.Any(predicate));\r\n        }\r\n\r\n        public static void ShouldHaveCount<T>(this IEnumerable<T> list, int expected)\r\n        {\r\n            list.Count().ShouldEqual(expected);\r\n        }\r\n\r\n        public static void ShouldBeTrue(this bool actual)\r\n        {\r\n            Assert.True(actual);\r\n        }\r\n\r\n        public static void ShouldBeFalse(this bool actual)\r\n        {\r\n            Assert.False(actual);\r\n        }\r\n\r\n        public static void ShouldEqual(this object actual, object expected)\r\n        {\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        public static void ShouldEqual(this DateTime actual, DateTime expected)\r\n        {\r\n            Assert.Equal(expected.Year, actual.Year);\r\n            Assert.Equal(expected.Month, actual.Month);\r\n            Assert.Equal(expected.Day, actual.Day);\r\n            Assert.Equal(expected.Hour, actual.Hour);\r\n            Assert.Equal(expected.Minute, actual.Minute);\r\n            Assert.Equal(expected.Second, actual.Second);\r\n        }\r\n\r\n        public static void ShouldEqualSequence<T>(this IEnumerable<T> actual, IEnumerable<T> expected)\r\n        {\r\n            Assert.True(actual.SequenceEqual(expected));\r\n        }\r\n\r\n        public static void ShouldBeGreaterThan(this int actual, int smallestValueNotAccepted)\r\n        {\r\n            Assert.True(actual > smallestValueNotAccepted);\r\n        }\r\n\r\n        public static void ShouldNotEqual(this object actual, object expected)\r\n        {\r\n            Assert.NotEqual(expected, actual);\r\n        }\r\n\r\n        public static void ShouldNotBeSameAs(this object actual, object expected)\r\n        {\r\n            Assert.NotSame(expected, actual);\r\n        }\r\n\r\n        public static void ShouldBeSameAs(this object actual, object expected)\r\n        {\r\n            Assert.Same(expected, actual);\r\n        }\r\n\r\n        public static void ShouldBeNull(this object actual)\r\n        {\r\n            Assert.Null(actual);\r\n        }\r\n\r\n        public static void ShouldNotBeNull(this object actual)\r\n        {\r\n            Assert.NotNull(actual);\r\n        }\r\n\r\n        public static void ShouldBeOfType<T>(this Type asserted)\r\n        {\r\n            Assert.True(asserted == typeof(T));\r\n        }\r\n\r\n        public static void ShouldBeOfType<T>(this object asserted)\r\n        {\r\n            asserted.ShouldBeOfType(typeof(T));\r\n        }\r\n\r\n        public static void ShouldBeOfType(this object asserted, Type expected)\r\n        {\r\n            Assert.IsAssignableFrom(expected, asserted);\r\n        }\r\n\r\n        public static void ShouldNotBeOfType<T>(this object asserted)\r\n        {\r\n            Assert.True(!asserted.GetType().Equals(typeof(T)));\r\n        }\r\n\r\n        public static void ShouldBeThrownBy(this Type expectedType, Action context)\r\n        {\r\n            try\r\n            {\r\n                context();\r\n            }\r\n            catch (Exception thrownException)\r\n            {\r\n                Assert.Equal(expectedType, thrownException.GetType());\r\n            }\r\n        }\r\n\r\n        public static void ShouldEqual(this MemoryStream stream, string expected, bool trim = false)\r\n        {\r\n            stream.Position = 0;\r\n            using (var reader = new StreamReader(stream))\r\n            {\r\n                var actual = reader.ReadToEnd();\r\n\r\n                if (trim)\r\n                {\r\n                    actual = actual.Trim();\r\n                }\r\n\r\n                actual.ShouldEqual(expected);\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/AfterPipelineFixture.cs",
    "content": "namespace Nancy.Tests.Unit\r\n{\r\n    using System;\r\n    using System.Linq;\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Tests.xUnitExtensions;\r\n    using Xunit;\r\n\r\n    public class AfterPipelineFixture\r\n    {\r\n        private AfterPipeline pipeline;\r\n\r\n        private static NancyContext CreateContext()\r\n        {\r\n            return new NancyContext();\r\n        }\r\n\r\n        public AfterPipelineFixture()\r\n        {\r\n            pipeline = new AfterPipeline();\r\n        }\r\n\r\n        [Fact]\r\n        public void PlusEquals_with_func_add_item_to_end_of_pipeline()\r\n        {\r\n            pipeline += r => { };\r\n\r\n            pipeline.PipelineDelegates.ShouldHaveCount(1);\r\n            Assert.Equal(1, pipeline.PipelineDelegates.Count());\r\n        }\r\n\r\n        [Fact]\r\n        public void PlusEquals_with_another_pipeline_adds_those_pipeline_items_to_end_of_pipeline()\r\n        {\r\n            pipeline.AddItemToEndOfPipeline(r => { });\r\n            pipeline.AddItemToEndOfPipeline(r => { });\r\n            var pipeline2 = new AfterPipeline();\r\n            pipeline2.AddItemToEndOfPipeline(r => { });\r\n            pipeline2.AddItemToEndOfPipeline(r => { });\r\n\r\n            pipeline += pipeline2;\r\n\r\n            Assert.Equal(4, pipeline.PipelineItems.Count());\r\n            Assert.Same(pipeline2.PipelineDelegates.ElementAt(0), pipeline.PipelineDelegates.ElementAt(2));\r\n            Assert.Same(pipeline2.PipelineDelegates.ElementAt(1), pipeline.PipelineDelegates.Last());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task When_cast_to_func_and_invoked_members_are_invoked()\r\n        {\r\n            var item1Called = false;\r\n            Action<NancyContext> item1 = (r) => { item1Called = true; };\r\n            var item2Called = false;\r\n            Action<NancyContext> item2 = (r) => { item2Called = true; };\r\n            var item3Called = false;\r\n            Action<NancyContext> item3 = (r) => { item3Called = true; };\r\n            pipeline.AddItemToEndOfPipeline(item1);\r\n            pipeline.AddItemToEndOfPipeline(item2);\r\n            pipeline.AddItemToEndOfPipeline(item3);\r\n\r\n            Action<NancyContext> action = context => { };\r\n            pipeline += action;\r\n\r\n            await pipeline.Invoke(CreateContext(), CancellationToken.None);\r\n\r\n            Assert.True(item1Called);\r\n            Assert.True(item2Called);\r\n            Assert.True(item3Called);\r\n        }\r\n\r\n        [Fact]\r\n        public void When_cast_from_func_creates_a_pipeline_with_one_item()\r\n        {\r\n            var castPipeline = new AfterPipeline();\r\n            castPipeline += r => { };\r\n\r\n            Assert.Equal(1, castPipeline.PipelineDelegates.Count());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Pipeline_containing_another_pipeline_will_invoke_items_in_both_pipelines()\r\n        {\r\n            var item1Called = false;\r\n            Action<NancyContext> item1 = (r) => { item1Called = true; };\r\n            var item2Called = false;\r\n            Action<NancyContext> item2 = (r) => { item2Called = true; };\r\n            var item3Called = false;\r\n            Action<NancyContext> item3 = (r) => { item3Called = true; };\r\n            var item4Called = false;\r\n            Action<NancyContext> item4 = (r) => { item4Called = true; };\r\n            pipeline += item1;\r\n            pipeline += item2;\r\n            var subPipeline = new AfterPipeline();\r\n            subPipeline += item3;\r\n            subPipeline += item4;\r\n\r\n            pipeline.AddItemToEndOfPipeline(subPipeline);\r\n            await pipeline.Invoke(CreateContext(), new CancellationToken());\r\n\r\n            Assert.True(item1Called);\r\n            Assert.True(item2Called);\r\n            Assert.True(item3Called);\r\n            Assert.True(item4Called);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/AppDomainAssemblyCatalogFixture.cs",
    "content": "﻿#if !CORE\r\nnamespace Nancy.Tests.Unit\r\n{\r\n    using System;\r\n    using System.CodeDom.Compiler;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using Xunit;\r\n\r\n    public class AppDomainAssemblyCatalogFixture\r\n    {\r\n        [Fact]\r\n        public void Modules_without_Nancy_references_should_not_keep_loaded_after_inspection()\r\n        {\r\n            // Given\r\n            var compilerAppDomain = AppDomain.CreateDomain(\"AssemblyGenerator\",\r\n                AppDomain.CurrentDomain.Evidence, AppDomain.CurrentDomain.SetupInformation);\r\n\r\n            var assemblyGenerator = (ProxyAssemblyGenerator)compilerAppDomain.CreateInstanceAndUnwrap(\r\n                typeof(ProxyAssemblyGenerator).Assembly.FullName,\r\n                typeof(ProxyAssemblyGenerator).FullName);\r\n\r\n            try\r\n            {\r\n                var generatedAssemblyName = assemblyGenerator.GenerateAssemblyAndGetName();\r\n\r\n                var assemblyCatalog = new AppDomainAssemblyCatalog();\r\n\r\n                // When\r\n\r\n                // the following call will load the assemblies into its own inspection AppDomain\r\n                // and release the assemblies that do not reference Nancy afterwards, \r\n                // keeping the application AppDomain free of such assemblies, that is, the created\r\n                // assembly should not be loaded by AppDomain.GetAssemblies after this call\r\n                assemblyCatalog.GetAssemblies();\r\n\r\n                var loadedAssembliesAfterInspection = AppDomain.CurrentDomain.GetAssemblies();\r\n\r\n                // Then\r\n                loadedAssembliesAfterInspection\r\n                    .Select(assembly => assembly.GetName().Name)\r\n                    .Contains(generatedAssemblyName.Name)\r\n                    .ShouldBeFalse();\r\n            }\r\n            finally\r\n            {\r\n                AppDomain.Unload(compilerAppDomain);\r\n            }\r\n        }\r\n\r\n        private class ProxyAssemblyGenerator : MarshalByRefObject\r\n        {\r\n            public AssemblyName GenerateAssemblyAndGetName()\r\n            {\r\n                var generatedAssembly = CodeDomProvider\r\n                    .CreateProvider(\"CSharp\")\r\n                    .CompileAssemblyFromSource(\r\n                        new CompilerParameters\r\n                        {\r\n                            GenerateInMemory = true,\r\n                            GenerateExecutable = false,\r\n                            IncludeDebugInformation = false,\r\n                            OutputAssembly = \"AssemblyShouldNotBeLoadedIntoAppDomain.dll\"\r\n                        },\r\n                        \"public class DummyClass { }\")\r\n                    .CompiledAssembly;\r\n\r\n                return generatedAssembly.GetName();\r\n            }\r\n        }\r\n    }\r\n}\r\n#endif\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/BeforePipelineFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit\r\n{\r\n    using System;\r\n    using System.Linq;\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Tests.xUnitExtensions;\r\n    using Xunit;\r\n\r\n    public class BeforePipelineFixture\r\n    {\r\n        private BeforePipeline pipeline;\r\n\r\n        private static Response CreateResponse()\r\n        {\r\n            return new Response();\r\n        }\r\n\r\n        private static NancyContext CreateContext()\r\n        {\r\n            return new NancyContext();\r\n        }\r\n\r\n        public BeforePipelineFixture()\r\n        {\r\n            this.pipeline = new BeforePipeline();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task When_invoked_pipeline_member_returning_a_response_stops_pipeline_execution()\r\n        {\r\n            // Given\r\n            var item1Called = false;\r\n            Func<NancyContext, Response> item1 = (r) => { item1Called = true; return null; };\r\n            var item2Called = false;\r\n            Func<NancyContext, Response> item2 = (r) => { item2Called = true; return CreateResponse(); };\r\n            var item3Called = false;\r\n            Func<NancyContext, Response> item3 = (r) => { item3Called = true; return null; };\r\n            pipeline.AddItemToEndOfPipeline(item1);\r\n            pipeline.AddItemToEndOfPipeline(item2);\r\n            pipeline.AddItemToEndOfPipeline(item3);\r\n\r\n            // When\r\n            await pipeline.Invoke(CreateContext(), new CancellationToken());\r\n\r\n            // Then\r\n            Assert.True(item1Called);\r\n            Assert.True(item2Called);\r\n            Assert.False(item3Called);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task When_invoked_pipeline_member_returning_a_response_returns_that_response()\r\n        {\r\n            // Given\r\n            var response = CreateResponse();\r\n            Func<NancyContext, Response> item1 = (r) => null;\r\n            Func<NancyContext, Response> item2 = (r) => response;\r\n            Func<NancyContext, Response> item3 = (r) => null;\r\n            pipeline.AddItemToEndOfPipeline(item1);\r\n            pipeline.AddItemToEndOfPipeline(item2);\r\n            pipeline.AddItemToEndOfPipeline(item3);\r\n            \r\n            // When\r\n            var result = await pipeline.Invoke(CreateContext(), new CancellationToken());\r\n\r\n            // Then\r\n            Assert.Same(result, result);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task When_invoked_pipeline_members_all_return_null_returns_null()\r\n        {\r\n            // Given\r\n            Func<NancyContext, Response> item1 = (r) => null;\r\n            Func<NancyContext, Response> item2 = (r) => null;\r\n            Func<NancyContext, Response> item3 = (r) => null;\r\n            pipeline.AddItemToEndOfPipeline(item1);\r\n            pipeline.AddItemToEndOfPipeline(item2);\r\n            pipeline.AddItemToEndOfPipeline(item3);\r\n\r\n            // When\r\n            var result = await pipeline.Invoke(CreateContext(), new CancellationToken());\r\n\r\n            // Then\r\n            Assert.Null(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void PlusEquals_with_func_add_item_to_end_of_pipeline()\r\n        {\r\n            // Given\r\n            pipeline.AddItemToEndOfPipeline(r => CreateResponse());\r\n\r\n            // When\r\n            pipeline += r => null;\r\n\r\n            // Then\r\n            Assert.Equal(2, pipeline.PipelineDelegates.Count());\r\n        }\r\n\r\n        [Fact]\r\n        public void PlusEquals_with_another_pipeline_adds_those_pipeline_items_to_end_of_pipeline()\r\n        {\r\n            // Given\r\n            pipeline.AddItemToEndOfPipeline(r => null);\r\n            pipeline.AddItemToEndOfPipeline(r => CreateResponse());\r\n            var pipeline2 = new BeforePipeline();\r\n            pipeline2.AddItemToEndOfPipeline(r => null);\r\n            pipeline2.AddItemToEndOfPipeline(r => CreateResponse());\r\n\r\n            // When\r\n            pipeline += pipeline2;\r\n\r\n            // Then\r\n            Assert.Equal(4, pipeline.PipelineItems.Count());\r\n            Assert.Same(pipeline2.PipelineDelegates.ElementAt(0), pipeline.PipelineDelegates.ElementAt(2));\r\n            Assert.Same(pipeline2.PipelineDelegates.ElementAt(1), pipeline.PipelineDelegates.Last());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task When_cast_to_func_and_invoked_members_are_invoked()\r\n        {\r\n            // Given\r\n            var item1Called = false;\r\n            Func<NancyContext, Response> item1 = r => { item1Called = true; return null; };\r\n            var item2Called = false;               \r\n            Func<NancyContext, Response> item2 = r => { item2Called = true; return null; };\r\n            var item3Called = false;               \r\n            Func<NancyContext, Response> item3 = r => { item3Called = true; return null; };\r\n            pipeline.AddItemToEndOfPipeline(item1);\r\n            pipeline.AddItemToEndOfPipeline(item2);\r\n            pipeline.AddItemToEndOfPipeline(item3);\r\n\r\n            // When\r\n            Func<NancyContext, CancellationToken, Task<Response>> func = pipeline;\r\n            await func.Invoke(CreateContext(), new CancellationToken());\r\n\r\n            // Then\r\n            Assert.True(item1Called);\r\n            Assert.True(item2Called);\r\n            Assert.True(item3Called);\r\n        }\r\n\r\n        [Fact]\r\n        public void When_cast_from_func_creates_a_pipeline_with_one_item()\r\n        {\r\n            // Given\r\n            Func <NancyContext, CancellationToken,Task<Response>> item2 = (token, task) => null;\r\n\r\n            // When\r\n            BeforePipeline castPipeline = item2;\r\n\r\n            // Then\r\n            Assert.Equal(1, castPipeline.PipelineDelegates.Count());\r\n            Assert.Same(item2, castPipeline.PipelineDelegates.First());\r\n        }\r\n\r\n\r\n        [Fact]\r\n        public async Task Should_be_able_to_throw_exception_from_async_pipeline_item()\r\n        {\r\n            // Given\r\n            Func<NancyContext, CancellationToken, Task<Response>> pipeLineItem = (ctx, token) =>\r\n            {\r\n                throw new Exception(\"aaarg\");\r\n            };\r\n\r\n            // When\r\n            pipeline.AddItemToStartOfPipeline(pipeLineItem);\r\n\r\n            // Then\r\n            await AssertAsync.Throws<Exception>(async () => await pipeline.Invoke(CreateContext(), new CancellationToken()));\r\n        }\r\n\r\n\r\n        [Fact]\r\n        public async Task Pipeline_containing_another_pipeline_will_invoke_items_in_both_pipelines()\r\n        {\r\n            // Given\r\n            var item1Called = false;\r\n            Func<NancyContext, Response> item1 = (r) => { item1Called = true; return null; };\r\n            var item2Called = false;\r\n            Func<NancyContext, Response> item2 = (r) => { item2Called = true; return null; };\r\n            var item3Called = false;\r\n            Func<NancyContext, Response> item3 = (r) => { item3Called = true; return null; };\r\n            var item4Called = false;\r\n            Func<NancyContext, Response> item4 = (r) => { item4Called = true; return null; };\r\n            pipeline += item1;\r\n            pipeline += item2;\r\n            var subPipeline = new BeforePipeline();\r\n            subPipeline += item3;\r\n            subPipeline += item4;\r\n\r\n            // When\r\n            pipeline.AddItemToEndOfPipeline(subPipeline);\r\n            await pipeline.Invoke(CreateContext(), new CancellationToken());\r\n\r\n            // Then\r\n            Assert.True(item1Called);\r\n            Assert.True(item2Called);\r\n            Assert.True(item3Called);\r\n            Assert.True(item4Called);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Bootstrapper/Base/BootstrapperBaseFixtureBase.cs",
    "content": "#if !MONO\r\nnamespace Nancy.Tests.Unit.Bootstrapper.Base\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Routing;\r\n\r\n    using Xunit;\r\n\r\n    /// <summary>\r\n    /// Base class for testing the basic behaviour of a bootstrapper that\r\n    /// implements either of the two bootstrapper base classes.\r\n    /// These tests only test basic external behaviour, they are not exhaustive;\r\n    /// it is expected that additional tests specific to the bootstrapper implementation\r\n    /// are also created.\r\n    /// </summary>\r\n    public abstract class BootstrapperBaseFixtureBase<TContainer>\r\n        where TContainer : class\r\n    {\r\n        private readonly Func<ITypeCatalog, NancyInternalConfiguration> configuration;\r\n\r\n        protected abstract NancyBootstrapperBase<TContainer> Bootstrapper { get; }\r\n\r\n        protected Func<ITypeCatalog, NancyInternalConfiguration> Configuration\r\n        {\r\n            get { return this.configuration; }\r\n        }\r\n\r\n        protected BootstrapperBaseFixtureBase()\r\n        {\r\n            this.configuration = NancyInternalConfiguration.WithOverrides(\r\n                builder =>\r\n                {\r\n                    builder.NancyEngine = typeof(FakeEngine);\r\n                });\r\n        }\r\n\r\n        [Fact]\r\n        public virtual void Should_throw_if_get_engine_called_without_being_initialised()\r\n        {\r\n            // Given / When\r\n            var result = Record.Exception(() => this.Bootstrapper.GetEngine());\r\n\r\n            result.ShouldNotBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public virtual void Should_resolve_engine_when_initialised()\r\n        {\r\n            // Given\r\n            this.Bootstrapper.Initialise();\r\n\r\n            // When\r\n            var result = this.Bootstrapper.GetEngine();\r\n\r\n            // Then\r\n            result.ShouldNotBeNull();\r\n            result.ShouldBeOfType(typeof(INancyEngine));\r\n        }\r\n\r\n        [Fact]\r\n        public virtual void Should_use_types_from_config()\r\n        {\r\n            // Given\r\n            this.Bootstrapper.Initialise();\r\n\r\n            // When\r\n            var result = this.Bootstrapper.GetEngine();\r\n\r\n            // Then\r\n            result.ShouldBeOfType(typeof(FakeEngine));\r\n        }\r\n\r\n        [Fact]\r\n        public virtual void Should_register_config_types_as_singletons()\r\n        {\r\n            // Given\r\n            this.Bootstrapper.Initialise();\r\n\r\n            // When\r\n            var result1 = this.Bootstrapper.GetEngine();\r\n            var result2 = this.Bootstrapper.GetEngine();\r\n\r\n            // Then\r\n            result1.ShouldBeSameAs(result2);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_honour_typeregistration_singleton_lifetimes()\r\n        {\r\n            // Given\r\n            this.Bootstrapper.Initialise();\r\n\r\n            // When\r\n            var result1 = ((TestDependencyModule)this.Bootstrapper.GetModule(typeof(TestDependencyModule), new NancyContext()));\r\n            var result2 = ((TestDependencyModule)this.Bootstrapper.GetModule(typeof(TestDependencyModule), new NancyContext()));\r\n\r\n            // Then\r\n            result1.Singleton.ShouldBeSameAs(result2.Singleton);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_honour_typeregistration_transient_lifetimes()\r\n        {\r\n            // Given\r\n            this.Bootstrapper.Initialise();\r\n\r\n            // When\r\n            var result1 = ((TestDependencyModule)this.Bootstrapper.GetModule(typeof(TestDependencyModule), new NancyContext()));\r\n            var result2 = ((TestDependencyModule)this.Bootstrapper.GetModule(typeof(TestDependencyModule), new NancyContext()));\r\n\r\n            // Then\r\n            result1.Transient.ShouldNotBeSameAs(result2.Transient);\r\n        }\r\n\r\n        public class FakeEngine : INancyEngine\r\n        {\r\n            private readonly IRouteResolver resolver;\r\n            private readonly IRouteCache routeCache;\r\n            private readonly INancyContextFactory contextFactory;\r\n\r\n            public INancyContextFactory ContextFactory\r\n            {\r\n                get { return this.contextFactory; }\r\n            }\r\n\r\n            public IRouteCache RouteCache\r\n            {\r\n                get { return this.routeCache; }\r\n            }\r\n\r\n            public IRouteResolver Resolver\r\n            {\r\n                get { return this.resolver; }\r\n            }\r\n\r\n            public Func<NancyContext, Response> PreRequestHook { get; set; }\r\n\r\n            public Action<NancyContext> PostRequestHook { get; set; }\r\n\r\n            public Func<NancyContext, Exception, dynamic> OnErrorHook { get; set; }\r\n\r\n            public Func<NancyContext, IPipelines> RequestPipelinesFactory { get; set; }\r\n\r\n            public Task<NancyContext> HandleRequest(Request request, Func<NancyContext, NancyContext> preRequest, CancellationToken cancellationToken)\r\n            {\r\n                throw new NotImplementedException();\r\n            }\r\n\r\n            public FakeEngine(IRouteResolver resolver, IRouteCache routeCache, INancyContextFactory contextFactory)\r\n            {\r\n                if (resolver == null)\r\n                {\r\n                    throw new ArgumentNullException(\"resolver\", \"The resolver parameter cannot be null.\");\r\n                }\r\n\r\n                if (routeCache == null)\r\n                {\r\n                    throw new ArgumentNullException(\"routeCache\", \"The routeCache parameter cannot be null.\");\r\n                }\r\n\r\n                if (contextFactory == null)\r\n                {\r\n                    throw new ArgumentNullException(\"contextFactory\");\r\n                }\r\n\r\n                this.resolver = resolver;\r\n                this.routeCache = routeCache;\r\n                this.contextFactory = contextFactory;\r\n            }\r\n\r\n            public void Dispose()\r\n            {}\r\n        }\r\n    }\r\n\r\n    public class TestRegistrations : IRegistrations\r\n    {\r\n        public IEnumerable<TypeRegistration> TypeRegistrations { get; private set; }\r\n\r\n        public IEnumerable<CollectionTypeRegistration> CollectionTypeRegistrations { get; private set; }\r\n\r\n        public IEnumerable<InstanceRegistration> InstanceRegistrations { get; private set; }\r\n\r\n        public TestRegistrations()\r\n        {\r\n            this.TypeRegistrations = new[]\r\n                                         {\r\n                                             new TypeRegistration(\r\n                                                 typeof(Singleton),\r\n                                                 typeof(Singleton),\r\n                                                 Lifetime.Singleton),\r\n                                             new TypeRegistration(\r\n                                                 typeof(Transient),\r\n                                                 typeof(Transient),\r\n                                                 Lifetime.Transient),\r\n                                         };\r\n        }\r\n    }\r\n\r\n    public class Singleton\r\n    {\r\n    }\r\n\r\n    public class Transient\r\n    {\r\n    }\r\n\r\n    public class TestDependencyModule : NancyModule\r\n    {\r\n        public Singleton Singleton { get; set; }\r\n\r\n        public Transient Transient { get; set; }\r\n\r\n        public TestDependencyModule(Singleton singleton, Transient transient)\r\n        {\r\n            this.Singleton = singleton;\r\n            this.Transient = transient;\r\n        }\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "test/Nancy.Tests/Unit/Bootstrapper/Base/ModuleCatalogFixtureBase.cs",
    "content": "namespace Nancy.Tests.Unit.Bootstrapper.Base\r\n{\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    using Nancy.Bootstrapper;\r\n\r\n    using Xunit;\r\n\r\n    public abstract class ModuleCatalogFixtureBase\r\n    {\r\n        /// <summary>\r\n        /// Gets the catalog under test - should have ModuleTypesToRegister\r\n        /// registred as modules for resolution.\r\n        /// </summary>\r\n        protected abstract INancyModuleCatalog Catalog { get; }\r\n\r\n        protected IEnumerable<ModuleRegistration> ModuleTypesToRegister\r\n        {\r\n            get\r\n            {\r\n                return new[]\r\n                {\r\n                    new ModuleRegistration(typeof(FakeModule)), \r\n                };\r\n            }\r\n        }\r\n\r\n        [Fact]\r\n        public void GetModule_returns_different_instance_with_different_context()\r\n        {\r\n            var context1 = new NancyContext();\r\n            var context2 = new NancyContext();\r\n            var output1 = this.Catalog.GetModule(typeof(FakeModule), context1);\r\n            var output2 = this.Catalog.GetModule(typeof(FakeModule), context2);\r\n\r\n            output1.ShouldNotBeNull();\r\n            output2.ShouldNotBeNull();\r\n            output1.ShouldNotBeSameAs(output2);\r\n        }\r\n\r\n        [Fact]\r\n        public void GetAllModules_returns_different_instances_with_different_context()\r\n        {\r\n            var context1 = new NancyContext();\r\n            var context2 = new NancyContext();\r\n            var output1 = this.Catalog.GetAllModules(context1).FirstOrDefault();\r\n            var output2 = this.Catalog.GetAllModules(context2).FirstOrDefault();\r\n\r\n            output1.ShouldNotBeNull();\r\n            output2.ShouldNotBeNull();\r\n            output1.ShouldNotBeSameAs(output2);\r\n        }\r\n        \r\n        public class FakeModule : NancyModule\r\n        {\r\n            \r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Bootstrapper/BootstrapperLocatorFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Bootstrapper\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    using Nancy.Bootstrapper;\r\n\r\n    using Xunit;\r\n\r\n    public class BootstrapperLocatorFixture\r\n    {\r\n        /// <summary>\r\n        /// Internal stuff\r\n        /// </summary>\r\n        public interface IBootstwapper\r\n        {\r\n            \r\n        }\r\n\r\n        /// <summary>\r\n        /// Base\r\n        /// </summary>\r\n        public abstract class BootstwapperBase : IBootstwapper\r\n        {\r\n            \r\n        }\r\n\r\n        /// <summary>\r\n        /// Default\r\n        /// </summary>\r\n        public class DefaultBootstwapper : BootstwapperBase\r\n        {\r\n            \r\n        }\r\n\r\n        /// <summary>\r\n        /// Custom \r\n        /// </summary>\r\n        public class MyOwnDefaultBootstwapper : BootstwapperBase\r\n        {\r\n\r\n        }\r\n\r\n        /// <summary>\r\n        /// Custom \r\n        /// </summary>\r\n        public class MyFirstBootstwapper : DefaultBootstwapper\r\n        {\r\n            \r\n        }\r\n\r\n        /// <summary>\r\n        /// Custom \r\n        /// </summary>\r\n        public class AnotherFirstBootstwapper : DefaultBootstwapper\r\n        {\r\n\r\n        }\r\n\r\n        /// <summary>\r\n        /// Another custom one\r\n        /// </summary>\r\n        public class MySecondBootstwapper: MyFirstBootstwapper\r\n        {\r\n             \r\n        }\r\n        \r\n        /// <summary>\r\n        /// Another custom one\r\n        /// </summary>\r\n        public class MyThirdBootstwapper: MyFirstBootstwapper\r\n        {\r\n             \r\n        }\r\n\r\n        /// <summary>\r\n        /// Another custom one\r\n        /// </summary>\r\n        public class MyFourthBootstwapper : MySecondBootstwapper\r\n        {\r\n\r\n        }\r\n\r\n        public class TestTypeCatalog : ITypeCatalog\r\n        {\r\n            private readonly IReadOnlyCollection<Type> types;\r\n\r\n            public TestTypeCatalog(IReadOnlyCollection<Type> types)\r\n            {\r\n                this.types = types;\r\n            }\r\n\r\n            public IReadOnlyCollection<Type> GetTypesAssignableTo(Type type, TypeResolveStrategy strategy)\r\n            {\r\n                return types;\r\n            }\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_exception_when_multiple_bootstrappers_are_located()\r\n        {\r\n            // Given\r\n            var list = new List<Type> { typeof(MyFirstBootstwapper), typeof(AnotherFirstBootstwapper) };\r\n            var typeCatalog = new TestTypeCatalog(list);\r\n\r\n            // When\r\n            var result = Record.Exception(() => NancyBootstrapperLocator.GetBootstrapperType(typeCatalog));\r\n\r\n            // Then\r\n            result.ShouldNotBeNull();\r\n            result.GetType().ShouldEqual(typeof(BootstrapperException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_resolve_bootstrapper_type_from_unique_type()\r\n        {\r\n            // Given\r\n            var list = new List<Type> {typeof (MyFirstBootstwapper)};\r\n            var typeCatalog = new TestTypeCatalog(list);\r\n\r\n            // When\r\n            var bootstrapperType = NancyBootstrapperLocator.GetBootstrapperType(typeCatalog);\r\n\r\n            // Then\r\n            bootstrapperType.ShouldEqual(typeof(MyFirstBootstwapper));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_automatically_resolve_the_most_derived_bootstrapper()\r\n        {\r\n            // Given\r\n            var list = new List<Type> {typeof (MyFirstBootstwapper), typeof (MySecondBootstwapper), typeof(MyFourthBootstwapper)};\r\n            Type found;\r\n\r\n            // When\r\n            var res = NancyBootstrapperLocator.TryFindMostDerivedType(list, out found);\r\n\r\n            // Then\r\n            res.ShouldEqual(true);\r\n            found.ShouldEqual(typeof(MyFourthBootstwapper));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_when_there_are_more_than_one_most_derived_types_and_their_base_is_not_included()\r\n        {\r\n            // Given\r\n            var list = new List<Type> { typeof(MyFirstBootstwapper), typeof(AnotherFirstBootstwapper)};\r\n            Type found;\r\n\r\n            // When\r\n            var res = NancyBootstrapperLocator.TryFindMostDerivedType(list, out found);\r\n\r\n            // Then\r\n            res.ShouldEqual(false);\r\n            found.ShouldEqual(null);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_when_there_are_more_than_one_most_derived_types()\r\n        {\r\n            // Given\r\n            var list = new List<Type> { typeof(MyFirstBootstwapper), typeof(MySecondBootstwapper), typeof(MyThirdBootstwapper) };\r\n            Type found;\r\n\r\n            // When\r\n            var res = NancyBootstrapperLocator.TryFindMostDerivedType(list, out found);\r\n\r\n            // Then\r\n            res.ShouldEqual(false);\r\n            found.ShouldEqual(null);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_handle_parent_and_grandparent_inheritance_of_internal_stuff()\r\n        {\r\n            // Given\r\n            var list = new List<Type> { typeof(MyOwnDefaultBootstwapper), typeof(MyFirstBootstwapper) };\r\n            Type found;\r\n\r\n            // When\r\n            var res = NancyBootstrapperLocator.TryFindMostDerivedType(list, out found);\r\n\r\n            // Then\r\n            res.ShouldEqual(false);\r\n            found.ShouldEqual(null);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_handle_a_complete_graph()\r\n        {\r\n            // Given\r\n            var list = new List<Type> { typeof(BootstwapperBase), typeof(DefaultBootstwapper), typeof(MyFirstBootstwapper), typeof(MySecondBootstwapper) };\r\n            Type found;\r\n\r\n            // When\r\n            var res = NancyBootstrapperLocator.TryFindMostDerivedType(list, out found);\r\n\r\n            // Then\r\n            res.ShouldEqual(true);\r\n            found.ShouldEqual(typeof(MySecondBootstwapper));\r\n        } \r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Bootstrapper/CollectionTypeRegistrationFixture.cs",
    "content": "namespace Nancy.Tests.Unit.Bootstrapper\r\n{\r\n    using System;\r\n\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Responses.Negotiation;\r\n\r\n    using Xunit;\r\n\r\n    public class CollectionTypeRegistrationFixture\r\n    {\r\n        [Fact]\r\n        public void Should_throw_if_registration_type_is_null()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => new CollectionTypeRegistration(null, new[] { typeof(object) }));\r\n\r\n            // Then\r\n            result.ShouldBeOfType(typeof(ArgumentNullException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_if_implementation_types_is_null()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => new CollectionTypeRegistration(typeof(object), null));\r\n\r\n            // Then\r\n            result.ShouldBeOfType(typeof(ArgumentNullException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_if_not_all_implementation_types_does_implement_registration_type()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => new CollectionTypeRegistration(typeof(IResponseProcessor), new[] { typeof(XmlProcessor), typeof(DefaultNancyBootstrapper) }));\r\n\r\n            // Then\r\n            result.ShouldBeOfType(typeof(ArgumentException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_throw_if_all_implementation_types_implements_registration_type()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => new CollectionTypeRegistration(typeof(IResponseProcessor), new[] { typeof(XmlProcessor), typeof(JsonProcessor) }));\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Bootstrapper/InstanceRegistrationFixture.cs",
    "content": "namespace Nancy.Tests.Unit.Bootstrapper\r\n{\r\n    using System;\r\n\r\n    using Nancy.Bootstrapper;\r\n\r\n    using Xunit;\r\n\r\n    public class InstanceRegistrationFixture\r\n    {\r\n        [Fact]\r\n        public void Should_throw_if_registration_type_is_null()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => new InstanceRegistration(null, new object()));\r\n\r\n            // Then\r\n            result.ShouldBeOfType(typeof(ArgumentNullException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_if_implementation_is_null()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => new InstanceRegistration(typeof(object), null));\r\n\r\n            // Then\r\n            result.ShouldBeOfType(typeof(ArgumentNullException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_if_implementation_instance_does_not_implement_registration_type()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => new InstanceRegistration(typeof(INancyBootstrapper), new object()));\r\n\r\n            // Then\r\n            result.ShouldBeOfType(typeof(ArgumentException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_throw_if_implementation_instance_implements_registration_type()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => new InstanceRegistration(typeof(INancyBootstrapper), new DefaultNancyBootstrapper()));\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Bootstrapper/NancyBootstrapperBaseFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Bootstrapper\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Configuration;\r\n    using Nancy.Diagnostics;\r\n    using Nancy.Tests.Fakes;\r\n\r\n    using Xunit;\r\n\r\n    public class NancyBootstrapperBaseFixture\r\n    {\r\n        private readonly FakeBootstrapperBaseImplementation bootstrapper;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the NancyBootstrapperBaseFixture class.\r\n        /// </summary>\r\n        public NancyBootstrapperBaseFixture()\r\n        {\r\n            this.bootstrapper = new FakeBootstrapperBaseImplementation();\r\n            this.bootstrapper.Initialise();\r\n        }\r\n\r\n        [Fact]\r\n        public void GetEngine_Returns_Engine_From_GetEngineInternal()\r\n        {\r\n            // Given\r\n            // When\r\n            var result = this.bootstrapper.GetEngine();\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(bootstrapper.FakeNancyEngine);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_invalidaoperationexception_when_get_engine_fails()\r\n        {\r\n            // Given\r\n            this.bootstrapper.ShouldThrowWhenGettingEngine = true;\r\n\r\n            // When\r\n            var exception = Record.Exception(() => this.bootstrapper.GetEngine());\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<InvalidOperationException>();\r\n            exception.Message.ShouldEqual(\"Something went wrong when trying to satisfy one of the dependencies during composition, make sure that you've registered all new dependencies in the container and inspect the innerexception for more details.\");\r\n        }\r\n\r\n        [Fact]\r\n        public void GetEngine_Calls_ConfigureApplicationContainer_With_Container_From_GetContainer()\r\n        {\r\n            // Given\r\n            // When\r\n            this.bootstrapper.GetEngine();\r\n\r\n            // Then\r\n            this.bootstrapper.AppContainer.ShouldBeSameAs(bootstrapper.FakeContainer);\r\n        }\r\n\r\n        [Fact]\r\n        public void GetEngine_Calls_RegisterModules_With_Assembly_Modules()\r\n        {\r\n            // Given\r\n            // When\r\n            this.bootstrapper.GetEngine();\r\n\r\n            // Then\r\n            this.bootstrapper.PassedModules.ShouldNotBeNull();\r\n            this.bootstrapper.PassedModules.Where(mr => mr.ModuleType == typeof(FakeNancyModuleWithBasePath)).FirstOrDefault().ShouldNotBeNull();\r\n            this.bootstrapper.PassedModules.Where(mr => mr.ModuleType == typeof(FakeNancyModuleWithoutBasePath)).FirstOrDefault().ShouldNotBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Overridden_Modules_Is_Used_For_Getting_ModuleTypes()\r\n        {\r\n            // Given\r\n            var localBootstrapper = new FakeBootstrapperBaseGetModulesOverride();\r\n\r\n            // When\r\n            localBootstrapper.Initialise();\r\n            localBootstrapper.GetEngine();\r\n\r\n            // Then\r\n            localBootstrapper.RegisterModulesRegistrationTypes.ShouldBeSameAs(localBootstrapper.ModuleRegistrations);\r\n        }\r\n\r\n        [Fact]\r\n        public void GetEngine_sets_request_pipelines_factory()\r\n        {\r\n            // Given\r\n            this.bootstrapper.PreRequest += ctx => null;\r\n\r\n            // When\r\n            var result = this.bootstrapper.GetEngine();\r\n\r\n            // Then\r\n            result.RequestPipelinesFactory.ShouldNotBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_startup_tasks()\r\n        {\r\n            // Given\r\n            var startupMock = A.Fake<IApplicationStartup>();\r\n            var startupMock2 = A.Fake<IApplicationStartup>();\r\n            this.bootstrapper.OverriddenApplicationStartupTasks = new[] { startupMock, startupMock2 };\r\n\r\n            // When\r\n            this.bootstrapper.Initialise();\r\n\r\n            // Then\r\n            A.CallTo(() => startupMock.Initialize(A<IPipelines>._)).MustHaveHappenedOnceExactly();\r\n            A.CallTo(() => startupMock2.Initialize(A<IPipelines>._)).MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_startup_tasks_after_registration_tasks()\r\n        {\r\n            // Given\r\n            var startup = A.Fake<IApplicationStartup>();\r\n            this.bootstrapper.OverriddenApplicationStartupTasks = new[] { startup };\r\n\r\n            var registrations = A.Fake<IRegistrations>();\r\n            this.bootstrapper.OverriddenRegistrationTasks = new[] { registrations };\r\n\r\n            // When\r\n            this.bootstrapper.Initialise();\r\n\r\n            // Then\r\n            A.CallTo(() => registrations.CollectionTypeRegistrations).MustHaveHappened()\r\n                .Then(A.CallTo(() => startup.Initialize(A<IPipelines>._)).MustHaveHappened());\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_register_application_registration_type_registrations_into_container()\r\n        {\r\n            // Given\r\n            var typeRegistrations = ArrayCache.Empty<TypeRegistration>();\r\n            var startupStub = A.Fake<IRegistrations>();\r\n            A.CallTo(() => startupStub.TypeRegistrations).Returns(typeRegistrations);\r\n            this.bootstrapper.OverriddenRegistrationTasks = new[] { startupStub };\r\n\r\n            // When\r\n            this.bootstrapper.Initialise();\r\n\r\n            // Then\r\n            this.bootstrapper.ApplicationTypeRegistrations.ShouldBeSameAs(typeRegistrations);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_register_application_registration_task_collection_registrations_into_container()\r\n        {\r\n            // Given\r\n            var collectionTypeRegistrations = ArrayCache.Empty<CollectionTypeRegistration>();\r\n            var startupStub = A.Fake<IRegistrations>();\r\n            A.CallTo(() => startupStub.CollectionTypeRegistrations).Returns(collectionTypeRegistrations);\r\n            this.bootstrapper.OverriddenRegistrationTasks = new[] { startupStub };\r\n\r\n            // When\r\n            this.bootstrapper.Initialise();\r\n\r\n            // Then\r\n            this.bootstrapper.CollectionTypeRegistrations.ShouldBeSameAs(collectionTypeRegistrations);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_register_application_registration_instance_registrations_into_container()\r\n        {\r\n            // Given\r\n            var instanceRegistrations = ArrayCache.Empty<InstanceRegistration>();\r\n            var startupStub = A.Fake<IRegistrations>();\r\n            A.CallTo(() => startupStub.InstanceRegistrations).Returns(instanceRegistrations);\r\n            this.bootstrapper.OverriddenRegistrationTasks = new[] { startupStub };\r\n\r\n            // When\r\n            this.bootstrapper.Initialise();\r\n\r\n            // Then\r\n            this.bootstrapper.InstanceRegistrations.ShouldBeSameAs(instanceRegistrations);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_favicon_override()\r\n        {\r\n            // Given\r\n            var favicon = new byte[] { 1, 2, 3 };\r\n            this.bootstrapper.Favicon = favicon;\r\n            var favIconRequest = new FakeRequest(\"GET\", \"/favicon.ico\");\r\n            var context = new NancyContext { Request = favIconRequest };\r\n            this.bootstrapper.Initialise();\r\n\r\n            // When\r\n            var result = this.bootstrapper.PreRequest.Invoke(context, new CancellationToken());\r\n\r\n            // Then\r\n            result.ShouldNotBeNull();\r\n            result.Result.ContentType.ShouldEqual(\"image/vnd.microsoft.icon\");\r\n            result.Result.StatusCode = HttpStatusCode.OK;\r\n            GetBodyBytes(result.Result).SequenceEqual(favicon).ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_get_diagnostics_and_initialise()\r\n        {\r\n            var fakeDiagnostics = A.Fake<IDiagnostics>();\r\n            this.bootstrapper.FakeDiagnostics = fakeDiagnostics;\r\n\r\n            this.bootstrapper.Initialise();\r\n\r\n            A.CallTo(() => fakeDiagnostics.Initialize(A<IPipelines>._)).MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_dispose_app_container_if_bootstrapper_disposed()\r\n        {\r\n            this.bootstrapper.Initialise();\r\n            this.bootstrapper.GetEngine();\r\n\r\n            this.bootstrapper.Dispose();\r\n\r\n            this.bootstrapper.AppContainer.Disposed.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_only_get_request_startup_tasks_once()\r\n        {\r\n            // Given\r\n            var uninitialiedBootstrapper = new FakeBootstrapperBaseImplementation();\r\n            uninitialiedBootstrapper.Initialise();\r\n            var engine = uninitialiedBootstrapper.GetEngine();\r\n\r\n            // When\r\n            await engine.HandleRequest(new FakeRequest(\"GET\", \"/\"));\r\n            await engine.HandleRequest(new FakeRequest(\"GET\", \"/\"));\r\n\r\n            // Then\r\n            uninitialiedBootstrapper.RequestStartupTasksCalls.ShouldEqual(1);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_request_startup_tasks_when_request_pipelines_initialised()\r\n        {\r\n            // Given\r\n            var uninitialiedBootstrapper = new FakeBootstrapperBaseImplementation();\r\n            var startupMock = A.Fake<IRequestStartup>();\r\n            var startupMock2 = A.Fake<IRequestStartup>();\r\n            uninitialiedBootstrapper.RequestStartupTypes = new[] { typeof(object) };\r\n            uninitialiedBootstrapper.RequestStartups = new[] { startupMock, startupMock2 };\r\n            uninitialiedBootstrapper.Initialise();\r\n\r\n            // When\r\n            uninitialiedBootstrapper.GetRequestPipelines(new NancyContext());\r\n\r\n            // Then\r\n            A.CallTo(() => startupMock.Initialize(A<IPipelines>._, A<NancyContext>._)).MustHaveHappenedOnceExactly();\r\n            A.CallTo(() => startupMock2.Initialize(A<IPipelines>._, A<NancyContext>._)).MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_ask_to_resolve_request_startups_if_none_registered()\r\n        {\r\n            // Given\r\n            var uninitialiedBootstrapper = new FakeBootstrapperBaseImplementation();\r\n            uninitialiedBootstrapper.RequestStartupTypes = ArrayCache.Empty<Type>();\r\n            uninitialiedBootstrapper.Initialise();\r\n\r\n            // When\r\n            uninitialiedBootstrapper.GetRequestPipelines(new NancyContext());\r\n\r\n            // Then\r\n            uninitialiedBootstrapper.GetRequestStartupTasksCalled.ShouldBeFalse();\r\n        }\r\n\r\n        private static IEnumerable<byte> GetBodyBytes(Response response)\r\n        {\r\n            using (var contentsStream = new MemoryStream())\r\n            {\r\n                response.Contents.Invoke(contentsStream);\r\n\r\n                return contentsStream.ToArray();\r\n            }\r\n        }\r\n    }\r\n\r\n    internal class FakeBootstrapperBaseImplementation : NancyBootstrapperBase<FakeContainer>\r\n    {\r\n        public IDiagnostics FakeDiagnostics { get; set; }\r\n        public INancyEngine FakeNancyEngine { get; set; }\r\n        public FakeContainer FakeContainer { get; set; }\r\n        public FakeContainer AppContainer { get; set; }\r\n        public IEnumerable<TypeRegistration> ApplicationTypeRegistrations { get; set; }\r\n        public IEnumerable<CollectionTypeRegistration> CollectionTypeRegistrations { get; set; }\r\n        public IEnumerable<InstanceRegistration> InstanceRegistrations { get; set; }\r\n        public List<ModuleRegistration> PassedModules { get; set; }\r\n        public IApplicationStartup[] OverriddenApplicationStartupTasks { get; set; }\r\n        public IRegistrations[] OverriddenRegistrationTasks { get; set; }\r\n        public bool ShouldThrowWhenGettingEngine { get; set; }\r\n        public int RequestStartupTasksCalls { get; set; }\r\n        public IEnumerable<IRequestStartup> RequestStartups { get; set; }\r\n        public bool GetRequestStartupTasksCalled { get; set; }\r\n        public IEnumerable<Type> RequestStartupTypes { get; set; }\r\n\r\n        public FakeBootstrapperBaseImplementation()\r\n        {\r\n            FakeNancyEngine = A.Fake<INancyEngine>();\r\n            FakeContainer = new FakeContainer();\r\n        }\r\n\r\n        protected override IEnumerable<Type> RequestStartupTasks\r\n        {\r\n            get\r\n            {\r\n                this.RequestStartupTasksCalls++;\r\n\r\n                return this.RequestStartupTypes ?? base.RequestStartupTasks;\r\n            }\r\n        }\r\n\r\n        protected override INancyEngine GetEngineInternal()\r\n        {\r\n            if (this.ShouldThrowWhenGettingEngine)\r\n            {\r\n                throw new Exception(\"Something when wrong when trying to compose the engine.\");\r\n            }\r\n\r\n            return this.FakeNancyEngine;\r\n        }\r\n\r\n        protected override INancyEnvironmentConfigurator GetEnvironmentConfigurator()\r\n        {\r\n            return new FakeEnvironmentConfigurator();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the diagnostics for initialisation\r\n        /// </summary>\r\n        /// <returns>IDiagnostics implementation</returns>\r\n        protected override IDiagnostics GetDiagnostics()\r\n        {\r\n            return this.FakeDiagnostics ?? new DisabledDiagnostics();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all registered startup tasks\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance containing <see cref=\"IApplicationStartup\"/> instances. </returns>\r\n        protected override IEnumerable<IApplicationStartup> GetApplicationStartupTasks()\r\n        {\r\n            return this.OverriddenApplicationStartupTasks ?? ArrayCache.Empty<IApplicationStartup>();\r\n        }\r\n\r\n        protected override IEnumerable<IRequestStartup> RegisterAndGetRequestStartupTasks(FakeContainer container, Type[] requestStartupTypes)\r\n        {\r\n            this.GetRequestStartupTasksCalled = true;\r\n\r\n            return this.RequestStartups;\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all registered application registration tasks\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance containing <see cref=\"IRegistrations\"/> instances.</returns>\r\n        protected override IEnumerable<IRegistrations> GetRegistrationTasks()\r\n        {\r\n            return this.OverriddenRegistrationTasks ?? ArrayCache.Empty<IRegistrations>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get all NancyModule implementation instances\r\n        /// </summary>\r\n        /// <param name=\"context\">The current context</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance containing <see cref=\"INancyModule\"/> instances.</returns>\r\n        public override IEnumerable<INancyModule> GetAllModules(NancyContext context)\r\n        {\r\n            return this.PassedModules.Select(m => (INancyModule)Activator.CreateInstance(m.ModuleType));\r\n        }\r\n\r\n        public override INancyModule GetModule(Type moduleType, NancyContext context)\r\n        {\r\n            return\r\n                this.PassedModules.Where(m => m.ModuleType == moduleType)\r\n                    .Select(m => (INancyModule)Activator.CreateInstance(m.ModuleType))\r\n                    .FirstOrDefault();\r\n        }\r\n\r\n        public override INancyEnvironment GetEnvironment()\r\n        {\r\n            throw new NotImplementedException();\r\n        }\r\n\r\n        protected override void ConfigureApplicationContainer(FakeContainer existingContainer)\r\n        {\r\n            this.AppContainer = existingContainer;\r\n        }\r\n\r\n        protected override FakeContainer GetApplicationContainer()\r\n        {\r\n            return FakeContainer;\r\n        }\r\n\r\n        protected override void RegisterNancyEnvironment(FakeContainer container, INancyEnvironment environment)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Register the bootstrapper's implemented types into the container.\r\n        /// This is necessary so a user can pass in a populated container but not have\r\n        /// to take the responsibility of registering things like INancyModuleCatalog manually.\r\n        /// </summary>\r\n        /// <param name=\"applicationContainer\">Application container to register into</param>\r\n        protected override void RegisterBootstrapperTypes(FakeContainer applicationContainer)\r\n        {\r\n        }\r\n\r\n        protected override void RegisterTypes(FakeContainer container, IEnumerable<TypeRegistration> typeRegistrations)\r\n        {\r\n            this.ApplicationTypeRegistrations = typeRegistrations;\r\n        }\r\n\r\n        protected override void RegisterCollectionTypes(FakeContainer container, IEnumerable<CollectionTypeRegistration> collectionTypeRegistrations)\r\n        {\r\n            this.CollectionTypeRegistrations = collectionTypeRegistrations;\r\n        }\r\n\r\n        protected override void RegisterModules(FakeContainer container, IEnumerable<ModuleRegistration> moduleRegistrationTypes)\r\n        {\r\n            PassedModules = new List<ModuleRegistration>(moduleRegistrationTypes);\r\n        }\r\n\r\n        protected override void RegisterInstances(FakeContainer container, IEnumerable<InstanceRegistration> instanceRegistrations)\r\n        {\r\n            this.InstanceRegistrations = instanceRegistrations;\r\n        }\r\n\r\n        protected override byte[] FavIcon\r\n        {\r\n            get { return this.Favicon ?? base.FavIcon; }\r\n        }\r\n\r\n        public BeforePipeline PreRequest\r\n        {\r\n            get { return this.ApplicationPipelines.BeforeRequest; }\r\n            set { this.ApplicationPipelines.BeforeRequest = value; }\r\n        }\r\n\r\n        public AfterPipeline PostRequest\r\n        {\r\n            get { return this.ApplicationPipelines.AfterRequest; }\r\n            set { this.ApplicationPipelines.AfterRequest = value; }\r\n        }\r\n\r\n        public byte[] Favicon { get; set; }\r\n\r\n        public IPipelines GetRequestPipelines(NancyContext context)\r\n        {\r\n            return this.InitializeRequestPipelines(context);\r\n        }\r\n    }\r\n\r\n    internal class FakeContainer : IDisposable\r\n    {\r\n        public void Dispose()\r\n        {\r\n            this.Disposed = true;\r\n        }\r\n\r\n        public bool Disposed { get; private set; }\r\n    }\r\n\r\n    internal class FakeEnvironmentConfigurator : INancyEnvironmentConfigurator\r\n    {\r\n        public INancyEnvironment ConfigureEnvironment(Action<INancyEnvironment> configuration)\r\n        {\r\n            return new DefaultNancyEnvironment();\r\n        }\r\n    }\r\n\r\n    internal class FakeBootstrapperBaseGetModulesOverride : NancyBootstrapperBase<object>\r\n    {\r\n        public IEnumerable<ModuleRegistration> RegisterModulesRegistrationTypes { get; set; }\r\n        public IEnumerable<ModuleRegistration> ModuleRegistrations { get; set; }\r\n\r\n        protected override IEnumerable<ModuleRegistration> Modules\r\n        {\r\n            get\r\n            {\r\n                return ModuleRegistrations;\r\n            }\r\n        }\r\n\r\n        public FakeBootstrapperBaseGetModulesOverride()\r\n        {\r\n            ModuleRegistrations = new List<ModuleRegistration>() { new ModuleRegistration(this.GetType()) };\r\n        }\r\n\r\n        protected override INancyEnvironmentConfigurator GetEnvironmentConfigurator()\r\n        {\r\n            return new FakeEnvironmentConfigurator();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets the diagnostics for initialisation\r\n        /// </summary>\r\n        /// <returns>IDiagnostics implementation</returns>\r\n        protected override IDiagnostics GetDiagnostics()\r\n        {\r\n            return new DisabledDiagnostics();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all registered startup tasks\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance containing <see cref=\"IApplicationStartup\"/> instances. </returns>\r\n        protected override IEnumerable<IApplicationStartup> GetApplicationStartupTasks()\r\n        {\r\n            return ArrayCache.Empty<IApplicationStartup>();\r\n        }\r\n\r\n        protected override IEnumerable<IRequestStartup> RegisterAndGetRequestStartupTasks(object container, Type[] requestStartupTypes)\r\n        {\r\n            return ArrayCache.Empty<IRequestStartup>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Gets all registered application registration tasks\r\n        /// </summary>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance containing <see cref=\"IRegistrations\"/> instances.</returns>\r\n        protected override IEnumerable<IRegistrations> GetRegistrationTasks()\r\n        {\r\n            return ArrayCache.Empty<IRegistrations>();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Get all NancyModule implementation instances\r\n        /// </summary>\r\n        /// <param name=\"context\">The current context</param>\r\n        /// <returns>An <see cref=\"IEnumerable{T}\"/> instance containing <see cref=\"INancyModule\"/> instances.</returns>\r\n        public override IEnumerable<INancyModule> GetAllModules(NancyContext context)\r\n        {\r\n            throw new NotImplementedException();\r\n        }\r\n\r\n        /// <summary>\r\n        /// Retrieves a specific <see cref=\"INancyModule\"/> implementation - should be per-request lifetime\r\n        /// </summary>\r\n        /// <param name=\"moduleType\">Module type</param>\r\n        /// <param name=\"context\">The current context</param>\r\n        /// <returns>The <see cref=\"INancyModule\"/> instance</returns>\r\n        public override INancyModule GetModule(Type moduleType, NancyContext context)\r\n        {\r\n            throw new NotImplementedException();\r\n        }\r\n\r\n        public override INancyEnvironment GetEnvironment()\r\n        {\r\n            throw new NotImplementedException();\r\n        }\r\n\r\n        protected override INancyEngine GetEngineInternal()\r\n        {\r\n            return A.Fake<INancyEngine>();\r\n        }\r\n\r\n        protected override object GetApplicationContainer()\r\n        {\r\n            return new object();\r\n        }\r\n\r\n        protected override void RegisterNancyEnvironment(object container, INancyEnvironment environment)\r\n        {\r\n        }\r\n\r\n        /// <summary>\r\n        /// Register the bootstrapper's implemented types into the container.\r\n        /// This is necessary so a user can pass in a populated container but not have\r\n        /// to take the responsibility of registering things like INancyModuleCatalog manually.\r\n        /// </summary>\r\n        /// <param name=\"applicationContainer\">Application container to register into</param>\r\n        protected override void RegisterBootstrapperTypes(object applicationContainer)\r\n        {\r\n        }\r\n\r\n        protected override void RegisterTypes(object container, IEnumerable<TypeRegistration> typeRegistrations)\r\n        {\r\n        }\r\n\r\n        protected override void RegisterCollectionTypes(object container, IEnumerable<CollectionTypeRegistration> collectionTypeRegistrationsn)\r\n        {\r\n        }\r\n\r\n        protected override void RegisterModules(object container, IEnumerable<ModuleRegistration> moduleRegistrationTypes)\r\n        {\r\n            this.RegisterModulesRegistrationTypes = moduleRegistrationTypes;\r\n        }\r\n\r\n        protected override void RegisterInstances(object container, IEnumerable<InstanceRegistration> instanceRegistrations)\r\n        {\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Bootstrapper/NancyBootstrapperWithRequestContainerBaseFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Bootstrapper\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Configuration;\r\n    using Nancy.Diagnostics;\r\n    using Nancy.Tests.Fakes;\r\n\r\n    using Xunit;\r\n\r\n    public class NancyBootstrapperWithRequestContainerBaseFixture\r\n    {\r\n        private readonly FakeBootstrapper bootstrapper;\r\n\r\n        public NancyBootstrapperWithRequestContainerBaseFixture()\r\n        {\r\n            this.bootstrapper = new FakeBootstrapper();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_register_request_lifetime_types_into_application_container()\r\n        {\r\n            // Given\r\n            var typeRegistrations = new[]\r\n                                    {\r\n                                        new TypeRegistration(typeof(object), typeof(object)),\r\n                                        new TypeRegistration(typeof(FakeBootstrapperBaseImplementation), typeof(FakeBootstrapperBaseImplementation), Lifetime.Transient),\r\n                                        new TypeRegistration(typeof(string), typeof(string), Lifetime.PerRequest),\r\n                                    };\r\n            var startupStub = A.Fake<IRegistrations>();\r\n            A.CallTo(() => startupStub.TypeRegistrations).Returns(typeRegistrations);\r\n            this.bootstrapper.OverriddenRegistrationTasks = new[] { startupStub };\r\n\r\n            // When\r\n            this.bootstrapper.Initialise();\r\n\r\n            // Then\r\n            this.bootstrapper.ApplicationTypeRegistrations.Any(tr => tr.RegistrationType == typeof(object)).ShouldBeTrue();\r\n            this.bootstrapper.ApplicationTypeRegistrations.Any(tr => tr.RegistrationType == typeof(FakeBootstrapperBaseImplementation)).ShouldBeTrue();\r\n            this.bootstrapper.ApplicationTypeRegistrations.Any(tr => tr.RegistrationType == typeof(string)).ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_register_request_lifetime_types_into_request_container_as_singletons()\r\n        {\r\n            // Given\r\n            var typeRegistrations = new[]\r\n                                    {\r\n                                        new TypeRegistration(typeof(object), typeof(object)),\r\n                                        new TypeRegistration(typeof(FakeBootstrapperBaseImplementation), typeof(FakeBootstrapperBaseImplementation), Lifetime.Transient),\r\n                                        new TypeRegistration(typeof(string), typeof(string), Lifetime.PerRequest),\r\n                                    };\r\n            var startupStub = A.Fake<IRegistrations>();\r\n            A.CallTo(() => startupStub.TypeRegistrations).Returns(typeRegistrations);\r\n            var engine = new FakeEngine();\r\n            this.bootstrapper.FakeNancyEngine = engine;\r\n            this.bootstrapper.OverriddenRegistrationTasks = new[] { startupStub };\r\n            this.bootstrapper.Initialise();\r\n\r\n            // When\r\n            var builtEngine = this.bootstrapper.GetEngine();\r\n            builtEngine.HandleRequest(new FakeRequest(\"GET\", \"/\"));\r\n\r\n            // Then\r\n            this.bootstrapper.RequestTypeRegistrations.Any(tr => tr.RegistrationType == typeof(string) && tr.Lifetime == Lifetime.Singleton).ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_register_request_lifetime_collectiontypes_into_application_container()\r\n        {\r\n            // Given\r\n            var collectionRegistrations = new[]\r\n                                    {\r\n                                        new CollectionTypeRegistration(typeof(object), new[] { typeof(object) }),\r\n                                        new CollectionTypeRegistration(typeof(FakeBootstrapperBaseImplementation), new[] { typeof(FakeBootstrapperBaseImplementation) }, Lifetime.Transient),\r\n                                        new CollectionTypeRegistration(typeof(string), new[] { typeof(string) }, Lifetime.PerRequest),\r\n                                    };\r\n            var startupStub = A.Fake<IRegistrations>();\r\n            A.CallTo(() => startupStub.CollectionTypeRegistrations).Returns(collectionRegistrations);\r\n            this.bootstrapper.OverriddenRegistrationTasks = new[] { startupStub };\r\n\r\n            // When\r\n            this.bootstrapper.Initialise();\r\n\r\n            // Then\r\n            this.bootstrapper.ApplicationCollectionTypeRegistrations.Any(tr => tr.RegistrationType == typeof(object)).ShouldBeTrue();\r\n            this.bootstrapper.ApplicationCollectionTypeRegistrations.Any(tr => tr.RegistrationType == typeof(FakeBootstrapperBaseImplementation)).ShouldBeTrue();\r\n            this.bootstrapper.ApplicationCollectionTypeRegistrations.Any(tr => tr.RegistrationType == typeof(string)).ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_register_request_lifetime_collectiontypes_into_request_container_as_singletons()\r\n        {\r\n            // Given\r\n            var collectionRegistrations = new[]\r\n                                    {\r\n                                        new CollectionTypeRegistration(typeof(object), new[] { typeof(object) }),\r\n                                        new CollectionTypeRegistration(typeof(FakeBootstrapperBaseImplementation), new[] { typeof(FakeBootstrapperBaseImplementation) }, Lifetime.Transient),\r\n                                        new CollectionTypeRegistration(typeof(string), new[] { typeof(string) }, Lifetime.PerRequest),\r\n                                    };\r\n            var startupStub = A.Fake<IRegistrations>();\r\n            A.CallTo(() => startupStub.CollectionTypeRegistrations).Returns(collectionRegistrations);\r\n            var engine = new FakeEngine();\r\n            this.bootstrapper.FakeNancyEngine = engine;\r\n            this.bootstrapper.OverriddenRegistrationTasks = new[] { startupStub };\r\n            this.bootstrapper.Initialise();\r\n\r\n            // When\r\n            var builtEngine = this.bootstrapper.GetEngine();\r\n            builtEngine.HandleRequest(new FakeRequest(\"GET\", \"/\"));\r\n\r\n            // Then\r\n            this.bootstrapper.RequestCollectionTypeRegistrations.Any(tr => tr.RegistrationType == typeof(string) && tr.Lifetime == Lifetime.Singleton).ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_request_startup_tasks_when_request_pipelines_initialised()\r\n        {\r\n            // Given\r\n            var startupMock = A.Fake<IRequestStartup>();\r\n            var startupMock2 = A.Fake<IRequestStartup>();\r\n            this.bootstrapper.RequestStartupTypes = new[] { typeof(object) };\r\n            this.bootstrapper.OverriddenRequestStartupTasks = new[] { startupMock, startupMock2 };\r\n            this.bootstrapper.Initialise();\r\n\r\n            // When\r\n            this.bootstrapper.GetRequestPipelines(new NancyContext());\r\n\r\n            // Then\r\n            A.CallTo(() => startupMock.Initialize(A<IPipelines>._, A<NancyContext>._)).MustHaveHappenedOnceExactly();\r\n            A.CallTo(() => startupMock2.Initialize(A<IPipelines>._, A<NancyContext>._)).MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_resolve_request_startup_tasks_from_request_container()\r\n        {\r\n            // Given\r\n            var startupMock = A.Fake<IRequestStartup>();\r\n            this.bootstrapper.RequestStartupTypes = new[] { typeof(object) };\r\n            this.bootstrapper.OverriddenRequestStartupTasks = new[] { startupMock };\r\n            this.bootstrapper.Initialise();\r\n\r\n            // When\r\n            this.bootstrapper.GetRequestPipelines(new NancyContext());\r\n\r\n            // Then\r\n            this.bootstrapper.RequestStartupTasksResolveContainer.Parent.ShouldNotBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_ask_to_resolve_request_startups_if_none_registered()\r\n        {\r\n            // Given\r\n            this.bootstrapper.RequestStartupTypes = ArrayCache.Empty<Type>();\r\n            this.bootstrapper.OverriddenRequestStartupTasks = ArrayCache.Empty<IRequestStartup>();\r\n            this.bootstrapper.Initialise();\r\n\r\n            // When\r\n            this.bootstrapper.GetRequestPipelines(new NancyContext());\r\n\r\n            // Then\r\n            this.bootstrapper.GetRequestStartupTasksCalled.ShouldBeFalse();\r\n        }\r\n\r\n        internal class FakeEngine : INancyEngine\r\n        {\r\n            public Func<NancyContext, IPipelines> RequestPipelinesFactory { get; set; }\r\n\r\n            public Task<NancyContext> HandleRequest(Request request, Func<NancyContext, NancyContext> preRequest, CancellationToken cancellationToken)\r\n            {\r\n                var tcs = new TaskCompletionSource<NancyContext>();\r\n\r\n                var nancyContext = new NancyContext() { Request = request };\r\n\r\n                this.RequestPipelinesFactory.Invoke(nancyContext);\r\n\r\n                tcs.SetResult(nancyContext);\r\n\r\n                return tcs.Task;\r\n            }\r\n\r\n            public void Dispose()\r\n            {\r\n            }\r\n        }\r\n\r\n        internal class FakeBootstrapper : NancyBootstrapperWithRequestContainerBase<FakeContainer>\r\n        {\r\n            public IDiagnostics FakeDiagnostics { get; set; }\r\n\r\n            public INancyEngine FakeNancyEngine { get; set; }\r\n\r\n            public FakeContainer FakeContainer { get; set; }\r\n\r\n            public FakeContainer AppContainer { get; set; }\r\n\r\n            public IEnumerable<TypeRegistration> ApplicationTypeRegistrations { get; set; }\r\n\r\n            public IEnumerable<TypeRegistration> RequestTypeRegistrations { get; set; }\r\n\r\n            public IEnumerable<CollectionTypeRegistration> ApplicationCollectionTypeRegistrations { get; set; }\r\n\r\n            public IEnumerable<CollectionTypeRegistration> RequestCollectionTypeRegistrations { get; set; }\r\n\r\n            public IEnumerable<InstanceRegistration> InstanceRegistrations { get; set; }\r\n\r\n            public List<ModuleRegistration> PassedModules { get; set; }\r\n\r\n            public IApplicationStartup[] OverriddenApplicationStartupTasks { get; set; }\r\n\r\n            public IRequestStartup[] OverriddenRequestStartupTasks { get; set; }\r\n\r\n            public IRegistrations[] OverriddenRegistrationTasks { get; set; }\r\n\r\n            public bool ShouldThrowWhenGettingEngine { get; set; }\r\n\r\n            public FakeContainer RequestStartupTasksResolveContainer { get; set; }\r\n\r\n            public bool GetRequestStartupTasksCalled { get; set; }\r\n\r\n            public IEnumerable<Type> RequestStartupTypes { get; set; }\r\n\r\n            public FakeBootstrapper()\r\n            {\r\n                FakeNancyEngine = A.Fake<INancyEngine>();\r\n                FakeContainer = new FakeContainer();\r\n            }\r\n\r\n            protected override IEnumerable<Type> RequestStartupTasks\r\n            {\r\n                get\r\n                {\r\n                    return this.RequestStartupTypes ?? base.RequestStartupTasks;\r\n                }\r\n            }\r\n\r\n            protected override INancyEngine GetEngineInternal()\r\n            {\r\n                if (this.ShouldThrowWhenGettingEngine)\r\n                {\r\n                    throw new Exception(\"Something when wrong when trying to compose the engine.\");\r\n                }\r\n\r\n                return this.FakeNancyEngine;\r\n            }\r\n\r\n            protected override INancyEnvironmentConfigurator GetEnvironmentConfigurator()\r\n            {\r\n                return new FakeEnvironmentConfigurator();\r\n            }\r\n\r\n            /// <summary>\r\n            /// Gets the diagnostics for initialisation\r\n            /// </summary>\r\n            /// <returns>IDiagnostics implementation</returns>\r\n            protected override IDiagnostics GetDiagnostics()\r\n            {\r\n                return this.FakeDiagnostics ?? new DisabledDiagnostics();\r\n            }\r\n\r\n            /// <summary>\r\n            /// Gets all registered startup tasks\r\n            /// </summary>\r\n            /// <returns>An <see cref=\"IEnumerable{T}\"/> instance containing <see cref=\"IApplicationStartup\"/> instances. </returns>\r\n            protected override IEnumerable<IApplicationStartup> GetApplicationStartupTasks()\r\n            {\r\n                return this.OverriddenApplicationStartupTasks ?? ArrayCache.Empty<IApplicationStartup>();\r\n            }\r\n\r\n            protected override IEnumerable<IRequestStartup> RegisterAndGetRequestStartupTasks(FakeContainer container, Type[] requestStartupTypes)\r\n            {\r\n                this.RequestStartupTasksResolveContainer = container;\r\n\r\n                this.GetRequestStartupTasksCalled = true;\r\n\r\n                return this.OverriddenRequestStartupTasks ?? ArrayCache.Empty<IRequestStartup>();\r\n            }\r\n\r\n            /// <summary>\r\n            /// Gets all registered application registration tasks\r\n            /// </summary>\r\n            /// <returns>An <see cref=\"IEnumerable{T}\"/> instance containing <see cref=\"IRegistrations\"/> instances.</returns>\r\n            protected override IEnumerable<IRegistrations> GetRegistrationTasks()\r\n            {\r\n                return this.OverriddenRegistrationTasks ?? ArrayCache.Empty<IRegistrations>();\r\n            }\r\n\r\n            public override INancyEnvironment GetEnvironment()\r\n            {\r\n                throw new NotImplementedException();\r\n            }\r\n\r\n            protected override void ConfigureApplicationContainer(FakeContainer existingContainer)\r\n            {\r\n                this.AppContainer = existingContainer;\r\n            }\r\n\r\n            protected override FakeContainer GetApplicationContainer()\r\n            {\r\n                return FakeContainer;\r\n            }\r\n\r\n            /// <summary>\r\n            /// Registers an <see cref=\"INancyEnvironment\"/> instance in the container.\r\n            /// </summary>\r\n            /// <param name=\"container\">The container to register into.</param>\r\n            /// <param name=\"environment\">The <see cref=\"INancyEnvironment\"/> instance to register.</param>\r\n            protected override void RegisterNancyEnvironment(FakeContainer container, INancyEnvironment environment)\r\n            {\r\n            }\r\n\r\n            /// <summary>\r\n            /// Register the bootstrapper's implemented types into the container.\r\n            /// This is necessary so a user can pass in a populated container but not have\r\n            /// to take the responsibility of registering things like INancyModuleCatalog manually.\r\n            /// </summary>\r\n            /// <param name=\"applicationContainer\">Application container to register into</param>\r\n            protected override void RegisterBootstrapperTypes(FakeContainer applicationContainer)\r\n            {\r\n            }\r\n\r\n            protected override void RegisterTypes(\r\n                FakeContainer container,\r\n                IEnumerable<TypeRegistration> typeRegistrations)\r\n            {\r\n                if (ReferenceEquals(container, this.AppContainer))\r\n                {\r\n                    this.ApplicationTypeRegistrations = typeRegistrations;\r\n                }\r\n                else\r\n                {\r\n                    this.RequestTypeRegistrations = typeRegistrations;\r\n                }\r\n            }\r\n\r\n            protected override void RegisterCollectionTypes(\r\n                FakeContainer container,\r\n                IEnumerable<CollectionTypeRegistration> collectionTypeRegistrations)\r\n            {\r\n                if (ReferenceEquals(container, this.AppContainer))\r\n                {\r\n                    this.ApplicationCollectionTypeRegistrations = collectionTypeRegistrations;\r\n                }\r\n                else\r\n                {\r\n                    this.RequestCollectionTypeRegistrations = collectionTypeRegistrations;\r\n                }\r\n            }\r\n\r\n            protected override FakeContainer CreateRequestContainer(NancyContext context)\r\n            {\r\n                return new FakeContainer(this.ApplicationContainer);\r\n            }\r\n\r\n            protected override void RegisterRequestContainerModules(FakeContainer container, IEnumerable<ModuleRegistration> moduleRegistrationTypes)\r\n            {\r\n                PassedModules = new List<ModuleRegistration>(moduleRegistrationTypes);\r\n            }\r\n\r\n            protected override IEnumerable<INancyModule> GetAllModules(FakeContainer container)\r\n            {\r\n                return this.PassedModules.Select(m => (INancyModule)Activator.CreateInstance(m.ModuleType));\r\n            }\r\n\r\n            protected override INancyModule GetModule(FakeContainer container, Type moduleType)\r\n            {\r\n                return\r\n                    this.PassedModules.Where(m => m.ModuleType == moduleType)\r\n                        .Select(m => (INancyModule)Activator.CreateInstance(m.ModuleType))\r\n                        .FirstOrDefault();\r\n            }\r\n\r\n            protected override void RegisterInstances(\r\n                FakeContainer container,\r\n                IEnumerable<InstanceRegistration> instanceRegistrations)\r\n            {\r\n                this.InstanceRegistrations = instanceRegistrations;\r\n            }\r\n\r\n            protected override byte[] FavIcon\r\n            {\r\n                get\r\n                {\r\n                    return this.Favicon ?? base.FavIcon;\r\n                }\r\n            }\r\n\r\n            public BeforePipeline PreRequest\r\n            {\r\n                get\r\n                {\r\n                    return this.ApplicationPipelines.BeforeRequest;\r\n                }\r\n                set\r\n                {\r\n                    this.ApplicationPipelines.BeforeRequest = value;\r\n                }\r\n            }\r\n\r\n            public AfterPipeline PostRequest\r\n            {\r\n                get\r\n                {\r\n                    return this.ApplicationPipelines.AfterRequest;\r\n                }\r\n                set\r\n                {\r\n                    this.ApplicationPipelines.AfterRequest = value;\r\n                }\r\n            }\r\n\r\n            public byte[] Favicon { get; set; }\r\n\r\n            public IPipelines GetRequestPipelines(NancyContext nancyContext)\r\n            {\r\n                return this.InitializeRequestPipelines(nancyContext);\r\n            }\r\n        }\r\n\r\n        internal class FakeContainer : IDisposable\r\n        {\r\n            public FakeContainer Parent { get; private set; }\r\n\r\n            public FakeContainer(FakeContainer parent = null)\r\n            {\r\n                this.Parent = parent;\r\n            }\r\n\r\n            public void Dispose()\r\n            {\r\n                this.Disposed = true;\r\n            }\r\n\r\n            public bool Disposed { get; private set; }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Bootstrapper/NancyInternalConfigurationFixture.cs",
    "content": "namespace Nancy.Tests.Unit.Bootstrapper\r\n{\r\n    using System.Linq;\r\n    using FakeItEasy;\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.ModelBinding;\r\n    using Xunit;\r\n\r\n    public class NancyInternalConfigurationFixture\r\n    {\r\n        private readonly ITypeCatalog typeCatalog;\r\n\r\n        public NancyInternalConfigurationFixture()\r\n        {\r\n            IAssemblyCatalog assemblyCatalog;\r\n\r\n#if !CORE\r\n            assemblyCatalog = new AppDomainAssemblyCatalog();\r\n#else\r\n            assemblyCatalog = new DependencyContextAssemblyCatalog();\r\n#endif\r\n\r\n            this.typeCatalog = new DefaultTypeCatalog(assemblyCatalog);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_default_instance()\r\n        {\r\n            // Given, When\r\n            var result = NancyInternalConfiguration.Default.Invoke(this.typeCatalog);\r\n\r\n            // Then\r\n            result.ShouldNotBeNull();\r\n            result.ShouldBeOfType(typeof(NancyInternalConfiguration));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_valid_default()\r\n        {\r\n            // Given\r\n            var config = NancyInternalConfiguration.Default.Invoke(this.typeCatalog);\r\n\r\n            // When\r\n            var result = config.IsValid;\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_have_type_registrations_in_default()\r\n        {\r\n            // Given\r\n            var config = NancyInternalConfiguration.Default.Invoke(this.typeCatalog);\r\n\r\n            // When\r\n            var result = config.GetTypeRegistrations();\r\n\r\n            // Then\r\n            result.ShouldNotBeNull();\r\n            result.Count().ShouldBeGreaterThan(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_overrides()\r\n        {\r\n            // Given\r\n            var fakeModelBinderLocator = A.Fake<IModelBinderLocator>();\r\n            var config = NancyInternalConfiguration.WithOverrides((c) => c.ModelBinderLocator = fakeModelBinderLocator.GetType());\r\n\r\n            // When\r\n            var result = config.Invoke(this.typeCatalog).GetTypeRegistrations();\r\n\r\n            // Then\r\n            result.Where(tr => tr.ImplementationType == fakeModelBinderLocator.GetType()).Any().ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_be_valid_if_any_types_null()\r\n        {\r\n            // Given\r\n            var config = NancyInternalConfiguration.WithOverrides((c) => c.ModelBinderLocator = null);\r\n\r\n            // When\r\n            var result = config.Invoke(this.typeCatalog).IsValid;\r\n\r\n             // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Bootstrapper/PipelinesFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Bootstrapper\r\n{\r\n    using System;\r\n    using System.Linq;\r\n\r\n    using Nancy.Bootstrapper;\r\n\r\n    using Xunit;\r\n\r\n    public class PipelinesFixture\r\n    {\r\n        [Fact]\r\n        public void Should_create_default_after_request_hook_when_created_with_default_ctor()\r\n        {\r\n            // Given, When\r\n            var pipelines = new Pipelines();\r\n\r\n            // Then\r\n            pipelines.AfterRequest.ShouldNotBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_create_default_before_request_hook_when_created_with_default_ctor()\r\n        {\r\n            // Given, When\r\n            var pipelines = new Pipelines();\r\n\r\n            // Then\r\n            pipelines.BeforeRequest.ShouldNotBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_create_default_error_hook_when_created_with_default_ctor()\r\n        {\r\n            // Given, When\r\n            var pipelines = new Pipelines();\r\n\r\n            // Then\r\n            pipelines.OnError.ShouldNotBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_clone_after_request_hooks_when_created_with_existing_pipeline()\r\n        {\r\n            // Given\r\n            Action<NancyContext> hook = ctx => ctx.Items.Add(\"foo\", 1);\r\n\r\n            var existing = new Pipelines();\r\n            existing.AfterRequest.AddItemToEndOfPipeline(hook);\r\n\r\n            // When\r\n            var pipelines = new Pipelines(existing);\r\n\r\n            // Then\r\n            pipelines.AfterRequest.PipelineItems.ShouldHaveCount(1);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_clone_before_request_hooks_when_created_with_existing_pipeline()\r\n        {\r\n            // Given\r\n            Func<NancyContext, Response> hook = ctx => null;\r\n\r\n            var existing = new Pipelines();\r\n            existing.BeforeRequest.AddItemToEndOfPipeline(hook);\r\n\r\n            // When\r\n            var pipelines = new Pipelines(existing);\r\n\r\n            // Then\r\n            pipelines.BeforeRequest.PipelineItems.ShouldHaveCount(1);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_clone_error_hooks_when_created_with_existing_pipeline()\r\n        {\r\n            // Given\r\n            Func<NancyContext, Exception, dynamic> hook = (ctx, ex) => null;\r\n\r\n            var existing = new Pipelines();\r\n            existing.OnError.AddItemToEndOfPipeline(hook);\r\n\r\n            // When\r\n            var pipelines = new Pipelines(existing);\r\n\r\n            // Then\r\n            pipelines.OnError.PipelineItems.First().Delegate.ShouldBeSameAs(hook);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Bootstrapper/TypeRegistrationFixture.cs",
    "content": "namespace Nancy.Tests.Unit.Bootstrapper\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Diagnostics;\r\n\r\n    using Xunit;\r\n\r\n    public class TypeRegistrationFixture\r\n    {\r\n        [Fact]\r\n        public void Should_throw_if_registration_type_null()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => new TypeRegistration(null, typeof(object)));\r\n\r\n            // Then\r\n            result.ShouldBeOfType(typeof(ArgumentNullException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_if_implementation_type_null()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => new TypeRegistration(typeof(object), null));\r\n\r\n            // Then\r\n            result.ShouldBeOfType(typeof(ArgumentNullException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_if_implementation_type_does_not_implement_registration_type()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => new TypeRegistration(typeof(INancyBootstrapper), typeof(object)));\r\n\r\n            // Then\r\n            result.ShouldBeOfType(typeof(ArgumentException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_throw_if_implementation_type_implements_registration_type()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => new TypeRegistration(typeof(INancyBootstrapper), typeof(DefaultNancyBootstrapper)));\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_throw_if_open_generic_implementation_type_is_assignable_to_open_generic_registration_type()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => new TypeRegistration(typeof(IEnumerable<>), typeof(ConcurrentLimitedCollection<>)));\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Configuration/DefaultNancyEnvironmentConfiguratorFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Configuration\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    using FakeItEasy;\r\n    using Nancy.Configuration;\r\n    using Xunit;\r\n    using Xunit.Extensions;\r\n\r\n    public class DefaultNancyEnvironmentConfiguratorFixture\r\n    {\r\n        private readonly DefaultNancyEnvironmentConfigurator configurator;\r\n        private readonly INancyEnvironmentFactory factory;\r\n        private readonly INancyEnvironment environment;\r\n        private readonly IEnumerable<INancyDefaultConfigurationProvider> defaultConfigurationProviders;\r\n\r\n        public DefaultNancyEnvironmentConfiguratorFixture()\r\n        {\r\n            this.environment = A.Fake<INancyEnvironment>();\r\n            this.factory = A.Fake<INancyEnvironmentFactory>();\r\n            this.defaultConfigurationProviders = A.Fake<IEnumerable<INancyDefaultConfigurationProvider>>();\r\n\r\n            A.CallTo(() => this.factory.CreateEnvironment()).Returns(this.environment);\r\n\r\n            this.configurator = new DefaultNancyEnvironmentConfigurator(this.factory, this.defaultConfigurationProviders);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_retrieve_environment_from_factory()\r\n        {\r\n            // Given, When\r\n            this.configurator.ConfigureEnvironment(env => { });\r\n\r\n            // Then\r\n            A.CallTo(() => this.factory.CreateEnvironment()).MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_call_configuration_with_instance_from_factory()\r\n        {\r\n            // Given\r\n            INancyEnvironment passedEnvironmentInstance = null;\r\n\r\n            Action<INancyEnvironment> configuration = env =>\r\n            {\r\n                passedEnvironmentInstance = env;\r\n            };\r\n\r\n            // When\r\n            this.configurator.ConfigureEnvironment(configuration);\r\n\r\n            // Then\r\n            passedEnvironmentInstance.ShouldBeSameAs(this.environment);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_instance_from_factory()\r\n        {\r\n            // Given, When\r\n            var result = this.configurator.ConfigureEnvironment(env => { });\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(this.environment);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(1)]\r\n        [InlineData(3)]\r\n        [InlineData(6)]\r\n        [InlineData(8)]\r\n        public void Should_retrieve_default_configurations_from_default_configuration_providers(int numberOfDefaultConfigurationProviders)\r\n        {\r\n            // Given\r\n            var providers = Enumerable\r\n                .Range(1, numberOfDefaultConfigurationProviders)\r\n                .Select(x => A.Fake<INancyDefaultConfigurationProvider>())\r\n                .ToArray();\r\n\r\n            var config = new DefaultNancyEnvironmentConfigurator(this.factory, providers);\r\n\r\n            // When\r\n            config.ConfigureEnvironment(env => { });\r\n\r\n            // Then\r\n            foreach (var provider in providers)\r\n            {\r\n                A.CallTo(() => provider.GetDefaultConfiguration()).MustHaveHappenedOnceExactly();\r\n            }\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_throw_exception_when_default_configuration_provider_returns_null()\r\n        {\r\n            // Given\r\n            var provider = A.Fake<INancyDefaultConfigurationProvider>();\r\n            A.CallTo(() => provider.GetDefaultConfiguration()).Returns(null);\r\n\r\n            var config = new DefaultNancyEnvironmentConfigurator(this.factory, new[] { provider });\r\n\r\n            // When\r\n            var result = config.ConfigureEnvironment(env => { });\r\n\r\n            // Then\r\n            Assert.NotNull(result);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(typeof(object))]\r\n        [InlineData(typeof(int))]\r\n        [InlineData(typeof(double))]\r\n        public void Should_get_key_from_configuration_provider_for_default_configuration_object(Type type)\r\n        {\r\n            // Given\r\n            var expectedKey = string.Concat(\"the-expected-key-\", type.Name);\r\n            var env = new DefaultNancyEnvironment();\r\n\r\n            var fact = A.Fake<INancyEnvironmentFactory>();\r\n            A.CallTo(() => fact.CreateEnvironment()).Returns(env);\r\n\r\n            var provider = A.Fake<INancyDefaultConfigurationProvider>();\r\n            A.CallTo(() => provider.GetDefaultConfiguration()).ReturnsLazily(() => Activator.CreateInstance(type));\r\n            A.CallTo(() => provider.Key).Returns(expectedKey);\r\n\r\n            var config = new DefaultNancyEnvironmentConfigurator(fact, new[] { provider });\r\n\r\n            // When\r\n            config.ConfigureEnvironment(x => { });\r\n\r\n            // Then\r\n            env.ContainsKey(expectedKey).ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_only_add_default_configurations_that_have_not_been_defined_by_user_code()\r\n        {\r\n            // Given\r\n            var key = typeof(object).FullName;\r\n\r\n            var env = A.Fake<INancyEnvironment>();\r\n            A.CallTo(() => env.ContainsKey(key)).Returns(true);\r\n\r\n            var fact = A.Fake<INancyEnvironmentFactory>();\r\n            A.CallTo(() => fact.CreateEnvironment()).Returns(env);\r\n\r\n            var provider = A.Fake<INancyDefaultConfigurationProvider>();\r\n            A.CallTo(() => provider.GetDefaultConfiguration()).Returns(new object());\r\n\r\n            var config = new DefaultNancyEnvironmentConfigurator(fact, new[] { provider });\r\n\r\n            // When\r\n            config.ConfigureEnvironment(x => { });\r\n\r\n            // Then\r\n            A.CallTo(() => env.AddValue(A<string>.That.Matches(x => x.Equals(key)), A<object>._)).MustNotHaveHappened();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Configuration/DefaultNancyEnvironmentFactoryFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Configuration\r\n{\r\n    using Nancy.Configuration;\r\n    using Xunit;\r\n\r\n    public class DefaultNancyEnvironmentFactoryFixture\r\n    {\r\n        [Fact]\r\n        public void Should_return_instance_of_default_environment()\r\n        {\r\n            // Given\r\n            var factory = new DefaultNancyEnvironmentFactory();\r\n\r\n            // When\r\n            var result = factory.CreateEnvironment();\r\n\r\n            // Then\r\n            result.ShouldBeOfType<DefaultNancyEnvironment>();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Configuration/DefaultNancyEnvironmentFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Configuration\r\n{\r\n    using System.Linq;\r\n    using Nancy.Configuration;\r\n    using Xunit;\r\n    using Xunit.Extensions;\r\n\r\n    public class DefaultNancyEnvironmentFixture\r\n    {\r\n        [Theory]\r\n        [InlineData(1)]\r\n        [InlineData(3)]\r\n        [InlineData(5)]\r\n        public void Should_add_key_to_environment_when_invoking_addvalue(int numberOfElementsToAdd)\r\n        {\r\n            // Given, When\r\n            var environment = CreateEnvironment(numberOfElementsToAdd);\r\n\r\n            // Then\r\n            for (var value = 0; value < numberOfElementsToAdd; value++)\r\n            {\r\n                environment.ContainsKey(value.ToString()).ShouldBeTrue();\r\n            }\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(2)]\r\n        [InlineData(4)]\r\n        [InlineData(6)]\r\n        public void Should_add_value_to_environment_when_invoking_addvalue(int numberOfElementsToAdd)\r\n        {\r\n            // Given, When\r\n            var environment = CreateEnvironment(numberOfElementsToAdd);\r\n\r\n            // Then\r\n            for (var value = 0; value < numberOfElementsToAdd; value++)\r\n            {\r\n                environment[value.ToString()].Equals(value).ShouldBeTrue();\r\n            }\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(7)]\r\n        [InlineData(9)]\r\n        [InlineData(12)]\r\n        public void Should_return_all_keys_when_invoking_keys(int numberOfElementsToAdd)\r\n        {\r\n            // Given\r\n            var environment = CreateEnvironment(numberOfElementsToAdd);\r\n\r\n            // When\r\n            var returnedKeys = environment.Keys.ToArray();\r\n\r\n            // Then\r\n            returnedKeys.Count().ShouldEqual(numberOfElementsToAdd);\r\n\r\n            for (var value = 0; value < numberOfElementsToAdd; value++)\r\n            {\r\n                returnedKeys.Contains(value.ToString()).ShouldBeTrue();\r\n            }\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(7)]\r\n        [InlineData(9)]\r\n        [InlineData(12)]\r\n        public void Should_return_all_values_when_invoking_values(int numberOfElementsToAdd)\r\n        {\r\n            // Given\r\n            var environment = CreateEnvironment(numberOfElementsToAdd);\r\n\r\n            // When\r\n            var returnedValues = environment.Values.ToArray();\r\n\r\n            // Then\r\n            returnedValues.Count().ShouldEqual(numberOfElementsToAdd);\r\n\r\n            for (var value = 0; value < numberOfElementsToAdd; value++)\r\n            {\r\n                returnedValues.Contains(value).ShouldBeTrue();\r\n            }\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(7)]\r\n        [InlineData(9)]\r\n        [InlineData(12)]\r\n        public void Should_return_count_when_invoking_count(int numberOfElementsToAdd)\r\n        {\r\n            // Given\r\n            var environment = CreateEnvironment(numberOfElementsToAdd);\r\n\r\n            // When\r\n            var returnedCount = environment.Count;\r\n\r\n            // Then\r\n            returnedCount.ShouldEqual(numberOfElementsToAdd);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"nancy\", \"nancy\", true)]\r\n        [InlineData(\"nancy\", \"frank\", false)]\r\n        public void Should_return_correct_key_presence_when_invoking_containskey(string keyToAdd, string keyToLookFor, bool expectedResult)\r\n        {\r\n            // Given\r\n            var environment = new DefaultNancyEnvironment();\r\n            environment.AddValue(keyToAdd, new object());\r\n\r\n            // When\r\n            var result = environment.ContainsKey(keyToLookFor);\r\n\r\n            // Then\r\n            result.ShouldEqual(expectedResult);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_value_if_key_exists_when_invoking_trygetvalue()\r\n        {\r\n            // Given\r\n            var environment = new DefaultNancyEnvironment();\r\n            var expectedValue = new object();\r\n            environment.AddValue(\"nancy\", expectedValue);\r\n            object output;\r\n\r\n            // When\r\n            environment.TryGetValue(\"nancy\", out output);\r\n\r\n            // Then\r\n            output.ShouldBeSameAs(expectedValue);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"nancy\", true)]\r\n        [InlineData(\"frank\", false)]\r\n        public void Should_return_correct_status_value_when_invoking_trygetvalue(string keyToLookFor, bool expectedResult)\r\n        {\r\n            // Given\r\n            var environment = new DefaultNancyEnvironment();\r\n            environment.AddValue(\"nancy\", new object());\r\n            object output;\r\n\r\n            // When\r\n            var result = environment.TryGetValue(keyToLookFor, out output);\r\n\r\n            // Then\r\n            result.ShouldEqual(expectedResult);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_default_value_if_key_does_not_exist_when_invoking_trygetvalue()\r\n        {\r\n            // Given\r\n            var environment = new DefaultNancyEnvironment();\r\n            var expectedValue = new object();\r\n            environment.AddValue(\"nancy\", expectedValue);\r\n            object output;\r\n\r\n            // When\r\n            environment.TryGetValue(\"foo\", out output);\r\n\r\n            // Then\r\n            output.ShouldEqual(default(object));\r\n        }\r\n\r\n        private static INancyEnvironment CreateEnvironment(int numberOfElementsToAdd)\r\n        {\r\n            var environment = new DefaultNancyEnvironment();\r\n\r\n            for (var value = 0; value < numberOfElementsToAdd; value++)\r\n            {\r\n                environment.AddValue(value.ToString(), value);\r\n            }\r\n\r\n            return environment;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Configuration/INancyEnvironmentExtensionsFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Configuration\r\n{\r\n    using System.Collections.Generic;\r\n    using Nancy.Configuration;\r\n    using Xunit;\r\n\r\n    public class INancyEnvironmentExtensionsFixture\r\n    {\r\n        [Fact]\r\n        public void Should_add_element_with_full_name_of_type_as_key_when_invoking_addvalue()\r\n        {\r\n            // Given\r\n            var environment = new DefaultNancyEnvironment();\r\n            var expected = typeof(INancyEnvironmentExtensionsFixture).FullName;\r\n\r\n            // When\r\n            environment.AddValue<INancyEnvironmentExtensionsFixture>(null);\r\n\r\n            // Then\r\n            environment.ContainsKey(expected).ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_element_with_value_when_invoking_addvalue()\r\n        {\r\n            // Given\r\n            var environment = new DefaultNancyEnvironment();\r\n            var expected = new object();\r\n\r\n            // When\r\n            environment.AddValue(expected);\r\n\r\n            // Then\r\n            ((IReadOnlyDictionary<string, object>)environment)[typeof(object).FullName].ShouldBeSameAs(expected);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_retrieve_value_using_full_name_of_type_when_invoking_getvalue_with_type()\r\n        {\r\n            // Given\r\n            var environment = new DefaultNancyEnvironment();\r\n            var expected = new object();\r\n\r\n            environment.AddValue(typeof(object).FullName, expected);\r\n\r\n            // When\r\n            var result = environment.GetValue<object>();\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(expected);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_retrieve_value_when_invoking_getvalue_with_string_key()\r\n        {\r\n            // Given\r\n            const string key = \"thekey\";\r\n\r\n            var environment = new DefaultNancyEnvironment();\r\n            var expected = new object();\r\n\r\n            environment.AddValue(key, expected);\r\n\r\n            // When\r\n            var result = environment.GetValue<object>(key);\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(expected);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_retrieve_value_using_full_name_of_type_when_invoking_getvaluewithdefault_with_type_and_element_exists()\r\n        {\r\n            // Given\r\n            var environment = new DefaultNancyEnvironment();\r\n            var expected = new object();\r\n\r\n            environment.AddValue(typeof(object).FullName, expected);\r\n\r\n            // When\r\n            var result = environment.GetValueWithDefault(new object());\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(expected);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_retrieve_default_value_using_full_name_of_type_when_invoking_getvaluewithdefault_with_type_and_element_does_not_exists()\r\n        {\r\n            // Given\r\n            var environment = new DefaultNancyEnvironment();\r\n            var defaultValue = new object();\r\n\r\n            environment.AddValue(typeof(string).FullName, new object());\r\n\r\n            // When\r\n            var result = environment.GetValueWithDefault(defaultValue);\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(defaultValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_retrieve_value_when_invoking_getvaluewithdefault_with_string_key_and_element_exists()\r\n        {\r\n            // Given\r\n            const string key = \"thekey\";\r\n            var environment = new DefaultNancyEnvironment();\r\n            var expected = new object();\r\n\r\n            environment.AddValue(key, expected);\r\n\r\n            // When\r\n            var result = environment.GetValueWithDefault(key, new object());\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(expected);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_retrieve_default_value_when_invoking_getvaluewithdefault_with_string_key_and_element_does_not_exists()\r\n        {\r\n            // Given\r\n            const string key = \"thekey\";\r\n            var environment = new DefaultNancyEnvironment();\r\n            var defaultValue = new object();\r\n\r\n            environment.AddValue(typeof(string).FullName, new object());\r\n\r\n            // When\r\n            var result = environment.GetValueWithDefault(key, defaultValue);\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(defaultValue);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Conventions/DefaultAcceptHeaderCoercionConventionsFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Conventions\r\n{\r\n    using System;\r\n    using System.Linq;\r\n    using FakeItEasy;\r\n    using Nancy.Conventions;\r\n\r\n    using Xunit;\r\n\r\n    public class DefaultAcceptHeaderCoercionConventionsFixture\r\n    {\r\n\r\n        private readonly NancyConventions conventions;\r\n        private readonly DefaultAcceptHeaderCoercionConventions acceptHeaderConventions;\r\n\r\n        public DefaultAcceptHeaderCoercionConventionsFixture()\r\n        {\r\n            var typeCatalog = A.Fake<ITypeCatalog>();\r\n            A.CallTo(() => typeCatalog.GetTypesAssignableTo(A<Type>._, A<TypeResolveStrategy>._)).Returns(ArrayCache.Empty<Type>());\r\n\r\n            this.conventions = new NancyConventions(typeCatalog);\r\n            this.acceptHeaderConventions = new DefaultAcceptHeaderCoercionConventions();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_be_valid_when_conventions_is_null()\r\n        {\r\n            // Given\r\n            this.conventions.AcceptHeaderCoercionConventions = null;\r\n\r\n            // When\r\n            var result = this.acceptHeaderConventions.Validate(this.conventions);\r\n\r\n            // Then\r\n            result.Item1.ShouldBeFalse();\r\n        }\r\n        [Fact]\r\n        public void Should_return_correct_error_message_when_not_be_valid_because_conventions_is_null()\r\n        {\r\n            // Given\r\n            this.conventions.AcceptHeaderCoercionConventions = null;\r\n\r\n            // When\r\n            var result = this.acceptHeaderConventions.Validate(this.conventions);\r\n\r\n            // Then\r\n            result.Item2.ShouldEqual(\"The accept header coercion conventions cannot be null.\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_conventions_when_initialised()\r\n        {\r\n            // Given, When\r\n            this.acceptHeaderConventions.Initialise(this.conventions);\r\n\r\n            // Then\r\n            this.conventions.AcceptHeaderCoercionConventions.Count.ShouldBeGreaterThan(0);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Conventions/DefaultCultureConventionsFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Conventions\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Globalization;\r\n    using FakeItEasy;\r\n    using Nancy.Conventions;\r\n\r\n    using Xunit;\r\n\r\n    public class DefaultCultureConventionsFixture\r\n    {\r\n        private readonly NancyConventions conventions;\r\n        private readonly DefaultCultureConventions cultureConventions;\r\n\r\n        public DefaultCultureConventionsFixture()\r\n        {\r\n            var typeCatalog = A.Fake<ITypeCatalog>();\r\n            A.CallTo(() => typeCatalog.GetTypesAssignableTo(A<Type>._, A<TypeResolveStrategy>._)).Returns(ArrayCache.Empty<Type>());\r\n\r\n            this.conventions = new NancyConventions(typeCatalog);\r\n            this.cultureConventions = new DefaultCultureConventions();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_be_valid_when_view_culture_conventions_is_null()\r\n        {\r\n            // Given\r\n            this.conventions.CultureConventions = null;\r\n\r\n            // When\r\n            var result = this.cultureConventions.Validate(this.conventions);\r\n\r\n            // Then\r\n            result.Item1.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_correct_error_message_when_not_valid_because_culture_conventions_is_null()\r\n        {\r\n            // Given\r\n            this.conventions.CultureConventions = null;\r\n\r\n            // When\r\n            var result = this.cultureConventions.Validate(this.conventions);\r\n\r\n            // Then\r\n            result.Item2.ShouldEqual(\"The culture conventions cannot be null.\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_be_valid_when_culture_conventions_is_empty()\r\n        {\r\n            // Given\r\n            this.conventions.CultureConventions =\r\n                new List<Func<NancyContext, GlobalizationConfiguration, CultureInfo>>();\r\n\r\n            // When\r\n            var result = this.cultureConventions.Validate(this.conventions);\r\n\r\n            // Then\r\n            result.Item1.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_correct_error_message_when_not_valid_because_culture_conventions_is_empty()\r\n        {\r\n            // Given\r\n            this.conventions.CultureConventions = new List<Func<NancyContext, GlobalizationConfiguration, CultureInfo>>();\r\n\r\n            // When\r\n            var result = this.cultureConventions.Validate(this.conventions);\r\n\r\n            // Then\r\n            result.Item2.ShouldEqual(\"The culture conventions cannot be empty.\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_valid_when_culture_conventions_is_not_empty()\r\n        {\r\n            // Given\r\n            this.conventions.CultureConventions =\r\n                new List<Func<NancyContext, GlobalizationConfiguration, CultureInfo>>\r\n                {\r\n                    (ctx, config) => {\r\n                        return new CultureInfo(\"en-GB\");\r\n                    }\r\n                };\r\n\r\n            // When\r\n            var result = this.cultureConventions.Validate(this.conventions);\r\n\r\n            // Then\r\n            result.Item1.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_error_message_when_valid()\r\n        {\r\n            // Given\r\n            this.conventions.CultureConventions =\r\n                new List<Func<NancyContext, GlobalizationConfiguration, CultureInfo>>\r\n                {\r\n                    (ctx, config) => {\r\n                        return new CultureInfo(\"en-GB\");\r\n                    }\r\n                };\r\n\r\n            // When\r\n            var result = this.cultureConventions.Validate(this.conventions);\r\n\r\n            // Then\r\n            result.Item2.ShouldBeEmpty();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_conventions_when_initialised()\r\n        {\r\n            // Given, When\r\n            this.cultureConventions.Initialise(this.conventions);\r\n\r\n            // Then\r\n            this.conventions.CultureConventions.Count.ShouldBeGreaterThan(0);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Conventions/DefaultStaticContentsConventionsFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Conventions\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using FakeItEasy;\r\n    using Nancy.Conventions;\r\n\r\n    using Xunit;\r\n\r\n    public class DefaultStaticContentsConventionsFixture\r\n    {\r\n        private readonly NancyConventions conventions;\r\n        private readonly DefaultStaticContentsConventions staticContentsConventions;\r\n\r\n        public DefaultStaticContentsConventionsFixture()\r\n        {\r\n            var typeCatalog = A.Fake<ITypeCatalog>();\r\n            A.CallTo(() => typeCatalog.GetTypesAssignableTo(A<Type>._, A<TypeResolveStrategy>._)).Returns(ArrayCache.Empty<Type>());\r\n\r\n            this.conventions = new NancyConventions(typeCatalog);\r\n            this.staticContentsConventions = new DefaultStaticContentsConventions();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_be_valid_when_view_location_conventions_is_null()\r\n        {\r\n            // Given\r\n            this.conventions.StaticContentsConventions = null;\r\n\r\n            // When\r\n            var result = this.staticContentsConventions.Validate(this.conventions);\r\n\r\n            // Then\r\n            result.Item1.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_correct_error_message_when_not_valid_because_view_location_conventions_is_null()\r\n        {\r\n            // Given\r\n            this.conventions.StaticContentsConventions = null;\r\n\r\n            // When\r\n            var result = this.staticContentsConventions.Validate(this.conventions);\r\n\r\n            // Then\r\n            result.Item2.ShouldEqual(\"The static contents conventions cannot be null.\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_be_valid_when_view_location_conventions_is_empty()\r\n        {\r\n            // Given\r\n            this.conventions.StaticContentsConventions =\r\n                new List<Func<NancyContext, string, Response>>();\r\n\r\n            // When\r\n            var result = this.staticContentsConventions.Validate(this.conventions);\r\n\r\n            // Then\r\n            result.Item1.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_correct_error_message_when_not_valid_because_view_location_conventions_is_empty()\r\n        {\r\n            // Given\r\n            this.conventions.StaticContentsConventions = new List<Func<NancyContext, string, Response>>();\r\n\r\n            // When\r\n            var result = this.staticContentsConventions.Validate(this.conventions);\r\n\r\n            // Then\r\n            result.Item2.ShouldEqual(\"The static contents conventions cannot be empty.\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_valid_when_view_conventions_is_not_empty()\r\n        {\r\n            // Given\r\n            this.conventions.StaticContentsConventions =\r\n                new List<Func<NancyContext, string, Response>>\r\n                {\r\n                    (ctx, folder) => {\r\n                        return new Response();\r\n                    }\r\n                };\r\n\r\n            // When\r\n            var result = this.staticContentsConventions.Validate(this.conventions);\r\n\r\n            // Then\r\n            result.Item1.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_error_message_when_valid()\r\n        {\r\n            // Given\r\n            this.conventions.StaticContentsConventions =\r\n                new List<Func<NancyContext, string, Response>>\r\n                {\r\n                    (ctx, folder) => {\r\n                        return new Response();\r\n                    }\r\n                };\r\n\r\n            // When\r\n            var result = this.staticContentsConventions.Validate(this.conventions);\r\n\r\n            // Then\r\n            result.Item2.ShouldBeEmpty();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_conventions_when_initialised()\r\n        {\r\n            // Given, When\r\n            this.staticContentsConventions.Initialise(this.conventions);\r\n\r\n            // Then\r\n            this.conventions.StaticContentsConventions.Count.ShouldBeGreaterThan(0);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Conventions/DefaultViewLocationConventionsFixture.cs",
    "content": "namespace Nancy.Tests.Unit.Conventions\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Globalization;\r\n    using FakeItEasy;\r\n    using Nancy.Conventions;\r\n    using Nancy.ViewEngines;\r\n\r\n    using Xunit;\r\n    using Xunit.Extensions;\r\n\r\n    public class DefaultViewLocationConventionsFixture\r\n    {\r\n        private readonly NancyConventions conventions;\r\n        private readonly DefaultViewLocationConventions viewLocationConventions;\r\n\r\n        public DefaultViewLocationConventionsFixture()\r\n        {\r\n            var typeCatalog = A.Fake<ITypeCatalog>();\r\n            A.CallTo(() => typeCatalog.GetTypesAssignableTo(A<Type>._, A<TypeResolveStrategy>._)).Returns(ArrayCache.Empty<Type>());\r\n\r\n            this.conventions = new NancyConventions(typeCatalog);\r\n            this.viewLocationConventions = new DefaultViewLocationConventions();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_be_valid_when_view_location_conventions_is_null()\r\n        {\r\n            // Given\r\n            this.conventions.ViewLocationConventions = null;\r\n\r\n            // When\r\n            var result = this.viewLocationConventions.Validate(this.conventions);\r\n\r\n            // Then\r\n            result.Item1.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_correct_error_message_when_not_valid_because_view_location_conventions_is_null()\r\n        {\r\n            // Given\r\n            this.conventions.ViewLocationConventions = null;\r\n\r\n            // When\r\n            var result = this.viewLocationConventions.Validate(this.conventions);\r\n\r\n            // Then\r\n            result.Item2.ShouldEqual(\"The view conventions cannot be null.\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_be_valid_when_view_location_conventions_is_empty()\r\n        {\r\n            // Given\r\n            this.conventions.ViewLocationConventions = new List<Func<string, dynamic, ViewLocationContext, string>>();\r\n\r\n            // When\r\n            var result = this.viewLocationConventions.Validate(this.conventions);\r\n\r\n            // Then\r\n            result.Item1.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_correct_error_message_when_not_valid_because_view_location_conventions_is_empty()\r\n        {\r\n            // Given\r\n            this.conventions.ViewLocationConventions = new List<Func<string, dynamic, ViewLocationContext, string>>();\r\n\r\n            // When\r\n            var result = this.viewLocationConventions.Validate(this.conventions);\r\n\r\n            // Then\r\n            result.Item2.ShouldEqual(\"The view conventions cannot be empty.\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_valid_when_view_conventions_is_not_empty()\r\n        {\r\n            // Given\r\n            this.conventions.ViewLocationConventions =\r\n                new List<Func<string, dynamic, ViewLocationContext, string>>\r\n                {\r\n                    (viewName, model, viewLocationContext) => {\r\n                        return string.Empty;\r\n                    }\r\n                };\r\n\r\n            // When\r\n            var result = this.viewLocationConventions.Validate(this.conventions);\r\n\r\n            // Then\r\n            result.Item1.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_error_message_when_valid()\r\n        {\r\n            // Given\r\n            this.conventions.ViewLocationConventions =\r\n                new List<Func<string, dynamic, ViewLocationContext, string>>\r\n                {\r\n                    (viewName, model, viewLocationContext) => {\r\n                        return string.Empty;\r\n                    }\r\n                };\r\n\r\n            // When\r\n            var result = this.viewLocationConventions.Validate(this.conventions);\r\n\r\n            // Then\r\n            result.Item2.ShouldBeEmpty();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_conventions_when_initialised()\r\n        {\r\n            // Given, When\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n\r\n            // Then\r\n            this.conventions.ViewLocationConventions.Count.ShouldBeGreaterThan(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_define_convention_that_returns_viewname()\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[15];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModulePath = string.Empty });\r\n\r\n            // Then\r\n            result.ShouldEqual(\"viewname\");\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"en-GB\")]\r\n        [InlineData(\"de-DE\")]\r\n        public void Should_define_convention_that_returns_viewname_with_culture(string culture)\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[14];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModulePath = string.Empty, Context = new NancyContext() { Culture = new CultureInfo(culture) } });\r\n\r\n            // Then\r\n            result.ShouldEqual(string.Concat(\"viewname-\", culture));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_define_convention_that_returns_viewname_in_views_folder()\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[13];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModulePath = string.Empty });\r\n\r\n            // Then\r\n            result.ShouldEqual(\"views/viewname\");\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"en-GB\")]\r\n        [InlineData(\"de-DE\")]\r\n        public void Should_define_convention_that_returns_viewname_in_views_folder_with_culture(string culture)\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[12];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModulePath = string.Empty, Context = new NancyContext() { Culture = new CultureInfo(culture) } });\r\n\r\n            // Then\r\n            result.ShouldEqual(string.Concat(\"views/viewname-\", culture));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_define_convention_that_returns_viewname_in_modulepath_subfolder_of_views_folder()\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[5];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModulePath = \"modulepath\" });\r\n\r\n            // Then\r\n            result.ShouldEqual(\"views/modulepath/viewname\");\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"en-GB\")]\r\n        [InlineData(\"de-DE\")]\r\n        public void Should_define_convention_that_returns_viewname_in_modulepath_subfolder_of_views_folder_with_culture(string culture)\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[4];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModulePath = \"modulepath\", Context = new NancyContext() { Culture = new CultureInfo(culture) } });\r\n\r\n            // Then\r\n            result.ShouldEqual(string.Concat(\"views/modulepath/viewname-\", culture));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_define_convention_that_returns_viewname_in_modulepath_subfolder_of_views_folder_when_modulepath_contains_leading_slash()\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[5];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModulePath = \"/modulepath\" });\r\n\r\n            // Then\r\n            result.ShouldEqual(\"views/modulepath/viewname\");\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"en-GB\")]\r\n        [InlineData(\"de-DE\")]\r\n        public void Should_define_convention_that_returns_viewname_in_modulepath_subfolder_of_views_folder_when_modulepath_contains_leading_slash_with_culture(string culture)\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[4];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModulePath = \"/modulepath\", Context = new NancyContext() { Culture = new CultureInfo(culture) } });\r\n\r\n            // Then\r\n            result.ShouldEqual(string.Concat(\"views/modulepath/viewname-\", culture));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_result_convention_that_returns_viewname_in_modulepath_subfolder_of_views_folder_when_modulepath_is_empty()\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[1];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModulePath = string.Empty });\r\n\r\n            // Then\r\n            result.ShouldEqual(string.Empty);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"en-GB\")]\r\n        [InlineData(\"de-DE\")]\r\n        public void Should_return_empty_result_convention_that_returns_viewname_in_modulepath_subfolder_of_views_folder_when_modulepath_is_empty_with_culture(string culture)\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[0];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModulePath = string.Empty, Context = new NancyContext() { Culture = new CultureInfo(culture) } });\r\n\r\n            // Then\r\n            result.ShouldEqual(string.Empty);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_result_convention_that_returns_viewname_in_modulepath_subfolder_of_views_folder_when_modulepath_is_null()\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[1];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModulePath = null });\r\n\r\n            // Then\r\n            result.ShouldEqual(string.Empty);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"en-GB\")]\r\n        [InlineData(\"de-DE\")]\r\n        public void Should_return_empty_result_convention_that_returns_viewname_in_modulepath_subfolder_of_views_folder_when_modulepath_is_null_with_culture(string culture)\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[0];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModulePath = null, Context = new NancyContext() { Culture = new CultureInfo(culture) } });\r\n\r\n            // Then\r\n            result.ShouldEqual(string.Empty);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_define_convention_that_returns_viewname_in_modulepath_folder()\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[7];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModulePath = \"modulepath\" });\r\n\r\n            // Then\r\n            result.ShouldEqual(\"modulepath/viewname\");\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"en-GB\")]\r\n        [InlineData(\"de-DE\")]\r\n        public void Should_define_convention_that_returns_viewname_in_modulepath_folder_with_culture(string culture)\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[6];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModulePath = \"modulepath\", Context = new NancyContext() { Culture = new CultureInfo(culture) } });\r\n\r\n            // Then\r\n            result.ShouldEqual(string.Concat(\"modulepath/viewname-\", culture));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_result_for_convention_that_returns_viewname_in_modulepath_folder_when_modulepath_is_empty()\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[5];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModulePath = string.Empty });\r\n\r\n            // Then\r\n            result.ShouldEqual(string.Empty);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"en-GB\")]\r\n        [InlineData(\"de-DE\")]\r\n        public void Should_return_empty_result_for_convention_that_returns_viewname_in_modulepath_folder_when_modulepath_is_empty_with_culture(string culture)\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[4];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModulePath = string.Empty, Context = new NancyContext() { Culture = new CultureInfo(culture) } });\r\n\r\n            // Then\r\n            result.ShouldEqual(string.Empty);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_result_for_convention_that_returns_viewname_in_modulepath_folder_when_modulepath_is_null()\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[5];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModulePath = null });\r\n\r\n            // Then\r\n            result.ShouldEqual(string.Empty);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"en-GB\")]\r\n        [InlineData(\"de-DE\")]\r\n        public void Should_return_empty_result_for_convention_that_returns_viewname_in_modulepath_folder_when_modulepath_is_null_with_culture(string culture)\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[4];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModulePath = null, Context = new NancyContext() { Culture = new CultureInfo(culture) } });\r\n\r\n            // Then\r\n            result.ShouldEqual(string.Empty);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_define_convention_that_returns_viewname_in_modulepath_folder_when_modulepath_contains_leading_slash()\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[7];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModulePath = \"/modulepath\" });\r\n\r\n            // Then\r\n            result.ShouldEqual(\"modulepath/viewname\");\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"en-GB\")]\r\n        [InlineData(\"de-DE\")]\r\n        public void Should_define_convention_that_returns_viewname_in_modulepath_folder_when_modulepath_contains_leading_slash_with_culture(string culture)\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[6];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModulePath = \"/modulepath\", Context = new NancyContext() { Culture = new CultureInfo(culture) } });\r\n\r\n            // Then\r\n            result.ShouldEqual(string.Concat(\"modulepath/viewname-\", culture));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_define_convention_that_returns_viewname_in_modulename_subfolder_of_views_folder()\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[9];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModuleName = \"modulename\" });\r\n\r\n            // Then\r\n            result.ShouldEqual(\"views/modulename/viewname\");\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"en-GB\")]\r\n        [InlineData(\"de-DE\")]\r\n        public void Should_define_convention_that_returns_viewname_in_modulename_subfolder_of_views_folder_with_culture(string culture)\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[8];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModuleName = \"modulename\", Context = new NancyContext() { Culture = new CultureInfo(culture) } });\r\n\r\n            // Then\r\n            result.ShouldEqual(string.Concat(\"views/modulename/viewname-\", culture));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_define_convention_that_returns_viewname_in_modulename_folder()\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[11];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModuleName = \"modulename\" });\r\n\r\n            // Then\r\n            result.ShouldEqual(\"modulename/viewname\");\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"en-GB\")]\r\n        [InlineData(\"de-DE\")]\r\n        public void Should_define_convention_that_returns_viewname_in_modulename_folder_with_culture(string culture)\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[10];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModuleName = \"modulename\", Context = new NancyContext() { Culture = new CultureInfo(culture) } });\r\n\r\n            // Then\r\n            result.ShouldEqual(string.Concat(\"modulename/viewname-\", culture));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_define_convention_that_returns_viewname_in_modulename_folder_in_modulepath_folder()\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[3];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModuleName = \"modulename\", ModulePath = \"modulepath\" });\r\n\r\n            // Then\r\n            result.ShouldEqual(\"modulepath/modulename/viewname\");\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"en-GB\")]\r\n        [InlineData(\"de-DE\")]\r\n        public void Should_define_convention_that_returns_viewname_in_modulename_folder_in_modulepath_folder_with_culture(string culture)\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[2];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModuleName = \"modulename\", ModulePath = \"modulepath\", Context = new NancyContext() { Culture = new CultureInfo(culture) } });\r\n\r\n            // Then\r\n            result.ShouldEqual(string.Concat(\"modulepath/modulename/viewname-\", culture));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_define_convention_that_returns_viewname_in_modulename_folder_in_modulepath_folder_in_views_folder()\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[1];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModuleName = \"modulename\", ModulePath = \"modulepath\" });\r\n\r\n            // Then\r\n            result.ShouldEqual(\"views/modulepath/modulename/viewname\");\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"en-GB\")]\r\n        [InlineData(\"de-DE\")]\r\n        public void Should_define_convention_that_returns_viewname_in_modulename_folder_in_modulepath_folder_in_views_folder_with_culture(string culture)\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[0];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModuleName = \"modulename\", ModulePath = \"modulepath\", Context = new NancyContext() { Culture = new CultureInfo(culture) } });\r\n\r\n            // Then\r\n            result.ShouldEqual(string.Concat(\"views/modulepath/modulename/viewname-\", culture));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_define_convention_that_returns_viewname_in_modulename_folder_in_modulepath_folder_when_modulepath_contains_leading_slash()\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[3];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModuleName = \"modulename\", ModulePath = \"/modulepath\" });\r\n\r\n            // Then\r\n            result.ShouldEqual(\"modulepath/modulename/viewname\");\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"en-GB\")]\r\n        [InlineData(\"de-DE\")]\r\n        public void Should_define_convention_that_returns_viewname_in_modulename_folder_in_modulepath_folder_when_modulepath_contains_leading_slash_with_culture(string culture)\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[2];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModuleName = \"modulename\", ModulePath = \"/modulepath\", Context = new NancyContext() { Culture = new CultureInfo(culture) } });\r\n\r\n            // Then\r\n            result.ShouldEqual(string.Concat(\"modulepath/modulename/viewname-\", culture));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_define_convention_that_returns_viewname_in_modulename_folder_in_modulepath_folder_in_views_folder_when_modulepath_contains_leading_slash()\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[1];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModuleName = \"modulename\", ModulePath = \"/modulepath\" });\r\n\r\n            // Then\r\n            result.ShouldEqual(\"views/modulepath/modulename/viewname\");\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"en-GB\")]\r\n        [InlineData(\"de-DE\")]\r\n        public void Should_define_convention_that_returns_viewname_in_modulename_folder_in_modulepath_folder_in_views_folder_when_modulepath_contains_leading_slash_with_culture(string culture)\r\n        {\r\n            // Given\r\n            this.viewLocationConventions.Initialise(this.conventions);\r\n            var convention = this.conventions.ViewLocationConventions[0];\r\n\r\n            // When\r\n            var result = convention.Invoke(\r\n                \"viewname\",\r\n                null,\r\n                new ViewLocationContext { ModuleName = \"modulename\", ModulePath = \"/modulepath\", Context = new NancyContext() { Culture = new CultureInfo(culture) } });\r\n\r\n            // Then\r\n            result.ShouldEqual(string.Concat(\"views/modulepath/modulename/viewname-\", culture));\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Cryptography/AesEncryptionProviderFixture.cs",
    "content": "namespace Nancy.Tests.Unit.Cryptography\r\n{\r\n    using Nancy.Cryptography;\r\n\r\n    using Xunit;\r\n\r\n    public class AesEncryptionProviderFixture\r\n    {\r\n        private AesEncryptionProvider provider;\r\n\r\n        public AesEncryptionProviderFixture()\r\n        {\r\n            this.provider = new AesEncryptionProvider(new PassphraseKeyGenerator(\"Passphrase\", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_cypher_text_when_encrypting()\r\n        {\r\n            var inputText = \"this is some text\";\r\n\r\n            var result = provider.Encrypt(inputText);\r\n            \r\n            result.ShouldNotEqual(inputText);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_original_text_when_decrypting_with_same_key()\r\n        {\r\n            var inputText = \"this is some text\";\r\n            var encText = provider.Encrypt(inputText);\r\n\r\n            var result = provider.Decrypt(encText);\r\n\r\n            result.ShouldEqual(inputText);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_return_original_text_when_decrypting_with_different_keys()\r\n        {\r\n            var inputText = \"this is some text\";\r\n            var encText = provider.Encrypt(inputText);\r\n\r\n            var result = new AesEncryptionProvider(new PassphraseKeyGenerator(\"Wrong\", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 })).Decrypt(encText);\r\n\r\n            result.ShouldNotEqual(inputText);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Cryptography/DefaultHmacProviderFixture.cs",
    "content": "namespace Nancy.Tests.Unit.Sessions\r\n{\r\n    using Nancy.Cryptography;\r\n\r\n    using Xunit;\r\n\r\n    public class DefaultHmacProviderFixture\r\n    {\r\n        [Fact]\r\n        public void Should_return_hmac_array()\r\n        {\r\n            var provider = new DefaultHmacProvider(new RandomKeyGenerator());\r\n\r\n            var result = provider.GenerateHmac(\"some data\");\r\n\r\n            result.ShouldNotBeNull();\r\n            result.Length.ShouldBeGreaterThan(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_array_the_same_size_as_hash_length()\r\n        {\r\n            var provider = new DefaultHmacProvider(new RandomKeyGenerator());\r\n            var hashLength = provider.HmacLength;\r\n\r\n            var result = provider.GenerateHmac(\"some data\");\r\n\r\n            result.Length.ShouldEqual(hashLength);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Cryptography/HmacComparerFixture.cs",
    "content": "namespace Nancy.Tests.Unit.Sessions\r\n{\r\n    using Nancy.Cryptography;\r\n\r\n    using Xunit;\r\n\r\n    public class HmacComparerFixture\r\n    {\r\n        [Fact]\r\n        public void Should_return_false_if_not_equal()\r\n        {\r\n            var hmac1 = new byte[] { 1, 2, 3, 4 };\r\n            var hmac2 = new byte[] { 1, 2, 3, 5 };\r\n\r\n            var result = HmacComparer.Compare(hmac1, hmac2, 4);\r\n\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_if_first_length_wrong()\r\n        {\r\n            var hmac1 = new byte[] { 1, 2, 3 };\r\n            var hmac2 = new byte[] { 1, 2, 3, 0 };\r\n\r\n            var result = HmacComparer.Compare(hmac1, hmac2, 4);\r\n\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_if_second_length_wrong()\r\n        {\r\n            var hmac1 = new byte[] { 1, 2, 3, 0 };\r\n            var hmac2 = new byte[] { 1, 2, 3 };\r\n\r\n            var result = HmacComparer.Compare(hmac1, hmac2, 4);\r\n\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_if_both_correct_length_and_equal()\r\n        {\r\n            var hmac1 = new byte[] { 1, 2, 3, 4 };\r\n            var hmac2 = new byte[] { 1, 2, 3, 4 };\r\n\r\n            var result = HmacComparer.Compare(hmac1, hmac2, 4);\r\n\r\n            result.ShouldBeTrue();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Cryptography/NoEncryptionProviderFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Cryptography\r\n{\r\n    using Nancy.Cryptography;\r\n\r\n    using Xunit;\r\n\r\n    public class NoEncryptionProviderFixture\r\n    {\r\n        private readonly IEncryptionProvider provider;\r\n\r\n        public NoEncryptionProviderFixture()\r\n        {\r\n            this.provider = new NoEncryptionProvider();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_cypher_text_when_encrypting()\r\n        {\r\n            var inputText = \"this is some text\";\r\n\r\n            var result = provider.Encrypt(inputText);\r\n            \r\n            result.ShouldNotEqual(inputText);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_original_text_when_decrypting()\r\n        {\r\n            var inputText = \"this is some text\";\r\n            var encText = provider.Encrypt(inputText);\r\n\r\n            var result = provider.Decrypt(encText);\r\n\r\n            result.ShouldEqual(inputText);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Culture/BuiltInCultureConventionFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Culture\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Globalization;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Threading;\r\n    using Nancy.Configuration;\r\n    using Nancy.Conventions;\r\n    using Nancy.IO;\r\n    using Nancy.Session;\r\n\r\n    using Xunit;\r\n    using Xunit.Extensions;\r\n\r\n    public class BuiltInCultureConventionFixture\r\n    {\r\n        [Fact]\r\n        public void Should_return_null_if_form_not_populated()\r\n        {\r\n            //Given\r\n            var context = CreateContextRequest(\"/\");\r\n\r\n            //When\r\n            var culture = BuiltInCultureConventions.FormCulture(context, context.Environment.GetValue<GlobalizationConfiguration>());\r\n\r\n            //Then\r\n            culture.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_culture_if_form_populated()\r\n        {\r\n            //Given\r\n            var context = PopulateForm(\"en-GB\");\r\n\r\n            //When\r\n            var culture = BuiltInCultureConventions.FormCulture(context, new GlobalizationConfiguration(new[] { \"en-GB\" }, \"en-GB\"));\r\n\r\n            //Then\r\n            culture.Name.ShouldEqual(\"en-GB\");\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"xx-xx\")]\r\n        [InlineData(\"123\")]\r\n        public void Should_return_null_if_form_populated_with_invalid_culture(string cultureName)\r\n        {\r\n            //Given\r\n            var context = PopulateForm(cultureName);\r\n\r\n            //When\r\n            var culture = BuiltInCultureConventions.FormCulture(context, GlobalizationConfiguration.Default);\r\n\r\n            //Then\r\n            culture.ShouldBeNull();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"/\")]\r\n        [InlineData(\"/__Nancy\")]\r\n        public void Should_return_null_if_first_path_parameter_not_valid_culture(string path)\r\n        {\r\n            //Given\r\n            var context = CreateContextRequest(path);\r\n\r\n            //When\r\n            var culture = BuiltInCultureConventions.PathCulture(context, context.Environment.GetValue<GlobalizationConfiguration>());\r\n\r\n            //Then\r\n            culture.ShouldBeNull();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"/nl\", \"nl\")]\r\n        [InlineData(\"/en-GB\", \"en-GB\")]\r\n        [InlineData(\"/en-GB/product\", \"en-GB\")]\r\n        public void Should_return_culture_if_first_path_parameter_valid_culture(string path, string expected)\r\n        {\r\n            //Given\r\n            var context = CreateContextRequest(path);\r\n\r\n            //When\r\n            var culture = BuiltInCultureConventions.PathCulture(context, new GlobalizationConfiguration(new[] { expected }, expected));\r\n\r\n            //Then\r\n            culture.Name.ShouldEqual(expected);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"/en-GB\", \"/\")]\r\n        [InlineData(\"/en-GB/product\", \"/product\")]\r\n        public void Should_culture_of_request_path_if_first_path_parameter_valid_culture(string path, string expectedPath)\r\n        {\r\n            //Given\r\n            var context = CreateContextRequest(path);\r\n\r\n            //When\r\n            var culture = BuiltInCultureConventions.PathCulture(context, new GlobalizationConfiguration(new string[] { \"en-GB\" }, \"en-GB\"));\r\n\r\n            //Then\r\n            context.Request.Url.Path.ShouldEqual(expectedPath);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_if_headers_not_populated()\r\n        {\r\n            //Given\r\n            var context = CreateContextRequest(\"/\");\r\n\r\n            //When\r\n            var culture = BuiltInCultureConventions.HeaderCulture(context, context.Environment.GetValue<GlobalizationConfiguration>());\r\n\r\n            //Then\r\n            culture.ShouldBeNull();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"xx-xx\")]\r\n        [InlineData(\"123\")]\r\n        public void Should_return_null_if_invalid_culture_in_header(string cultureName)\r\n        {\r\n            //Given\r\n            var headers =\r\n                new Dictionary<string, IEnumerable<string>>\r\n                {\r\n                    { \"Accept-Language\", new[] { cultureName } }\r\n                };\r\n\r\n            var context = CreateContextRequest(\"/\", headers);\r\n\r\n            //When\r\n            var culture = BuiltInCultureConventions.HeaderCulture(context, context.Environment.GetValue<GlobalizationConfiguration>());\r\n\r\n            //Then\r\n            culture.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_highest_weighted_header()\r\n        {\r\n            //Given\r\n            var headers =\r\n                new Dictionary<string, IEnumerable<string>>\r\n                {\r\n                    { \"Accept-Language\", new[] { \"en-GB;q=0.8\", \"de-DE;q=0.7\", \"nl;q=0.5\", \"es;q=0.4\" } }\r\n                };\r\n\r\n            var context = CreateContextRequest(\"/\", headers);\r\n\r\n            //When\r\n            var culture = BuiltInCultureConventions.HeaderCulture(context, new GlobalizationConfiguration(new[] { \"en-GB\", \"de-DE\", \"nl\", \"es\" }, \"en-GB\"));\r\n\r\n            //Then\r\n            culture.Name.ShouldEqual(\"en-GB\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_valid_culture_if_header_populated()\r\n        {\r\n            //Given\r\n            var headers =\r\n                new Dictionary<string, IEnumerable<string>>\r\n                {\r\n                    { \"Accept-Language\", new[] { \"en-GB\" } }\r\n                };\r\n\r\n            var context = CreateContextRequest(\"/\", headers);\r\n\r\n            //When\r\n            var culture = BuiltInCultureConventions.HeaderCulture(context, new GlobalizationConfiguration(new[] { \"en-GB\" }, \"en-GB\"));\r\n\r\n            //Then\r\n            culture.Name.ShouldEqual(\"en-GB\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_if_session_not_populated()\r\n        {\r\n            //Given\r\n            var context = CreateContextRequest(\"/\");\r\n\r\n            //When\r\n            var culture = BuiltInCultureConventions.SessionCulture(context, context.Environment.GetValue<GlobalizationConfiguration>());\r\n\r\n            //Then\r\n            culture.ShouldBeNull();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"xx-xx\")]\r\n        [InlineData(\"123\")]\r\n        public void Should_throw_exception_if_invalid_session_value(string cultureName)\r\n        {\r\n            //Given\r\n            var context = CreateContextRequest(\"/\");\r\n\r\n            var sessionValues = new Dictionary<string, object>\r\n                              {\r\n                                  { \"CurrentCulture\", cultureName }\r\n                              };\r\n\r\n            context.Request.Session = new Session(new Dictionary<string, object>(sessionValues));\r\n\r\n            //When\r\n            var exception =\r\n                Record.Exception(() => BuiltInCultureConventions.SessionCulture(context, context.Environment.GetValue<GlobalizationConfiguration>()));\r\n\r\n            //Then\r\n            exception.ShouldBeOfType<InvalidCastException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_culture_if_session_populated()\r\n        {\r\n            //Given\r\n            var context = CreateContextRequest(\"/\");\r\n\r\n            var sessionValues = new Dictionary<string, object>\r\n                              {\r\n                                  { \"CurrentCulture\", new CultureInfo(\"en-GB\") }\r\n                              };\r\n\r\n            context.Request.Session = new Session(new Dictionary<string, object>(sessionValues));\r\n\r\n            //When\r\n            var culture = BuiltInCultureConventions.SessionCulture(context, context.Environment.GetValue<GlobalizationConfiguration>());\r\n\r\n            //Then\r\n            culture.Name.ShouldEqual(\"en-GB\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_if_no_cookie_populated()\r\n        {\r\n            //Given\r\n            var context = CreateContextRequest(\"/\");\r\n\r\n            //When\r\n            var culture = BuiltInCultureConventions.CookieCulture(context, context.Environment.GetValue<GlobalizationConfiguration>());\r\n\r\n            //Then\r\n            culture.ShouldBeNull();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"xx-xx\")]\r\n        [InlineData(\"123\")]\r\n        public void Should_return_null_if_invalid_culture_in_cookie(string cultureName)\r\n        {\r\n            // Given\r\n            const string cookieName = \"CurrentCulture\";\r\n            string cookieData = cultureName;\r\n\r\n            var headers = new Dictionary<string, IEnumerable<string>>\r\n                              {\r\n                                  { \"cookie\", new[]{ string.Format(\"{0}={1}\", cookieName, cookieData) } }\r\n                              };\r\n\r\n            var context = CreateContextRequest(\"/\", headers);\r\n\r\n            //When\r\n            var culture = BuiltInCultureConventions.CookieCulture(context, context.Environment.GetValue<GlobalizationConfiguration>());\r\n\r\n            //Then\r\n            culture.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_culture_if_cookie_populated()\r\n        {\r\n            // Given\r\n            const string cookieName = \"CurrentCulture\";\r\n            const string cookieData = \"en-GB\";\r\n\r\n            var headers = new Dictionary<string, IEnumerable<string>>\r\n                              {\r\n                                  { \"cookie\", new[]{ string.Format(\"{0}={1}\", cookieName, cookieData) } }\r\n                              };\r\n\r\n            var context = CreateContextRequest(\"/\", headers);\r\n\r\n            //When\r\n            var culture = BuiltInCultureConventions.CookieCulture(context, new GlobalizationConfiguration(new[] { \"en-GB\" }, \"en-GB\"));\r\n\r\n            // Then\r\n            culture.Name.ShouldEqual(\"en-GB\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_culture_from_default_culture_on_globalization_configuration()\r\n        {\r\n            //Given\r\n            var context = CreateContextRequest(\"/\");\r\n\r\n            //When\r\n            var culture = BuiltInCultureConventions.GlobalizationConfigurationCulture(context, context.Environment.GetValue<GlobalizationConfiguration>());\r\n\r\n            //Then\r\n            culture.Name.ShouldEqual(\"en-US\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_first_supported_culture_for_default_culture_on_globalization_configuration()\r\n        {\r\n            //Given\r\n            var context = CreateContextRequest(\"/\");\r\n\r\n            //When\r\n            var environment = new DefaultNancyEnvironment();\r\n            environment.Globalization(new[] { \"en-US\" }, defaultCulture: null);\r\n            var culture = BuiltInCultureConventions.GlobalizationConfigurationCulture(context, environment.GetValue<GlobalizationConfiguration>());\r\n\r\n            //Then\r\n            culture.Name.ShouldEqual(\"en-US\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_configuration_exception_if_default_culture_not_supported_globalization_configuration()\r\n        {\r\n            //Given\r\n            var context = CreateContextRequest(\"/\");\r\n\r\n            //When\r\n            var environment = new DefaultNancyEnvironment();\r\n            var exception = Record.Exception(() => environment.Globalization(new[] { \"en-GB\" }, defaultCulture: \"quz-EC\"));\r\n\r\n            //Then\r\n            exception.ShouldBeOfType<ConfigurationException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_configuration_exception_if_empty_list_of_supported_culutres_passed_to_globalization_configuration()\r\n        {\r\n            //Given, When\r\n            var environment = new DefaultNancyEnvironment();\r\n            var exception = Record.Exception(() => environment.Globalization(Enumerable.Empty<string>()));\r\n\r\n            //Then\r\n            exception.ShouldBeOfType<ConfigurationException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_configuration_exception_if_list_of_blank_strings_used_for_supported_culutres_passed_to_globalization_configuration()\r\n        {\r\n            //Given, When\r\n            var environment = new DefaultNancyEnvironment();\r\n            var exception = Record.Exception(() => environment.Globalization(new []{\"\"}));\r\n\r\n            //Then\r\n            exception.ShouldBeOfType<ConfigurationException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_configuration_exception_if_null_value_used_for_supported_culutres_passed_to_globalization_configuration()\r\n        {\r\n            //Given, When\r\n            var environment = new DefaultNancyEnvironment();\r\n            var exception = Record.Exception(() => environment.Globalization(null));\r\n\r\n            //Then\r\n            exception.ShouldBeOfType<ConfigurationException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Validation_should_return_false_if_null_culture_name()\r\n        {\r\n            //Given/When\r\n            var result = BuiltInCultureConventions.IsValidCultureInfoName(null, null);\r\n\r\n            //Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"xx-xx\")]\r\n        [InlineData(\"123\")]\r\n        public void Validation_should_return_false_if_invalid_culture_name(string cultureName)\r\n        {\r\n            //Given/When\r\n            var configuration = new GlobalizationConfiguration(new []{\"en-US\"});\r\n            var result = BuiltInCultureConventions.IsValidCultureInfoName(cultureName, configuration);\r\n\r\n            //Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"en-GB\")]\r\n        [InlineData(\"de-DE\")]\r\n        [InlineData(\"en-US\")]\r\n        [InlineData(\"nl\")]\r\n        [InlineData(\"es\")]\r\n#if !MONO\r\n        [InlineData(\"iu-Latn-CA\")]\r\n#endif\r\n        public void Validation_should_return_true_if_valid_culture_name(string cultureName)\r\n        {\r\n            //Given/When\r\n            var configuration = new GlobalizationConfiguration(new[] { cultureName }, cultureName);\r\n            var result = BuiltInCultureConventions.IsValidCultureInfoName(cultureName, configuration);\r\n\r\n            //Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        private NancyContext PopulateForm(string cultureName)\r\n        {\r\n            string bodyContent = string.Concat(\"CurrentCulture=\", cultureName);\r\n            var memory = new MemoryStream();\r\n            var writer = new StreamWriter(memory);\r\n            writer.Write(bodyContent);\r\n            writer.Flush();\r\n            memory.Position = 0;\r\n\r\n            var headers =\r\n                new Dictionary<string, IEnumerable<string>>\r\n                {\r\n                    { \"content-type\", new[] { \"application/x-www-form-urlencoded\" } }\r\n                };\r\n\r\n\r\n            var context = new NancyContext();\r\n            context.Request = new Request(\"POST\", new Url { Path = \"/\", Scheme = \"http\" }, RequestStream.FromStream(memory), headers);\r\n            return context;\r\n        }\r\n\r\n        private NancyContext CreateContextRequest(string path, IDictionary<string, IEnumerable<string>> cultureHeaders = null)\r\n        {\r\n            var context = new NancyContext();\r\n            var request = new Request(\"GET\", new Url { Path = path, Scheme = \"http\" }, null, cultureHeaders);\r\n            context.Request = request;\r\n            var environment = new DefaultNancyEnvironment();\r\n            environment.Globalization(new[] { \"en-US\" }, \"en-US\");\r\n            context.Environment = environment;\r\n            return context;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/DefaultNancyBootstrapperBootstrapperBaseFixture.cs",
    "content": "﻿#if !MONO\r\nnamespace Nancy.Tests.Unit\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Tests.Unit.Bootstrapper.Base;\r\n    using Nancy.TinyIoc;\r\n\r\n    public class DefaultNancyBootstrapperBootstrapperBaseFixture : BootstrapperBaseFixtureBase<TinyIoCContainer>\r\n    {\r\n        private readonly FakeBootstrapper bootstrapper;\r\n\r\n        protected override NancyBootstrapperBase<TinyIoCContainer> Bootstrapper\r\n        {\r\n            get { return this.bootstrapper; }\r\n        }\r\n\r\n        public DefaultNancyBootstrapperBootstrapperBaseFixture()\r\n        {\r\n            this.bootstrapper = new FakeBootstrapper(this.Configuration);\r\n        }\r\n\r\n        public class FakeBootstrapper : DefaultNancyBootstrapper\r\n        {\r\n            private readonly Func<ITypeCatalog, NancyInternalConfiguration> configuration;\r\n\r\n            protected override Func<ITypeCatalog, NancyInternalConfiguration> InternalConfiguration\r\n            {\r\n                get { return configuration; }\r\n            }\r\n\r\n            protected override IEnumerable<Type> RegistrationTasks\r\n            {\r\n                get\r\n                {\r\n                    return new[] { typeof(TestRegistrations) };\r\n                }\r\n            }\r\n\r\n            public FakeBootstrapper(Func<ITypeCatalog, NancyInternalConfiguration> configuration)\r\n            {\r\n                this.configuration = configuration;\r\n            }\r\n        }\r\n    }\r\n}\r\n#endif"
  },
  {
    "path": "test/Nancy.Tests/Unit/DefaultNancyBootstrapperFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using System.Threading.Tasks;\r\n    using Microsoft.CodeAnalysis;\r\n    using Microsoft.CodeAnalysis.CSharp;\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Extensions;\r\n    using Nancy.Tests.Fakes;\r\n    using Nancy.Tests.Helpers;\r\n    using Nancy.TinyIoc;\r\n\r\n    using Xunit;\r\n\r\n    public class DefaultNancyBootstrapperFixture\r\n    {\r\n        private readonly FakeDefaultNancyBootstrapper bootstrapper;\r\n\r\n        public DefaultNancyBootstrapperFixture()\r\n        {\r\n            this.bootstrapper = new FakeDefaultNancyBootstrapper();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_only_initialise_request_container_once_per_request()\r\n        {\r\n            // Given\r\n            this.bootstrapper.Initialise();\r\n            var engine = this.bootstrapper.GetEngine();\r\n            var request = new FakeRequest(\"GET\", \"/\");\r\n            var request2 = new FakeRequest(\"GET\", \"/\");\r\n\r\n            // When\r\n            await engine.HandleRequest(request);\r\n            await engine.HandleRequest(request2);\r\n\r\n            // Then\r\n            bootstrapper.RequestContainerInitialisations.Any(kvp => kvp.Value > 1).ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Request_should_be_available_to_configure_request_container()\r\n        {\r\n            // Given\r\n            this.bootstrapper.Initialise();\r\n            var engine = this.bootstrapper.GetEngine();\r\n            var request = new FakeRequest(\"GET\", \"/\");\r\n\r\n            // When\r\n            engine.HandleRequest(request);\r\n\r\n            // Then\r\n            this.bootstrapper.ConfigureRequestContainerLastRequest.ShouldNotBeNull();\r\n            this.bootstrapper.ConfigureRequestContainerLastRequest.ShouldBeSameAs(request);\r\n        }\r\n\r\n        [Fact]\r\n        public void Request_should_be_available_to_request_startup()\r\n        {\r\n            // Given\r\n            this.bootstrapper.Initialise();\r\n            var engine = this.bootstrapper.GetEngine();\r\n            var request = new FakeRequest(\"GET\", \"/\");\r\n\r\n            // When\r\n            engine.HandleRequest(request);\r\n\r\n            // Then\r\n            this.bootstrapper.RequestStartupLastRequest.ShouldNotBeNull();\r\n            this.bootstrapper.RequestStartupLastRequest.ShouldBeSameAs(request);\r\n        }\r\n\r\n        [Fact]\r\n        public void Container_should_ignore_specified_assemblies()\r\n        {\r\n            // Given\r\n            var syntaxTree = CSharpSyntaxTree.ParseText(\r\n                \"public interface IWillNotBeResolved { int i { get; set; } }\" +\r\n                \"public class WillNotBeResolved : IWillNotBeResolved { public int i { get; set; } }\");\r\n\r\n            var mscorlib = MetadataReference.CreateFromFile(typeof(object).GetAssembly().Location);\r\n            var compilation = CSharpCompilation.Create(\"MyCompilation\",\r\n                new[] { syntaxTree },\r\n                new[] { mscorlib },\r\n                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));\r\n\r\n            Assembly ass;\r\n            using (var memoryStream = new MemoryStream())\r\n            {\r\n                var emitResult = compilation.Emit(memoryStream);\r\n\r\n                Assert.True(emitResult.Success,\r\n                    \"Compilation failed:\" + Environment.NewLine + \"  \" +\r\n                    string.Join(Environment.NewLine + \"  \", emitResult.Diagnostics));\r\n\r\n                ass = AssemblyHelpers.Load(memoryStream);\r\n            }\r\n\r\n            // When\r\n            this.bootstrapper.Initialise ();\r\n\r\n            // Then\r\n            Assert.Throws<TinyIoCResolutionException>(\r\n                () => this.bootstrapper.Container.Resolve(ass.GetType(\"IWillNotBeResolved\")));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_honour_registration_lifetimes()\r\n        {\r\n            // Given\r\n            this.bootstrapper.OverriddenRegistrationTasks = new [] { typeof(FakeRegistrations) };\r\n\r\n            // When\r\n            this.bootstrapper.Initialise();\r\n            var instance1 = this.bootstrapper.Container.Resolve<IMultiInstance>();\r\n            var instance2 = this.bootstrapper.Container.Resolve<IMultiInstance>();\r\n\r\n            // Then\r\n            ReferenceEquals(instance1, instance2).ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_honour_collection_registration_lifetimes()\r\n        {\r\n            // Given\r\n            this.bootstrapper.OverriddenRegistrationTasks = new[] { typeof(FakeRegistrations) };\r\n\r\n            // When\r\n            this.bootstrapper.Initialise();\r\n            var instance1 = this.bootstrapper.Container.ResolveAll<IMultiInstance>(false);\r\n            var instance2 = this.bootstrapper.Container.ResolveAll<IMultiInstance>(false);\r\n\r\n            // Then\r\n            ReferenceEquals(instance1.Single(), instance2.Single()).ShouldBeFalse();\r\n        }\r\n    }\r\n\r\n    public class FakeRegistrations : IRegistrations\r\n    {\r\n        public IEnumerable<TypeRegistration> TypeRegistrations { get; private set; }\r\n\r\n        public IEnumerable<CollectionTypeRegistration> CollectionTypeRegistrations { get; private set; }\r\n\r\n        public IEnumerable<InstanceRegistration> InstanceRegistrations { get; private set; }\r\n\r\n        public FakeRegistrations()\r\n        {\r\n            this.TypeRegistrations = new[] { new TypeRegistration(typeof(IMultiInstance), typeof(MultiInstance), Lifetime.Transient) };\r\n            this.CollectionTypeRegistrations = new[]\r\n                                               {\r\n                                                   new CollectionTypeRegistration(\r\n                                                       typeof(IMultiInstance),\r\n                                                       new[] { typeof(MultiInstance) },\r\n                                                       Lifetime.Transient)\r\n                                               };\r\n        }\r\n    }\r\n\r\n    public class MultiInstance : IMultiInstance\r\n    {\r\n    }\r\n\r\n    public interface IMultiInstance\r\n    {\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/DefaultNancyBootstrapperModuleCatalogFixture.cs",
    "content": "namespace Nancy.Tests.Unit\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Tests.Unit.Bootstrapper.Base;\r\n\r\n    public class DefaultNancyBootstrapperModuleCatalogFixture : ModuleCatalogFixtureBase\r\n    {\r\n        private TestBootstrapper bootstrapper;\r\n\r\n        /// <summary>\r\n        /// Gets the catalog under test - should have ModuleTypesToRegister\r\n        /// registred as modules for resolution.\r\n        /// </summary>\r\n        protected override INancyModuleCatalog Catalog\r\n        {\r\n            get { return this.bootstrapper; }\r\n        }\r\n\r\n        public DefaultNancyBootstrapperModuleCatalogFixture()\r\n        {\r\n            this.bootstrapper = new TestBootstrapper(this.ModuleTypesToRegister);\r\n            this.bootstrapper.Initialise();\r\n        }\r\n\r\n        private class TestBootstrapper : DefaultNancyBootstrapper\r\n        {\r\n            private IEnumerable<ModuleRegistration> moduleRegistrations;\r\n\r\n            protected override IEnumerable<ModuleRegistration> Modules\r\n            {\r\n                get { return this.moduleRegistrations; }\r\n            }\r\n\r\n            public TestBootstrapper(IEnumerable<ModuleRegistration> moduleRegistrations)\r\n            {\r\n                this.moduleRegistrations = moduleRegistrations;\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/DefaultResponseFormatterFactoryFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit\r\n{\r\n    using FakeItEasy;\r\n    using Nancy.Configuration;\r\n    using Nancy.Responses.Negotiation;\r\n    using Xunit;\r\n\r\n    public class DefaultResponseFormatterFactoryFixture\r\n    {\r\n        private readonly IRootPathProvider rootPathProvider;\r\n        private readonly DefaultResponseFormatterFactory factory;\r\n        private readonly ISerializerFactory serializerFactory;\r\n        private readonly INancyEnvironment environment;\r\n\r\n        public DefaultResponseFormatterFactoryFixture()\r\n        {\r\n            this.rootPathProvider = A.Fake<IRootPathProvider>();\r\n            A.CallTo(() => this.rootPathProvider.GetRootPath()).Returns(\"RootPath\");\r\n\r\n            this.serializerFactory = A.Fake<ISerializerFactory>();\r\n\r\n            this.environment = A.Fake<INancyEnvironment>();\r\n\r\n            this.factory = new DefaultResponseFormatterFactory(this.rootPathProvider, this.serializerFactory, this.environment);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_create_response_formatter_with_root_path_set()\r\n        {\r\n            // Given, When\r\n            var formatter = this.factory.Create(null);\r\n\r\n            // Then\r\n            formatter.RootPath.ShouldEqual(\"RootPath\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_create_response_formatter_with_context_set()\r\n        {\r\n            // Given\r\n            var context = new NancyContext();\r\n\r\n            // When\r\n            var formatter = this.factory.Create(context);\r\n\r\n            // Then\r\n            formatter.Context.ShouldBeSameAs(context);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_create_response_formater_with_serializer_factory()\r\n        {\r\n            // Given\r\n            var context = new NancyContext();\r\n\r\n            // When\r\n            var formatter = this.factory.Create(context);\r\n\r\n            // Then\r\n            formatter.SerializerFactory.ShouldBeSameAs(this.serializerFactory);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/DefaultResponseFormatterFixture.cs",
    "content": "namespace Nancy.Tests.Unit\r\n{\r\n    using FakeItEasy;\r\n    using Nancy.Configuration;\r\n    using Xunit;\r\n\r\n    public class DefaultResponseFormatterFixture\r\n    {\r\n        [Fact]\r\n        public void Should_return_path_provided_by_root_path_provider()\r\n        {\r\n            // Given\r\n            var rootPathProvider = A.Fake<IRootPathProvider>();\r\n            A.CallTo(() => rootPathProvider.GetRootPath()).Returns(\"foo\");\r\n            var formatter = new DefaultResponseFormatter(rootPathProvider, null, new DefaultSerializerFactory(null), A.Fake<INancyEnvironment>());\r\n\r\n            // When\r\n            var result = formatter.RootPath;\r\n\r\n            // Then\r\n            result.ShouldEqual(\"foo\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_context_that_was_used_when_creating_instance()\r\n        {\r\n            // Given\r\n            var context = new NancyContext();\r\n\r\n            // When\r\n            var formatter = new DefaultResponseFormatter(null, context, new DefaultSerializerFactory(null), A.Fake<INancyEnvironment>());\r\n\r\n            // Then\r\n            formatter.Context.ShouldBeSameAs(context);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/DefaultSerializerFactoryFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Threading;\r\n    using Nancy.Configuration;\r\n    using Nancy.Json;\r\n    using Nancy.Responses;\r\n    using Nancy.Responses.Negotiation;\r\n    using Xunit;\r\n    using Xunit.Extensions;\r\n\r\n    public class DefaultSerializerFactoryFixture\r\n    {\r\n        private DefaultSerializerFactory serializerFactory;\r\n\r\n        public DefaultSerializerFactoryFixture()\r\n        {\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"application/json\")]\r\n        [InlineData(\"application/xml\")]\r\n        [InlineData(\"image/png\")]\r\n        public void Should_return_serializer_for_media_range(string expectedMediaRange)\r\n        {\r\n            // Given\r\n            var expectedSerializer =\r\n                new TestableSerializer(expectedMediaRange);\r\n\r\n            var serializers = new ISerializer[]\r\n            {\r\n                expectedSerializer,\r\n                new TestableSerializer(\"custom/foo\"),\r\n                new TestableSerializer(\"custom/bar\"),\r\n                new TestableSerializer(\"custom/baz\"),\r\n            };\r\n\r\n            this.serializerFactory = new DefaultSerializerFactory(serializers);\r\n\r\n            // When\r\n            var result = this.serializerFactory.GetSerializer(expectedMediaRange);\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(expectedSerializer);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_if_no_serializer_matched_media_range()\r\n        {\r\n            // Given\r\n            var serializers = new ISerializer[]\r\n            {\r\n                new TestableSerializer(\"custom/foo\"),\r\n                new TestableSerializer(\"custom/bar\"),\r\n                new TestableSerializer(\"custom/baz\"),\r\n            };\r\n\r\n            this.serializerFactory = new DefaultSerializerFactory(serializers);\r\n\r\n            // When\r\n            var result = this.serializerFactory.GetSerializer(\"application/json\");\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_throw_exception_if_a_serializer_throws()\r\n        {\r\n            // Given\r\n            var serializers = new ISerializer[]\r\n            {\r\n                new ExceptionThrowingSerializer()\r\n            };\r\n\r\n            this.serializerFactory = new DefaultSerializerFactory(serializers);\r\n\r\n            // When\r\n            var result = this.serializerFactory.GetSerializer(\"application/json\");\r\n\r\n            // Then\r\n            Assert.Null(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_if_multiple_serializers_matched_media_range()\r\n        {\r\n            var serializers = new ISerializer[]\r\n            {\r\n                new TestableSerializer(\"application/json\"),\r\n                new TestableSerializer(\"application/json\")\r\n            };\r\n\r\n            this.serializerFactory = new DefaultSerializerFactory(serializers);\r\n\r\n            // When, Then\r\n            Assert.Throws<InvalidOperationException>(() => this.serializerFactory.GetSerializer(\"application/json\"));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_include_default_serializers_when_counting_matches()\r\n        {\r\n            var serializers = new ISerializer[]\r\n            {\r\n                new TestableSerializer(\"application/json\"),\r\n                new DefaultJsonSerializer(GetTestingEnvironment())\r\n            };\r\n\r\n            this.serializerFactory = new DefaultSerializerFactory(serializers);\r\n\r\n            // When\r\n            var result = this.serializerFactory.GetSerializer(\"application/json\");\r\n\r\n            // Then\r\n            Assert.NotNull(result);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_prioritize_non_default_serializer_match()\r\n        {\r\n            const string expectedMediaRange = \"application/json\";\r\n\r\n            var expectedSerializer =\r\n                new TestableSerializer(expectedMediaRange);\r\n\r\n            var serializers = new ISerializer[]\r\n            {\r\n                new DefaultJsonSerializer(GetTestingEnvironment()),\r\n                expectedSerializer\r\n            };\r\n\r\n            this.serializerFactory = new DefaultSerializerFactory(serializers);\r\n\r\n            // When\r\n            var result = this.serializerFactory.GetSerializer(expectedMediaRange);\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(expectedSerializer);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_default_serializer_if_no_other_match_could_be_made()\r\n        {\r\n            // Given\r\n            var expectedSerializer =\r\n                new DefaultJsonSerializer(GetTestingEnvironment());\r\n\r\n            var serializers = new ISerializer[]\r\n            {\r\n                expectedSerializer,\r\n                new TestableSerializer(\"application/xml\"),\r\n                new TestableSerializer(\"application/xml\"),\r\n            };\r\n\r\n            this.serializerFactory = new DefaultSerializerFactory(serializers);\r\n\r\n            // When\r\n            var result = this.serializerFactory.GetSerializer(\"application/json\");\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(expectedSerializer);\r\n        }\r\n\r\n        private static INancyEnvironment GetTestingEnvironment()\r\n        {\r\n            var environment =\r\n                new DefaultNancyEnvironment();\r\n\r\n            environment.Tracing(\r\n                enabled: true,\r\n                displayErrorTraces: true);\r\n\r\n            environment.Json();\r\n            environment.Globalization(new []{\"en-US\"});\r\n\r\n            return environment;\r\n        }\r\n\r\n        internal class ExceptionThrowingSerializer : ISerializer\r\n        {\r\n            public bool CanSerialize(MediaRange mediaRange)\r\n            {\r\n                throw new Exception();\r\n            }\r\n\r\n            public IEnumerable<string> Extensions { get; set; }\r\n\r\n            public void Serialize<TModel>(MediaRange mediaRange, TModel model, Stream outputStream)\r\n            {\r\n                throw new System.NotImplementedException();\r\n            }\r\n        }\r\n\r\n        internal class TestableSerializer : ISerializer\r\n        {\r\n            private readonly MediaRange mediaRange;\r\n\r\n            public TestableSerializer(MediaRange mediaRange)\r\n            {\r\n                this.mediaRange = mediaRange;\r\n            }\r\n\r\n            public bool CanSerialize(MediaRange mediaRange)\r\n            {\r\n                return this.mediaRange.Matches(mediaRange);\r\n            }\r\n\r\n            public IEnumerable<string> Extensions { get; set; }\r\n\r\n            public void Serialize<TModel>(MediaRange mediaRange, TModel model, Stream outputStream)\r\n            {\r\n                throw new System.NotImplementedException();\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Diagnostics/ConcurrentLimitedCollectionFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Diagnostics\r\n{\r\n    using System.Linq;\r\n\r\n    using Nancy.Diagnostics;\r\n\r\n    using Xunit;\r\n\r\n    public class ConcurrentLimitedCollectionFixture\r\n    {\r\n        private const int MaxSize = 5;\r\n\r\n        private readonly ConcurrentLimitedCollection<object> collection;\r\n\r\n        public ConcurrentLimitedCollectionFixture()\r\n        {\r\n            this.collection = new ConcurrentLimitedCollection<object>(MaxSize);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_add_items()\r\n        {\r\n            var obj = new object();\r\n            var obj2 = new object();\r\n\r\n            this.collection.Add(obj);\r\n            this.collection.Add(obj2);\r\n\r\n            this.collection.Any(o => ReferenceEquals(obj, o)).ShouldBeTrue();\r\n            this.collection.Any(o => ReferenceEquals(obj2, o)).ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_get_current_size()\r\n        {\r\n            var obj = new object();\r\n            var obj2 = new object();\r\n\r\n            this.collection.Add(obj);\r\n            this.collection.Add(obj2);\r\n\r\n            this.collection.CurrentSize.ShouldEqual(2);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_clear()\r\n        {\r\n            var obj = new object();\r\n            var obj2 = new object();\r\n            this.collection.Add(obj);\r\n            this.collection.Add(obj2);\r\n\r\n            this.collection.Clear();\r\n\r\n            this.collection.CurrentSize.ShouldEqual(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_grow_beyond_limit()\r\n        {\r\n            var obj = new object();\r\n            var obj2 = new object();\r\n            var obj3 = new object();\r\n            var obj4 = new object();\r\n            var obj5 = new object();\r\n            var obj6 = new object();\r\n\r\n            this.collection.Add(obj);\r\n            this.collection.Add(obj2);\r\n            this.collection.Add(obj3);\r\n            this.collection.Add(obj4);\r\n            this.collection.Add(obj5);\r\n            this.collection.Add(obj6);\r\n            \r\n            this.collection.CurrentSize.ShouldEqual(MaxSize);\r\n        }\r\n\r\n        [Fact]\r\n        public void First_element_should_drop_off_when_over_limit()\r\n        {\r\n            var obj = new object();\r\n            var obj2 = new object();\r\n            var obj3 = new object();\r\n            var obj4 = new object();\r\n            var obj5 = new object();\r\n            var obj6 = new object();\r\n\r\n            this.collection.Add(obj);\r\n            this.collection.Add(obj2);\r\n            this.collection.Add(obj3);\r\n            this.collection.Add(obj4);\r\n            this.collection.Add(obj5);\r\n            this.collection.Add(obj6);\r\n\r\n            this.collection.Any(o => ReferenceEquals(obj, o)).ShouldBeFalse();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Diagnostics/CustomInteractiveDiagnosticsFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Diagnostics\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Configuration;\r\n    using Nancy.Conventions;\r\n    using Nancy.Cryptography;\r\n    using Nancy.Culture;\r\n    using Nancy.Diagnostics;\r\n    using Nancy.Localization;\r\n    using Nancy.ModelBinding;\r\n    using Nancy.Responses.Negotiation;\r\n    using Nancy.Routing;\r\n    using Nancy.Routing.Constraints;\r\n    using Nancy.Testing;\r\n    using Xunit;\r\n\r\n    public class CustomInteractiveDiagnosticsHookFixture\r\n    {\r\n        private const string DiagsCookieName = \"__ncd\";\r\n        private readonly CryptographyConfiguration cryptoConfig;\r\n        private readonly IObjectSerializer objectSerializer;\r\n\r\n        public CustomInteractiveDiagnosticsHookFixture()\r\n        {\r\n            this.cryptoConfig = CryptographyConfiguration.Default;\r\n            this.objectSerializer = new DefaultObjectSerializer();\r\n        }\r\n\r\n        private class FakeDiagnostics : IDiagnostics\r\n        {\r\n            private readonly IEnumerable<IDiagnosticsProvider> diagnosticProviders;\r\n            private readonly IRootPathProvider rootPathProvider;\r\n            private readonly IRequestTracing requestTracing;\r\n            private readonly NancyInternalConfiguration configuration;\r\n            private readonly IModelBinderLocator modelBinderLocator;\r\n            private readonly IEnumerable<IResponseProcessor> responseProcessors;\r\n            private readonly IEnumerable<IRouteSegmentConstraint> routeSegmentConstraints;\r\n            private readonly ICultureService cultureService;\r\n            private readonly IRequestTraceFactory requestTraceFactory;\r\n            private readonly IEnumerable<IRouteMetadataProvider> routeMetadataProviders;\r\n            private readonly ITextResource textResource;\r\n            private readonly INancyEnvironment environment;\r\n            private readonly ITypeCatalog typeCatalog;\r\n            private readonly IAssemblyCatalog assemblyCatalog;\r\n            private readonly AcceptHeaderCoercionConventions acceptHeaderCoercionConventions;\r\n\r\n            public FakeDiagnostics(\r\n                IRootPathProvider rootPathProvider,\r\n                IRequestTracing requestTracing,\r\n                NancyInternalConfiguration configuration,\r\n                IModelBinderLocator modelBinderLocator,\r\n                IEnumerable<IResponseProcessor> responseProcessors,\r\n                IEnumerable<IRouteSegmentConstraint> routeSegmentConstraints,\r\n                ICultureService cultureService,\r\n                IRequestTraceFactory requestTraceFactory,\r\n                IEnumerable<IRouteMetadataProvider> routeMetadataProviders,\r\n                ITextResource textResource,\r\n                INancyEnvironment environment,\r\n                ITypeCatalog typeCatalog,\r\n                IAssemblyCatalog assemblyCatalog,\r\n                AcceptHeaderCoercionConventions acceptHeaderCoercionConventions)\r\n            {\r\n                this.diagnosticProviders = (new IDiagnosticsProvider[] { new FakeDiagnosticsProvider() }).ToArray();\r\n                this.rootPathProvider = rootPathProvider;\r\n                this.requestTracing = requestTracing;\r\n                this.configuration = configuration;\r\n                this.modelBinderLocator = modelBinderLocator;\r\n                this.responseProcessors = responseProcessors;\r\n                this.routeSegmentConstraints = routeSegmentConstraints;\r\n                this.cultureService = cultureService;\r\n                this.requestTraceFactory = requestTraceFactory;\r\n                this.routeMetadataProviders = routeMetadataProviders;\r\n                this.textResource = textResource;\r\n                this.environment = environment;\r\n                this.typeCatalog = typeCatalog;\r\n                this.assemblyCatalog = assemblyCatalog;\r\n                this.acceptHeaderCoercionConventions = acceptHeaderCoercionConventions;\r\n            }\r\n\r\n            public void Initialize(IPipelines pipelines)\r\n            {\r\n                DiagnosticsHook.Enable(\r\n                    pipelines,\r\n                    this.diagnosticProviders,\r\n                    this.rootPathProvider,\r\n                    this.requestTracing,\r\n                    this.configuration,\r\n                    this.modelBinderLocator,\r\n                    this.responseProcessors,\r\n                    this.routeSegmentConstraints,\r\n                    this.cultureService,\r\n                    this.requestTraceFactory,\r\n                    this.routeMetadataProviders,\r\n                    this.textResource,\r\n                    this.environment,\r\n                    this.typeCatalog,\r\n                    this.assemblyCatalog,\r\n                    this.acceptHeaderCoercionConventions);\r\n            }\r\n        }\r\n\r\n        private class FakeDiagnosticsProvider : IDiagnosticsProvider\r\n        {\r\n            public string Name\r\n            {\r\n                get { return \"Fake testing provider\"; }\r\n            }\r\n\r\n            public string Description\r\n            {\r\n                get { return \"Fake testing provider\"; }\r\n            }\r\n\r\n            public object DiagnosticObject\r\n            {\r\n                get { return this; }\r\n            }\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_main_page_with_valid_auth_cookie()\r\n        {\r\n            // Given\r\n            var bootstrapper = new ConfigurableBootstrapper(with =>\r\n            {\r\n                with.Configure(env =>\r\n                {\r\n                    env.Diagnostics(\r\n                        enabled: true,\r\n                        password: \"password\",\r\n                        cryptographyConfiguration: this.cryptoConfig);\r\n                });\r\n\r\n                with.EnableAutoRegistration();\r\n                with.Diagnostics<FakeDiagnostics>();\r\n            });\r\n\r\n            var browser = new Browser(bootstrapper);\r\n\r\n            // When\r\n            var result = await browser.Get(DiagnosticsConfiguration.Default.Path + \"/interactive/providers/\", with =>\r\n                {\r\n                    with.Cookie(DiagsCookieName, this.GetSessionCookieValue(\"password\"));\r\n                });\r\n\r\n            // Then should see our fake provider and not the default testing provider\r\n            result.Body.AsString().ShouldContain(\"Fake testing provider\");\r\n            result.Body.AsString().ShouldNotContain(\"Testing Diagnostic Provider\");\r\n        }\r\n\r\n        private string GetSessionCookieValue(string password, DateTime? expiry = null)\r\n        {\r\n            var salt = DiagnosticsSession.GenerateRandomSalt();\r\n            var hash = DiagnosticsSession.GenerateSaltedHash(password, salt);\r\n            var session = new DiagnosticsSession\r\n                {\r\n                    Hash = hash,\r\n                    Salt = salt,\r\n                    Expiry = expiry.HasValue ? expiry.Value : DateTime.Now.AddMinutes(15),\r\n                };\r\n\r\n            var serializedSession = this.objectSerializer.Serialize(session);\r\n\r\n            var encryptedSession = this.cryptoConfig.EncryptionProvider.Encrypt(serializedSession);\r\n            var hmacBytes = this.cryptoConfig.HmacProvider.GenerateHmac(encryptedSession);\r\n            var hmacString = Convert.ToBase64String(hmacBytes);\r\n\r\n            return string.Format(\"{1}{0}\", encryptedSession, hmacString);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Diagnostics/DefaultRequestTraceFactoryFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Diagnostics\r\n{\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using Nancy.Configuration;\r\n    using Nancy.Diagnostics;\r\n    using Nancy.IO;\r\n    using Nancy.Testing;\r\n\r\n    using Xunit;\r\n\r\n    public class DefaultRequestTraceFactoryFixture\r\n    {\r\n        private DefaultRequestTraceFactory factory;\r\n        private readonly Request request;\r\n\r\n        public DefaultRequestTraceFactoryFixture()\r\n        {\r\n            this.factory = CreateFactory();\r\n            this.request = CreateRequest();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_create_default_trace_log_instance_when_error_tracing_is_activated()\r\n        {\r\n            // Given\r\n            this.factory = CreateFactory(true);\r\n\r\n            // When\r\n            var trace = this.factory.Create(this.request);\r\n\r\n            // Then\r\n            trace.TraceLog.ShouldNotBeNull();\r\n            trace.TraceLog.ShouldBeOfType<DefaultTraceLog>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_create_null_trace_log_instance_when_error_tracing_is_deactivated()\r\n        {\r\n            // Given\r\n            this.factory = CreateFactory(false);\r\n\r\n            // When\r\n            var trace = this.factory.Create(this.request);\r\n\r\n            // Then\r\n            trace.TraceLog.ShouldNotBeNull();\r\n            trace.TraceLog.ShouldBeOfType<NullLog>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_initialize_case_insensitive_items_collection_when_case_sensitivity_is_disabled()\r\n        {\r\n            using (new StaticConfigurationContext(x => x.CaseSensitive = false))\r\n            {\r\n                // Given\r\n                var trace = this.factory.Create(this.request);\r\n\r\n                // When\r\n                trace.Items.Add(\"foo\", \"bar\");\r\n\r\n                // Then\r\n                Record.Exception(() => trace.Items[\"FOO\"]).ShouldBeNull();\r\n            }\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_initialize_case_sensitive_items_collection_when_case_sensitivity_is_enabled()\r\n        {\r\n            using (new StaticConfigurationContext(x => x.CaseSensitive = true))\r\n            {\r\n                // Given\r\n                var trace = this.factory.Create(this.request);\r\n\r\n                // When\r\n                trace.Items.Add(\"foo\", \"bar\");\r\n\r\n                // Then\r\n                Assert.Throws<KeyNotFoundException>(() =>\r\n                {\r\n                    var value = trace.Items[\"FOO\"];\r\n                });\r\n            }\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_create_request_info_from_request()\r\n        {\r\n            // Given\r\n            // When\r\n            var trace = this.factory.Create(this.request);\r\n\r\n            // Then\r\n            trace.RequestData.ContentType.Matches(this.request.Headers.ContentType).ShouldBeTrue();\r\n            trace.RequestData.Headers.ShouldBeSameAs(this.request.Headers);\r\n            trace.RequestData.Method.ShouldEqual(this.request.Method);\r\n            trace.RequestData.Url.ShouldBeSameAs(this.request.Url);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_create_response_info()\r\n        {\r\n            // Given\r\n            // When\r\n            var trace = this.factory.Create(this.request);\r\n\r\n            // Then\r\n            trace.ResponseData.ShouldBeNull();\r\n        }\r\n\r\n        private static DefaultRequestTraceFactory CreateFactory(bool displayErrorTraces = true)\r\n        {\r\n            var environment =\r\n                new DefaultNancyEnvironment();\r\n\r\n            environment.Tracing(\r\n                enabled: true,\r\n                displayErrorTraces: displayErrorTraces);\r\n\r\n            return new DefaultRequestTraceFactory(environment);\r\n        }\r\n\r\n        private static Request CreateRequest()\r\n        {\r\n            return new Request(\r\n                \"GET\",\r\n                new Url(),\r\n                RequestStream.FromStream(new MemoryStream()),\r\n                new Dictionary<string, IEnumerable<string>>\r\n                {\r\n                    {\"Content-Type\", new[] {\"text/plain\"}}\r\n                });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Diagnostics/DiagnosticsHookFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Diagnostics\r\n{\r\n    using System;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using System.Threading.Tasks;\r\n    using FakeItEasy;\r\n    using Nancy.Cookies;\r\n    using Nancy.Cryptography;\r\n    using Nancy.Diagnostics;\r\n    using Nancy.Diagnostics.Modules;\r\n    using Nancy.Testing;\r\n\r\n    using Xunit;\r\n\r\n    public class DiagnosticsHookFixture\r\n    {\r\n        private const string DiagsCookieName = \"__ncd\";\r\n        private readonly CryptographyConfiguration cryptoConfig;\r\n        private readonly IObjectSerializer objectSerializer;\r\n\r\n        public DiagnosticsHookFixture()\r\n        {\r\n            this.cryptoConfig = CryptographyConfiguration.Default;\r\n            this.objectSerializer = new DefaultObjectSerializer();\r\n        }\r\n\r\n#if DEBUG\r\n        [Fact]\r\n        public async Task Should_return_info_page_if_password_null()\r\n        {\r\n            // Given\r\n            var bootstrapper = new ConfigurableBootstrapper(with =>\r\n            {\r\n                with.Configure(env =>\r\n                {\r\n                    env.Diagnostics(\r\n                        enabled: true,\r\n                        password: null,\r\n                        cryptographyConfiguration: this.cryptoConfig);\r\n                });\r\n\r\n                with.EnableAutoRegistration();\r\n                with.Diagnostics<DefaultDiagnostics>();\r\n            });\r\n\r\n            var browser = new Browser(bootstrapper);\r\n\r\n            // When\r\n            var result = await browser.Get(DiagnosticsConfiguration.Default.Path);\r\n\r\n            // Then\r\n            Assert.True(result.Body.AsString().Contains(\"Diagnostics Disabled\"));\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_info_page_if_password_empty()\r\n        {\r\n            // Given\r\n            var bootstrapper = new ConfigurableBootstrapper(with =>\r\n            {\r\n                with.Configure(env =>\r\n                {\r\n                    env.Diagnostics(\r\n                        enabled: true,\r\n                        password: string.Empty,\r\n                        cryptographyConfiguration: this.cryptoConfig);\r\n                });\r\n\r\n                with.EnableAutoRegistration();\r\n                with.Diagnostics<DefaultDiagnostics>();\r\n            });\r\n\r\n            var browser = new Browser(bootstrapper);\r\n\r\n            // When\r\n            var result = await browser.Get(DiagnosticsConfiguration.Default.Path);\r\n\r\n            // Then\r\n            Assert.True(result.Body.AsString().Contains(\"Diagnostics Disabled\"));\r\n        }\r\n#endif\r\n\r\n        [Fact]\r\n        public async Task Should_return_login_page_with_no_auth_cookie()\r\n        {\r\n            // Given\r\n            var bootstrapper = new ConfigurableBootstrapper(with =>\r\n            {\r\n                with.Configure(env =>\r\n                {\r\n                    env.Diagnostics(\r\n                        enabled: true,\r\n                        password: \"password\",\r\n                        cryptographyConfiguration: this.cryptoConfig);\r\n                });\r\n\r\n                with.EnableAutoRegistration();\r\n                with.Diagnostics<DefaultDiagnostics>();\r\n            });\r\n\r\n            var browser = new Browser(bootstrapper);\r\n\r\n            // When\r\n            var result = await browser.Get(DiagnosticsConfiguration.Default.Path);\r\n\r\n            // Then\r\n            result.Body[\"#login\"].ShouldExistOnce();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_main_page_with_valid_auth_cookie()\r\n        {\r\n            // Given\r\n            var bootstrapper = new ConfigurableBootstrapper(with =>\r\n            {\r\n                with.Configure(env =>\r\n                {\r\n                    env.Diagnostics(\r\n                        enabled: true,\r\n                        password: \"password\",\r\n                        cryptographyConfiguration: this.cryptoConfig);\r\n                });\r\n\r\n                with.EnableAutoRegistration();\r\n                with.Diagnostics<DefaultDiagnostics>();\r\n            });\r\n\r\n            var browser = new Browser(bootstrapper);\r\n\r\n            // When\r\n            var result = await browser.Get(DiagnosticsConfiguration.Default.Path, with =>\r\n                {\r\n                    with.Cookie(DiagsCookieName, this.GetSessionCookieValue(\"password\"));\r\n                });\r\n\r\n            // Then\r\n            result.Body[\"#infoBox\"].ShouldExistOnce();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_login_page_with_expired_auth_cookie()\r\n        {\r\n            // Given\r\n            var bootstrapper = new ConfigurableBootstrapper(with =>\r\n            {\r\n                with.Configure(env =>\r\n                {\r\n                    env.Diagnostics(\r\n                        enabled: true,\r\n                        password: \"password\",\r\n                        cryptographyConfiguration: this.cryptoConfig);\r\n                });\r\n\r\n                with.EnableAutoRegistration();\r\n                with.Diagnostics<DefaultDiagnostics>();\r\n            });\r\n\r\n            var browser = new Browser(bootstrapper);\r\n\r\n            // When\r\n            var result = await browser.Get(DiagnosticsConfiguration.Default.Path, with =>\r\n            {\r\n                with.Cookie(DiagsCookieName, this.GetSessionCookieValue(\"password\", DateTime.Now.AddMinutes(-10)));\r\n            });\r\n\r\n            // Then\r\n            result.Body[\"#login\"].ShouldExistOnce();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_login_page_with_auth_cookie_with_incorrect_password()\r\n        {\r\n            // Given\r\n            var bootstrapper = new ConfigurableBootstrapper(with =>\r\n            {\r\n                with.Configure(env =>\r\n                {\r\n                    env.Diagnostics(\r\n                        enabled: true,\r\n                        password: \"password\",\r\n                        cryptographyConfiguration: this.cryptoConfig);\r\n                });\r\n\r\n                with.EnableAutoRegistration();\r\n                with.Diagnostics<DefaultDiagnostics>();\r\n            });\r\n\r\n            var browser = new Browser(bootstrapper);\r\n\r\n            // When\r\n            var result = await browser.Get(DiagnosticsConfiguration.Default.Path, with =>\r\n            {\r\n                with.Cookie(DiagsCookieName, this.GetSessionCookieValue(\"wrongPassword\"));\r\n            });\r\n\r\n            // Then\r\n            result.Body[\"#login\"].ShouldExistOnce();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_accept_invalid_password()\r\n        {\r\n            // Given\r\n            var bootstrapper = new ConfigurableBootstrapper(with =>\r\n            {\r\n                with.Configure(env =>\r\n                {\r\n                    env.Diagnostics(\r\n                        enabled: true,\r\n                        password: \"password\",\r\n                        cryptographyConfiguration: this.cryptoConfig);\r\n                });\r\n\r\n                with.EnableAutoRegistration();\r\n                with.Diagnostics<DefaultDiagnostics>();\r\n            });\r\n\r\n            var browser = new Browser(bootstrapper);\r\n\r\n            // When\r\n            var result = await browser.Post(DiagnosticsConfiguration.Default.Path, with =>\r\n            {\r\n                with.FormValue(\"Password\", \"wrongpassword\");\r\n            });\r\n\r\n            // Then\r\n            result.Body[\"#login\"].ShouldExistOnce();\r\n            result.Cookies.Any(c => c.Name == DiagsCookieName && !string.IsNullOrEmpty(c.Value)).ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_set_login_cookie_when_password_correct()\r\n        {\r\n            // Given\r\n            var bootstrapper = new ConfigurableBootstrapper(with =>\r\n            {\r\n                with.Configure(env =>\r\n                {\r\n                    env.Diagnostics(\r\n                        enabled: true,\r\n                        password: \"password\",\r\n                        cryptographyConfiguration: this.cryptoConfig);\r\n                });\r\n\r\n                with.EnableAutoRegistration();\r\n                with.Diagnostics<DefaultDiagnostics>();\r\n            });\r\n\r\n            var browser = new Browser(bootstrapper);\r\n\r\n            // When\r\n            var result = await browser.Post(DiagnosticsConfiguration.Default.Path, with =>\r\n            {\r\n                with.FormValue(\"Password\", \"password\");\r\n            });\r\n\r\n            // Then\r\n            result.Cookies.Any(c => c.Name == DiagsCookieName).ShouldBeTrue();\r\n            string.IsNullOrEmpty(result.Cookies.First(c => c.Name == DiagsCookieName).Value).ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_use_rolling_expiry_for_auth_cookie()\r\n        {\r\n            // Given\r\n            var bootstrapper = new ConfigurableBootstrapper(with =>\r\n            {\r\n                with.Configure(env =>\r\n                {\r\n                    env.Diagnostics(\r\n                        enabled: true,\r\n                        password: \"password\",\r\n                        cryptographyConfiguration: this.cryptoConfig);\r\n                });\r\n\r\n                with.EnableAutoRegistration();\r\n                with.Diagnostics<DefaultDiagnostics>();\r\n            });\r\n\r\n            var browser = new Browser(bootstrapper);\r\n            var expiryDate = DateTime.Now.AddMinutes(5);\r\n\r\n            // When\r\n            var result = await browser.Get(DiagnosticsConfiguration.Default.Path, with =>\r\n            {\r\n                with.Cookie(DiagsCookieName, this.GetSessionCookieValue(\"password\", expiryDate));\r\n            });\r\n\r\n            // Then\r\n            result.Cookies.Any(c => c.Name == DiagsCookieName).ShouldBeTrue();\r\n            this.DecodeCookie(result.Cookies.First(c => c.Name == DiagsCookieName))\r\n                .Expiry.ShouldNotEqual(expiryDate);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_diagnostic_example()\r\n        {\r\n            // Given\r\n            var bootstrapper = new ConfigurableBootstrapper(with =>\r\n            {\r\n                with.Configure(env =>\r\n                {\r\n                    env.Diagnostics(\r\n                        enabled: true,\r\n                        password: \"password\",\r\n                        cryptographyConfiguration: this.cryptoConfig);\r\n                });\r\n\r\n                with.EnableAutoRegistration();\r\n                with.Diagnostics<DefaultDiagnostics>();\r\n            });\r\n\r\n            var browser = new Browser(bootstrapper);\r\n\r\n            // When\r\n            var result = await browser.Get(DiagnosticsConfiguration.Default.Path + \"/interactive/providers/\", with =>\r\n                {\r\n                    with.Cookie(DiagsCookieName, this.GetSessionCookieValue(\"password\"));\r\n                });\r\n\r\n            // Then\r\n            result.Body.AsString().ShouldNotContain(\"Fake testing provider\");\r\n            result.Body.AsString().ShouldContain(\"Testing Diagnostic Provider\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_ok_for_post_settings()\r\n        {\r\n            // Given\r\n            var bootstrapper = new ConfigurableBootstrapper(with =>\r\n            {\r\n                with.Configure(env =>\r\n                {\r\n                    env.Diagnostics(\r\n                        enabled: true,\r\n                        password: \"password\",\r\n                        cryptographyConfiguration: this.cryptoConfig);\r\n                });\r\n\r\n                with.EnableAutoRegistration();\r\n                with.Diagnostics<DefaultDiagnostics>();\r\n            });\r\n            var browser = new Browser(bootstrapper);\r\n            \r\n            // When\r\n            var result = await browser.Post(DiagnosticsConfiguration.Default.Path + \"/settings\", with =>\r\n            {\r\n                with.Cookie(DiagsCookieName, this.GetSessionCookieValue(\"password\"));\r\n                with.JsonBody(new SettingsModel { Name = \"CaseSensitive\", Value = true });\r\n            });\r\n            \r\n            // Then\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.OK);\r\n        }\r\n\r\n        private string GetSessionCookieValue(string password, DateTime? expiry = null)\r\n        {\r\n            var salt = DiagnosticsSession.GenerateRandomSalt();\r\n            var hash = DiagnosticsSession.GenerateSaltedHash(password, salt);\r\n            var session = new DiagnosticsSession\r\n                {\r\n                    Hash = hash,\r\n                    Salt = salt,\r\n                    Expiry = expiry.HasValue ? expiry.Value : DateTime.Now.AddMinutes(15),\r\n                };\r\n\r\n            var serializedSession = this.objectSerializer.Serialize(session);\r\n\r\n            var encryptedSession = this.cryptoConfig.EncryptionProvider.Encrypt(serializedSession);\r\n            var hmacBytes = this.cryptoConfig.HmacProvider.GenerateHmac(encryptedSession);\r\n            var hmacString = Convert.ToBase64String(hmacBytes);\r\n\r\n            return String.Format(\"{1}{0}\", encryptedSession, hmacString);\r\n        }\r\n\r\n        private DiagnosticsSession DecodeCookie(INancyCookie nancyCookie)\r\n        {\r\n            var cookieValue = nancyCookie.Value;\r\n            var hmacStringLength = Base64Helpers.GetBase64Length(this.cryptoConfig.HmacProvider.HmacLength);\r\n            var encryptedSession = cookieValue.Substring(hmacStringLength);\r\n            var decrypted = this.cryptoConfig.EncryptionProvider.Decrypt(encryptedSession);\r\n\r\n            return this.objectSerializer.Deserialize(decrypted) as DiagnosticsSession;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Diagnostics/InteractiveDiagnosticsFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Diagnostics\r\n{\r\n    using Nancy.Diagnostics;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using Xunit;\r\n\r\n    public class InteractiveDiagnosticsFixture\r\n    {\r\n        private class FakeParentDiagnosticsProvider : IDiagnosticsProvider\r\n        {\r\n            public string Name\r\n            {\r\n                get { return \"Fake testing provider\"; }\r\n            }\r\n\r\n            public string Description\r\n            {\r\n                get { return \"Fake testing provider\"; }\r\n            }\r\n\r\n            public object DiagnosticObject\r\n            {\r\n                get { return this; }\r\n            }\r\n\r\n            [Description(\"Parent public method.\")]\r\n            [Template(\"<h1>{{model.Result}}</h1>\")]\r\n            public string ParentPublicMethod()\r\n            {\r\n                return \"In parent public.\";\r\n            }\r\n        }\r\n\r\n        private class FakeChildDiagnosticsProvider : FakeParentDiagnosticsProvider\r\n        {\r\n            [Description(\"Child public method.\")]\r\n            [Template(\"<h1>{{model.Result}}</h1>\")]\r\n            public string ChildPublicMethod()\r\n            {\r\n                return \"In child public.\";\r\n            }\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_methods_from_entire_hierarchy()\r\n        {\r\n            //Given\r\n            var child = new FakeChildDiagnosticsProvider();\r\n            var parent = new FakeParentDiagnosticsProvider();\r\n\r\n            var diagnostics = new InteractiveDiagnostics(new[] {child, parent});\r\n            var availableDiagnostics = diagnostics.AvailableDiagnostics.ToList();\r\n\r\n            //When\r\n            var methodsInChild = availableDiagnostics[0].Methods.Count();\r\n            var methodsInParent = availableDiagnostics[1].Methods.Count();\r\n\r\n            //Then\r\n            Assert.True(methodsInChild == methodsInParent + 1);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_exclude_object_methods()\r\n        {\r\n            //Given\r\n            var child = new FakeChildDiagnosticsProvider();\r\n\r\n            var diagnostics = new InteractiveDiagnostics(new[] { child });\r\n            var availableDiagnostics = diagnostics.AvailableDiagnostics.ToList();\r\n\r\n            var objectMethodNames = typeof(object).GetMethods()\r\n                .Select(x => x.Name)\r\n                .ToList();\r\n\r\n            //When\r\n            var methodsInChild = availableDiagnostics[0].Methods;\r\n\r\n            //Then\r\n            foreach (var childMethod in methodsInChild)\r\n            {\r\n                Assert.DoesNotContain(childMethod.MethodName, objectMethodNames);\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/DynamicDictionaryFixture.cs",
    "content": "namespace Nancy.Tests.Unit\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Globalization;\r\n    using System.Linq;\r\n\r\n    using Nancy.Json;\r\n\r\n    using Xunit;\r\n    using Xunit.Extensions;\r\n\r\n    public class DynamicDictionaryFixture\r\n    {\r\n        private readonly dynamic dictionary;\r\n\r\n        public DynamicDictionaryFixture()\r\n        {\r\n            this.dictionary = new DynamicDictionary();\r\n            this.dictionary[\"TestString\"] = \"Testing\";\r\n            this.dictionary[\"TestInt\"] = 2;\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_create_instance_from_dictionary()\r\n        {\r\n            // Given\r\n            var values = new Dictionary<string, object>\r\n            {\r\n                { \"foo\", 10 },\r\n                { \"bar\", \"some value\" },\r\n            };\r\n\r\n            // When\r\n            dynamic instance = DynamicDictionary.Create(values, GlobalizationConfiguration.Default);\r\n\r\n            // Then\r\n            ((int)GetIntegerValue(instance.foo)).ShouldEqual(10);\r\n            ((string)GetStringValue(instance.bar)).ShouldEqual(\"some value\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_strip_dash_from_name_when_using_indexer_to_add_value()\r\n        {\r\n            // Given\r\n            this.dictionary[\"foo-bar\"] = 10;\r\n\r\n            // When\r\n            int result = GetIntegerValue(this.dictionary.foobar);\r\n\r\n            // Then\r\n            result.ShouldEqual(10);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_retrieve_value_for_key_containing_dash_when_using_indexer()\r\n        {\r\n            // Given\r\n            this.dictionary[\"foo-bar\"] = 10;\r\n\r\n            // When\r\n            int result = GetIntegerValue(this.dictionary[\"foo-bar\"]);\r\n\r\n            // Then\r\n            result.ShouldEqual(10);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_retrive_value_stores_with_dash_using_key_without_dash_when_using_indexer()\r\n        {\r\n            // Given\r\n            this.dictionary[\"foo-bar\"] = 10;\r\n\r\n            // When\r\n            int result = GetIntegerValue(this.dictionary[\"foobar\"]);\r\n\r\n            // Then\r\n            result.ShouldEqual(10);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_retrive_value_stores_using_dash_using_key_with_dash_when_using_indexer()\r\n        {\r\n            // Given\r\n            this.dictionary[\"foobar\"] = 10;\r\n\r\n            // When\r\n            int result = GetIntegerValue(this.dictionary[\"foo-bar\"]);\r\n\r\n            // Then\r\n            result.ShouldEqual(10);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_retrieving_non_existing_index_should_return_empty_value()\r\n        {\r\n            // Given\r\n            var value = this.dictionary[\"nonexisting\"];\r\n\r\n            // When\r\n            bool result = value.HasValue;\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_retrieving_non_existing_member_should_return_empty_value()\r\n        {\r\n            // Given\r\n            var value = this.dictionary.nonexisting;\r\n\r\n            // When\r\n            bool result = value.HasValue;\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_string_when_value_is_retrieved_as_member()\r\n        {\r\n            // Given\r\n            this.dictionary.value = \"foo\";\r\n\r\n            // When\r\n            string result = GetStringValue(this.dictionary.value);\r\n\r\n            // Then\r\n            result.ShouldEqual(\"foo\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_string_when_value_is_retrieved_as_index()\r\n        {\r\n            // Given\r\n            this.dictionary.value = \"foo\";\r\n\r\n            // When\r\n            string result = GetStringValue(this.dictionary[\"value\"]);\r\n\r\n            // Then\r\n            result.ShouldEqual(\"foo\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_integer_when_value_is_retrieved_as_member()\r\n        {\r\n            // Given\r\n            this.dictionary.value = 10;\r\n\r\n            // When\r\n            int result = GetIntegerValue(this.dictionary.value);\r\n\r\n            // Then\r\n            result.ShouldEqual(10);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_integer_when_value_is_retrieved_as_index()\r\n        {\r\n            // Given\r\n            this.dictionary.value = 10;\r\n\r\n            // When\r\n            int result = GetIntegerValue(this.dictionary[\"value\"]);\r\n\r\n            // Then\r\n            result.ShouldEqual(10);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_integer_when_value_is_string_and_is_retrieved_as_member()\r\n        {\r\n            // Given\r\n            this.dictionary.value = \"10\";\r\n\r\n            // When\r\n            int result = GetIntegerValue(this.dictionary.value);\r\n\r\n            // Then\r\n            result.ShouldEqual(10);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_integer_when_value_is_string_and_is_retrieved_as_index()\r\n        {\r\n            // Given\r\n            this.dictionary.value = \"10\";\r\n\r\n            // When\r\n            int result = GetIntegerValue(this.dictionary[\"value\"]);\r\n\r\n            // Then\r\n            result.ShouldEqual(10);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_guid_when_value_is_retrieved_as_member()\r\n        {\r\n            // Given\r\n            var id = Guid.NewGuid();\r\n            this.dictionary.value = id;\r\n\r\n            // When\r\n            Guid result = GetGuidValue(this.dictionary.value);\r\n\r\n            // Then\r\n            result.ShouldEqual(id);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_guid_when_value_is_retrieved_as_index()\r\n        {\r\n            // Given\r\n            var id = Guid.NewGuid();\r\n            this.dictionary.value = id;\r\n\r\n            // When\r\n            Guid result = GetGuidValue(this.dictionary[\"value\"]);\r\n\r\n            // Then\r\n            result.ShouldEqual(id);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_guid_when_value_is_string_and_is_retrieved_as_member()\r\n        {\r\n            // Given\r\n            var id = Guid.NewGuid();\r\n            this.dictionary.value = id.ToString(\"N\");\r\n\r\n            // When\r\n            Guid result = GetGuidValue(this.dictionary.value);\r\n\r\n            // Then\r\n            result.ShouldEqual(id);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_guid_when_value_is_string_and_is_retrieved_as_index()\r\n        {\r\n            // Given\r\n            var id = Guid.NewGuid();\r\n            this.dictionary.value = id.ToString(\"N\");\r\n\r\n            // When\r\n            Guid result = GetGuidValue(this.dictionary[\"value\"]);\r\n\r\n            // Then\r\n            result.ShouldEqual(id);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_datetime_when_value_is_retrieved_as_member()\r\n        {\r\n            // Given\r\n            var date = DateTime.Now;\r\n            this.dictionary.value = date;\r\n\r\n            // When\r\n            DateTime result = GetDateTimeValue(this.dictionary.value);\r\n\r\n            // Then\r\n            result.ShouldEqual(date);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_datetime_when_value_is_retrieved_as_index()\r\n        {\r\n            // Given\r\n            var date = DateTime.Now;\r\n            this.dictionary.value = date;\r\n\r\n            // When\r\n            DateTime result = GetDateTimeValue(this.dictionary[\"value\"]);\r\n\r\n            // Then\r\n            result.ShouldEqual(date);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_datetime_when_value_is_string_and_is_retrieved_as_member()\r\n        {\r\n            // Given\r\n            var date = new DateTime(2016, 05, 25, 10, 0, 05, DateTimeKind.Utc);\r\n            this.dictionary.value = date.ToString(\"O\");\r\n\r\n            // When\r\n            DateTime result = GetDateTimeValue(this.dictionary.value);\r\n\r\n            // Then\r\n            result.ShouldEqual(date);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_datetime_when_value_is_string_and_is_retrieved_as_index()\r\n        {\r\n            // Given\r\n            var date = new DateTime(2016, 05, 25, 10, 0, 05, DateTimeKind.Utc);\r\n            this.dictionary.value = date.ToString(\"O\");\r\n\r\n            // When\r\n            DateTime result = GetDateTimeValue(this.dictionary[\"value\"]);\r\n\r\n            // Then\r\n            result.ShouldEqual(date);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_timespan_when_value_is_retrieved_as_member()\r\n        {\r\n            // Given\r\n            var span = new TimeSpan(1, 2, 3, 4);\r\n            this.dictionary.value = span;\r\n\r\n            // When\r\n            TimeSpan result = GetTimeSpanValue(this.dictionary.value);\r\n\r\n            // Then\r\n            result.ShouldEqual(span);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_timespan_when_value_is_retrieved_as_index()\r\n        {\r\n            // Given\r\n            var span = new TimeSpan(1, 2, 3, 4);\r\n            this.dictionary.value = span;\r\n\r\n            // When\r\n            TimeSpan result = GetTimeSpanValue(this.dictionary[\"value\"]);\r\n\r\n            // Then\r\n            result.ShouldEqual(span);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_timespan_when_value_is_string_and_is_retrieved_as_member()\r\n        {\r\n            // Given\r\n            var span = new TimeSpan(1, 2, 3, 4);\r\n            this.dictionary.value = span.ToString();\r\n\r\n            // When\r\n            TimeSpan result = GetTimeSpanValue(this.dictionary.value);\r\n\r\n            // Then\r\n            result.ShouldEqual(span);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_timespan_when_value_is_string_and_is_retrieved_as_index()\r\n        {\r\n            // Given\r\n            var span = new TimeSpan(1, 2, 3, 4);\r\n            this.dictionary.value = span.ToString();\r\n\r\n            // When\r\n            TimeSpan result = GetTimeSpanValue(this.dictionary[\"value\"]);\r\n\r\n            // Then\r\n            result.ShouldEqual(span);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_long_when_value_is_retrieved_as_member()\r\n        {\r\n            // Given\r\n            this.dictionary.value = 10L;\r\n\r\n            // When\r\n            long result = GetLongValue(this.dictionary.value);\r\n\r\n            // Then\r\n            result.ShouldEqual(10L);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_long_when_value_is_retrieved_as_index()\r\n        {\r\n            // Given\r\n            this.dictionary.value = 10L;\r\n\r\n            // When\r\n            long result = GetLongValue(this.dictionary[\"value\"]);\r\n\r\n            // Then\r\n            result.ShouldEqual(10L);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_long_when_value_is_string_and_is_retrieved_as_member()\r\n        {\r\n            // Given\r\n            this.dictionary.value = \"10\";\r\n\r\n            // When\r\n            long result = GetLongValue(this.dictionary.value);\r\n\r\n            // Then\r\n            result.ShouldEqual(10L);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_long_when_value_is_string_and_is_retrieved_as_index()\r\n        {\r\n            // Given\r\n            this.dictionary.value = \"10\";\r\n\r\n            // When\r\n            long result = GetLongValue(this.dictionary[\"value\"]);\r\n\r\n            // Then\r\n            result.ShouldEqual(10L);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_float_when_value_is_retrieved_as_member()\r\n        {\r\n            // Given\r\n            this.dictionary.value = 10f;\r\n\r\n            // When\r\n            float result = GetFloatValue(this.dictionary.value);\r\n\r\n            // Then\r\n            result.ShouldEqual(10f);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_float_when_value_is_retrieved_as_index()\r\n        {\r\n            // Given\r\n            this.dictionary.value = 10f;\r\n\r\n            // When\r\n            float result = GetFloatValue(this.dictionary[\"value\"]);\r\n\r\n            // Then\r\n            result.ShouldEqual(10f);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_float_when_value_is_string_and_is_retrieved_as_member()\r\n        {\r\n            // Given\r\n            this.dictionary.value = \"10\";\r\n\r\n            // When\r\n            float result = GetFloatValue(this.dictionary.value);\r\n\r\n            // Then\r\n            result.ShouldEqual(10f);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_float_when_value_is_string_and_is_retrieved_as_index()\r\n        {\r\n            // Given\r\n            this.dictionary.value = \"10\";\r\n\r\n            // When\r\n            float result = GetFloatValue(this.dictionary[\"value\"]);\r\n\r\n            // Then\r\n            result.ShouldEqual(10f);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_decimal_when_value_is_retrieved_as_member()\r\n        {\r\n            // Given\r\n            this.dictionary.value = 10m;\r\n\r\n            // When\r\n            decimal result = GetDecimalValue(this.dictionary.value);\r\n\r\n            // Then\r\n            result.ShouldEqual(10m);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_decimal_when_value_is_retrieved_as_index()\r\n        {\r\n            // Given\r\n            this.dictionary.value = 10m;\r\n\r\n            // When\r\n            decimal result = GetDecimalValue(this.dictionary[\"value\"]);\r\n\r\n            // Then\r\n            result.ShouldEqual(10m);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_decimal_when_value_is_string_and_is_retrieved_as_member()\r\n        {\r\n            // Given\r\n            this.dictionary.value = \"10\";\r\n\r\n            // When\r\n            decimal result = GetDecimalValue(this.dictionary.value);\r\n\r\n            // Then\r\n            result.ShouldEqual(10m);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_decimal_when_value_is_string_and_is_retrieved_as_index()\r\n        {\r\n            // Given\r\n            this.dictionary.value = \"10\";\r\n\r\n            // When\r\n            decimal result = GetDecimalValue(this.dictionary[\"value\"]);\r\n\r\n            // Then\r\n            result.ShouldEqual(10m);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_double_when_value_is_retrieved_as_member()\r\n        {\r\n            // Given\r\n            this.dictionary.value = 10d;\r\n\r\n            // When\r\n            double result = GetDoubleValue(this.dictionary.value);\r\n\r\n            // Then\r\n            result.ShouldEqual(10d);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_double_when_value_is_retrieved_as_index()\r\n        {\r\n            // Given\r\n            this.dictionary.value = 10d;\r\n\r\n            // When\r\n            double result = GetDoubleValue(this.dictionary[\"value\"]);\r\n\r\n            // Then\r\n            result.ShouldEqual(10d);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_double_when_value_is_string_and_is_retrieved_as_member()\r\n        {\r\n            // Given\r\n            this.dictionary.value = \"10\";\r\n\r\n            // When\r\n            double result = GetDoubleValue(this.dictionary.value);\r\n\r\n            // Then\r\n            result.ShouldEqual(10d);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_double_when_value_is_string_and_is_retrieved_as_index()\r\n        {\r\n            // Given\r\n            this.dictionary.value = \"10\";\r\n\r\n            // When\r\n            double result = GetDoubleValue(this.dictionary[\"value\"]);\r\n\r\n            // Then\r\n            result.ShouldEqual(10d);\r\n        }\r\n\r\n        private static double GetDoubleValue(double value)\r\n        {\r\n            return value;\r\n        }\r\n\r\n        private static decimal GetDecimalValue(decimal value)\r\n        {\r\n            return value;\r\n        }\r\n\r\n        private static float GetFloatValue(float value)\r\n        {\r\n            return value;\r\n        }\r\n\r\n        private static long GetLongValue(long value)\r\n        {\r\n            return value;\r\n        }\r\n\r\n        private static TimeSpan GetTimeSpanValue(TimeSpan value)\r\n        {\r\n            return value;\r\n        }\r\n\r\n        private static DateTime GetDateTimeValue(DateTime value)\r\n        {\r\n            return value;\r\n        }\r\n\r\n        private static Guid GetGuidValue(Guid value)\r\n        {\r\n            return value;\r\n        }\r\n\r\n        private static int GetIntegerValue(int value)\r\n        {\r\n            return value;\r\n        }\r\n\r\n        private static string GetStringValue(string value)\r\n        {\r\n            return value;\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_actual_string_value_when_tostring_called_on_string_entry()\r\n        {\r\n            // Given, When\r\n            string result = dictionary.TestString.ToString();\r\n\r\n            // Then\r\n            result.ShouldEqual(\"Testing\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_string_representation_of_value_when_tostring_called_on_int_entry()\r\n        {\r\n            // Given, When\r\n            string result = dictionary.TestInt.ToString();\r\n\r\n            // Then\r\n            result.ShouldEqual(\"2\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_support_dynamic_properties()\r\n        {\r\n            // Given\r\n            dynamic parameters = new DynamicDictionary();\r\n            parameters.test = 10;\r\n\r\n            // When\r\n            var value = (int)parameters.test;\r\n\r\n            // Then\r\n            value.ShouldEqual(10);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_support_dynamic_casting_of_properties_to_ints()\r\n        {\r\n            //Given\r\n            dynamic parameters = new DynamicDictionary();\r\n            parameters.test = \"10\";\r\n\r\n            // When\r\n            var value = (int)parameters.test;\r\n\r\n            // Then\r\n            value.ShouldEqual(10);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_support_dynamic_casting_of_properties_to_guids()\r\n        {\r\n            //Given\r\n            dynamic parameters = new DynamicDictionary();\r\n            var guid = Guid.NewGuid();\r\n            parameters.test = guid.ToString();\r\n\r\n            // When\r\n            var value = (Guid)parameters.test;\r\n\r\n            // Then\r\n            value.ShouldEqual(guid);\r\n        }\r\n\r\n\r\n        [Fact]\r\n        public void Should_support_dynamic_casting_of_properties_to_timespans()\r\n        {\r\n            //Given\r\n            dynamic parameters = new DynamicDictionary();\r\n            parameters.test = new TimeSpan(1, 2, 3, 4).ToString();\r\n\r\n            // When\r\n            var value = (TimeSpan)parameters.test;\r\n\r\n            // Then\r\n            value.ShouldEqual(new TimeSpan(1, 2, 3, 4));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_support_dynamic_casting_of_properties_to_datetimes()\r\n        {\r\n            //Given\r\n            dynamic parameters = new DynamicDictionary();\r\n\r\n            parameters.test = new DateTime(2001, 3, 4);\r\n\r\n            // When\r\n            var value = (DateTime)parameters.test;\r\n\r\n            // Then\r\n            value.ShouldEqual(new DateTime(2001, 3, 4));\r\n        }\r\n\r\n\r\n        [Fact]\r\n        public void Should_support_dynamic_casting_of_nullable_properties()\r\n        {\r\n            //Given\r\n            dynamic parameters = new DynamicDictionary();\r\n            var guid = Guid.NewGuid();\r\n            parameters.test = guid.ToString();\r\n\r\n            // When\r\n            var value = (Guid?)parameters.test;\r\n\r\n            // Then\r\n            value.ShouldEqual(guid);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_support_implicit_casting()\r\n        {\r\n            // Given\r\n            dynamic parameters = new DynamicDictionary();\r\n\r\n            parameters.test = \"10\";\r\n\r\n            // When\r\n            int value = parameters.test;\r\n\r\n            // Then\r\n            value.ShouldEqual(10);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_support_casting_when_using_indexer_to_set_values()\r\n        {\r\n            // Given\r\n            dynamic parameters = new DynamicDictionary();\r\n\r\n            parameters[\"test\"] = \"10\";\r\n\r\n            // When\r\n            int value = parameters.test;\r\n\r\n            // Then\r\n            value.ShouldEqual(10);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_support_GetDynamicMemberNames()\r\n        {\r\n            // Given\r\n            dynamic parameters = new DynamicDictionary();\r\n\r\n            parameters[\"test\"] = \"10\";\r\n            parameters[\"rest\"] = \"20\";\r\n\r\n            // When\r\n            var names = ((DynamicDictionary)parameters).GetDynamicMemberNames();\r\n\r\n            // Then\r\n            Assert.True(names.SequenceEqual(new[] { \"test\", \"rest\" }));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_enumerate_keys()\r\n        {\r\n            // Given\r\n            dynamic parameters = new DynamicDictionary();\r\n\r\n            parameters[\"test\"] = \"10\";\r\n            parameters[\"rest\"] = \"20\";\r\n\r\n            // When\r\n            var names = new List<string>();\r\n            foreach (var name in parameters)\r\n            {\r\n                names.Add(name);\r\n            }\r\n\r\n            // Then\r\n            Assert.True(names.SequenceEqual(new[] { \"test\", \"rest\" }));\r\n        }\r\n\r\n        [Fact]\r\n        public void String_dictionary_values_are_Json_serialized_as_strings()\r\n        {\r\n            dynamic value = \"42\";\r\n            var input = new DynamicDictionaryValue(value, GlobalizationConfiguration.Default);\r\n\r\n            var sut = new JavaScriptSerializer();\r\n            var actual = sut.Serialize(input);\r\n\r\n            actual.ShouldEqual(@\"\"\"42\"\"\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Integer_dictionary_values_are_Json_serialized_as_integers()\r\n        {\r\n            dynamic value = 42;\r\n            var input = new DynamicDictionaryValue(value, GlobalizationConfiguration.Default);\r\n\r\n            var sut = new JavaScriptSerializer();\r\n            var actual = sut.Serialize(input);\r\n\r\n            actual.ShouldEqual(@\"42\");\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(2)]\r\n        [InlineData(5)]\r\n        public void Should_return_correct_count(int expectedNumberOfEntries)\r\n        {\r\n            // Given\r\n            var input = new DynamicDictionary();\r\n\r\n            // When\r\n            for (var i = 0; i < expectedNumberOfEntries; i++)\r\n            {\r\n                input[i.ToString(CultureInfo.InvariantCulture)] = i;\r\n            }\r\n\r\n            // Then\r\n            input.Count.ShouldEqual(expectedNumberOfEntries);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_value_when_invoking_string_dynamic_overload_of_add_method()\r\n        {\r\n            // Given\r\n            var input = new DynamicDictionary();\r\n\r\n            // When\r\n            input.Add(\"test\", 10);\r\n            var value = (int)input[\"test\"];\r\n\r\n            // Then\r\n            value.ShouldEqual(10);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_value_when_invoking_keyvaluepair_overload_of_add_method()\r\n        {\r\n            // Given\r\n            var input = new DynamicDictionary();\r\n\r\n            // When\r\n            input.Add(new KeyValuePair<string, dynamic>(\"test\", 10));\r\n            var value = (int)input[\"test\"];\r\n\r\n            // Then\r\n            value.ShouldEqual(10);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"test1\", true)]\r\n        [InlineData(\"test2\", false)]\r\n        public void Should_return_correct_value_for_containskey(string key, bool expectedResult)\r\n        {\r\n            // Given\r\n            var input = new DynamicDictionary();\r\n            input[\"test1\"] = 10;\r\n\r\n            // When\r\n            var result = input.ContainsKey(key);\r\n\r\n            // Then\r\n            result.ShouldEqual(expectedResult);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_all_keys()\r\n        {\r\n            // Given\r\n            var input = new DynamicDictionary();\r\n            input[\"test1\"] = 10;\r\n            input[\"test2\"] = 10;\r\n\r\n            // When\r\n            var result = input.Keys;\r\n\r\n            // Then\r\n            result.ShouldHave(x => x.Equals(\"test1\"));\r\n            result.ShouldHave(x => x.Equals(\"test2\"));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_when_trygetvalue_could_not_find_key()\r\n        {\r\n            // Given\r\n            var input = new DynamicDictionary();\r\n            object output;\r\n\r\n            // When\r\n            var result = input.TryGetValue(\"test\", out output);\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_when_trygetvalue_could_find_key()\r\n        {\r\n            // Given\r\n            var input = new DynamicDictionary();\r\n            input[\"test\"] = 10;\r\n            object output;\r\n\r\n            // When\r\n            var result = input.TryGetValue(\"test\", out output);\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_value_when_trygetvalue_could_find_key()\r\n        {\r\n            // Given\r\n            var input = new DynamicDictionary();\r\n            input[\"test\"] = 10;\r\n            dynamic output;\r\n\r\n            // When\r\n            input.TryGetValue(\"test\", out output);\r\n\r\n            // Then\r\n            ((int)output).ShouldEqual(10);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_all_values()\r\n        {\r\n            // Given\r\n            var input = new DynamicDictionary();\r\n            input[\"test1\"] = 10;\r\n            input[\"test2\"] = \"test2\";\r\n\r\n            // When\r\n            var result = input.Values;\r\n\r\n            // Then\r\n            result.ShouldHave(x => ((int)x).Equals(10));\r\n            result.ShouldHave(x => ((string)x).Equals(\"test2\"));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_remove_all_values_when_clear_is_invoked()\r\n        {\r\n            // Given\r\n            var input = new DynamicDictionary();\r\n            input[\"test1\"] = 10;\r\n            input[\"test2\"] = \"test2\";\r\n\r\n            // When\r\n            input.Clear();\r\n\r\n            // Then\r\n            input.Count.ShouldEqual(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_when_contains_does_not_find_match()\r\n        {\r\n            // Given\r\n            var input = new DynamicDictionary();\r\n            input[\"test1\"] = 10;\r\n\r\n            // When\r\n            var result = input.Contains(new KeyValuePair<string, dynamic>(\"test1\", 11));\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_when_contains_does_find_match()\r\n        {\r\n            // Given\r\n            var input = new DynamicDictionary();\r\n            input[\"test1\"] = 10;\r\n\r\n            // When\r\n            var result = input.Contains(new KeyValuePair<string, dynamic>(\"test1\", 10));\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(0)]\r\n        [InlineData(2)]\r\n        public void Should_copy_to_destination_array_from_given_index_when_copyto_is_invoked(int arrayIndex)\r\n        {\r\n            // Given\r\n            var input = new DynamicDictionary();\r\n            input[\"test\"] = 1;\r\n\r\n            var output =\r\n                new KeyValuePair<string, dynamic>[4];\r\n\r\n            // When\r\n            input.CopyTo(output, arrayIndex);\r\n\r\n            // Then\r\n            output[arrayIndex].Key.ShouldEqual(input.Keys.First());\r\n            ((int)output[arrayIndex].Value).ShouldEqual((int)input.Values.First());\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_for_isreadonly()\r\n        {\r\n            // Given\r\n            var input = new DynamicDictionary();\r\n\r\n            // When\r\n            var result = input.IsReadOnly;\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_remove_item_when_string_overload_of_remove_method_is_invoked()\r\n        {\r\n            // Given\r\n            var input = new DynamicDictionary();\r\n            input[\"test\"] = 10;\r\n\r\n            // When\r\n            input.Remove(\"test\");\r\n\r\n            // Then\r\n            input.ContainsKey(\"test\").ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_when_string_overload_of_remove_method_can_match_key()\r\n        {\r\n            var input = new DynamicDictionary();\r\n            input[\"test\"] = 10;\r\n\r\n            // When\r\n            var result = input.Remove(\"test\");\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_when_string_overload_of_remove_method_cannot_match_key()\r\n        {\r\n            var input = new DynamicDictionary();\r\n            input[\"test\"] = 10;\r\n\r\n            // When\r\n            var result = input.Remove(\"test1\");\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_remove_item_when_keyvaluepair_overload_of_remove_method_is_invoked()\r\n        {\r\n            // Given\r\n            var input = new DynamicDictionary();\r\n            input[\"test\"] = 10;\r\n\r\n            // When\r\n            input.Remove(new KeyValuePair<string, dynamic>(\"test\", 10));\r\n\r\n            // Then\r\n            input.ContainsKey(\"test\").ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_when_keyvaluepair_overload_of_remove_method_can_match_key()\r\n        {\r\n            var input = new DynamicDictionary();\r\n            input[\"test\"] = 10;\r\n\r\n            // When\r\n            var result = input.Remove(new KeyValuePair<string, dynamic>(\"test\", 10));\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_when_keyvaluepair_overload_of_remove_method_cannot_match_key()\r\n        {\r\n            var input = new DynamicDictionary();\r\n            input[\"test\"] = 10;\r\n\r\n            // When\r\n            var result = input.Remove(new KeyValuePair<string, dynamic>(\"test1\", 10));\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n\t[Fact]\r\n        public void Should_remove_natural_key()\r\n        {\r\n            // Given\r\n            var input = new DynamicDictionary();\r\n            input.Add(\"a-b-c\", \"hello\");\r\n\r\n            //when\r\n            input.Remove(\"a-b-c\");\r\n\r\n            //then\r\n            input.ContainsKey(\"abc\").ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_dictionary_from_dynamic_dictionary()\r\n        {\r\n            //Given\r\n            var input = new DynamicDictionary();\r\n\r\n            //When\r\n            var result = input.ToDictionary();\r\n\r\n            //Then\r\n            Assert.IsType(typeof(Dictionary<string, object>), result);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_dynamic_values_as_objects()\r\n        {\r\n            //Given/When\r\n            var result = this.dictionary.ToDictionary();\r\n\r\n            //Then\r\n            Assert.IsType(typeof(long), GetLongValue(result[\"TestInt\"]));\r\n            Assert.IsType(typeof(string), GetStringValue(result[\"TestString\"]));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_dynamic_objects_as_objects()\r\n        {\r\n            //Given\r\n            var input = new DynamicDictionary();\r\n            input.Add(\"Test\", new { Title = \"Fred\", Number = 123 });\r\n\r\n            //When\r\n            var result = input.ToDictionary();\r\n\r\n            //Then\r\n            Assert.Equal(\"Fred\", ((dynamic)result[\"Test\"]).Title);\r\n            Assert.Equal(123, ((dynamic)result[\"Test\"]).Number);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/DynamicDictionaryValueFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit\r\n{\r\n    using System;\r\n    using System.Dynamic;\r\n    using System.Globalization;\r\n    using FakeItEasy;\r\n    using Xunit;\r\n\r\n    public class DynamicDictionaryValueFixture\r\n    {\r\n        [Fact]\r\n        public void Should_return_false_when_hasvalue_is_checked_when_value_is_not_null()\r\n        {\r\n            // Given\r\n            var value = new DynamicDictionaryValue(null);\r\n\r\n            // When\r\n            var result = value.HasValue;\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_when_hasvalue_is_checked_when_value_is_null()\r\n        {\r\n            // Given\r\n            var value = new DynamicDictionaryValue(string.Empty);\r\n\r\n            // When\r\n            var result = value.HasValue;\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_when_value_is_null_and_compared_with_null_using_equality_operator()\r\n        {\r\n            // Given\r\n            var value = new DynamicDictionaryValue(null);\r\n\r\n            // When\r\n            var result = (value == null);\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_when_value_is_not_null_and_compared_with_null_using_equality_operator()\r\n        {\r\n            // Given\r\n            var value = new DynamicDictionaryValue(string.Empty);\r\n\r\n            // When\r\n            var result = (value == null);\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_when_value_is_not_null_and_compared_with_equal_value_using_equality_operator()\r\n        {\r\n            // Given\r\n            var value = new DynamicDictionaryValue(10);\r\n\r\n            // When\r\n            var result = (value == 10);\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n\r\n        [Fact]\r\n        public void Should_not_throw_null_reference_exception_if_value_is_null_using_equality_operator()\r\n        {\r\n            // Given\r\n            DynamicDictionaryValue value = null;\r\n\r\n            // When\r\n            var result = (value == 11);\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_when_value_is_not_null_and_compared_with_non_equal_value_using_equality_operator()\r\n        {\r\n            // Given\r\n            var value = new DynamicDictionaryValue(10);\r\n\r\n            // When\r\n            var result = (value == 11);\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_when_value_is_null_and_compared_with_non_null_value_using_equality_operator()\r\n        {\r\n            // Given\r\n            var value = new DynamicDictionaryValue(null);\r\n\r\n            // When\r\n            var result = (value == 10);\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_when_value_is_null_and_compared_with_null_using_non_equality_operator()\r\n        {\r\n            // Given\r\n            var value = new DynamicDictionaryValue(null);\r\n\r\n            // When\r\n            var result = (value != null);\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_when_value_is_not_null_and_compared_with_null_using_non_equality_operator()\r\n        {\r\n            // Given\r\n            var value = new DynamicDictionaryValue(string.Empty);\r\n\r\n            // When\r\n            var result = (value != null);\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_when_value_is_not_null_and_compared_with_equal_value_using_non_equality_operator()\r\n        {\r\n            // Given\r\n            var value = new DynamicDictionaryValue(10);\r\n\r\n            // When\r\n            var result = (value != 10);\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_when_value_is_not_null_and_compared_with_non_equal_value_using_non_equality_operator()\r\n        {\r\n            // Given\r\n            var value = new DynamicDictionaryValue(10);\r\n\r\n            // When\r\n            var result = (value != 11);\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_when_value_is_null_and_compared_with_non_null_value_using_non_equality_operator()\r\n        {\r\n            // Given\r\n            var value = new DynamicDictionaryValue(null);\r\n\r\n            // When\r\n            var result = (value != 10);\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_when_value_is_null_and_implicitly_cast_to_bool()\r\n        {\r\n            // Given, When\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            // Then\r\n            Assert.False(value);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_when_value_is_0_and_implicitly_cast_to_bool()\r\n        {\r\n            // Given, When\r\n            dynamic valueInt = new DynamicDictionaryValue(0);\r\n            dynamic valueFloat = new DynamicDictionaryValue(0.0);\r\n            dynamic valueDec = new DynamicDictionaryValue(0.0M);\r\n\r\n            // Then\r\n            Assert.False(valueInt);\r\n            Assert.False(valueFloat);\r\n            Assert.False(valueDec);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_when_value_is_non_zero_and_implicitly_cast_to_bool()\r\n        {\r\n            // Given, When\r\n            dynamic valueInt = new DynamicDictionaryValue(8);\r\n            dynamic valueFloat = new DynamicDictionaryValue(0.1);\r\n            dynamic valueDec = new DynamicDictionaryValue(0.1M);\r\n\r\n            // Then\r\n            Assert.True(valueInt);\r\n            Assert.True(valueFloat);\r\n            Assert.True(valueDec);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_when_value_is_a_not_null_reference_type()\r\n        {\r\n            // Given, When\r\n            dynamic value = new DynamicDictionaryValue(new object());\r\n\r\n            // Then\r\n            Assert.True(value);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_and_false_for_true_false_strings()\r\n        {\r\n            // Given, When\r\n            dynamic valueTrue = new DynamicDictionaryValue(\"true\");\r\n            dynamic valueFalse = new DynamicDictionaryValue(\"false\");\r\n\r\n            // Then\r\n            Assert.True(valueTrue);\r\n            Assert.False(valueFalse);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_implictly_cast_long_to_other_value_types()\r\n        {\r\n            // Given\r\n            dynamic valueLong = new DynamicDictionaryValue((long)10);\r\n\r\n            // Then\r\n            Assert.Equal(10, valueLong);\r\n            Assert.Equal(10.0, valueLong);\r\n            Assert.Equal(10M, valueLong);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_call_ConvertToBoolean()\r\n        {\r\n            //Given\r\n            const bool expected = true;\r\n            object value = new DynamicDictionaryValue(expected);\r\n\r\n            //When\r\n            var actual = Convert.ToBoolean(value);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_call_ConvertToChar()\r\n        {\r\n            //Given\r\n            const char expected = 'a';\r\n            object value = new DynamicDictionaryValue(expected);\r\n\r\n            //When\r\n            var actual = Convert.ToChar(value);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_call_ConvertToSByte()\r\n        {\r\n            //Given\r\n            const sbyte expected = 42;\r\n            object value = new DynamicDictionaryValue(expected);\r\n\r\n            //When\r\n            var actual = Convert.ToSByte(value);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_call_ConvertToByte()\r\n        {\r\n            //Given\r\n            const byte expected = 42;\r\n            object value = new DynamicDictionaryValue(expected);\r\n\r\n            //When\r\n            var actual = Convert.ToByte(value);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_call_ConvertToInt16()\r\n        {\r\n            //Given\r\n            const short expected = 42;\r\n            object value = new DynamicDictionaryValue(expected);\r\n\r\n            //When\r\n            var actual = Convert.ToInt16(value);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_call_ConvertToUInt16()\r\n        {\r\n            //Given\r\n            const ushort expected = 42;\r\n            object value = new DynamicDictionaryValue(expected);\r\n\r\n            //When\r\n            var actual = Convert.ToUInt16(value);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_call_ConvertToInt32()\r\n        {\r\n            //Given\r\n            const int expected = 42;\r\n            object value = new DynamicDictionaryValue(expected);\r\n\r\n            //When\r\n            var actual = Convert.ToInt32(value);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_call_ConvertToUInt32()\r\n        {\r\n            //Given\r\n            const uint expected = 42;\r\n            object value = new DynamicDictionaryValue(expected);\r\n\r\n            //When\r\n            var actual = Convert.ToUInt32(value);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_call_ConvertToInt64()\r\n        {\r\n            //Given\r\n            const long expected = 42;\r\n            object value = new DynamicDictionaryValue(expected);\r\n\r\n            //When\r\n            var actual = Convert.ToInt64(value);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_call_ConvertToUInt64()\r\n        {\r\n            //Given\r\n            const ulong expected = 42;\r\n            object value = new DynamicDictionaryValue(expected);\r\n\r\n            //When\r\n            var actual = Convert.ToUInt64(value);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_call_ConvertToSingle()\r\n        {\r\n            //Given\r\n            const float expected = 42;\r\n            object value = new DynamicDictionaryValue(expected);\r\n\r\n            //When\r\n            var actual = Convert.ToSingle(value);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_call_ConvertToDouble()\r\n        {\r\n            //Given\r\n            const double expected = 42;\r\n            object value = new DynamicDictionaryValue(expected);\r\n\r\n            //When\r\n            var actual = Convert.ToDouble(value);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_call_ConvertToDecimal()\r\n        {\r\n            //Given\r\n            const decimal expected = 42;\r\n            object value = new DynamicDictionaryValue(expected);\r\n\r\n            //When\r\n            var actual = Convert.ToDecimal(value);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_call_ConvertToDateTime()\r\n        {\r\n            //Given\r\n            DateTime expected = new DateTime(1952, 3, 11);\r\n            object value = new DynamicDictionaryValue(expected);\r\n\r\n            //When\r\n            var actual = Convert.ToDateTime(value);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_call_ConvertToString()\r\n        {\r\n            //Given\r\n            const string expected = \"Forty two\";\r\n            object value = new DynamicDictionaryValue(expected);\r\n\r\n            //When\r\n            var actual = Convert.ToString(value);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_call_ConvertChangeType()\r\n        {\r\n            //Given\r\n            const int expected = 42;\r\n            object value = new DynamicDictionaryValue(expected);\r\n\r\n            //When\r\n            var actual = Convert.ChangeType(value, typeof(int));\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_when_value_is_null_and_casting_to_string()\r\n        {\r\n            //Given\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n            String actual = value;\r\n\r\n            //Then\r\n            Assert.Null(actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_default_value_of_int_when_calling_default_given_null()\r\n        {\r\n            //Given\r\n            const int expected = 123;\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            //When\r\n            int actual = value.Default(expected);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_default_value_of_string_when_calling_default_given_null()\r\n        {\r\n            //Given\r\n            const string expected = \"default value\";\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            //When\r\n            string actual = value.Default(expected);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_default_value_of_decimal_when_calling_default_given_null()\r\n        {\r\n            //Given\r\n            const decimal expected = 88.43m;\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            //When\r\n            decimal actual = value.Default(expected);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_default_value_of_double_when_calling_default_given_null()\r\n        {\r\n            //Given\r\n            const double expected = 44.23d;\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            //When\r\n            double actual = value.Default(expected);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_default_value_of_short_when_calling_default_given_null()\r\n        {\r\n            //Given\r\n            const short expected = (short)4;\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            //When\r\n            short actual = value.Default(expected);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_default_value_of_float_when_calling_default_given_null()\r\n        {\r\n            //Given\r\n            const float expected = 9.343f;\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            //When\r\n            float actual = value.Default(expected);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_default_value_of_long_when_calling_default_given_null()\r\n        {\r\n            //Given\r\n            const long expected = 1000333000222000333L;\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            //When\r\n            long actual = value.Default(expected);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_default_value_of_bool_when_calling_default_given_null()\r\n        {\r\n            //Given\r\n            const bool expected = true;\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            //When\r\n            bool actual = value.Default(expected);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_default_value_of_datetime_when_calling_default_given_null()\r\n        {\r\n            //Given\r\n            DateTime expected = DateTime.Parse(\"10 Dec, 2012\");\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            //When\r\n            DateTime actual = value.Default(expected);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_still_return_default_int_type_when_no_default_value_given()\r\n        {\r\n            //Given\r\n            const int expected = 0;\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            //When\r\n            int actual = value.Default<int>();\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_still_return_default_string_type_when_no_default_value_given()\r\n        {\r\n            //Given\r\n            const string expected = null;\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            //When\r\n            string actual = value.Default<string>();\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_still_return_default_decimal_type_when_no_default_value_given()\r\n        {\r\n            //Given\r\n            const decimal expected = 0m;\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            //When\r\n            decimal actual = value.Default<decimal>();\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_still_return_default_double_type_when_no_default_value_given()\r\n        {\r\n            //Given\r\n            const double expected = 0d;\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            //When\r\n            double actual = value.Default<double>();\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_still_return_default_short_type_when_no_default_value_given()\r\n        {\r\n            //Given\r\n            const short expected = (short)0;\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            //When\r\n            short actual = value.Default<short>();\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_still_return_default_float_type_when_no_default_value_given()\r\n        {\r\n            //Given\r\n            const float expected = 0f;\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            //When\r\n            float actual = value.Default<float>();\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_still_return_default_long_type_when_no_default_value_given()\r\n        {\r\n            //Given\r\n            const long expected = 0L;\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            //When\r\n            long actual = value.Default<long>();\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_still_return_default_bool_type_when_no_default_value_given()\r\n        {\r\n            //Given\r\n            const bool expected = false;\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            //When\r\n            bool actual = value.Default<bool>();\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_still_return_default_int_datetime_when_no_default_value_given()\r\n        {\r\n            //Given\r\n            DateTime expected = DateTime.MinValue;\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            //When\r\n            DateTime actual = value.Default<DateTime>();\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_if_unable_to_explicitly_cast()\r\n        {\r\n            //Given\r\n            dynamic value = new DynamicDictionaryValue(12.25);\r\n\r\n            //When\r\n            Exception exception = Assert.Throws<InvalidCastException>(() => value.Default<int>());\r\n\r\n            //Then\r\n            Assert.Equal(\"Cannot convert value of type 'Double' to type 'Int32'\", exception.Message);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_convert_from_string_based_on_given_parameter_type_of_int()\r\n        {\r\n            //Given\r\n            const int expected = 42;\r\n            const int notExpected = 100;\r\n            dynamic value = new DynamicDictionaryValue(\"42\");\r\n\r\n            //When\r\n            int actual = value.TryParse(notExpected);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_convert_from_string_based_on_given_parameter_type_of_decimal()\r\n        {\r\n            //Given\r\n            const decimal expected = 55.23m;\r\n            const decimal notExpected = 99.99m;\r\n            dynamic value = new DynamicDictionaryValue(\"55.23\");\r\n\r\n            //When\r\n            decimal actual = value.TryParse(notExpected);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_convert_from_string_based_on_given_parameter_type_of_double()\r\n        {\r\n            //Given\r\n            const double expected = 37.48d;\r\n            const double notExpected = 99.99d;\r\n            dynamic value = new DynamicDictionaryValue(\"37.48\");\r\n\r\n            //When\r\n            double actual = value.TryParse(notExpected);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_convert_from_string_based_on_given_parameter_type_of_short()\r\n        {\r\n            //Given\r\n            const short expected = (short)13;\r\n            const short notExpected = (short)31;\r\n            dynamic value = new DynamicDictionaryValue(\"13\");\r\n\r\n            //When\r\n            short actual = value.TryParse(notExpected);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_convert_from_string_based_on_given_parameter_type_of_datetime()\r\n        {\r\n            //Given\r\n            DateTime expected = DateTime.Parse(\"13 Dec, 2012\");\r\n            DateTime notExpected = DateTime.Parse(\"15 Mar, 1986\");\r\n            dynamic value = new DynamicDictionaryValue(\"13 December 2012\");\r\n\r\n            //When\r\n            DateTime actual = value.TryParse(notExpected);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_convert_from_string_based_on_given_generic_type_of_int()\r\n        {\r\n            //Given\r\n            const int expected = 42;\r\n            dynamic value = new DynamicDictionaryValue(\"42\");\r\n\r\n            //When\r\n            int actual = value.TryParse<int>();\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_default_when_given_string_that_is_not_a_number()\r\n        {\r\n            //Given\r\n            const int expected = 100;\r\n            dynamic value = new DynamicDictionaryValue(\"4abc2\");\r\n\r\n            //When\r\n            int actual = value.TryParse<int>(expected);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_convert_from_string_based_on_given_generic_type_of_decimal()\r\n        {\r\n            //Given\r\n            const decimal expected = 55.23m;\r\n            dynamic value = new DynamicDictionaryValue(\"55.23\");\r\n\r\n            //When\r\n            decimal actual = value.TryParse<decimal>();\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_convert_from_string_based_on_given_generic_type_of_double()\r\n        {\r\n            //Given\r\n            const double expected = 37.48d;\r\n            dynamic value = new DynamicDictionaryValue(\"37.48\");\r\n\r\n            //When\r\n            double actual = value.TryParse<double>();\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_convert_from_string_based_on_given_generic_type_of_short()\r\n        {\r\n            //Given\r\n            const short expected = (short)13;\r\n            dynamic value = new DynamicDictionaryValue(\"13\");\r\n\r\n            //When\r\n            short actual = value.TryParse<short>();\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_convert_from_string_based_on_given_generic_type_of_datetime()\r\n        {\r\n            //Given\r\n            DateTime expected = DateTime.Parse(\"13 Dec, 2012\");\r\n            dynamic value = new DynamicDictionaryValue(\"13 December 2012\");\r\n\r\n            //When\r\n            DateTime actual = value.TryParse<DateTime>();\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_convert_from_int_based_on_given_parameter_type_of_short()\r\n        {\r\n            //Given\r\n            const int expected = 42;\r\n            const short notExpected = 100;\r\n            dynamic value = new DynamicDictionaryValue (expected);\r\n\r\n            //When\r\n            int actual = (int)value.TryParse<short> (notExpected);\r\n\r\n            //Then\r\n            Assert.Equal (expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_convert_from_int_based_on_given_parameter_type_of_long()\r\n        {\r\n            //Given\r\n            const int expected = 42;\r\n            const long notExpected = 100;\r\n            dynamic value = new DynamicDictionaryValue (expected);\r\n\r\n            //When\r\n            int actual = (int)value.TryParse<long> (notExpected);\r\n\r\n            //Then\r\n            Assert.Equal (expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_convert_from_int_based_on_given_parameter_type_of_nullable_long()\r\n        {\r\n            //Given\r\n            const int expected = 42;\r\n            long? notExpected = 100;\r\n            dynamic value = new DynamicDictionaryValue (expected);\r\n\r\n            //When\r\n            int actual = (int)value.TryParse<long?> (notExpected);\r\n\r\n            //Then\r\n            Assert.Equal (expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_convert_from_datetime_based_on_given_parameter_type_of_nullable_datetime()\r\n        {\r\n            //Given\r\n            DateTime expected = DateTime.Parse (\"13 December 2012\");\r\n            DateTime? notExpected = expected.AddDays (10);\r\n            dynamic value = new DynamicDictionaryValue (expected);\r\n\r\n            //When\r\n            DateTime actual = (DateTime)value.TryParse<DateTime?> (notExpected);\r\n\r\n            //Then\r\n            Assert.Equal (expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_default_value_if_implicit_convert_fails_on_datetime()\r\n        {\r\n            //Given\r\n            DateTime expected = DateTime.Parse(\"13 December 2012\");\r\n            dynamic value = new DynamicDictionaryValue(\"Rawrrrr\");\r\n\r\n            //When\r\n            DateTime actual = value.TryParse(expected);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_adjust_to_universal_time_when_globalizationconfiguration_datetimestyles_requires_it()\r\n        {\r\n            // Given\r\n            var expected = new DateTime(2016, 05, 24, 08, 41, 37, DateTimeKind.Utc);\r\n\r\n            var config = new GlobalizationConfiguration(new [] {\"en-US\"}, dateTimeStyles: DateTimeStyles.AdjustToUniversal);\r\n            var value = new DynamicDictionaryValue(\"2016-05-24T10:41:37+02:00\", config);\r\n\r\n            // When\r\n            DateTime actual = value;\r\n\r\n            // Then\r\n            actual.ShouldEqual(expected);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_assume_local_time_when_globalizationconfiguration_datetimestyles_requires_it()\r\n        {\r\n            // Given\r\n            var expected = DateTime.Now;\r\n\r\n            var config = new GlobalizationConfiguration(new[] { \"en-US\" }, dateTimeStyles: DateTimeStyles.AssumeLocal);\r\n            var value = new DynamicDictionaryValue(expected.ToString(\"O\"), config);\r\n\r\n            // When\r\n            DateTime actual = value;\r\n\r\n            // Then\r\n            actual.ShouldEqual(expected);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_convert_from_int_based_on_given_type_of_string()\r\n        {\r\n            //Given\r\n            const string expected = \"13\";\r\n            const string notExpected = \"11\";\r\n            dynamic value = new DynamicDictionaryValue(13);\r\n\r\n            //When\r\n            string actual = value.TryParse(notExpected);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_convert_from_double_based_on_given_type_of_string()\r\n        {\r\n            //Given\r\n            const string expected = \"134.22\";\r\n            const string notExpected = \"187.34\";\r\n            dynamic value = new DynamicDictionaryValue(134.22d);\r\n\r\n            //When\r\n            string actual = value.TryParse(notExpected);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_convert_from_decimal_based_on_given_type_of_string()\r\n        {\r\n            //Given\r\n            const string expected = \"88.53234423\";\r\n            const string notExpected = \"76.3422\";\r\n            dynamic value = new DynamicDictionaryValue(88.53234423m);\r\n\r\n            //When\r\n            string actual = value.TryParse(notExpected);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_convert_from_datetime_based_on_given_type_of_string()\r\n        {\r\n            //This test is unrealistic in my opinion, but it should still call ToString on the datetime value\r\n\r\n            //Given\r\n            string expected = DateTime.Parse(\"22 Nov, 2012\").ToString(CultureInfo.InvariantCulture);\r\n            string notExpected = DateTime.Parse(\"18 Jun, 2011\").ToString(CultureInfo.InvariantCulture);\r\n            dynamic value = new DynamicDictionaryValue(DateTime.Parse(\"22 Nov, 2012\"));\r\n\r\n            //When\r\n            string actual = value.TryParse(notExpected);\r\n\r\n            //Then\r\n            Assert.Equal(expected, actual);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_cast_to_arbitrary_object()\r\n        {\r\n            //Given\r\n            dynamic value = new DynamicDictionaryValue(new EventArgs());\r\n\r\n            //When, Then\r\n            Record.Exception(() => (EventArgs)value).ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_when_converting_enums_of_different_types()\r\n        {\r\n            // Given\r\n            var binder = A.Fake<ConvertBinder>(o => o.WithArgumentsForConstructor(new object[] { typeof(IntEnum), false }));\r\n            var value = new DynamicDictionaryValue(ByteEnum.Value1);\r\n\r\n            // When\r\n            object valueResult;\r\n            var result = value.TryConvert(binder, out valueResult);\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n            valueResult.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_when_converting_enums_of_same_type()\r\n        {\r\n            // Given\r\n            var binder = A.Fake<ConvertBinder>(o => o.WithArgumentsForConstructor(new object[] { typeof(IntEnum), false }));\r\n            var value = new DynamicDictionaryValue(IntEnum.Value1);\r\n\r\n            // When\r\n            object valueResult;\r\n            var result = value.TryConvert(binder, out valueResult);\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n            valueResult.ShouldEqual(IntEnum.Value1);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_when_converting_incorrect_enum_base_type_to_enum()\r\n        {\r\n            // Given\r\n            var binder = A.Fake<ConvertBinder>(o => o.WithArgumentsForConstructor(new object[] { typeof(IntEnum), false }));\r\n            var value = new DynamicDictionaryValue((byte)1);\r\n\r\n            // When\r\n            object valueResult;\r\n            var result = value.TryConvert(binder, out valueResult);\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n            valueResult.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_when_converting_enum_base_type_to_enum()\r\n        {\r\n            // Given\r\n            var binder = A.Fake<ConvertBinder>(o => o.WithArgumentsForConstructor(new object[] { typeof(IntEnum), false }));\r\n            var value = new DynamicDictionaryValue(1);\r\n\r\n            // When\r\n            object valueResult;\r\n            var result = value.TryConvert(binder, out valueResult);\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n            valueResult.ShouldEqual(IntEnum.Value1);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_cast_null_to_default_int()\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            // When\r\n            int result = value;\r\n\r\n            // Then\r\n            result.ShouldEqual(default(int));\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(1234)]\r\n        [InlineData(4321)]\r\n        public void Should_be_able_to_cast_int_to_int(int expectedValue)\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(expectedValue);\r\n\r\n            // When\r\n            int result = value;\r\n\r\n            // Then\r\n            result.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_cast_null_to_nullable_int()\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            // When\r\n            int? result = value;\r\n\r\n            // Then\r\n            result.HasValue.ShouldBeFalse();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(1234)]\r\n        [InlineData(4321)]\r\n        public void Should_be_able_to_cast_int_to_nullable_int(int expectedValue)\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(expectedValue);\r\n\r\n            // When\r\n            int? result = value;\r\n\r\n            // Then\r\n            result.HasValue.ShouldBeTrue();\r\n            result.Value.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_cast_null_to_default_bool()\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            // When\r\n            bool result = value;\r\n\r\n            // Then\r\n            result.ShouldEqual(default(bool));\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(false)]\r\n        [InlineData(true)]\r\n        public void Should_be_able_to_cast_bool_to_bool(bool expectedValue)\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(expectedValue);\r\n\r\n            // When\r\n            bool result = value;\r\n\r\n            // Then\r\n            result.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_cast_null_to_nullable_bool()\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            // When\r\n            bool? result = value;\r\n\r\n            // Then\r\n            result.HasValue.ShouldBeFalse();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(false)]\r\n        [InlineData(true)]\r\n        public void Should_be_able_to_cast_bool_to_nullable_bool(bool expectedValue)\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(expectedValue);\r\n\r\n            // When\r\n            bool? result = value;\r\n\r\n            // Then\r\n            result.HasValue.ShouldBeTrue();\r\n            result.Value.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_cast_null_to_default_datetime()\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            // When\r\n            DateTime result = value;\r\n\r\n            // Then\r\n            result.ShouldEqual(default(DateTime));\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(2015, 10, 13)]\r\n        [InlineData(2015, 10, 24)]\r\n        public void Should_be_able_to_cast_datetime_to_datetime(int year, int month, int day)\r\n        {\r\n            // Given\r\n            var expectedValue = new DateTime(year, month, day);\r\n            dynamic value = new DynamicDictionaryValue(expectedValue);\r\n\r\n            // When\r\n            DateTime result = value;\r\n\r\n            // Then\r\n            result.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_cast_null_to_nullable_datetime()\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            // When\r\n            DateTime? result = value;\r\n\r\n            // Then\r\n            result.HasValue.ShouldBeFalse();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(2015, 10, 13)]\r\n        [InlineData(2015, 10, 24)]\r\n        public void Should_be_able_to_cast_datetime_to_nullable_datetime(int year, int month, int day)\r\n        {\r\n            // Given\r\n            var expectedValue = new DateTime(year, month, day);\r\n            dynamic value = new DynamicDictionaryValue(expectedValue);\r\n\r\n            // When\r\n            DateTime? result = value;\r\n\r\n            // Then\r\n            result.HasValue.ShouldBeTrue();\r\n            result.Value.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_cast_null_to_default_decimal()\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            // When\r\n            decimal result = value;\r\n\r\n            // Then\r\n            result.ShouldEqual(default(decimal));\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"1234\")]\r\n        [InlineData(\"4321\")]\r\n        public void Should_be_able_to_cast_decimal_to_decimal(string input)\r\n        {\r\n            // Given\r\n            var expectedValue = decimal.Parse(input);\r\n            dynamic value = new DynamicDictionaryValue(expectedValue);\r\n\r\n            // When\r\n            decimal result = value;\r\n\r\n            // Then\r\n            result.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_cast_null_to_nullable_decimal()\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            // When\r\n            decimal? result = value;\r\n\r\n            // Then\r\n            result.HasValue.ShouldBeFalse();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"1234\")]\r\n        [InlineData(\"4321\")]\r\n        public void Should_be_able_to_cast_decimal_to_nullable_decimal(string input)\r\n        {\r\n            // Given\r\n            var expectedValue = decimal.Parse(input);\r\n            dynamic value = new DynamicDictionaryValue(expectedValue);\r\n\r\n            // When\r\n            decimal? result = value;\r\n\r\n            // Then\r\n            result.HasValue.ShouldBeTrue();\r\n            result.Value.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_cast_null_to_default_double()\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            // When\r\n            double result = value;\r\n\r\n            // Then\r\n            result.ShouldEqual(default(double));\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(1234d)]\r\n        [InlineData(4321d)]\r\n        public void Should_be_able_to_cast_double_to_double(double expectedValue)\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(expectedValue);\r\n\r\n            // When\r\n            double result = value;\r\n\r\n            // Then\r\n            result.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_cast_null_to_nullable_double()\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            // When\r\n            double? result = value;\r\n\r\n            // Then\r\n            result.HasValue.ShouldBeFalse();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(1234d)]\r\n        [InlineData(4321d)]\r\n        public void Should_be_able_to_cast_double_to_nullable_double(double expectedValue)\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(expectedValue);\r\n\r\n            // When\r\n            double? result = value;\r\n\r\n            // Then\r\n            result.HasValue.ShouldBeTrue();\r\n            result.Value.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_cast_null_to_default_float()\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            // When\r\n            float result = value;\r\n\r\n            // Then\r\n            result.ShouldEqual(default(float));\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(1234f)]\r\n        [InlineData(4321f)]\r\n        public void Should_be_able_to_cast_float_to_float(float expectedValue)\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(expectedValue);\r\n\r\n            // When\r\n            float result = value;\r\n\r\n            // Then\r\n            result.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_cast_null_to_nullable_float()\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            // When\r\n            float? result = value;\r\n\r\n            // Then\r\n            result.HasValue.ShouldBeFalse();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(1234f)]\r\n        [InlineData(4321f)]\r\n        public void Should_be_able_to_cast_float_to_nullable_float(float expectedValue)\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(expectedValue);\r\n\r\n            // When\r\n            float? result = value;\r\n\r\n            // Then\r\n            result.HasValue.ShouldBeTrue();\r\n            result.Value.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_cast_null_to_default_long()\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            // When\r\n            long result = value;\r\n\r\n            // Then\r\n            result.ShouldEqual(default(long));\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(1234L)]\r\n        [InlineData(4321L)]\r\n        public void Should_be_able_to_cast_long_to_long(long expectedValue)\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(expectedValue);\r\n\r\n            // When\r\n            long result = value;\r\n\r\n            // Then\r\n            result.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_cast_null_to_nullable_long()\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            // When\r\n            long? result = value;\r\n\r\n            // Then\r\n            result.HasValue.ShouldBeFalse();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(1234L)]\r\n        [InlineData(4321L)]\r\n        public void Should_be_able_to_cast_long_to_nullable_long(long expectedValue)\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(expectedValue);\r\n\r\n            // When\r\n            long? result = value;\r\n\r\n            // Then\r\n            result.HasValue.ShouldBeTrue();\r\n            result.Value.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_cast_null_to_default_guid()\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            // When\r\n            Guid result = value;\r\n\r\n            // Then\r\n            result.ShouldEqual(default(Guid));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_cast_guid_to_guid()\r\n        {\r\n            // Given\r\n            var expectedValue = Guid.NewGuid();\r\n            dynamic value = new DynamicDictionaryValue(expectedValue);\r\n\r\n            // When\r\n            Guid result = value;\r\n\r\n            // Then\r\n            result.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_cast_null_to_nullable_guid()\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            // When\r\n            Guid? result = value;\r\n\r\n            // Then\r\n            result.HasValue.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_cast_guid_to_nullable_guid()\r\n        {\r\n            // Given\r\n            var expectedValue = Guid.NewGuid();\r\n            dynamic value = new DynamicDictionaryValue(expectedValue);\r\n\r\n            // When\r\n            Guid? result = value;\r\n\r\n            // Then\r\n            result.HasValue.ShouldBeTrue();\r\n            result.Value.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_cast_null_to_default_timespan()\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            // When\r\n            TimeSpan result = value;\r\n\r\n            // Then\r\n            result.ShouldEqual(default(TimeSpan));\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(4, 24, 18)]\r\n        [InlineData(16, 10, 34)]\r\n        public void Should_be_able_to_cast_timespan_to_timespan(int hours, int minutes, int seconds)\r\n        {\r\n            // Given\r\n            var expectedValue = new TimeSpan(hours, minutes, seconds);\r\n            dynamic value = new DynamicDictionaryValue(expectedValue);\r\n\r\n            // When\r\n            TimeSpan result = value;\r\n\r\n            // Then\r\n            result.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_cast_null_to_nullable_timespan()\r\n        {\r\n            // Given\r\n            dynamic value = new DynamicDictionaryValue(null);\r\n\r\n            // When\r\n            TimeSpan? result = value;\r\n\r\n            // Then\r\n            result.HasValue.ShouldBeFalse();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(4, 24, 18)]\r\n        [InlineData(16, 10, 34)]\r\n        public void Should_be_able_to_cast_timespan_to_nullable_timespan(int hours, int minutes, int seconds)\r\n        {\r\n            // Given\r\n            var expectedValue = new TimeSpan(hours, minutes, seconds);\r\n            dynamic value = new DynamicDictionaryValue(expectedValue);\r\n\r\n            // When\r\n            TimeSpan? result = value;\r\n\r\n            // Then\r\n            result.HasValue.ShouldBeTrue();\r\n            result.Value.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        private enum ByteEnum : byte\r\n        {\r\n            Value1 = 1,\r\n            Value2 = 2\r\n        }\r\n\r\n        private enum IntEnum\r\n        {\r\n            Value1 = 1,\r\n            Value2 = 2\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/ErrorHandling/DefaultStatusCodeHandlerFixture.cs",
    "content": "namespace Nancy.Tests.Unit.ErrorHandling\r\n{\r\n    using System;\r\n    using System.IO;\r\n    using FakeItEasy;\r\n    using Nancy.Configuration;\r\n    using Nancy.ErrorHandling;\r\n    using Nancy.Responses.Negotiation;\r\n    using Nancy.ViewEngines;\r\n    using Xunit;\r\n    using Xunit.Extensions;\r\n\r\n    public class DefaultStatusCodeHandlerFixture\r\n    {\r\n        private readonly IResponseNegotiator responseNegotiator;\r\n        private readonly IStatusCodeHandler statusCodeHandler;\r\n\r\n        public DefaultStatusCodeHandlerFixture()\r\n        {\r\n            var environment =\r\n                new DefaultNancyEnvironment();\r\n\r\n            environment.Tracing(\r\n                enabled: true,\r\n                displayErrorTraces: true);\r\n\r\n            this.responseNegotiator = A.Fake<IResponseNegotiator>();\r\n            this.statusCodeHandler = new DefaultStatusCodeHandler(this.responseNegotiator, environment);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(HttpStatusCode.Continue)]\r\n        [InlineData(HttpStatusCode.SwitchingProtocols)]\r\n        [InlineData(HttpStatusCode.Processing)]\r\n        [InlineData(HttpStatusCode.Checkpoint)]\r\n        [InlineData(HttpStatusCode.OK)]\r\n        [InlineData(HttpStatusCode.Created)]\r\n        [InlineData(HttpStatusCode.Accepted)]\r\n        [InlineData(HttpStatusCode.NonAuthoritativeInformation)]\r\n        [InlineData(HttpStatusCode.NoContent)]\r\n        [InlineData(HttpStatusCode.ResetContent)]\r\n        [InlineData(HttpStatusCode.PartialContent)]\r\n        [InlineData(HttpStatusCode.MultipleStatus)]\r\n        [InlineData(HttpStatusCode.IMUsed)]\r\n        [InlineData(HttpStatusCode.MultipleChoices)]\r\n        [InlineData(HttpStatusCode.MovedPermanently)]\r\n        [InlineData(HttpStatusCode.Found)]\r\n        [InlineData(HttpStatusCode.SeeOther)]\r\n        [InlineData(HttpStatusCode.NotModified)]\r\n        [InlineData(HttpStatusCode.UseProxy)]\r\n        [InlineData(HttpStatusCode.SwitchProxy)]\r\n        [InlineData(HttpStatusCode.TemporaryRedirect)]\r\n        [InlineData(HttpStatusCode.ResumeIncomplete)]\r\n        [InlineData(HttpStatusCode.Unauthorized)]\r\n        public void Should_not_handle_non_error_codes(HttpStatusCode statusCode)\r\n        {\r\n            var result = this.statusCodeHandler.HandlesStatusCode(statusCode, null);\r\n\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(HttpStatusCode.Continue)]\r\n        [InlineData(HttpStatusCode.SwitchingProtocols)]\r\n        [InlineData(HttpStatusCode.Processing)]\r\n        [InlineData(HttpStatusCode.Checkpoint)]\r\n        [InlineData(HttpStatusCode.OK)]\r\n        [InlineData(HttpStatusCode.Created)]\r\n        [InlineData(HttpStatusCode.Accepted)]\r\n        [InlineData(HttpStatusCode.NonAuthoritativeInformation)]\r\n        [InlineData(HttpStatusCode.NoContent)]\r\n        [InlineData(HttpStatusCode.ResetContent)]\r\n        [InlineData(HttpStatusCode.PartialContent)]\r\n        [InlineData(HttpStatusCode.MultipleStatus)]\r\n        [InlineData(HttpStatusCode.IMUsed)]\r\n        [InlineData(HttpStatusCode.MultipleChoices)]\r\n        [InlineData(HttpStatusCode.MovedPermanently)]\r\n        [InlineData(HttpStatusCode.Found)]\r\n        [InlineData(HttpStatusCode.SeeOther)]\r\n        [InlineData(HttpStatusCode.NotModified)]\r\n        [InlineData(HttpStatusCode.UseProxy)]\r\n        [InlineData(HttpStatusCode.SwitchProxy)]\r\n        [InlineData(HttpStatusCode.TemporaryRedirect)]\r\n        [InlineData(HttpStatusCode.ResumeIncomplete)]\r\n        [InlineData(HttpStatusCode.Unauthorized)]\r\n        public void Should_not_respond_when_handling_non_error_codes(HttpStatusCode statusCode)\r\n        {\r\n            // Given\r\n            var context = new NancyContext();\r\n\r\n            // When\r\n            this.statusCodeHandler.Handle(statusCode, context);\r\n\r\n            // Then\r\n            context.Response.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_response_contents_if_required()\r\n        {\r\n            // Given\r\n            var context = new NancyContext();\r\n            context.Response = new Response();\r\n\r\n            // When\r\n            this.statusCodeHandler.Handle(HttpStatusCode.NotFound, context);\r\n\r\n            // Then\r\n            context.Response.Contents.ShouldNotBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_overwrite_response_contents()\r\n        {\r\n            // Given\r\n            var context = new NancyContext();\r\n            Action<Stream> contents = stream => { };\r\n            context.Response = new Response() { StatusCode = HttpStatusCode.NotFound, Contents = contents };\r\n\r\n            // When\r\n            this.statusCodeHandler.Handle(HttpStatusCode.NotFound, context);\r\n\r\n            // Then\r\n            context.Response.Contents.ShouldEqual(contents);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_overwrite_response_contents_if_the_body_is_null_object()\r\n        {\r\n            // Given\r\n            var context = new NancyContext();\r\n            context.Response = new Response { StatusCode = HttpStatusCode.NotFound };\r\n            A.CallTo(() => this.responseNegotiator.NegotiateResponse(A<DefaultStatusCodeHandler.DefaultStatusCodeHandlerResult>._, context)).Throws(new ViewNotFoundException(string.Empty));\r\n\r\n            // When\r\n            this.statusCodeHandler.Handle(HttpStatusCode.NotFound, context);\r\n\r\n            // Then\r\n            using (var stream = new MemoryStream())\r\n            {\r\n                context.Response.Contents.Invoke(stream);\r\n                stream.ToArray().Length.ShouldBeGreaterThan(0);\r\n            }\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_create_response_if_it_doesnt_exist_in_context()\r\n        {\r\n            // Given\r\n            var context = new NancyContext();\r\n\r\n            // When\r\n            this.statusCodeHandler.Handle(HttpStatusCode.NotFound, context);\r\n\r\n            // Then\r\n            context.Response.ShouldNotBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_leave_reponse_stream_open_if_response_is_InternalServerError()\r\n        {\r\n            // Given\r\n            var context = new NancyContext();\r\n            var memoryStream = new MemoryStream();\r\n\r\n            // When\r\n            this.statusCodeHandler.Handle(HttpStatusCode.InternalServerError, context);\r\n            context.Response.Contents(memoryStream);\r\n\r\n            // Then\r\n            memoryStream.CanRead.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_negotiate_response_with_content_negotiator()\r\n        {\r\n            // Given\r\n            var context = new NancyContext();\r\n\r\n            // When\r\n            this.statusCodeHandler.Handle(HttpStatusCode.InternalServerError, context);\r\n\r\n            // Then\r\n            A.CallTo(() => this.responseNegotiator.NegotiateResponse(A<DefaultStatusCodeHandler.DefaultStatusCodeHandlerResult>._, context)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_render_html_response_from_static_resources()\r\n        {\r\n            // Given\r\n            var context = new NancyContext();\r\n            A.CallTo(() => this.responseNegotiator.NegotiateResponse(A<DefaultStatusCodeHandler.DefaultStatusCodeHandlerResult>._, context)).Throws(new ViewNotFoundException(string.Empty));\r\n\r\n            // When\r\n            this.statusCodeHandler.Handle(HttpStatusCode.InternalServerError, context);\r\n\r\n            // Then\r\n            Assert.Equal(\"text/html\", context.Response.ContentType);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_reset_negotiation_context()\r\n        {\r\n            // Given\r\n            var context = new NancyContext();\r\n            var negotiationContext = new NegotiationContext { ViewName = \"Index\" };\r\n            context.NegotiationContext = negotiationContext;\r\n\r\n            // When\r\n            this.statusCodeHandler.Handle(HttpStatusCode.InternalServerError, context);\r\n\r\n            // Then\r\n            Assert.Null(context.NegotiationContext.ViewName);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_xml_serializable()\r\n        {\r\n            // Given\r\n            var environment = new DefaultNancyEnvironment();\r\n            environment.AddValue(Xml.XmlConfiguration.Default);\r\n            environment.Tracing(\r\n                enabled: true,\r\n                displayErrorTraces: true);\r\n            var serializer = new Nancy.Responses.DefaultXmlSerializer(environment);\r\n            var model = new DefaultStatusCodeHandler.DefaultStatusCodeHandlerResult()\r\n            {\r\n                StatusCode = HttpStatusCode.NotFound,\r\n                Message =  \"not found\",\r\n                Details = \"not found details\"\r\n            };\r\n\r\n            // When\r\n            var xml = new System.Xml.XmlDocument();\r\n            using (var stream = new MemoryStream())\r\n            {\r\n                serializer.Serialize(\"application/xml\", model, stream);\r\n\r\n                stream.Position = 0;\r\n                xml.Load(stream);\r\n            }\r\n\r\n            // Then\r\n            Assert.Equal(\"DefaultStatusCodeHandlerResult\", xml.DocumentElement.Name);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/ErrorPipelineFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit\r\n{\r\n    using System;\r\n    using System.Linq;\r\n\r\n    using Xunit;\r\n\r\n    public class ErrorPipelineFixture\r\n    {\r\n        private ErrorPipeline pipeline;\r\n\r\n        private static NancyContext CreateContext()\r\n        {\r\n            return new NancyContext();\r\n        }\r\n\r\n        public ErrorPipelineFixture()\r\n        {\r\n            pipeline = new ErrorPipeline();\r\n        }\r\n\r\n        [Fact]\r\n        public void PlusEquals_with_func_adds_item_to_end_of_pipeline()\r\n        {\r\n            // Given, When\r\n            pipeline += (ctx, ex) => null;\r\n            pipeline += (ctx, ex) => null;\r\n\r\n            // Then\r\n            pipeline.PipelineDelegates.ShouldHaveCount(2);\r\n        }\r\n\r\n        [Fact]\r\n        public void PlusEquals_with_another_pipeline_adds_those_pipeline_items_to_end_of_pipeline()\r\n        {\r\n            // Given\r\n            pipeline.AddItemToEndOfPipeline((ctx, ex) => null);\r\n            pipeline.AddItemToEndOfPipeline((ctx, ex) => null);\r\n            var pipeline2 = new ErrorPipeline();\r\n            pipeline2.AddItemToEndOfPipeline((ctx, ex) => null);\r\n            pipeline2.AddItemToEndOfPipeline((ctx, ex) => null);\r\n\r\n            // When\r\n            pipeline += pipeline2;\r\n\r\n            // Then\r\n            pipeline.PipelineItems.ShouldHaveCount(4);\r\n            pipeline2.PipelineDelegates.ElementAt(0).ShouldBeSameAs(pipeline.PipelineDelegates.ElementAt(2));\r\n            pipeline2.PipelineDelegates.ElementAt(1).ShouldBeSameAs(pipeline.PipelineDelegates.Last());\r\n        }\r\n\r\n        [Fact]\r\n        public void When_cast_to_func_and_invoked_members_are_invoked()\r\n        {\r\n            // Given\r\n            var item1Called = false;\r\n            Func<NancyContext, Exception, dynamic> item1 = (ctx, ex) => { item1Called = true; return null; };\r\n            var item2Called = false;\r\n            Func<NancyContext, Exception, dynamic> item2 = (ctx, ex) => { item2Called = true; return null; };\r\n            var item3Called = false;\r\n            Func<NancyContext, Exception, dynamic> item3 = (ctx, ex) => { item3Called = true; return null; };\r\n            pipeline.AddItemToEndOfPipeline(item1);\r\n            pipeline.AddItemToEndOfPipeline(item2);\r\n            pipeline.AddItemToEndOfPipeline(item3);\r\n\r\n            // When\r\n            pipeline.Invoke(CreateContext(), new Exception());\r\n\r\n            // Then\r\n            item1Called.ShouldBeTrue();\r\n            item2Called.ShouldBeTrue();\r\n            item3Called.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void When_cast_from_func_creates_a_pipeline_with_one_item()\r\n        {\r\n            // Given\r\n            var castPipeline = new ErrorPipeline();\r\n\r\n            // When\r\n            castPipeline += (ctx, ex) => null;\r\n\r\n            // Then\r\n            castPipeline.PipelineDelegates.ShouldHaveCount(1);\r\n        }\r\n\r\n        [Fact]\r\n        public void Pipeline_containing_another_pipeline_will_invoke_items_in_both_pipelines()\r\n        {\r\n            // Given\r\n            var item1Called = false;\r\n            Func<NancyContext, Exception, dynamic> item1 = (ctx, ex) => { item1Called = true; return null; };\r\n            var item2Called = false;\r\n            Func<NancyContext, Exception, dynamic> item2 = (ctx, ex) => { item2Called = true; return null; };\r\n            var item3Called = false;\r\n            Func<NancyContext, Exception, dynamic> item3 = (ctx, ex) => { item3Called = true; return null; };\r\n            var item4Called = false;\r\n            Func<NancyContext, Exception, dynamic> item4 = (ctx, ex) => { item4Called = true; return null; };\r\n            pipeline += item1;\r\n            pipeline += item2;\r\n            var subPipeline = new ErrorPipeline();\r\n            subPipeline += item3;\r\n            subPipeline += item4;\r\n\r\n            // When\r\n            pipeline.AddItemToEndOfPipeline(subPipeline);\r\n            pipeline.Invoke(CreateContext(), new Exception());\r\n\r\n            // Then\r\n            item1Called.ShouldBeTrue();\r\n            item2Called.ShouldBeTrue();\r\n            item3Called.ShouldBeTrue();\r\n            item4Called.ShouldBeTrue();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Extensions/ContextExtensionsFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Extensions\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using Nancy.Extensions;\r\n    using Nancy.Tests.Fakes;\r\n\r\n    using Xunit;\r\n    using Xunit.Extensions;\r\n\r\n    public class ContextExtensionsFixture\r\n    {\r\n        [Fact]\r\n        public static void IsAjaxRequest_should_return_true_if_request_is_ajax()\r\n        {\r\n            // Given \r\n            var headers =\r\n                new Dictionary<string, IEnumerable<string>>\r\n                    {\r\n                        { \"X-Requested-With\", new[] { \"XMLHttpRequest\" } }\r\n                    };\r\n\r\n            // When\r\n            var context = new NancyContext\r\n                              {\r\n                                  Request = new FakeRequest(\"POST\", \"/\", headers)\r\n                              };\r\n\r\n            // Then\r\n            Assert.True(context.IsAjaxRequest());\r\n        }\r\n\r\n        [Fact]\r\n        public void IsAjaxRequest_should_return_false_if_request_is_null()\r\n        {\r\n            // Given when\r\n            var context = new NancyContext();\r\n\r\n            // Then\r\n            Assert.False(context.IsAjaxRequest());\r\n        }\r\n\r\n        [Fact]\r\n        public void IsAjaxRequest_should_return_false_if_request_is_not_ajax()\r\n        {\r\n            // Given when\r\n            var context = new NancyContext\r\n                              {\r\n                                  Request = new FakeRequest(\"POST\", \"/\")\r\n                              };\r\n\r\n            // Then\r\n            Assert.False(context.IsAjaxRequest());\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_same_path_when_parsing_path_if_path_doesnt_contain_tilde()\r\n        {\r\n            // Given\r\n            const string input = \"/scripts/test.js\";\r\n            var url = new Url\r\n            {\r\n                BasePath = \"/base/path\",\r\n                Path = \"/\"\r\n            };\r\n            var request = new Request(\"GET\", url);\r\n            var nancyContext = new NancyContext { Request = request };\r\n\r\n            // When\r\n            var result = nancyContext.ToFullPath(input);\r\n\r\n            // Then\r\n            result.ShouldEqual(input);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_replace_tilde_with_base_path_when_parsing_path_if_one_present()\r\n        {\r\n            // Given\r\n            const string input = \"~/scripts/test.js\";\r\n            var url = new Url\r\n            {\r\n                BasePath = \"/base/path/\",\r\n                Path = \"/\"\r\n            };\r\n            var request = new Request(\"GET\", url);\r\n            var nancyContext = new NancyContext { Request = request };\r\n\r\n            // When\r\n            var result = nancyContext.ToFullPath(input);\r\n\r\n            // Then\r\n            result.ShouldEqual(\"/base/path/scripts/test.js\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_replace_tilde_with_nothing_when_parsing_path_if_one_present_and_base_path_is_null()\r\n        {\r\n            // Given\r\n            const string input = \"~/scripts/test.js\";\r\n            var url = new Url\r\n            {\r\n                BasePath = null,\r\n                Path = \"/\"\r\n            };\r\n            var request = new Request(\"GET\", url);\r\n            var nancyContext = new NancyContext { Request = request };\r\n\r\n            // When\r\n            var result = nancyContext.ToFullPath(input);\r\n\r\n            // Then\r\n            result.ShouldEqual(\"/scripts/test.js\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_report_simple_relative_path_as_local()\r\n        {\r\n            // Given\r\n            var context = this.CreateContext();\r\n\r\n            // When\r\n            var result = context.IsLocalUrl(\"/stuff\");\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_report_same_host_absolute_url_as_local()\r\n        {\r\n            // Given\r\n            var context = this.CreateContext();\r\n\r\n            // When\r\n            var result = context.IsLocalUrl(\"http://test.com/someotherpath\");\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_report_empty_string_as_nonlocal()\r\n        {\r\n            // Given\r\n            var context = this.CreateContext();\r\n\r\n            // When\r\n            var result = context.IsLocalUrl(\"\");\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_report_different_host_absolute_url_as_nonlocal()\r\n        {\r\n            // Given\r\n            var context = this.CreateContext();\r\n\r\n            // When\r\n            var result = context.IsLocalUrl(\"http://anothertest.com/someotherpath\");\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_report_protocol_relative_url_different_host_as_nonlocal()\r\n        {\r\n            // Given\r\n            var context = this.CreateContext();\r\n\r\n            // When\r\n            var result = context.IsLocalUrl(\"//anothertest.com\");\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_report_protocol_relative_url_same_host_as_local()\r\n        {\r\n            // Given\r\n            var context = this.CreateContext();\r\n\r\n            // When\r\n            var result = context.IsLocalUrl(\"//test.com\");\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(@\"/\\anothertest.com\")]\r\n        [InlineData(@\"\\/anothertest.com\")]\r\n        public void Should_report_malformed_url_as_nonlocal(string malformedUrl)\r\n        {\r\n            // Given\r\n            var context = this.CreateContext();\r\n            \r\n            // When\r\n            var result = context.IsLocalUrl(malformedUrl);\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_string_if_no_exception_details()\r\n        {\r\n            // Given\r\n            var context = this.CreateContext();\r\n\r\n            // When\r\n            var exceptionDetails = context.GetExceptionDetails();\r\n\r\n            // Then\r\n            exceptionDetails.ShouldBeEmpty();\r\n        }\r\n\r\n        private NancyContext CreateContext(Url url = null)\r\n        {\r\n            var request = new Request(\r\n                \"GET\",\r\n                url ?? new Url() { Scheme = \"http\", BasePath = \"testing\", HostName = \"test.com\", Path = \"test\" });\r\n\r\n            return new NancyContext() { Request = request };\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Extensions/RequestExtensionsFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Extensions\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using Nancy.Extensions;\r\n    using Nancy.Tests.Fakes;\r\n\r\n    using Xunit;\r\n\r\n    public class RequestExtensionsFixture\r\n    {\r\n        [Fact]\r\n        public void IsAjaxRequest_should_return_true_if_request_is_ajax()\r\n        {\r\n            // Given\r\n            var headers = new Dictionary<string, IEnumerable<string>>\r\n            {\r\n                { \"X-Requested-With\", new[] { \"XMLHttpRequest\" } }\r\n            };\r\n\r\n            // When\r\n            var request = new FakeRequest(\"POST\", \"/\", headers);\r\n\r\n            // Then\r\n            Assert.True(request.IsAjaxRequest());\r\n        }\r\n\r\n        [Fact]\r\n        public void IsAjaxRequest_should_return_false_if_request_is_not_ajax()\r\n        {\r\n            // Given when\r\n            var request = new FakeRequest(\"POST\", \"/\");\r\n\r\n            // Then\r\n            Assert.False(request.IsAjaxRequest());\r\n        }\r\n\r\n        [Fact]\r\n        public void IsLocal_should_return_true_if_userHostAddr_is_localhost_IPV6()\r\n        {\r\n            // Given when\r\n            var request = new FakeRequest(\"GET\", \"/\", string.Empty, \"::1\");\r\n\r\n            // Then\r\n            Assert.True(request.IsLocal());\r\n        }\r\n\r\n        [Fact]\r\n        public void IsLocal_should_return_false_if_userHostAddr_is_empty()\r\n        {\r\n            // Given when\r\n            var request = new FakeRequest(\"GET\", \"/\", string.Empty,  string.Empty);\r\n\r\n            // Then\r\n            Assert.False(request.IsLocal());\r\n        }\r\n\r\n        [Fact]\r\n        public void IsLocal_should_return_false_if_urlString_is_empty()\r\n        {\r\n            // Given when\r\n            var request = new FakeRequest(\"GET\", string.Empty, string.Empty, string.Empty);\r\n\r\n            // Then\r\n            Assert.False(request.IsLocal());\r\n        }\r\n\r\n        [Fact]\r\n        public void IsLocal_should_return_true_if_userHostAddr_is_localhost_IPV4()\r\n        {\r\n            // Given when\r\n            var request = new FakeRequest(\"POST\", \"/\", string.Empty, \"127.0.0.1\");\r\n\r\n            // Then\r\n            Assert.True(request.IsLocal());\r\n        }\r\n\r\n        [Fact]\r\n        public void IsLocal_should_return_false_if_userHostAddr_is_not_localhost()\r\n        {\r\n            // Given when\r\n            var request = new FakeRequest(\"GET\", \"/\", string.Empty, \"86.13.73.12\");\r\n\r\n            // Then\r\n            Assert.False(request.IsLocal());\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Extensions/StreamExtensionsFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Extensions\r\n{\r\n    using System.IO;\r\n    using System.Text;\r\n    using Nancy.Extensions;\r\n    using Nancy.IO;\r\n    using Xunit;\r\n\r\n    public class StreamExtensionsFixture\r\n    {\r\n        [Fact]\r\n        public void AsString_should_always_start_from_position_0_and_reset_it_afterwards()\r\n        {\r\n            // Given\r\n            using (var innerStream = new MemoryStream())\r\n            using (var streamWriter = new StreamWriter(innerStream, Encoding.UTF8) { AutoFlush = true })\r\n            {\r\n                streamWriter.Write(\"fake request body\");\r\n\r\n                var requestStream = RequestStream.FromStream(innerStream);\r\n\r\n                var initialPosition = requestStream.Position = 3;\r\n\r\n                // When\r\n                var result = requestStream.AsString(Encoding.UTF8);\r\n\r\n                // Then\r\n                Assert.Equal(\"fake request body\", result);\r\n                Assert.Equal(initialPosition, requestStream.Position);\r\n            }\r\n        }\r\n\r\n        [Fact]\r\n        public void AsString_should_not_close_stream()\r\n        {\r\n            // Given\r\n            using (var innerStream = new MemoryStream())\r\n            using (var streamWriter = new StreamWriter(innerStream, Encoding.UTF8) { AutoFlush = true })\r\n            {\r\n                streamWriter.Write(\"fake request body\");\r\n\r\n                // When\r\n                innerStream.AsString(Encoding.UTF8);\r\n\r\n                // Then\r\n                Assert.True(innerStream.CanRead);\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Extensions/StringExtensionsFixture.cs",
    "content": "namespace Nancy.Tests.Unit.Extensions\r\n{\r\n    using Nancy.Extensions;\r\n\r\n    using Xunit;\r\n\r\n    public class StringExtensionsFixture\r\n    {\r\n        [Fact]\r\n        public void IsParameterized_should_return_false_when_there_are_parameters()\r\n        {\r\n            \"route\".IsParameterized().ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void IsParameterized_should_return_true_when_there_is_a_parameter()\r\n        {\r\n            \"{param}\".IsParameterized().ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void IsParameterized_should_return_false_for_empty_string()\r\n        {\r\n            string.Empty.IsParameterized().ShouldBeFalse();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Extensions/TypeExtensionsFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Extensions\r\n{\r\n    using System;\r\n\r\n    using Nancy.Extensions;\r\n\r\n    using Xunit;\r\n\r\n    public class TypeExtensionsFixture\r\n    {\r\n        [Fact]\r\n        public void Should_test_non_numeric_types()\r\n        {\r\n            Assert.False(TypeExtensions.IsNumeric(null));\r\n            Assert.False(typeof(object).IsNumeric());\r\n            Assert.False(typeof(DBNull).IsNumeric());\r\n            Assert.False(typeof(bool).IsNumeric());\r\n            Assert.False(typeof(char).IsNumeric());\r\n            Assert.False(typeof(DateTime).IsNumeric());\r\n            Assert.False(typeof(string).IsNumeric());\r\n            Assert.False(typeof(HttpStatusCode).IsNumeric());\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_test_Arrays_of_numeric_and_non_numeric_types()\r\n        {\r\n            Assert.False(typeof(object[]).IsNumeric());\r\n            Assert.False(typeof(DBNull[]).IsNumeric());\r\n            Assert.False(typeof(bool[]).IsNumeric());\r\n            Assert.False(typeof(char[]).IsNumeric());\r\n            Assert.False(typeof(DateTime[]).IsNumeric());\r\n            Assert.False(typeof(string[]).IsNumeric());\r\n            Assert.False(typeof(byte[]).IsNumeric());\r\n            Assert.False(typeof(decimal[]).IsNumeric());\r\n            Assert.False(typeof(double[]).IsNumeric());\r\n            Assert.False(typeof(short[]).IsNumeric());\r\n            Assert.False(typeof(int[]).IsNumeric());\r\n            Assert.False(typeof(long[]).IsNumeric());\r\n            Assert.False(typeof(sbyte[]).IsNumeric());\r\n            Assert.False(typeof(float[]).IsNumeric());\r\n            Assert.False(typeof(ushort[]).IsNumeric());\r\n            Assert.False(typeof(uint[]).IsNumeric());\r\n            Assert.False(typeof(ulong[]).IsNumeric());\r\n            Assert.False(typeof(HttpStatusCode[]).IsNumeric());\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_test_numeric_types()\r\n        {\r\n            Assert.True(typeof(byte).IsNumeric());\r\n            Assert.True(typeof(decimal).IsNumeric());\r\n            Assert.True(typeof(double).IsNumeric());\r\n            Assert.True(typeof(short).IsNumeric());\r\n            Assert.True(typeof(int).IsNumeric());\r\n            Assert.True(typeof(long).IsNumeric());\r\n            Assert.True(typeof(sbyte).IsNumeric());\r\n            Assert.True(typeof(float).IsNumeric());\r\n            Assert.True(typeof(ushort).IsNumeric());\r\n            Assert.True(typeof(uint).IsNumeric());\r\n            Assert.True(typeof(ulong).IsNumeric());\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_test_nullable_non_numeric_types()\r\n        {\r\n            Assert.False(typeof(bool?).IsNumeric());\r\n            Assert.False(typeof(char?).IsNumeric());\r\n            Assert.False(typeof(DateTime?).IsNumeric());\r\n            Assert.False(typeof(HttpStatusCode?).IsNumeric());\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_test_nullable_numeric_types()\r\n        {\r\n            Assert.True(typeof(byte?).IsNumeric());\r\n            Assert.True(typeof(decimal?).IsNumeric());\r\n            Assert.True(typeof(double?).IsNumeric());\r\n            Assert.True(typeof(short?).IsNumeric());\r\n            Assert.True(typeof(int?).IsNumeric());\r\n            Assert.True(typeof(long?).IsNumeric());\r\n            Assert.True(typeof(sbyte?).IsNumeric());\r\n            Assert.True(typeof(float?).IsNumeric());\r\n            Assert.True(typeof(ushort?).IsNumeric());\r\n            Assert.True(typeof(uint?).IsNumeric());\r\n            Assert.True(typeof(ulong?).IsNumeric());\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_test_non_numeric_gettype()\r\n        {\r\n            Assert.False((new object()).GetType().IsNumeric());\r\n            Assert.False(DBNull.Value.GetType().IsNumeric());\r\n            Assert.False(true.GetType().IsNumeric());\r\n            Assert.False('a'.GetType().IsNumeric());\r\n            Assert.False((new DateTime(2009, 1, 1)).GetType().IsNumeric());\r\n            Assert.False(string.Empty.GetType().IsNumeric());\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_test_numeric_gettype()\r\n        {\r\n            Assert.True((new byte()).GetType().IsNumeric());\r\n            Assert.True(43.2m.GetType().IsNumeric());\r\n            Assert.True(43.2d.GetType().IsNumeric());\r\n            Assert.True(((short)2).GetType().IsNumeric());\r\n            Assert.True(((int)2).GetType().IsNumeric());\r\n            Assert.True(((long)2).GetType().IsNumeric());\r\n            Assert.True(((sbyte)2).GetType().IsNumeric());\r\n            Assert.True(2f.GetType().IsNumeric());\r\n            Assert.True(((ushort)2).GetType().IsNumeric());\r\n            Assert.True(((uint)2).GetType().IsNumeric());\r\n            Assert.True(((ulong)2).GetType().IsNumeric());\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_test_nullable_non_numeric_types_gettype()\r\n        {\r\n            bool? nullableBool = true;\r\n            Assert.False(nullableBool.GetType().IsNumeric());\r\n\r\n            char? nullableChar = ' ';\r\n            Assert.False(nullableChar.GetType().IsNumeric());\r\n\r\n            DateTime? nullableDateTime = new DateTime(2009, 1, 1);\r\n            Assert.False(nullableDateTime.GetType().IsNumeric());\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_test_nullable_numeric_types_gettype()\r\n        {\r\n            byte? nullableByte = 12;\r\n            Assert.True(nullableByte.GetType().IsNumeric());\r\n\r\n            decimal? nullableDecimal = 12.2m;\r\n            Assert.True(nullableDecimal.GetType().IsNumeric());\r\n\r\n            double? nullableDouble = 12.32;\r\n            Assert.True(nullableDouble.GetType().IsNumeric());\r\n\r\n            short? nullableInt16 = 12;\r\n            Assert.True(nullableInt16.GetType().IsNumeric());\r\n\r\n            short? nullableInt32 = 12;\r\n            Assert.True(nullableInt32.GetType().IsNumeric());\r\n\r\n            short? nullableInt64 = 12;\r\n            Assert.True(nullableInt64.GetType().IsNumeric());\r\n\r\n            sbyte? nullableSByte = 12;\r\n            Assert.True(nullableSByte.GetType().IsNumeric());\r\n\r\n            float? nullableSingle = 3.2f;\r\n            Assert.True(nullableSingle.GetType().IsNumeric());\r\n\r\n            ushort? nullableUInt16 = 12;\r\n            Assert.True(nullableUInt16.GetType().IsNumeric());\r\n\r\n            ushort? nullableUInt32 = 12;\r\n            Assert.True(nullableUInt32.GetType().IsNumeric());\r\n\r\n            ushort? nullableUInt64 = 12;\r\n            Assert.True(nullableUInt64.GetType().IsNumeric());\r\n\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/FormatterExtensionsFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit\r\n{\r\n    using FakeItEasy;\r\n    using Nancy.Configuration;\r\n    using Xunit;\r\n\r\n    public class FormatterExtensionsFixture\r\n    {\r\n        private readonly IResponseFormatter formatter;\r\n        private readonly NancyContext context;\r\n\r\n        public FormatterExtensionsFixture()\r\n        {\r\n            this.context = new NancyContext();\r\n            this.formatter = new DefaultResponseFormatter(A.Fake<IRootPathProvider>(), context, new DefaultSerializerFactory(null), A.Fake<INancyEnvironment>());\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_expand_base_path_for_redirect_if_tilde_present()\r\n        {\r\n            // Given\r\n            this.context.Request = new Request(\r\n                \"GET\",\r\n                new Url\r\n                    {\r\n                        BasePath = \"/basePath\",\r\n                        Path = \"Path\",\r\n                        Scheme = \"http\",\r\n                    });\r\n\r\n            // When\r\n            var result = this.formatter.AsRedirect(\"~/test\");\r\n\r\n            // Then\r\n            result.Headers[\"Location\"].ShouldEqual(\"/basePath/test\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_leave_path_untouched_for_redirect_if_no_tilde()\r\n        {\r\n            // Given\r\n            this.context.Request = new Request(\r\n                \"GET\",\r\n                new Url\r\n                {\r\n                    BasePath = \"/basePath\",\r\n                    Path = \"Path\",\r\n                    Scheme = \"http\",\r\n                });\r\n\r\n            // When\r\n            var result = this.formatter.AsRedirect(\"/test\");\r\n\r\n            // Then\r\n            result.Headers[\"Location\"].ShouldEqual(\"/test\");\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/HeadResponseFixture.cs",
    "content": "namespace Nancy.Tests.Unit\r\n{\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n\r\n    using Nancy.Tests.Extensions;\r\n    using FakeItEasy;\r\n\r\n    using Xunit;\r\n\r\n    public class HeadResponseFixture\r\n    {\r\n        private readonly IDictionary<string, string> headers;\r\n        private readonly Response response;\r\n\r\n        public HeadResponseFixture()\r\n        {\r\n            // Given\r\n            this.headers = new Dictionary<string, string> { { \"Test\", \"Value \" } };\r\n            this.response = \"This is the content\";\r\n\r\n            this.response.ContentType = \"application/json\";\r\n            this.response.Headers = headers;\r\n            this.response.StatusCode = HttpStatusCode.ResetContent;\r\n        }\r\n\r\n        private HeadResponse CreateHeadResponse()\r\n        {\r\n            var head = new HeadResponse(this.response);\r\n            head.PreExecute(A.Dummy<NancyContext>());\r\n            head.Contents(new MemoryStream());\r\n            return head;\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_status_property_to_that_of_decorated_response()\r\n        {\r\n            //When\r\n            var head = this.CreateHeadResponse();\r\n            \r\n            // Then\r\n            head.StatusCode.ShouldEqual(this.response.StatusCode);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_headers_property_to_that_of_decorated_response()\r\n        {\r\n            //When\r\n            var head = this.CreateHeadResponse();\r\n\r\n            // Then\r\n            head.Headers.ShouldBeSameAs(this.headers);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_content_type_property_to_that_of_decorated_response()\r\n        {\r\n            //When\r\n            var head = this.CreateHeadResponse();\r\n\r\n            // Then\r\n            head.ContentType.ShouldEqual(this.response.ContentType);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_empty_content()\r\n        {\r\n            //When\r\n            var head = this.CreateHeadResponse();\r\n\r\n            // Then\r\n            head.GetStringContentsFromResponse().ShouldBeEmpty();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_content_length()\r\n        {\r\n            //When\r\n            var head = this.CreateHeadResponse();\r\n\r\n            // Then\r\n            head.Headers.ContainsKey(\"Content-Length\").ShouldBeTrue();\r\n            head.Headers[\"Content-Length\"].ShouldNotEqual(\"0\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_overwrite_content_length()\r\n        {\r\n            // Given, When\r\n            this.response.Headers.Add(\"Content-Length\", \"foo\");\r\n            var head = this.CreateHeadResponse();\r\n\r\n            // Then\r\n            head.Headers.ContainsKey(\"Content-Length\").ShouldBeTrue();\r\n            head.Headers[\"Content-Length\"].ShouldEqual(\"foo\");\r\n        }\r\n\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Helpers/HttpUtilityFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Helpers\r\n{\r\n    using System.Text;\r\n    using Nancy.Helpers;\r\n\r\n    using Xunit;\r\n    using Xunit.Extensions;\r\n\r\n    public class HttpUtilityFixture\r\n    {\r\n        [Fact]\r\n        public void ParseQueryString_respects_case_insensitive_setting()\r\n        {\r\n            // Given\r\n            StaticConfiguration.CaseSensitive = false;\r\n            var query = \"key=value\";\r\n\r\n            // When\r\n            var collection = HttpUtility.ParseQueryString(query);\r\n\r\n            // Then\r\n            collection[\"key\"].ShouldEqual(\"value\");\r\n            collection[\"KEY\"].ShouldEqual(\"value\");\r\n        }\r\n\r\n        [Fact]\r\n        public void ParseQueryString_respects_case_sensitive_setting()\r\n        {\r\n            // Given\r\n            StaticConfiguration.CaseSensitive = true;\r\n            var query = \"key=value\";\r\n\r\n            // When\r\n            var collection = HttpUtility.ParseQueryString(query);\r\n\r\n            // Then\r\n            collection[\"key\"].ShouldEqual(\"value\");\r\n            collection[\"KEY\"].ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void ParseQueryString_handles_duplicate_keys_when_case_insensitive()\r\n        {\r\n            // Given\r\n            StaticConfiguration.CaseSensitive = false;\r\n            var query = \"key=value&key=value&KEY=VALUE\";\r\n\r\n            // When\r\n            var collection = HttpUtility.ParseQueryString(query);\r\n\r\n            // Then\r\n            collection[\"key\"].ShouldEqual(\"value,value,VALUE\");\r\n            collection[\"KEY\"].ShouldEqual(\"value,value,VALUE\");\r\n        }\r\n\r\n        [Fact]\r\n        public void ParseQueryString_handles_duplicate_keys_when_case_sensitive()\r\n        {\r\n            // Given\r\n            StaticConfiguration.CaseSensitive = true;\r\n            var query = \"key=value&key=value&KEY=VALUE\";\r\n\r\n            // When\r\n            var collection = HttpUtility.ParseQueryString(query);\r\n\r\n            // Then\r\n            collection[\"key\"].ShouldEqual(\"value,value\");\r\n            collection[\"KEY\"].ShouldEqual(\"VALUE\");\r\n        }\r\n\r\n        [Fact]\r\n        public void ParseQueryString_explicit_case_insensitivity_overrides_global_setting()\r\n        {\r\n            // Given\r\n            StaticConfiguration.CaseSensitive = true;\r\n            var query = \"key=value\";\r\n\r\n            // When\r\n            var collection = HttpUtility.ParseQueryString(query, caseSensitive: false);\r\n\r\n            // Then\r\n            collection[\"key\"].ShouldEqual(\"value\");\r\n            collection[\"KEY\"].ShouldEqual(\"value\");\r\n        }\r\n\r\n        [Fact]\r\n        public void ParseQueryString_explicit_case_sensitivity_overrides_global_setting()\r\n        {\r\n            // Given\r\n            StaticConfiguration.CaseSensitive = false;\r\n            var query = \"key=value\";\r\n\r\n            // When\r\n            var collection = HttpUtility.ParseQueryString(query, caseSensitive: true);\r\n\r\n            // Then\r\n            collection[\"key\"].ShouldEqual(\"value\");\r\n            collection[\"KEY\"].ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void ParseQueryString_handles_keys_without_values()\r\n        {\r\n            // Given\r\n            var query = \"key1&key2\";\r\n\r\n            // When\r\n            var collection = HttpUtility.ParseQueryString(query);\r\n\r\n            // Then\r\n            collection[\"key1\"].ShouldEqual(\"key1\");\r\n            collection[\"key2\"].ShouldEqual(\"key2\");\r\n        }\r\n\r\n        [Fact]\r\n        public void ParseQueryString_handles_duplicate_keys_when_one_has_no_value()\r\n        {\r\n            // Given\r\n            var query = \"key&key=value\";\r\n\r\n            // When\r\n            var collection = HttpUtility.ParseQueryString(query);\r\n\r\n            // Then\r\n            collection[\"key\"].ShouldEqual(\"key,value\");\r\n        }\r\n\r\n        [Fact]\r\n        public void ParseQueryString_handles_duplicate_keys_when_they_have_no_values()\r\n        {\r\n            // Given\r\n            var query = \"key&key\";\r\n\r\n            // When\r\n            var collection = HttpUtility.ParseQueryString(query);\r\n\r\n            // Then\r\n            collection[\"key\"].ShouldEqual(\"key,key\");\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"/a/a&/b&/c\")]\r\n        [InlineData(\"/build/app-transitions-css/app-transitions-css-min.css&/build/widget-base/assets/skins/sam/widget-base.css&/build/scrollview-base/assets/skins/sam/scrollview-base.css&/build/scrollview-scrollbars/assets/skins/sam/scrollview-scrollbars.css&/build/widget-stack/assets/skins/sam/widget-stack.css&/build/overlay/assets/skins/sam/overlay.css&/build/console/assets/skins/sam/console.css\")]\r\n        public void ParseQueryString_handles_irregular_yui_format(string query)\r\n        {\r\n            Record.Exception(() =>\r\n            {\r\n                var collection = HttpUtility.ParseQueryString(query);\r\n                collection.ShouldNotBeNull();\r\n            }).ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void UrlDecode_returns_null_when_input_is_null()\r\n        {\r\n            byte[] input = null;\r\n            Record.Exception(() =>\r\n            {\r\n                var result = HttpUtility.UrlDecode(input, 0, 10, Encoding.UTF8);\r\n                result.ShouldBeNull();\r\n            }).ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void UrlDecode_returns_null_when_input_string_is_null()\r\n        {\r\n            string input = null;\r\n            Record.Exception(() =>\r\n            {\r\n                var result = HttpUtility.UrlDecode(input, Encoding.UTF8);\r\n                result.ShouldBeNull();\r\n            }).ShouldBeNull();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/HttpLinkBuilderFixture.cs",
    "content": "namespace Nancy.Tests.Unit\n{\n    using Xunit;\n\n    public class HttpLinkBuilderFixture\n    {\n        [Fact]\n        public void Add_existing_relation_in_different_types_should_add_all()\n        {\n            // Given\n            var linkBuilder = new HttpLinkBuilder();\n\n            // When\n            linkBuilder.Add(new HttpLink(\"/first\", \"ALTERNATE\", \"application/json\"));\n            linkBuilder.Add(new HttpLink(\"/second\", \"AlterNate\", \"application/xml\"));\n            linkBuilder.Add(new HttpLink(\"/third\", \"alternate\", \"text/html\"));\n\n            // Then\n            linkBuilder.Count.ShouldEqual(3);\n            linkBuilder[0].TargetUri.ToString().ShouldEqual(\"/first\");\n            linkBuilder[0].Relation.ToString().ShouldEqual(\"ALTERNATE\");\n            linkBuilder[0].Type.ToString().ShouldEqual(\"application/json\");\n            linkBuilder[1].TargetUri.ToString().ShouldEqual(\"/second\");\n            linkBuilder[1].Relation.ToString().ShouldEqual(\"AlterNate\");\n            linkBuilder[1].Type.ToString().ShouldEqual(\"application/xml\");\n            linkBuilder[2].TargetUri.ToString().ShouldEqual(\"/third\");\n            linkBuilder[2].Relation.ToString().ShouldEqual(\"alternate\");\n            linkBuilder[2].Type.ToString().ShouldEqual(\"text/html\");\n        }\n\n        [Fact]\n        public void Count_should_be_zero_after_instantiation()\n        {\n            // Given, When\n            var linkHeader = new HttpLinkBuilder();\n\n            // Then\n            linkHeader.Count.ShouldEqual(0);\n        }\n\n        [Fact]\n        public void Count_should_equal_four_after_adding_four_links_with_same_relation_in_different_casing()\n        {\n            // Given\n            var linkBuilder = new HttpLinkBuilder();\n\n            // When\n            linkBuilder.Add(new HttpLink(\"/first\", \"ALTERNATE\"));\n            linkBuilder.Add(new HttpLink(\"/first\", \"AlterNate\"));\n            linkBuilder.Add(new HttpLink(\"/first\", \"alternate\"));\n            linkBuilder.Add(new HttpLink(\"/first\", HttpLinkRelation.IanaLinkRelationPrefix + \"alternate\"));\n\n            // Then\n            linkBuilder.Count.ShouldEqual(4);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/HttpLinkFixture.cs",
    "content": "namespace Nancy.Tests.Unit\n{\n    using System;\n    using Xunit;\n\n    public class HttpLinkFixture\n    {\n        [Fact]\n        public void Add_duplicate_parameter_in_different_casing_throws_argument_exception()\n        {\n            // Given\n            var link = new HttpLink(\"http://nancyfx.org/\", \"home\");\n            link.Parameters.Add(\"up\", \"up\");\n\n            // When, Then\n            Assert.Throws<ArgumentException>(() => link.Parameters.Add(\"UP\", \"UP\"));\n        }\n\n        [Fact]\n        public void Links_in_different_casing_should_be_considered_equal()\n        {\n            // Given\n            var first = new HttpLink(\"http://NANCYFX.ORG/\", \"home\");\n            var second = new HttpLink(\"http://nancyfx.org/\", \"home\");\n\n            // When\n            var equal = first.Equals(second);\n\n            // Then\n            equal.ShouldBeTrue();\n        }\n\n        [Fact]\n        public void Links_in_different_casing_should_have_same_hash_code()\n        {\n            // Given\n            var first = new HttpLink(\"http://NANCYFX.ORG/\", \"home\");\n            var second = new HttpLink(\"http://nancyfx.org/\", \"home\");\n\n            // When\n            var firstHashCode = first.GetHashCode();\n            var secondHashCode = second.GetHashCode();\n\n            // Then\n            firstHashCode.ShouldEqual(secondHashCode);\n        }\n\n        [Fact]\n        public void Links_with_different_parameters_should_not_be_considered_equal()\n        {\n            // Given\n            var first = new HttpLink(\"http://nancyfx.org/\", \"home\");\n            first.Parameters.Add(\"a\", \"b\");\n\n            var second = new HttpLink(\"http://nancyfx.org/\", \"home\");\n            second.Parameters.Add(\"x\", \"y\");\n\n            // When\n            var equal = first.Equals(second);\n\n            // Then\n            equal.ShouldBeFalse();\n        }\n\n        [Fact]\n        public void Links_with_different_parameters_should_not_have_same_hash_code()\n        {\n            // Given\n            var first = new HttpLink(\"http://nancyfx.org/\", \"home\");\n            first.Parameters.Add(\"a\", \"b\");\n\n            var second = new HttpLink(\"http://nancyfx.org/\", \"home\");\n            second.Parameters.Add(\"x\", \"y\");\n\n            // When\n            var firstHashCode = first.GetHashCode();\n            var secondHashCode = second.GetHashCode();\n\n            // Then\n            firstHashCode.ShouldNotEqual(secondHashCode);\n        }\n\n        [Fact]\n        public void Links_with_equal_parameters_in_different_casing_should_be_considered_equal()\n        {\n            // Given\n            var first = new HttpLink(\"http://nancyfx.org/\", \"home\");\n            first.Parameters.Add(\"param\", \"value\");\n\n            var second = new HttpLink(\"http://nancyfx.org/\", \"home\");\n            second.Parameters.Add(\"PARAM\", \"value\");\n\n            // When\n            var equal = first.Equals(second);\n\n            // Then\n            equal.ShouldBeTrue();\n        }\n\n        [Fact]\n        public void Links_with_equal_parameters_in_different_casing_should_have_same_hash_code()\n        {\n            // Given\n            var first = new HttpLink(\"http://nancyfx.org/\", \"home\");\n            first.Parameters.Add(\"param\", \"value\");\n\n            var second = new HttpLink(\"http://nancyfx.org/\", \"home\");\n            second.Parameters.Add(\"PARAM\", \"value\");\n\n            // When\n            var firstHashCode = first.GetHashCode();\n            var secondHashCode = second.GetHashCode();\n\n            // Then\n            firstHashCode.ShouldEqual(secondHashCode);\n        }\n\n        [Fact]\n        public void Links_with_equal_parameters_should_be_considered_equal()\n        {\n            // Given\n            var first = new HttpLink(\"http://nancyfx.org/\", \"home\");\n            first.Parameters.Add(\"param\", \"value\");\n\n            var second = new HttpLink(\"http://nancyfx.org/\", \"home\");\n            second.Parameters.Add(\"param\", \"value\");\n\n            // When\n            var equal = first.Equals(second);\n\n            // Then\n            equal.ShouldBeTrue();\n        }\n\n        [Fact]\n        public void Links_with_equal_parameters_should_have_same_hash_code()\n        {\n            // Given\n            var first = new HttpLink(\"http://nancyfx.org/\", \"home\");\n            first.Parameters.Add(\"param\", \"value\");\n\n            var second = new HttpLink(\"http://nancyfx.org/\", \"home\");\n            second.Parameters.Add(\"param\", \"value\");\n\n            // When\n            var firstHashCode = first.GetHashCode();\n            var secondHashCode = second.GetHashCode();\n\n            // Then\n            firstHashCode.ShouldEqual(secondHashCode);\n        }\n\n        [Fact]\n        public void Links_with_relations_in_different_casing_should_be_considered_equal()\n        {\n            // Given\n            var first = new HttpLink(\"http://nancyfx.org/\", \"home\");\n            var second = new HttpLink(\"http://nancyfx.org/\", \"HOME\");\n\n            // When\n            var equal = first.Equals(second);\n\n            // Then\n            equal.ShouldBeTrue();\n        }\n\n        [Fact]\n        public void Links_with_relations_in_different_casing_should_have_same_hash_code()\n        {\n            // Given\n            var first = new HttpLink(\"http://nancyfx.org/\", \"home\");\n            var second = new HttpLink(\"http://nancyfx.org/\", \"HOME\");\n\n            // When\n            var firstHashCode = first.GetHashCode();\n            var secondHashCode = second.GetHashCode();\n\n            // Then\n            firstHashCode.ShouldEqual(secondHashCode);\n        }\n\n        [Fact]\n        public void ToString_link_with_boolean_parameter_should_exist_without_value_in_string()\n        {\n            // Given\n            var link = new HttpLink(\"http://nancyfx.org/\", \"up\");\n            link.Parameters.Add(\"parameter\", null);\n\n            // When\n            var stringValue = link.ToString();\n\n            // Then\n            stringValue.ShouldEqual(\"<http://nancyfx.org/>; rel=\\\"up\\\"; parameter\");\n        }\n\n        [Fact]\n        public void ToString_link_with_empty_parameter_should_not_exist_in_string()\n        {\n            // Given\n            var link = new HttpLink(\"http://nancyfx.org/\", \"up\");\n            link.Parameters.Add(string.Empty, null);\n\n            // When\n            var stringValue = link.ToString();\n\n            // Then\n            stringValue.ShouldEqual(\"<http://nancyfx.org/>; rel=\\\"up\\\"\");\n        }\n\n        [Fact]\n        public void ToString_link_with_extension_parameter_should_exist_in_string()\n        {\n            // Given\n            var link = new HttpLink(\"http://nancyfx.org/\", \"up\");\n            link.Parameters.Add(\"ext\", \"extension-param\");\n\n            // When\n            var stringValue = link.ToString();\n\n            // Then\n            stringValue.ShouldEqual(\"<http://nancyfx.org/>; rel=\\\"up\\\"; ext=\\\"extension-param\\\"\");\n        }\n\n        [Fact]\n        public void ToString_link_with_relation_should_exist_in_string()\n        {\n            // Given\n            var link = new HttpLink(\"http://nancyfx.org/\", \"up\");\n\n            // When\n            var stringValue = link.ToString();\n\n            // Then\n            stringValue.ShouldEqual(\"<http://nancyfx.org/>; rel=\\\"up\\\"\");\n        }\n\n        [Fact]\n        public void ToString_link_with_type_should_exist_in_string()\n        {\n            // Given\n            var link = new HttpLink(\"http://nancyfx.org/\", \"up\", \"application/json\");\n\n            // When\n            var stringValue = link.ToString();\n\n            // Then\n            stringValue.ShouldEqual(\"<http://nancyfx.org/>; rel=\\\"up\\\"; type=\\\"application/json\\\"\");\n        }\n\n        [Fact]\n        public void ToString_link_with_whitespace_parameter_should_not_exist_in_string()\n        {\n            // Given\n            var link = new HttpLink(\"http://nancyfx.org/\", \"up\");\n            link.Parameters.Add(\"    \", null);\n\n            // When\n            var stringValue = link.ToString();\n\n            // Then\n            stringValue.ShouldEqual(\"<http://nancyfx.org/>; rel=\\\"up\\\"\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/HttpLinkRelationFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit\n{\n    using System;\n    using Xunit;\n\n    public class HttpLinkRelationFixture\n    {\n        [Fact]\n        public void Different_relations_should_not_be_equal()\n        {\n            // Given\n            var first = new HttpLinkRelation(\"alternate\");\n            var second = new HttpLinkRelation(new Uri(\"http://nancyfx.org/rels/\"), \"home\");\n            var third = new HttpLinkRelation(\"http://nancyfx.org/rels/nancy\");\n\n            // When, Then\n            first.ShouldNotEqual(second);\n            second.ShouldNotEqual(third);\n        }\n\n        [Fact]\n        public void Different_relations_should_not_have_equal_hash_code()\n        {\n            // Given\n            var first = new HttpLinkRelation(\"alternate\");\n            var second = new HttpLinkRelation(new Uri(\"http://nancyfx.org/rels/\"), \"home\");\n            var third = new HttpLinkRelation(\"http://nancyfx.org/rels/nancy\");\n\n            // When\n            var firstHashCode = first.GetHashCode();\n            var secondHashCode = second.GetHashCode();\n            var thirdHashCode = third.GetHashCode();\n\n            // Then\n            firstHashCode.ShouldNotEqual(secondHashCode);\n            secondHashCode.ShouldNotEqual(thirdHashCode);\n        }\n\n        [Fact]\n        public void Iana_relations_with_different_casing_and_prefix_should_all_be_equal()\n        {\n            // Given\n            var first = new HttpLinkRelation(\"AlterNate\");\n            var second = new HttpLinkRelation(\"ALTERNATE\");\n            var third = new HttpLinkRelation(\"alternate\");\n            var fourth = new HttpLinkRelation(HttpLinkRelation.IanaLinkRelationPrefix + \"alternate\");\n\n            // When, Then\n            first.ShouldEqual(second);\n            second.ShouldEqual(third);\n            third.ShouldEqual(fourth);\n        }\n\n        [Fact]\n        public void Iana_relations_with_different_casing_and_prefix_should_have_equal_hash_code()\n        {\n            // Given\n            var first = new HttpLinkRelation(\"AlterNate\");\n            var second = new HttpLinkRelation(\"ALTERNATE\");\n            var third = new HttpLinkRelation(\"alternate\");\n            var fourth = new HttpLinkRelation(HttpLinkRelation.IanaLinkRelationPrefix + \"alternate\");\n\n            // When\n            var firstHashCode = first.GetHashCode();\n            var secondHashCode = second.GetHashCode();\n            var thirdHashCode = third.GetHashCode();\n            var fourthHashCode = fourth.GetHashCode();\n\n            // Then\n            firstHashCode.ShouldEqual(secondHashCode);\n            secondHashCode.ShouldEqual(thirdHashCode);\n            thirdHashCode.ShouldEqual(fourthHashCode);\n        }\n\n        [Fact]\n        public void Parse_null_should_throw_argument_null_exception()\n        {\n            // Given\n            const string relation = null;\n\n            // When\n            var exception = Assert.Throws<ArgumentNullException>(() => HttpLinkRelation.Parse(relation));\n\n            // Then\n            exception.ParamName.ShouldEqual(\"relation\");\n        }\n\n        [Fact]\n        public void Parse_relative_value_should_return_iana_prefixed_link_relation()\n        {\n            // Given\n            const string relation = \"alternate\";\n\n            // When\n            var rel = HttpLinkRelation.Parse(relation);\n\n            // Then\n            rel.ShouldNotBeNull();\n            rel.Prefix.ShouldEqual(HttpLinkRelation.IanaLinkRelationPrefix);\n            rel.Value.ShouldEqual(relation);\n        }\n\n        [Fact]\n        public void Parse_uri_should_return_link_relation()\n        {\n            // Given\n            const string relation = \"http://nancyfx.org/rels/something\";\n\n            // When\n            var rel = HttpLinkRelation.Parse(relation);\n\n            // Then\n            rel.ShouldNotBeNull();\n            rel.Prefix.ShouldEqual(new Uri(\"http://nancyfx.org/rels/\"));\n            rel.Value.ShouldEqual(\"something\");\n        }\n\n        [Fact]\n        public void Parse_uri_with_path_that_ends_with_slash_throws_format_exception()\n        {\n            // Given\n            const string uri = \"http://nancyfx.org/rels/\";\n\n            // When\n            var exception = Assert.Throws<FormatException>(() => HttpLinkRelation.Parse(uri));\n\n            // Then\n            exception.Message.ShouldContain(uri);\n        }\n\n        [Fact]\n        public void Parse_uri_without_path_throws_format_exception()\n        {\n            // Given\n            const string uri = \"http://nancyfx.org/\";\n\n            // When\n            var exception = Assert.Throws<FormatException>(() => HttpLinkRelation.Parse(uri));\n\n            // Then\n            exception.Message.ShouldContain(uri);\n        }\n\n        [Fact]\n        public void Prefix_and_value_on_iana_relation()\n        {\n            // Given, When\n            var rel = new HttpLinkRelation(\"alternate\");\n\n            // Then\n            rel.Prefix.ShouldEqual(HttpLinkRelation.IanaLinkRelationPrefix);\n            rel.Value.ShouldEqual(\"alternate\");\n        }\n\n        [Fact]\n        public void Prefix_and_value_on_non_iana_relation_created_from_prefix_and_value()\n        {\n            // Given\n            var prefix = new Uri(\"http://nancyfx.org/rels/\");\n\n            // When\n            var rel = new HttpLinkRelation(prefix, \"home\");\n\n            // Then\n            rel.Prefix.ShouldEqual(prefix);\n            rel.Value.ShouldEqual(\"home\");\n        }\n\n        [Fact]\n        public void Prefix_and_value_on_non_iana_relation_created_from_string()\n        {\n            // Given\n            const string relValue = \"http://nancyfx.org/rels/home\";\n\n            // When\n            var rel = new HttpLinkRelation(relValue);\n\n            // Then\n            rel.Prefix.ToString().ShouldEqual(\"http://nancyfx.org/rels/\");\n            rel.Value.ShouldEqual(\"home\");\n        }\n\n        [Fact]\n        public void Relation_should_be_equal_to_itself()\n        {\n            // Given\n            var rel = new HttpLinkRelation(\"alternate\");\n\n            // When, Then\n            rel.ShouldEqual(rel);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/HttpMultipartBoundaryFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit\r\n{\r\n    using System.IO;\r\n    using System.Text;\r\n\r\n    using Xunit;\r\n\r\n    public class HttpMultipartBoundaryFixture\r\n    {\r\n        [Fact]\r\n        public void Should_extract_name_from_boundary_headers()\r\n        {\r\n            // Given\r\n            var stream = BuildStreamForSingleFile(\r\n                \"name\", \r\n                null,\r\n                null,\r\n                null\r\n                );\r\n\r\n            // When\r\n            var boundary = new HttpMultipartBoundary(stream);\r\n\r\n            // Then\r\n            boundary.Name.ShouldEqual(\"name\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_handle_non_ASCII_filenames()\r\n        {\r\n            // Given\r\n            var stream = BuildStreamForSingleFile(\r\n                \"file_content\",\r\n                \"Данные.txt\",\r\n                \"application/octet-stream\",\r\n                null\r\n                );\r\n\r\n            // When\r\n            var boundary = new HttpMultipartBoundary(stream);\r\n\r\n            // Then\r\n            boundary.Filename.ShouldEqual(\"Данные.txt\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_handle_presence_of_filenamestar_param_in_content_disposition_header()\r\n        {\r\n            // Given\r\n            var contentDispositionHeader = BuildContentDispositionHeader(\r\n                \"file_content\",\r\n                \"sample.txt\",\r\n                \"utf-8''foo-%c3%a4.html\",\r\n                unquotedFilenameValue: true\r\n                );\r\n\r\n            var stream = BuildStreamForSingleFile(\r\n                contentDispositionHeader,\r\n                \"application/octet-stream\",\r\n                null\r\n                );\r\n\r\n            // When\r\n            var boundary = new HttpMultipartBoundary(stream);\r\n\r\n            // Then\r\n            boundary.Filename.ShouldEqual(\"sample.txt\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_handle_utf_8_filenamestar_param()\r\n        {\r\n            // Given\r\n            var contentDispositionHeader = BuildContentDispositionHeader(\r\n            \"file_content\",\r\n            \"utf-8''file_%C3%A9%C3%A0%C3%A2%C3%A8%C3%A9%C3%A7.txt\");\r\n            var stream = BuildStreamForSingleFile(\r\n            contentDispositionHeader,\r\n            \"application/octet-stream\",\r\n            null\r\n            );\r\n\r\n            // When\r\n            var boundary = new HttpMultipartBoundary(stream);\r\n\r\n            // Then\r\n            boundary.Filename.ShouldEqual(\"file_éàâèéç.txt\");\r\n\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_file_name_to_empty_when_it_could_not_be_found_in_header()\r\n        {\r\n            // Given\r\n            var stream = BuildStreamForSingleFile(\r\n                \"name\",\r\n                null,\r\n                null,\r\n                null\r\n                );\r\n\r\n            // When\r\n            var boundary = new HttpMultipartBoundary(stream);\r\n\r\n            // Then\r\n            boundary.Filename.ShouldBeEmpty();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_extract_file_name_from_boundary_headers_when_available()\r\n        {\r\n            // Given\r\n            var stream = BuildStreamForSingleFile(\r\n                \"name\",\r\n                \"sample.txt\",\r\n                null,\r\n                null\r\n                );\r\n\r\n            // When\r\n            var boundary = new HttpMultipartBoundary(stream);\r\n\r\n            // Then\r\n            boundary.Filename.ShouldEqual(\"sample.txt\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_content_type_to_empty_when_it_could_not_be_found_in_header()\r\n        {\r\n            // Given\r\n            var stream = BuildStreamForSingleFile(\r\n                \"name\",\r\n                null,\r\n                null,\r\n                null\r\n                );\r\n\r\n            // When\r\n            var boundary = new HttpMultipartBoundary(stream);\r\n\r\n            // Then\r\n            boundary.ContentType.ShouldBeEmpty();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_extract_content_type_from_boundary_headers_when_available()\r\n        {\r\n            // Given\r\n            var stream = BuildStreamForSingleFile(\r\n                \"name\",\r\n                null,\r\n                \"text/plain\",\r\n                null\r\n                );\r\n\r\n            // When\r\n            var boundary = new HttpMultipartBoundary(stream);\r\n\r\n            // Then\r\n            boundary.ContentType.ShouldEqual(\"text/plain\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_extract_value_from_boundary_when_available()\r\n        {\r\n            // Given\r\n            var stream = BuildStreamForSingleFile(\r\n                \"name\",\r\n                \"sample.txt\",\r\n                \"text/plain\",\r\n                \"This is some contents\"\r\n                );\r\n\r\n            // When\r\n            var boundary = new HttpMultipartBoundary(stream);\r\n\r\n            // Then\r\n            GetValueAsString(boundary.Value).ShouldEqual(\"This is some contents\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_extract_empty_value_from_boundary_when_not_available()\r\n        {\r\n            // Given\r\n            var stream = BuildStreamForSingleFile(\r\n                \"name\",\r\n                \"sample.txt\",\r\n                \"text/plain\",\r\n                null\r\n                );\r\n\r\n            // When\r\n            var boundary = new HttpMultipartBoundary(stream);\r\n\r\n            // Then\r\n            GetValueAsString(boundary.Value).ShouldBeEmpty();\r\n        }\r\n\r\n        private static string GetValueAsString(Stream value)\r\n        {\r\n            return new StreamReader(value, Encoding.UTF8).ReadToEnd();\r\n        }\r\n\r\n        private static HttpMultipartSubStream BuildStreamForSingleFile(string contentDispositionHeader, string contentType, string content)\r\n        {\r\n            var memory = new MemoryStream(BuildBoundaryWithSingleFile(contentDispositionHeader, contentType, content));\r\n\r\n            return new HttpMultipartSubStream(memory, 0, memory.Length);\r\n        }\r\n\r\n        private static HttpMultipartSubStream BuildStreamForSingleFile(string name, string filename, string contentType, string content)\r\n        {\r\n            return BuildStreamForSingleFile(BuildContentDispositionHeader(name, filename), contentType, content);\r\n        }\r\n\r\n        private static byte[] BuildBoundaryWithSingleFile(string contentDispositionHeader, string contentType, string content)\r\n        {\r\n            var boundaryBuilder = new StringBuilder();\r\n\r\n            boundaryBuilder.Append(contentDispositionHeader);\r\n            boundaryBuilder.Append('\\r');\r\n            boundaryBuilder.Append('\\n');\r\n\r\n            if (!string.IsNullOrEmpty(contentType))\r\n            {\r\n                boundaryBuilder.AppendFormat(\"Content-Type: {0}\", contentType);\r\n                boundaryBuilder.Append('\\r');\r\n                boundaryBuilder.Append('\\n');\r\n            }\r\n\r\n            if (!string.IsNullOrEmpty(content))\r\n            {\r\n                boundaryBuilder.Append('\\r');\r\n                boundaryBuilder.Append('\\n');\r\n                boundaryBuilder.Append(content);\r\n            }\r\n\r\n            return Encoding.UTF8.GetBytes(boundaryBuilder.ToString());\r\n        }\r\n\r\n        private static string BuildContentDispositionHeader(string name, string filename = null, string filenamestar = null,\r\n         bool unquotedFilenameValue = false)\r\n        {\r\n            var headerBuilder = new StringBuilder();\r\n\r\n            headerBuilder.AppendFormat(\"Content-Disposition: form-data; name=\\\"{0}\\\"\", name);\r\n\r\n            if (!string.IsNullOrEmpty(filename))\r\n            {\r\n                headerBuilder.AppendFormat(\"; filename={0}\",\r\n                    string.Format(unquotedFilenameValue ? \"{0}\" : \"\\\"{0}\\\"\", filename));\r\n            }\r\n\r\n            if (!string.IsNullOrEmpty(filenamestar))\r\n            {\r\n                headerBuilder.AppendFormat(\"; filename*={0}\", filenamestar);\r\n            }\r\n\r\n            return headerBuilder.ToString();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/HttpMultipartBufferFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit\r\n{\r\n    using System.Text;\r\n\r\n    using Xunit;\r\n\r\n    public class HttpMultipartBufferFixture\r\n    {\r\n        private HttpMultipartBuffer buffer;\r\n        private readonly byte[] boundary;\r\n\r\n        public HttpMultipartBufferFixture()\r\n        {\r\n            this.boundary = GetBoundaryAsBytes();\r\n            this.buffer = new HttpMultipartBuffer(this.boundary, new byte[1]);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_have_same_lenght_as_boundary()\r\n        {\r\n            // Given, When, Then\r\n            this.buffer.Length.ShouldEqual(this.boundary.Length);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_for_isfull_when_less_contents_than_length_has_been_added()\r\n        {\r\n            // Given, When\r\n            for (var counter = 0; counter < this.boundary.Length - 1; counter++)\r\n            {\r\n                this.buffer.Insert(67);\r\n            }\r\n\r\n            // Then\r\n            this.buffer.IsFull.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_for_isfull_when_same_amount_of_contents_as_length_has_been_added()\r\n        {\r\n            // Given, When\r\n            foreach (var t in this.boundary)\r\n            {\r\n                this.buffer.Insert(67);\r\n            }\r\n\r\n            // Then\r\n            this.buffer.IsFull.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_for_isboundary_when_boundary_does_not_exist_in_buffer()\r\n        {\r\n            // Given, When, Then\r\n            this.buffer.IsBoundary.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_for_isboundary_when_boundary_does_exist_in_buffer()\r\n        {\r\n            // Given, When\r\n            foreach (var t in this.boundary)\r\n            {\r\n                this.buffer.Insert(t);\r\n            }\r\n\r\n            //Then\r\n            this.buffer.IsBoundary.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_reset_buffer_when_reset_is_called()\r\n        {\r\n            // Given\r\n            this.buffer.Insert(10);\r\n\r\n            // When\r\n            this.buffer.Reset();\r\n\r\n            foreach (var t in this.boundary)\r\n            {\r\n                this.buffer.Insert(t);\r\n            }\r\n\r\n            // Then\r\n            this.buffer.IsBoundary.ShouldBeTrue();\r\n        }\r\n\r\n        private static byte[] GetBoundaryAsBytes()\r\n        {\r\n            var boundaryBuilder = new StringBuilder();\r\n\r\n            boundaryBuilder.Append(\"--\");\r\n            boundaryBuilder.Append(\"----NancyFormBoundary\");\r\n            boundaryBuilder.Append('\\r');\r\n            boundaryBuilder.Append('\\n');\r\n\r\n            var bytes =\r\n                Encoding.ASCII.GetBytes(boundaryBuilder.ToString());\r\n\r\n            return bytes;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/HttpMultipartFixture.cs",
    "content": "namespace Nancy.Tests.Unit\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Text;\r\n\r\n    using Nancy.IO;\r\n\r\n    using Xunit;\r\n\r\n    public class HttpMultipartFixture\r\n    {\r\n        private const string Boundary = \"----NancyFormBoundary\";\r\n\r\n        [Fact]\r\n        public void Should_locate_all_boundaries()\r\n        {\r\n            // Given\r\n            var stream = BuildInputStream(null, 10);\r\n            var multipart = new HttpMultipart(stream, Boundary);\r\n\r\n            // When\r\n            var boundaries = multipart.GetBoundaries();\r\n\r\n            // Then\r\n            boundaries.Count().ShouldEqual(10);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_locate_boundary_when_it_is_not_at_the_beginning_of_stream()\r\n        {\r\n            // Given\r\n            var stream = BuildInputStream(\"some padding in the stream\", 1);\r\n            var multipart = new HttpMultipart(stream, Boundary);\r\n\r\n            // When\r\n            var boundaries = multipart.GetBoundaries();\r\n\r\n            // Then\r\n            boundaries.Count().ShouldEqual(1);\r\n        }\r\n\r\n        //http://www.freesoft.org/CIE/RFC/1521/16.htm\r\n        [Fact]\r\n        public void Should_preserve_the_content_of_the_file_even_though_there_is_data_at_the_end_of_the_multipart()\r\n        {\r\n            // Given\r\n            var expected = \"wazaa\";\r\n\r\n            var stream = new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>>\r\n            {\r\n                { \"sample.txt\", new Tuple<string, string, string>(\"content/type\", expected, \"name\")}\r\n            }, null, \"epilogue\"));\r\n\r\n            var headers = new Dictionary<string, IEnumerable<string>>\r\n            {\r\n                { \"content-type\", new[] { \"multipart/form-data; boundary=----NancyFormBoundary\" } }\r\n            };\r\n\r\n            // When\r\n            var request = new Request(\"POST\", new Url { Path = \"/\" }, CreateRequestStream(stream), headers);\r\n            \r\n            // Then\r\n            var fileValue = request.Files.Single().Value;\r\n            var actualBytes = new byte[fileValue.Length];\r\n            fileValue.Read(actualBytes, 0, (int)fileValue.Length);\r\n\r\n            var actual = Encoding.ASCII.GetString(actualBytes);\r\n\r\n            actual.ShouldEqual(expected);\r\n        }\r\n\r\n        //http://www.freesoft.org/CIE/RFC/1521/16.htm\r\n        [Fact]\r\n        public void Should_have_a_file_with_the_correct_data_in_it()\r\n        {\r\n            // Given\r\n            var expected = \"wazaa\";\r\n\r\n            var stream = new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>>\r\n            {\r\n                { \"sample.txt\", new Tuple<string, string, string>(\"content/type\", expected, \"name\")}\r\n            }));\r\n\r\n            var headers = new Dictionary<string, IEnumerable<string>>\r\n            {\r\n                { \"content-type\", new[] { \"multipart/form-data; boundary=----NancyFormBoundary\" } }\r\n            };\r\n\r\n            // When\r\n            var request = new Request(\"POST\", new Url { Path = \"/\", Scheme = \"http\" }, CreateRequestStream(stream), headers);\r\n\r\n\r\n            // Then\r\n            var fileValue = request.Files.Single().Value;\r\n            var actualBytes = new byte[fileValue.Length];\r\n            fileValue.Read(actualBytes, 0, (int)fileValue.Length);\r\n\r\n            var actual = Encoding.ASCII.GetString(actualBytes);\r\n\r\n            actual.ShouldEqual(expected);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_have_a_file_with_the_correct_data_in_it_using_quotes()\r\n        {\r\n            // Given\r\n            var expected = \"wazaa\";\r\n\r\n            var stream = new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>>\r\n            {\r\n                { \"sample.txt\", new Tuple<string, string, string>(\"content/type\", expected, \"name\")}\r\n            }, null, null, true));\r\n\r\n            var headers = new Dictionary<string, IEnumerable<string>>\r\n            {\r\n                { \"content-type\", new[] { \"multipart/form-data; boundary=\\\"----NancyFormBoundary\\\"\" } }\r\n            };\r\n\r\n            // When\r\n            var request = new Request(\"POST\", new Url { Path = \"/\", Scheme = \"http\" }, CreateRequestStream(stream), headers);\r\n\r\n\r\n            // Then\r\n            var fileValue = request.Files.Single().Value;\r\n            var actualBytes = new byte[fileValue.Length];\r\n            fileValue.Read(actualBytes, 0, (int)fileValue.Length);\r\n\r\n            var actual = Encoding.ASCII.GetString(actualBytes);\r\n\r\n            actual.ShouldEqual(expected);\r\n        }\r\n\r\n        //http://www.freesoft.org/CIE/RFC/1521/16.htm\r\n        [Fact]\r\n        public void Should_preserve_the_content_of_the_file_even_though_there_is_data_at_the_beginning_of_the_multipart()\r\n        {\r\n            // Given\r\n            var expected = \"wazaa\";\r\n\r\n            var stream = new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>>\r\n            {\r\n                { \"sample.txt\", new Tuple<string, string, string>(\"content/type\", expected, \"name\")}\r\n            }, \"preamble\", null));\r\n\r\n            var headers = new Dictionary<string, IEnumerable<string>>\r\n            {\r\n                { \"content-type\", new[] { \"multipart/form-data; boundary=----NancyFormBoundary\" } }\r\n            };\r\n\r\n            // When\r\n            var request = new Request(\"POST\", new Url { Path = \"/\", Scheme = \"http\" }, CreateRequestStream(stream), headers);\r\n\r\n\r\n            // Then\r\n            var fileValue = request.Files.Single().Value;\r\n            var actualBytes = new byte[fileValue.Length];\r\n            fileValue.Read(actualBytes, 0, (int)fileValue.Length);\r\n\r\n            var actual = Encoding.ASCII.GetString(actualBytes);\r\n\r\n            actual.ShouldEqual(expected);\r\n        }\r\n\r\n        [Fact]\r\n        public void If_the_stream_ends_with_carriage_return_characters_it_should_not_affect_the_multipart()\r\n        {\r\n            // Given\r\n            var expected = \"#!/usr/bin/env rake\\n# Add your own tasks in files placed in lib/tasks ending in .rake,\\n# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.\\n\\nrequire File.expand_path('../config/application', __FILE__)\\n\\nOnlinebackupWebclient::Application.load_tasks\";\r\n            var data = string.Format(\"--69989\\r\\nContent-Disposition: form-data; name=\\\"Stream\\\"; filename=\\\"Rakefile\\\"\\r\\nContent-Type: text/plain\\r\\n\\r\\n{0}\\r\\n--69989--\\r\\n\", expected);\r\n            var stream = new MemoryStream(Encoding.ASCII.GetBytes(data));\r\n            \r\n            var headers = new Dictionary<string, IEnumerable<string>>\r\n            {\r\n                {\"Content-Type\", new [] { \"multipart/form-data; boundary=69989\"} },\r\n                {\"Content-Length\", new [] {\"403\"} }\r\n            };\r\n\r\n            // When\r\n            var request = new Request(\"POST\", new Url { Path = \"/\", Scheme = \"http\" }, CreateRequestStream(stream), headers);\r\n            \r\n            // Then\r\n            var fileValue = request.Files.Single().Value;\r\n            var actualBytes = new byte[fileValue.Length];\r\n            fileValue.Read(actualBytes, 0, (int)fileValue.Length);\r\n\r\n            var actual = Encoding.ASCII.GetString(actualBytes);\r\n\r\n            actual.ShouldEqual(expected);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_limit_the_number_of_boundaries()\r\n        {\r\n            // Given\r\n            var stream = BuildInputStream(null, StaticConfiguration.RequestQueryFormMultipartLimit + 10);\r\n            var multipart = new HttpMultipart(stream, Boundary);\r\n\r\n            // When\r\n            var boundaries = multipart.GetBoundaries();\r\n\r\n            // Then\r\n            boundaries.Count().ShouldEqual(StaticConfiguration.RequestQueryFormMultipartLimit);\r\n        }\r\n\r\n        //\r\n        private static HttpMultipartSubStream BuildInputStream(string padding, int numberOfBoundaries)\r\n        {\r\n            return BuildInputStream(padding, numberOfBoundaries, (i,b) => InsertRandomContent(b), null);\r\n        }\r\n\r\n        private static HttpMultipartSubStream BuildInputStream(string padding, int numberOfBoundaries, Action<int, StringBuilder> insertContent, string dataAtTheEnd)\r\n        {\r\n            var memory = new MemoryStream(BuildRandomBoundaries(padding, numberOfBoundaries, insertContent, dataAtTheEnd));\r\n\r\n            return new HttpMultipartSubStream(memory, 0, memory.Length);\r\n        }\r\n\r\n        private static byte[] BuildRandomBoundaries(string padding, int numberOfBoundaries, Action<int, StringBuilder> insertContent, string dataAtTheEnd)\r\n        {\r\n            var boundaryBuilder = new StringBuilder();\r\n\r\n            if (!string.IsNullOrEmpty(padding))\r\n            {\r\n                boundaryBuilder.Append(padding);\r\n                boundaryBuilder.Append('\\r');\r\n                boundaryBuilder.Append('\\n');\r\n            }\r\n\r\n            for (var index = 0; index < numberOfBoundaries; index++)\r\n            {\r\n                boundaryBuilder.Append(\"--\");\r\n                boundaryBuilder.Append(\"----NancyFormBoundary\");\r\n                boundaryBuilder.Append('\\r');\r\n                boundaryBuilder.Append('\\n');\r\n\r\n                insertContent(index, boundaryBuilder);\r\n\r\n                boundaryBuilder.Append('\\r');\r\n                boundaryBuilder.Append('\\n');\r\n            }\r\n\r\n            boundaryBuilder.Append('\\r');\r\n            boundaryBuilder.Append('\\n');\r\n            boundaryBuilder.AppendFormat(\"------NancyFormBoundary--{0}\", dataAtTheEnd);\r\n\r\n            var bytes = Encoding.ASCII.GetBytes(boundaryBuilder.ToString());\r\n            return bytes;\r\n        }\r\n\r\n        private static void InsertRandomContent(StringBuilder builder)\r\n        {\r\n            var random = \r\n                new Random((int)DateTime.Now.Ticks);\r\n\r\n            for (var index = 0; index < random.Next(1, 200); index++)\r\n            {\r\n                builder.Append((char) random.Next(0, 255));\r\n            }\r\n        }\r\n\r\n        private static byte[] BuildMultipartFileValues(Dictionary<string, Tuple<string, string, string>> formValues, string preamble, string epilogue, bool surroundWithQuotes = false)\r\n        {\r\n            var boundaryBuilder = new StringBuilder();\r\n\r\n            boundaryBuilder.Append(preamble);\r\n            foreach (var key in formValues.Keys)\r\n            {\r\n                var name = key;\r\n                var filename = formValues[key].Item3;\r\n                if (surroundWithQuotes)\r\n                {\r\n                    name = \"\\\"\" + name + \"\\\"\";\r\n                    filename = \"\\\"\" + filename + \"\\\"\";   \r\n                }\r\n\r\n                boundaryBuilder.Append('\\r');\r\n                boundaryBuilder.Append('\\n');\r\n                boundaryBuilder.Append(\"--\");\r\n                boundaryBuilder.Append(\"----NancyFormBoundary\");\r\n                boundaryBuilder.Append('\\r');\r\n                boundaryBuilder.Append('\\n');\r\n                boundaryBuilder.AppendFormat(\"Content-Disposition: form-data; name={1}; filename={0}\", name, filename);\r\n                boundaryBuilder.Append('\\r');\r\n                boundaryBuilder.Append('\\n');\r\n                boundaryBuilder.AppendFormat(\"Content-Type: {0}\", formValues[key].Item1);\r\n                boundaryBuilder.Append('\\r');\r\n                boundaryBuilder.Append('\\n');\r\n                boundaryBuilder.Append('\\r');\r\n                boundaryBuilder.Append('\\n');\r\n                boundaryBuilder.Append(formValues[key].Item2);\r\n            }\r\n\r\n            boundaryBuilder.Append('\\r');\r\n            boundaryBuilder.Append('\\n');\r\n            boundaryBuilder.AppendFormat(\"------NancyFormBoundary--{0}\", epilogue);\r\n\r\n            var bytes =\r\n                Encoding.ASCII.GetBytes(boundaryBuilder.ToString());\r\n\r\n            return bytes;\r\n        }\r\n\r\n        private static RequestStream CreateRequestStream()\r\n        {\r\n            return CreateRequestStream(new MemoryStream());\r\n        }\r\n\r\n        private static RequestStream CreateRequestStream(Stream stream)\r\n        {\r\n            return RequestStream.FromStream(stream);\r\n        }\r\n\r\n        private static byte[] BuildMultipartFileValues(Dictionary<string, Tuple<string, string, string>> formValues)\r\n        {\r\n            return BuildMultipartFileValues(formValues, null, null);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/IO/RequestStreamFixture.cs",
    "content": "namespace Nancy.Tests.Unit.IO\r\n{\r\n    using System;\r\n    using System.IO;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Nancy.IO;\r\n\r\n    using Xunit;\r\n\r\n    public class RequestStreamFixture\r\n    {\r\n        [Fact]\r\n        public void Should_not_dispose_wrapped_stream_when_not_switched()\r\n        {\r\n            // Given\r\n            var stream = new ConfigurableMemoryStream();\r\n            var instance = RequestStream.FromStream(stream, 0, 1, true);\r\n\r\n            // When\r\n            instance.Dispose();\r\n\r\n            // Then\r\n            stream.HasBeenDisposed.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_move_non_seekable_stream_into_seekable_stream_when_stream_switching_is_disabled()\r\n        {\r\n            // Given\r\n            var stream = new ConfigurableMemoryStream(Seekable: false);\r\n\r\n            // When\r\n            var result = RequestStream.FromStream(stream, 0, 1, true);\r\n\r\n            // Then\r\n            result.CanSeek.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_move_stream_out_of_memory_if_longer_than_threshold_and_stream_switching_is_enabled()\r\n        {\r\n            // Given\r\n            var inputStream = new MemoryStream(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });\r\n\r\n            // When\r\n            var result = RequestStream.FromStream(inputStream, 0, 4, false);\r\n\r\n            // Then\r\n            result.IsInMemory.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_move_stream_out_of_memory_if_longer_than_threshold_and_stream_switching_is_disabled()\r\n        {\r\n            // Given\r\n            var inputStream = new MemoryStream(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });\r\n\r\n            // When\r\n            var result = RequestStream.FromStream(inputStream, 0, 4, true);\r\n\r\n            // Then\r\n            result.IsInMemory.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_invalidoperationexception_when_created_with_non_readable_stream()\r\n        {\r\n            // Given\r\n            var stream = new ConfigurableMemoryStream(Readable: false);\r\n\r\n            // When\r\n            var exception = Record.Exception(() => RequestStream.FromStream(stream));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<InvalidOperationException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_argumentoutofrangeexception_when_expected_lenght_is_less_than_zero()\r\n        {\r\n            // Given\r\n            var stream = new ConfigurableMemoryStream();\r\n            const int expectedLength = -1;\r\n\r\n            // When\r\n            var exception = Record.Exception(() => RequestStream.FromStream(stream, expectedLength));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ArgumentOutOfRangeException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_argumentoutofrangeexception_when_thresholdLength_is_less_than_zero()\r\n        {\r\n            // Given\r\n            var stream = new ConfigurableMemoryStream();\r\n            const int tresholdLength = -1;\r\n\r\n            // When\r\n            var exception = Record.Exception(() => RequestStream.FromStream(stream, 0, tresholdLength));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ArgumentOutOfRangeException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_work_even_with_a_non_seekable_stream()\r\n        {\r\n            // Given\r\n            var stream = new ConfigurableMemoryStream(Seekable: false);\r\n            var request = RequestStream.FromStream(stream, 0, 1, false);\r\n\r\n            // When\r\n            var result = request.CanRead;\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_when_queried_about_supporting_reading()\r\n        {\r\n            // Given\r\n            var stream = new ConfigurableMemoryStream();\r\n            var request = RequestStream.FromStream(stream, 0, 1, false);\r\n\r\n            // When\r\n            var result = request.CanRead;\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_when_queried_about_supporting_writing()\r\n        {\r\n            // Given\r\n            var stream = new ConfigurableMemoryStream();\r\n            var request = RequestStream.FromStream(stream, 0, 1, false);\r\n\r\n            // When\r\n            var result = request.CanWrite;\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_when_queried_about_supporting_seeking()\r\n        {\r\n            // Given\r\n            var stream = new ConfigurableMemoryStream();\r\n            var request = RequestStream.FromStream(stream, 0, 1, false);\r\n\r\n            // When\r\n            var result = request.CanSeek;\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_when_queried_about_supporting_timeout()\r\n        {\r\n            // Given\r\n            var stream = new ConfigurableMemoryStream();\r\n            var request = RequestStream.FromStream(stream, 0, 1, false);\r\n\r\n            // When\r\n            var result = request.CanTimeout;\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_length_of_underlaying_stream()\r\n        {\r\n            // Given\r\n            var stream = new ConfigurableMemoryStream(Length: 1234L);\r\n            var request = RequestStream.FromStream(stream, 0, 1235, false);\r\n\r\n            // When\r\n            var result = request.Length;\r\n\r\n            // Then\r\n            result.ShouldEqual(1234L);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_position_of_underlaying_stream()\r\n        {\r\n            // Given\r\n            var stream = new ConfigurableMemoryStream();\r\n            var request = RequestStream.FromStream(stream, 0, 1, false);\r\n            stream.Position = 1234L;\r\n\r\n            // When\r\n            var result = request.Position;\r\n\r\n            // Then\r\n            result.ShouldEqual(1234L);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_position_of_underlaying_stream()\r\n        {\r\n            // Given\r\n            var stream = new ConfigurableMemoryStream(Length: 2000L);\r\n            var request = RequestStream.FromStream(stream, 2000L, 2001L, false);\r\n\r\n            // When\r\n            request.Position = 1234L;\r\n\r\n            // Then\r\n            stream.Position.ShouldEqual(1234L);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_argumentoutofrangexception_when_setting_position_to_less_than_zero()\r\n        {\r\n            // Given\r\n            var stream = new ConfigurableMemoryStream();\r\n            var request = RequestStream.FromStream(stream, 2000L, 2001L, false);\r\n\r\n            // When\r\n            var exception = Record.Exception(() => request.Position = -1);\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<InvalidOperationException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_invalidoperationexception_when_position_is_set_to_greater_than_length_of_stream()\r\n        {\r\n            // Given\r\n            var stream = new ConfigurableMemoryStream(Length: 100L);\r\n            var request = RequestStream.FromStream(stream, 0, 1, false);\r\n\r\n            // When\r\n            var exception = Record.Exception(() => request.Position = 1000);\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<InvalidOperationException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_flush_underlaying_stream()\r\n        {\r\n            // Given\r\n            var stream = new ConfigurableMemoryStream();\r\n            var request = RequestStream.FromStream(stream, 0, 1, false);\r\n\r\n            // When\r\n            request.Flush();\r\n\r\n            // Then\r\n            stream.HasBeenFlushed.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_notsupportedexception_when_setting_length()\r\n        {\r\n            // Given\r\n            var stream = new ConfigurableMemoryStream();\r\n            var request = RequestStream.FromStream(stream, 0, 1, false);\r\n\r\n            // When\r\n            var exception = Record.Exception(() => request.SetLength(10L));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<NotSupportedException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_position_of_underlaying_stream_to_zero_when_created()\r\n        {\r\n            // Given\r\n            var stream = new ConfigurableMemoryStream(Position: 10L);\r\n\r\n            // When\r\n            var request = RequestStream.FromStream(stream, 0, 1, false);\r\n\r\n            // Then\r\n            stream.Position.ShouldEqual(0L);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_seek_in_the_underlaying_stream_when_seek_is_called()\r\n        {\r\n            // Given\r\n            var stream = new ConfigurableMemoryStream();\r\n            var request = RequestStream.FromStream(stream, 0, 1, false);\r\n\r\n            // When\r\n            request.Seek(10L, SeekOrigin.Current);\r\n\r\n            // Then\r\n            stream.HasBeenSeeked.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_the_new_position_of_the_underlaying_stream_when_seek_is_called()\r\n        {\r\n            // Given\r\n            var stream = CreateFakeStream();\r\n            A.CallTo(() => stream.Seek(A<long>.Ignored, A<SeekOrigin>.Ignored)).Returns(100L);\r\n            var request = RequestStream.FromStream(stream, 0, 1, false);\r\n\r\n            // When\r\n            var result = request.Seek(10L, SeekOrigin.Current);\r\n\r\n            // Then\r\n            result.ShouldEqual(100L);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_read_byte_from_underlaying_stream_when_reading_byte()\r\n        {\r\n            // Given\r\n            var stream = CreateFakeStream();\r\n            var request = RequestStream.FromStream(stream, 0, 1, false);\r\n\r\n            // When\r\n            request.ReadByte();\r\n\r\n            // Then\r\n            A.CallTo(() => stream.ReadByte()).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_read_byte_from_underlaying_stream_when_readbyte_is_called()\r\n        {\r\n            // Given\r\n            var stream = CreateFakeStream();\r\n            A.CallTo(() => stream.ReadByte()).Returns(5);\r\n            var request = RequestStream.FromStream(stream, 0, 1, false);\r\n\r\n            // When\r\n            var result = request.ReadByte();\r\n\r\n            // Then\r\n            result.ShouldEqual(5);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_read_from_underlaying_stream_when_read_is_called()\r\n        {\r\n            // Given\r\n            var stream = CreateFakeStream();\r\n            var buffer = new byte[1];\r\n            var request = RequestStream.FromStream(stream, 0, 1, false);\r\n\r\n            // When\r\n            request.Read(buffer, 0, buffer.Length);\r\n\r\n            // Then\r\n            A.CallTo(() => stream.Read(buffer, 0, buffer.Length)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_result_from_reading_underlaying_stream()\r\n        {\r\n            // Given\r\n            var stream = CreateFakeStream();\r\n            var buffer = new byte[1];\r\n            var request = RequestStream.FromStream(stream, 0, 1, false);\r\n            A.CallTo(() => stream.Read(buffer, 0, buffer.Length)).Returns(3);\r\n\r\n            // When\r\n            var result = request.Read(buffer, 0, buffer.Length);\r\n\r\n            // Then\r\n            result.ShouldEqual(3);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_write_to_underlaying_stream_when_write_is_called()\r\n        {\r\n            // Given\r\n            var stream = CreateFakeStream();\r\n            var buffer = new byte[1];\r\n            var request = RequestStream.FromStream(stream, 0, 1, false);\r\n\r\n            // When\r\n            request.Write(buffer, 0, buffer.Length);\r\n\r\n            // Then\r\n            A.CallTo(() => stream.Write(buffer, 0, buffer.Length)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_no_longer_be_in_memory_if_expected_length_is_greater_or_equal_to_threshold_length()\r\n        {\r\n            // Given\r\n            var stream = CreateFakeStream();\r\n            \r\n            // When\r\n            var request = RequestStream.FromStream(stream, 1, 0, false);\r\n\r\n            // Then\r\n            request.IsInMemory.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_no_longer_be_in_memory_when_more_bytes_have_been_written_to_stream_then_size_of_the_threshold_and_stream_swapping_is_enabled()\r\n        {\r\n            // Given\r\n            var stream = CreateFakeStream();\r\n            var buffer = new byte[100];\r\n            var request = RequestStream.FromStream(stream, 0, 10, false);\r\n            A.CallTo(() => stream.Length).Returns(100);\r\n\r\n            // When\r\n            request.Write(buffer, 0, buffer.Length);\r\n\r\n            // Then\r\n            request.IsInMemory.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_still_be_in_memory_when_more_bytes_have_been_written_to_stream_than_size_of_threshold_and_stream_swapping_is_disabled()\r\n        {\r\n            // Given\r\n            var stream = CreateFakeStream();\r\n            var buffer = new byte[100];\r\n            var request = RequestStream.FromStream(stream, 0, 10, true);\r\n            A.CallTo(() => stream.Length).Returns(100);\r\n\r\n            // When\r\n            request.Write(buffer, 0, buffer.Length);\r\n\r\n            // Then\r\n            request.IsInMemory.ShouldBeTrue();\r\n        }\r\n\r\n#if !CORE // BeginRead, EndRead, BeginWrite, EndWrite don't exist in .NET Core\r\n        [Fact]\r\n        public void Should_call_beginread_on_underlaying_stream_when_beginread_is_called()\r\n        {\r\n            // Given\r\n            var stream = CreateFakeStream();\r\n            var buffer = new byte[10];\r\n            AsyncCallback callback = x => { };\r\n            var state = new object();\r\n            var request = RequestStream.FromStream(stream, 0, 10, true);\r\n\r\n            // When\r\n            request.BeginRead(buffer, 0, buffer.Length, callback, state);\r\n\r\n            // Then\r\n            A.CallTo(() => stream.BeginRead(buffer, 0, buffer.Length, callback, state)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_result_from_underlaying_beginread_when_beginread_is_called()\r\n        {\r\n            // Given\r\n            var stream = CreateFakeStream();\r\n            var buffer = new byte[10];\r\n            var asyncResult = A.Fake<IAsyncResult>();\r\n            AsyncCallback callback = x => { };\r\n            var state = new object();\r\n            var request = RequestStream.FromStream(stream, 0, 10, true);\r\n            A.CallTo(() => stream.BeginRead(buffer, 0, buffer.Length, callback, state)).Returns(asyncResult);\r\n\r\n            // When\r\n            var result = request.BeginRead(buffer, 0, buffer.Length, callback, state);\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(asyncResult);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_call_beginwrite_on_underlaying_stream_when_beginwrite_is_called()\r\n        {\r\n            // Given\r\n            var stream = CreateFakeStream();\r\n            var buffer = new byte[10];\r\n            AsyncCallback callback = x => { };\r\n            var state = new object();\r\n            var request = RequestStream.FromStream(stream, 0, 10, true);\r\n\r\n            // When\r\n            request.BeginWrite(buffer, 0, buffer.Length, callback, state);\r\n\r\n            // Then\r\n            A.CallTo(() => stream.BeginWrite(buffer, 0, buffer.Length, callback, state)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_result_from_underlaying_beginwrite_when_beginwrite_is_called()\r\n        {\r\n            // Given\r\n            var stream = CreateFakeStream();\r\n            var buffer = new byte[10];\r\n            var asyncResult = A.Fake<IAsyncResult>();\r\n            AsyncCallback callback = x => { };\r\n            var state = new object();\r\n            var request = RequestStream.FromStream(stream, 0, 10, true);\r\n            A.CallTo(() => stream.BeginWrite(buffer, 0, buffer.Length, callback, state)).Returns(asyncResult);\r\n\r\n            // When\r\n            var result = request.BeginWrite(buffer, 0, buffer.Length, callback, state);\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(asyncResult);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_call_endread_on_underlaying_stream_when_endread_is_called()\r\n        {\r\n            // Given\r\n            var stream = CreateFakeStream();\r\n            var asyncResult = A.Fake<IAsyncResult>();\r\n            var request = RequestStream.FromStream(stream, 0, 10, true);\r\n\r\n            // When\r\n            request.EndRead(asyncResult);\r\n\r\n            // Then\r\n            A.CallTo(() => stream.EndRead(asyncResult)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_result_from_underlaying_endread_when_endread_is_called()\r\n        {\r\n            // Given\r\n            var stream = CreateFakeStream();\r\n            var asyncResult = A.Fake<IAsyncResult>();\r\n            var request = RequestStream.FromStream(stream, 0, 10, true);\r\n            A.CallTo(() => stream.EndRead(A<IAsyncResult>.Ignored)).Returns(4);\r\n\r\n            // When\r\n            var result = request.EndRead(asyncResult);\r\n\r\n            // Then\r\n            result.ShouldEqual(4);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_call_endwrite_on_underlaying_stream_when_endwrite_is_called()\r\n        {\r\n            // Given\r\n            var stream = CreateFakeStream();\r\n            var asyncResult = A.Fake<IAsyncResult>();\r\n            var request = RequestStream.FromStream(stream, 0, 10, true);\r\n\r\n            // When\r\n            request.EndWrite(asyncResult);\r\n\r\n            // Then\r\n            A.CallTo(() => stream.EndWrite(asyncResult)).MustHaveHappened();\r\n        }\r\n#endif\r\n\r\n        private static Stream CreateFakeStream()\r\n        {\r\n            var stream = A.Fake<Stream>(x =>\r\n            {\r\n                x.Implements(typeof(IDisposable));\r\n            });\r\n\r\n            A.CallTo(() => stream.CanRead).Returns(true);\r\n            A.CallTo(() => stream.CanSeek).Returns(true);\r\n            A.CallTo(() => stream.CanTimeout).Returns(true);\r\n            A.CallTo(() => stream.CanWrite).Returns(true);\r\n            \r\n            return stream;\r\n        }\r\n\r\n        private class ConfigurableMemoryStream : MemoryStream\r\n        {\r\n            private readonly bool readable;\r\n            private readonly bool seekable;\r\n            private readonly bool timeoutable;\r\n            private readonly bool writable;\r\n            private readonly long length;\r\n            private long position;\r\n\r\n            public bool HasBeenDisposed { get; private set; }\r\n            public bool HasBeenFlushed { get; private set; }\r\n            public bool HasBeenSeeked { get; private set; }\r\n\r\n            public ConfigurableMemoryStream(bool Readable = true, bool Seekable = true, bool Timeoutable = true, bool Writable = true, long Length = 0, long Position = 0)\r\n            {\r\n                this.readable = Readable;\r\n                this.seekable = Seekable;\r\n                this.timeoutable = Timeoutable;\r\n                this.writable = Writable;\r\n                this.length = Length;\r\n                this.position = Position;\r\n            }\r\n\r\n            public override bool CanRead\r\n            {\r\n                get { return this.readable; }\r\n            }\r\n\r\n            public override bool CanSeek\r\n            {\r\n                get { return this.seekable; }\r\n            }\r\n\r\n            public override bool CanTimeout\r\n            {\r\n                get { return this.timeoutable; }\r\n            }\r\n\r\n            public override bool CanWrite\r\n            {\r\n                get { return this.writable; }\r\n            }\r\n\r\n            public override long Length\r\n            {\r\n                get { return this.length; }\r\n            }\r\n\r\n            public override long Position\r\n            {\r\n                get { return this.position; }\r\n                set { this.position = value ; }\r\n            }\r\n\r\n            protected override void Dispose(bool disposing)\r\n            {\r\n                base.Dispose(disposing);\r\n                this.HasBeenDisposed = true;\r\n            }\r\n\r\n            public override void Flush()\r\n            {\r\n                base.Flush();\r\n                this.HasBeenFlushed = true;\r\n            }\r\n\r\n            public override long Seek(long offset, SeekOrigin loc)\r\n            {\r\n                this.HasBeenSeeked = true;\r\n                return base.Seek(offset, loc);\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Json/JavaScriptSerializerFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Json\r\n{\r\n    using System;\r\n    using System.Globalization;\r\n    using System.Text;\r\n    using Nancy.Configuration;\r\n    using Nancy.Json;\r\n    using Nancy.Json.Converters;\r\n    using Xunit;\r\n    using Xunit.Sdk;\r\n\r\n    public class JavaScriptSerializerFixture\r\n    {\r\n        [Fact]\r\n        public void Should_register_converters_when_asked()\r\n        {\r\n            // Given\r\n            var defaultSerializer = new JavaScriptSerializer();\r\n            var configuration = new JsonConfiguration(Encoding.UTF8, new[] { new TestConverter() }, new[] { new TestPrimitiveConverter() }, false, false, false);\r\n\r\n            // When\r\n            var serializer = new JavaScriptSerializer(configuration, true, GlobalizationConfiguration.Default);\r\n\r\n            var data =\r\n                new TestData()\r\n                {\r\n                    ConverterData =\r\n                        new TestConverterType()\r\n                        {\r\n                            Data = 42,\r\n                        },\r\n\r\n                    PrimitiveConverterData =\r\n                        new TestPrimitiveConverterType()\r\n                        {\r\n                            Data = 1701,\r\n                        },\r\n                };\r\n\r\n            const string ExpectedJSON = @\"{\"\"converterData\"\":{\"\"dataValue\"\":42},\"\"primitiveConverterData\"\":1701}\";\r\n\r\n            // Then\r\n            serializer.Serialize(data).ShouldEqual(ExpectedJSON);\r\n\r\n            serializer.Deserialize<TestData>(ExpectedJSON).ShouldEqual(data);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_register_converters_when_not_asked()\r\n        {\r\n            // Given\r\n            var defaultSerializer = new JavaScriptSerializer();\r\n\r\n            // When\r\n            var serializer = new JavaScriptSerializer(JsonConfiguration.Default, GlobalizationConfiguration.Default);\r\n\r\n            var data =\r\n                new TestData()\r\n                {\r\n                    ConverterData =\r\n                        new TestConverterType()\r\n                        {\r\n                            Data = 42,\r\n                        },\r\n\r\n                    PrimitiveConverterData =\r\n                        new TestPrimitiveConverterType()\r\n                        {\r\n                            Data = 1701,\r\n                        },\r\n                };\r\n\r\n            const string ExpectedJSON = @\"{\"\"converterData\"\":{\"\"data\"\":42},\"\"primitiveConverterData\"\":{\"\"data\"\":1701}}\";\r\n\r\n            // Then\r\n            serializer.Serialize(data).ShouldEqual(ExpectedJSON);\r\n\r\n            serializer.Deserialize<TestData>(ExpectedJSON).ShouldEqual(data);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_primitive_converter_when_available()\r\n        {\r\n            // When\r\n            var serializer = new JavaScriptSerializer();\r\n\r\n            serializer.RegisterConverters(new JavaScriptPrimitiveConverter[] { new TestPrimitiveConverter() });\r\n\r\n            // Then\r\n            serializer.Serialize(new TestPrimitiveConverterType() { Data = 12345 }).ShouldEqual(\"12345\");\r\n\r\n            serializer.Deserialize<TestPrimitiveConverterType>(\"12345\").ShouldEqual(new TestPrimitiveConverterType() { Data = 12345 });\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_use_primitive_converter_for_wrong_type()\r\n        {\r\n            // When\r\n            var serializer = new JavaScriptSerializer();\r\n\r\n            serializer.RegisterConverters(new JavaScriptPrimitiveConverter[] { new TestPrimitiveConverter() });\r\n\r\n            // Then\r\n            serializer.Serialize(new TestConverterType() { Data = 12345 }).ShouldEqual(@\"{\"\"data\"\":12345}\");\r\n\r\n            serializer.Deserialize<TestConverterType>(@\"{\"\"data\"\":12345}\").ShouldEqual(new TestConverterType() { Data = 12345 });\r\n\r\n            try\r\n            {\r\n                serializer.Deserialize<TestConverterType>(\"12345\");\r\n                throw new ThrowsException(typeof(InvalidCastException));\r\n            }\r\n            catch { }\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_serialize_tuples()\r\n        {\r\n            var serializer = new JavaScriptSerializer();\r\n            serializer.RegisterConverters(new[] { new TupleConverter() });\r\n\r\n            var tuple = Tuple.Create(10, 11);\r\n            serializer.Serialize(tuple).ShouldEqual(@\"{\"\"item1\"\":10,\"\"item2\"\":11}\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_deserialize_tuple()\r\n        {\r\n            var serializer = new JavaScriptSerializer();\r\n            serializer.RegisterConverters(new[] { new TupleConverter() });\r\n\r\n            string body = @\"{\"\"item1\"\":10,\"\"item2\"\":11}\";\r\n            Tuple<int, int> result = serializer.Deserialize<Tuple<int, int>>(body);\r\n            result.ToString().ShouldEqual(\"(10, 11)\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_deserialize_string_tuple()\r\n        {\r\n            var serializer = new JavaScriptSerializer();\r\n            serializer.RegisterConverters(new[] { new TupleConverter() });\r\n\r\n            string body = @\"{\"\"item1\"\":\"\"Hello\"\",\"\"item2\"\":\"\"World\"\",\"\"item3\"\":42}\";\r\n            var result = serializer.Deserialize<Tuple<string, string, int>>(body);\r\n            result.ToString().ShouldEqual(\"(Hello, World, 42)\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_deserialize_type_with_tuples()\r\n        {\r\n            // When\r\n            var serializer = new JavaScriptSerializer();\r\n            serializer.RegisterConverters(new[] { new TupleConverter() });\r\n\r\n            // Then\r\n            var typeWithTuple = serializer.Deserialize<TypeWithTuple>(@\"{\"\"value\"\":{\"\"item1\"\":10,\"\"item2\"\":11}}\");\r\n            typeWithTuple.Value.Item1.ShouldEqual(10);\r\n            typeWithTuple.Value.Item2.ShouldEqual(11);\r\n        }\r\n\r\n        private INancyEnvironment GetTestingEnvironment(JsonConfiguration configuration)\r\n        {\r\n            var environment =\r\n                new DefaultNancyEnvironment();\r\n\r\n            environment.AddValue(configuration);\r\n\r\n            return environment;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Json/Simple/NancySerializationStrategyFixture.cs",
    "content": "namespace Nancy.Tests.Unit.Json.Simple\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Globalization;\r\n    using Nancy.Extensions;\r\n    using Nancy.Json;\r\n    using Nancy.Json.Simple;\r\n    using Xunit;\r\n\r\n    public class NancySerializationStrategyFixture\r\n    {\r\n        [Fact]\r\n        public void Should_retain_casing_of_properties_when_asked()\r\n        {\r\n            // Given\r\n            var strategy = CreateStrategy(true);\r\n            const string propertyName = \"SomeMixedCase\";\r\n\r\n            // When\r\n            var fieldName = strategy.MapClrMemberNameToJsonFieldName(propertyName);\r\n\r\n            // Then\r\n            fieldName.ShouldEqual(propertyName);\r\n            fieldName.ShouldNotEqual(propertyName.ToLowerInvariant());\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_camel_case_property_name_when_retain_casing_is_off()\r\n        {\r\n            // Given\r\n            var strategy = CreateStrategy();\r\n            const string propertyName = \"SomeMixedCase\";\r\n\r\n            // When\r\n            var fieldName = strategy.MapClrMemberNameToJsonFieldName(propertyName);\r\n\r\n            // Then\r\n            fieldName.ShouldNotEqual(propertyName);\r\n            fieldName.ShouldEqual(propertyName.ToCamelCase());\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_registered_javascript_converter_to_serialize_object()\r\n        {\r\n            // Given\r\n            var strategy = CreateStrategy();\r\n            strategy.RegisterConverters(new[] { new DateTimeJavaScriptConverter() });\r\n            var expectedValue = new DateTime(2016, 2, 27);\r\n            object serialized;\r\n\r\n            // When\r\n            strategy.TrySerializeKnownTypes(expectedValue, out serialized);\r\n\r\n            //Then\r\n            var result = (IDictionary<string, object>)serialized;\r\n            result.ShouldNotBeNull();\r\n            result.ShouldHaveCount(1);\r\n            result[\"serializedValue\"].ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_registered_javascript_converter_to_deserialize_object()\r\n        {\r\n            // Given\r\n            var expectedValue = new DateTime(2016, 2, 27);\r\n            var objectToDeserialize = new Dictionary<string, object>\r\n            {\r\n                {\"serializedValue\", expectedValue}\r\n            };\r\n            var strategy = this.CreateStrategy();\r\n            strategy.RegisterConverters(new[] { new DateTimeJavaScriptConverter() });\r\n\r\n            // When\r\n            var result = (DateTime)strategy.DeserializeObject(objectToDeserialize, typeof(DateTime), DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);\r\n\r\n            // Then\r\n            result.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_serialize_unspecified_datetime_object()\r\n        {\r\n            // Given\r\n            var unspecifiedDateTime = new DateTime(2014, 3, 9, 17, 03, 25, DateTimeKind.Unspecified).AddMilliseconds(234);\r\n            var strategy = this.CreateStrategy();\r\n            object serializedObject;\r\n            var offset = TimeZoneInfo.Local.GetUtcOffset(unspecifiedDateTime);\r\n\r\n            // When\r\n            var canSerialize = strategy.TrySerializeKnownTypes(unspecifiedDateTime, out serializedObject);\r\n\r\n            //Then\r\n            canSerialize.ShouldBeTrue();\r\n            serializedObject.ShouldEqual(string.Format(\"2014-03-09T17:03:25.2340000{0}:{1}\", \r\n                offset.Hours.ToString(\"+00;-00\"), offset.Minutes.ToString(\"00\")));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_serialize_local_datetime_object()\r\n        {\r\n            // Given\r\n            var localDateTime = new DateTime(2014, 3, 9, 17, 03, 25, DateTimeKind.Local).AddMilliseconds(234);\r\n            var strategy = this.CreateStrategy();\r\n            object serializedObject;\r\n            var offset = TimeZoneInfo.Local.GetUtcOffset(localDateTime);\r\n\r\n            // When\r\n            var canSerialize = strategy.TrySerializeKnownTypes(localDateTime, out serializedObject);\r\n\r\n            //Then\r\n            canSerialize.ShouldBeTrue();\r\n            serializedObject.ShouldEqual(string.Format(\"2014-03-09T17:03:25.2340000{0}:{1}\",\r\n                offset.Hours.ToString(\"+00;-00\"), offset.Minutes.ToString(\"00\")));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_serialize_utc_datetime_object()\r\n        {\r\n            // Given\r\n            var unspecifiedDateTime = new DateTime(2014, 3, 9, 16, 03, 25, DateTimeKind.Utc).AddMilliseconds(234);\r\n            var strategy = this.CreateStrategy();\r\n            object serializedObject;\r\n\r\n            // When\r\n            var canSerialize = strategy.TrySerializeKnownTypes(unspecifiedDateTime, out serializedObject);\r\n\r\n            //Then\r\n            canSerialize.ShouldBeTrue();\r\n            serializedObject.ShouldEqual(\"2014-03-09T16:03:25.2340000Z\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_serialize_utc_datetimeoffset_object()\r\n        {\r\n            // Given\r\n            const string expectedValue = \"2016-02-27T12:12:12.0000000+00:00\";\r\n            var objectToSerialize = new DateTimeOffset(2016, 2, 27, 12, 12, 12, TimeSpan.Zero);\r\n            var strategy = this.CreateStrategy();\r\n            object serializedObject;\r\n\r\n            // When\r\n            var canSerialize = strategy.TrySerializeKnownTypes(objectToSerialize, out serializedObject);\r\n\r\n            //Then\r\n            canSerialize.ShouldBeTrue();\r\n            serializedObject.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_serialize_offset_datetimeoffset_object()\r\n        {\r\n            // Given\r\n            const string expectedValue = \"2016-02-27T12:12:12.0000000-06:00\";\r\n            var objectToSerialize = new DateTimeOffset(2016, 2, 27, 12, 12, 12, TimeSpan.FromHours(-6));\r\n            var strategy = this.CreateStrategy();\r\n            object serializedObject;\r\n\r\n            // When\r\n            var canSerialize = strategy.TrySerializeKnownTypes(objectToSerialize, out serializedObject);\r\n\r\n            //Then\r\n            canSerialize.ShouldBeTrue();\r\n            serializedObject.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        private NancySerializationStrategyTestWrapper CreateStrategy(bool retainCasing = false)\r\n        {\r\n            return new NancySerializationStrategyTestWrapper(retainCasing);\r\n        }\r\n    }\r\n\r\n    public class NancySerializationStrategyTestWrapper : NancySerializationStrategy\r\n    {\r\n        public NancySerializationStrategyTestWrapper(\r\n            bool retainCasing = false, bool serializeEnumToString = false)\r\n            : base(retainCasing, serializeEnumToString)\r\n        {\r\n\r\n        }\r\n\r\n        public new string MapClrMemberNameToJsonFieldName(string clrPropertyName)\r\n        {\r\n            return base.MapClrMemberNameToJsonFieldName(clrPropertyName);\r\n        }\r\n\r\n        public new bool TrySerializeKnownTypes(object input, out object output)\r\n        {\r\n            return base.TrySerializeKnownTypes(input, out output);\r\n        }\r\n    }\r\n\r\n    public class DateTimeJavaScriptConverter : JavaScriptConverter\r\n    {\r\n        public override IEnumerable<Type> SupportedTypes\r\n        {\r\n            get { yield return typeof(DateTime); }\r\n        }\r\n\r\n        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)\r\n        {\r\n            return Convert.ToDateTime(dictionary[\"serializedValue\"]);\r\n        }\r\n\r\n        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)\r\n        {\r\n            return new Dictionary<string, object>\r\n            {\r\n                {\"serializedValue\", obj}\r\n            };\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Json/SimpleJsonFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Json\r\n{\r\n    using System.Globalization;\r\n    using Nancy.Json.Simple;\r\n    using Xunit;\r\n\r\n    public class SimpleJsonFixture\r\n    {\r\n        [Fact]\r\n        public void String_dictionary_values_are_Json_serialized_as_strings()\r\n        {\r\n            // Given\r\n            dynamic value = \"42\";\r\n            var input = new DynamicDictionaryValue(value);\r\n\r\n            // When\r\n            var actual = SimpleJson.SerializeObject(input, new NancySerializationStrategy(), false);\r\n\r\n            // Then\r\n            actual.ShouldEqual(@\"\"\"42\"\"\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Integer_dictionary_values_are_Json_serialized_as_integers()\r\n        {\r\n            // Given\r\n            dynamic value = 42;\r\n            var input = new DynamicDictionaryValue(value);\r\n\r\n            // When\r\n            var actual = SimpleJson.SerializeObject(input, new NancySerializationStrategy(), false);\r\n\r\n            // Then\r\n            actual.ShouldEqual(@\"42\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_serialize_enum_to_string()\r\n        {\r\n            // Given\r\n            var model = new ModelTest { EnumModel = TestEnum.Freddy };\r\n\r\n            // When\r\n            var result = SimpleJson.SerializeObject(model, new NancySerializationStrategy(false, true), false);\r\n\r\n            // Then\r\n            result.ShouldEqual(\"{\\\"enumModel\\\":\\\"Freddy\\\"}\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_deserialize_json_number_to_ulong()\r\n        {\r\n            // Given\r\n            var json = \"42\";\r\n\r\n            // When\r\n            var result = SimpleJson.DeserializeObject(json, typeof(ulong), DateTimeStyles.None);\r\n\r\n            // Then\r\n            result.ShouldEqual(42ul);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_deserialize_json_number_to_ushort()\r\n        {\r\n            // Given\r\n            var json = \"42\";\r\n\r\n            // When\r\n            var result = SimpleJson.DeserializeObject(json, typeof(ushort), DateTimeStyles.None);\r\n\r\n            // Then\r\n            result.ShouldEqual((ushort)42);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_serialize_nullable_int_to_number()\r\n        {\r\n            // Given\r\n            var model = new NumberModel { SomeNullableInt = 42 };\r\n\r\n            // When\r\n            var result = SimpleJson.SerializeObject(model);\r\n\r\n            // Then\r\n            result.ShouldEqual(\"{\\\"SomeNullableInt\\\":42}\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_deserialize_number_to_nullable_int()\r\n        {\r\n            // Given\r\n            const string json = \"{\\\"SomeNullableInt\\\":42}\";\r\n\r\n            // When\r\n            var result = SimpleJson.DeserializeObject<NumberModel>(json);\r\n\r\n            // Then\r\n            result.SomeNullableInt.ShouldEqual(42);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_deserialize_numberstring_to_nullable_int()\r\n        {\r\n            // Given\r\n            const string json = \"{\\\"SomeNullableInt\\\":\\\"42\\\"}\";\r\n\r\n            // When\r\n            var result = SimpleJson.DeserializeObject<NumberModel>(json);\r\n\r\n            // Then\r\n            result.SomeNullableInt.ShouldEqual(42);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_serialize_nullable_int_to_null()\r\n        {\r\n            // Given\r\n            var model = new NumberModel { SomeNullableInt = null };\r\n\r\n            // When\r\n            var result = SimpleJson.SerializeObject(model);\r\n\r\n            // Then\r\n            result.ShouldEqual(\"{\\\"SomeNullableInt\\\":null}\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_deserialize_empty_string_to_nullable_int()\r\n        {\r\n            // Given\r\n            const string json = \"{\\\"SomeNullableInt\\\":\\\"\\\"}\";\r\n\r\n            // When\r\n            var result = SimpleJson.DeserializeObject<NumberModel>(json);\r\n\r\n            // Then\r\n            result.SomeNullableInt.ShouldEqual(null);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_deserialize_null_string_to_null_object()\r\n        {\r\n            // Given\r\n            const string json = null;\r\n\r\n            // When\r\n            var result = SimpleJson.DeserializeObject(json);\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_deserialize_empty_string_to_null_object()\r\n        {\r\n            // Given\r\n            var json = string.Empty;\r\n\r\n            // When\r\n            var result = SimpleJson.DeserializeObject(json);\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_deserialize_white_space_to_null_object()\r\n        {\r\n            // Given\r\n            const string json = \" \\t\\r\\n \";\r\n\r\n            // When\r\n            var result = SimpleJson.DeserializeObject(json);\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n\r\n        public class ModelTest\r\n        {\r\n            public TestEnum EnumModel { get; set; }\r\n        }\r\n\r\n        public class NumberModel\r\n        {\r\n            public int? SomeNullableInt { get; set; }\r\n        }\r\n\r\n        public enum TestEnum\r\n        {\r\n            Rod = 1,\r\n            Jane = 2,\r\n            Freddy = 3\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Json/TestConverter.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Json\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    using Nancy.Json;\r\n\r\n    public class TestConverter : JavaScriptConverter\r\n    {\r\n        public override IEnumerable<Type> SupportedTypes\r\n        {\r\n            get { yield return typeof(TestConverterType); }\r\n        }\r\n\r\n        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)\r\n        {\r\n            if (type != typeof(TestConverterType))\r\n                return null;\r\n\r\n            var data = new TestConverterType();\r\n\r\n            data.Data = Convert.ToInt32(dictionary[\"DataValue\"]);\r\n\r\n            return data;\r\n        }\r\n\r\n        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)\r\n        {\r\n            TestConverterType data = obj as TestConverterType;\r\n\r\n            if (data == null)\r\n                return null;\r\n\r\n            var fields = new Dictionary<string, object>();\r\n\r\n            fields[\"DataValue\"] = data.Data;\r\n\r\n            return fields;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Json/TestConverterType.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Json\r\n{\r\n    using System;\r\n\r\n    public class TestConverterType : IEquatable<TestConverterType>\r\n\t{\r\n\t\tpublic int Data;\r\n\r\n\t\tpublic bool Equals(TestConverterType other)\r\n\t\t{\r\n\t\t\tif (other == null)\r\n\t\t\t\treturn false;\r\n\r\n\t\t\treturn (this.Data == other.Data);\r\n\t\t}\r\n\r\n\t\tpublic override bool Equals(object obj)\r\n\t\t{\r\n\t\t\treturn this.Equals(obj as TestConverterType);\r\n\t\t}\r\n\r\n\t\tpublic override int GetHashCode()\r\n\t\t{\r\n\t\t\treturn this.Data.GetHashCode();\r\n\t\t}\r\n\t}\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Json/TestData.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Json\r\n{\r\n    using System;\r\n\r\n    public class TestData : IEquatable<TestData>\r\n\t{\r\n\t\tpublic TestConverterType ConverterData;\r\n\t\tpublic TestPrimitiveConverterType PrimitiveConverterData;\r\n\r\n\t\tpublic bool Equals(TestData other)\r\n\t\t{\r\n\t\t\tif (other == null)\r\n\t\t\t\treturn false;\r\n\r\n\t\t\tif ((this.ConverterData != null) != (other.ConverterData != null))\r\n\t\t\t\treturn false;\r\n\r\n\t\t\tif ((this.PrimitiveConverterData != null) != (other.PrimitiveConverterData != null))\r\n\t\t\t\treturn false;\r\n\r\n\t\t\treturn\r\n\t\t\t\t(ReferenceEquals(this.ConverterData, other.ConverterData) || this.ConverterData.Equals(other.ConverterData)) &&\r\n\t\t\t\t(ReferenceEquals(this.PrimitiveConverterData, other.PrimitiveConverterData) || this.PrimitiveConverterData.Equals(other.PrimitiveConverterData));\r\n\t\t}\r\n\r\n\t\tpublic override bool Equals(object obj)\r\n\t\t{\r\n\t\t\treturn this.Equals(obj as TestData);\r\n\t\t}\r\n\r\n\t\tpublic override int GetHashCode()\r\n\t\t{\r\n\t\t\treturn ConverterData.GetHashCode() ^ PrimitiveConverterData.GetHashCode();\r\n\t\t}\r\n\t}\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Json/TestPrimitiveConverter.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Json\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n\r\n    using Nancy.Json;\r\n\r\n    public class TestPrimitiveConverter : JavaScriptPrimitiveConverter\r\n\t{\r\n\t\tpublic override IEnumerable<Type> SupportedTypes\r\n\t\t{\r\n\t\t\tget { yield return typeof(TestPrimitiveConverterType); }\r\n\t\t}\r\n\r\n\t\tpublic override object Deserialize(object primitiveValue, Type type, JavaScriptSerializer serializer)\r\n\t\t{\r\n\t\t\tif (type != typeof(TestPrimitiveConverterType))\r\n\t\t\t\treturn null;\r\n\r\n\t\t\tvar data = new TestPrimitiveConverterType();\r\n\r\n\t\t\tdata.Data = Convert.ToInt32(primitiveValue);\r\n\r\n\t\t\treturn data;\r\n\t\t}\r\n\r\n\t\tpublic override object Serialize(object obj, JavaScriptSerializer serializer)\r\n\t\t{\r\n\t\t\tvar data = obj as TestPrimitiveConverterType;\r\n\r\n\t\t\tif (data == null)\r\n\t\t\t\treturn null;\r\n\t\t\telse\r\n\t\t\t\treturn data.Data;\r\n\t\t}\r\n\t}\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Json/TestPrimitiveConverterType.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Json\r\n{\r\n    using System;\r\n\r\n    public class TestPrimitiveConverterType : IEquatable<TestPrimitiveConverterType>\r\n\t{\r\n\t\tpublic int Data;\r\n\r\n\t\tpublic bool Equals(TestPrimitiveConverterType other)\r\n\t\t{\r\n\t\t\tif (other == null)\r\n\t\t\t\treturn false;\r\n\r\n\t\t\treturn (this.Data == other.Data);\r\n\t\t}\r\n\r\n\t\tpublic override bool Equals(object obj)\r\n\t\t{\r\n\t\t\treturn this.Equals(obj as TestPrimitiveConverterType);\r\n\t\t}\r\n\r\n\t\tpublic override int GetHashCode()\r\n\t\t{\r\n\t\t\treturn this.Data.GetHashCode();\r\n\t\t}\r\n\t}\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Json/TypeWithTuple.cs",
    "content": "namespace Nancy.Tests.Unit.Json\r\n{\r\n    using System;\r\n\r\n    public class TypeWithTuple\r\n    {\r\n        public Tuple<int, int> Value { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/JsonFormatterExtensionsFixtures.cs",
    "content": "namespace Nancy.Tests.Unit\r\n{\r\n    using System.IO;\r\n    using System.Text;\r\n\r\n    using FakeItEasy;\r\n    using Nancy.Configuration;\r\n    using Nancy.Json;\r\n    using Nancy.Responses;\r\n    using Nancy.Tests.Fakes;\r\n\r\n    using Xunit;\r\n\r\n    public class JsonFormatterExtensionsFixtures\r\n    {\r\n        private readonly IResponseFormatter formatter;\r\n        private readonly Person model;\r\n        private readonly Response response;\r\n\r\n        public JsonFormatterExtensionsFixtures()\r\n        {\r\n            var environment = GetTestingEnvironment();\r\n            var serializerFactory =\r\n               new DefaultSerializerFactory(new ISerializer[] { new DefaultJsonSerializer(environment) });\r\n\r\n            this.formatter = A.Fake<IResponseFormatter>();\r\n            A.CallTo(() => this.formatter.Environment).Returns(environment);\r\n            A.CallTo(() => this.formatter.SerializerFactory).Returns(serializerFactory);\r\n            this.model = new Person { FirstName = \"Andy\", LastName = \"Pike\" };\r\n            this.response = this.formatter.AsJson(model);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_a_response_with_the_standard_json_content_type()\r\n        {\r\n            response.ContentType.ShouldEqual(\"application/json; charset=utf-8\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_a_response_with_status_code_200_OK()\r\n        {\r\n            response.StatusCode.ShouldEqual(HttpStatusCode.OK);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_a_valid_model_in_json_format()\r\n        {\r\n            using (var stream = new MemoryStream())\r\n            {\r\n                response.Contents(stream);\r\n\r\n                Encoding.UTF8.GetString(stream.ToArray()).ShouldEqual(\"{\\\"firstName\\\":\\\"Andy\\\",\\\"lastName\\\":\\\"Pike\\\"}\");\r\n            }\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_in_json_format()\r\n        {\r\n            var nullResponse = formatter.AsJson<Person>(null);\r\n            using (var stream = new MemoryStream())\r\n            {\r\n                nullResponse.Contents(stream);\r\n                Encoding.UTF8.GetString(stream.ToArray()).ShouldHaveCount(0);\r\n            }\r\n        }\r\n\r\n        [Fact]\r\n        public void Json_formatter_can_deserialize_objects_of_type_Type()\r\n        {\r\n            var response = formatter.AsJson(new { type = typeof(string) });\r\n            using (var stream = new MemoryStream())\r\n            {\r\n                response.Contents(stream);\r\n                Encoding.UTF8.GetString(stream.ToArray()).ShouldEqual(@\"{\"\"type\"\":\"\"System.String\"\"}\");\r\n            }\r\n        }\r\n\r\n        [Fact]\r\n        public void Can_set_status_on_json_response()\r\n        {\r\n            var response = formatter.AsJson(new { foo = \"bar\" }, HttpStatusCode.InternalServerError);\r\n            Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\r\n        }\r\n\r\n        private static INancyEnvironment GetTestingEnvironment()\r\n        {\r\n            var envionment =\r\n                new DefaultNancyEnvironment();\r\n\r\n            envionment.AddValue(JsonConfiguration.Default);\r\n            envionment.AddValue(GlobalizationConfiguration.Default);\r\n\r\n            envionment.Tracing(\r\n                enabled: true,\r\n                displayErrorTraces: true);\r\n\r\n            return envionment;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/JsonSerializerFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit\r\n{\r\n    using System;\r\n\r\n    using Nancy.Json;\r\n\r\n    using Xunit;\r\n\r\n    public class JsonSerializerFixture\r\n    {\r\n        [Fact]\r\n        public void Should_be_able_to_serialise_datetimeoffset_iso_format()\r\n        {\r\n            // Given\r\n            var serializer = new JavaScriptSerializer();\r\n            var offset = new DateTimeOffset(2014, 12, 1, 17, 0, 0, new TimeSpan(0, 6, 0, 0));\r\n\r\n            // When\r\n            var result = serializer.Serialize(offset);\r\n\r\n            // Then\r\n            result.ShouldEqual(@\"\"\"2014-12-01T17:00:00.0000000+06:00\"\"\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_deserialise_datetimeoffset_iso_format()\r\n        {\r\n            // Given\r\n            var serializer = new JavaScriptSerializer();\r\n            var serialized = @\"\"\"2014-12-01T17:00:00.0000000+06:00\"\"\";\r\n\r\n            // When\r\n            var actual = serializer.Deserialize<DateTimeOffset>(serialized);\r\n\r\n            // Then\r\n            actual.ShouldEqual(new DateTimeOffset(2014, 12, 1, 17, 0, 0, new TimeSpan(0, 6, 0, 0)));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_serialise_and_deserialise_datetimeoffset_iso_format()\r\n        {\r\n            // Given\r\n            var serializer = new JavaScriptSerializer();\r\n            var offset = new DateTimeOffset(2014, 12, 1, 17, 0, 0, new TimeSpan(0, 6, 0, 0));\r\n\r\n            // When\r\n            var result = serializer.Serialize(offset);\r\n\r\n            var actual = serializer.Deserialize<DateTimeOffset>(result);\r\n\r\n            // Then\r\n            actual.ShouldEqual(offset);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Localization/ResourceBasedTextResourceFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Localization\r\n{\r\n    using System;\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Extensions;\r\n    using Nancy.Localization;\r\n\r\n    using Xunit;\r\n\r\n    public class ResourceBasedTextResourceFixture\r\n    {\r\n        [Fact]\r\n        public void Should_Return_Null_If_No_Assembly_Found()\r\n        {\r\n            // Given\r\n            var resourceAssemblyProvider = A.Fake<IResourceAssemblyProvider>();\r\n            A.CallTo(() => resourceAssemblyProvider.GetAssembliesToScan()).Returns(new[] { typeof(NancyEngine).GetAssembly() });\r\n\r\n            var defaultTextResource = new ResourceBasedTextResource(resourceAssemblyProvider);\r\n            var context = new NancyContext();\r\n\r\n            // When\r\n            var result = defaultTextResource[\"Texts.Greeting\", context];\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_resource_string_if_unique_match_could_be_made()\r\n        {\r\n            // Given\r\n            var resourceAssemblyProvider = A.Fake<IResourceAssemblyProvider>();\r\n            A.CallTo(() => resourceAssemblyProvider.GetAssembliesToScan()).Returns(new[] { this.GetType().GetAssembly() });\r\n\r\n            var defaultTextResource = new ResourceBasedTextResource(resourceAssemblyProvider);\r\n            var context = new NancyContext();\r\n\r\n            // When\r\n            var result = defaultTextResource[\"Menu.Home\", context];\r\n\r\n            // Then\r\n            result.ShouldEqual(\"This is the home link\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_exception_when_multiple_resources_matches_key()\r\n        {\r\n            // Given\r\n            const string expectedMessage = \r\n                \"More than one text resources match the Texts key. Try providing a more specific key.\";\r\n\r\n            var resourceAssemblyProvider = A.Fake<IResourceAssemblyProvider>();\r\n            A.CallTo(() => resourceAssemblyProvider.GetAssembliesToScan()).Returns(new[] { this.GetType().GetAssembly() });\r\n\r\n            var defaultTextResource = new ResourceBasedTextResource(resourceAssemblyProvider);\r\n            var context = new NancyContext();\r\n\r\n            // When\r\n            var exception = Assert.Throws<InvalidOperationException>(() =>\r\n            {\r\n                var result = defaultTextResource[\"Texts.Home\", context];\r\n            });\r\n\r\n            // Then\r\n            exception.Message.ShouldEqual(expectedMessage);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/MimeTypesFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit\r\n{\r\n    using Xunit;\r\n\r\n    public class MimeTypesFixture\r\n    {\r\n        [Fact] \r\n        public void Should_return_appropriate_mime_for_common_extensions()\r\n        {\r\n            // Given, When, Then\r\n            MimeTypes.GetMimeType(\".js\").ShouldEqual(\"application/javascript\");\r\n            MimeTypes.GetMimeType(\".css\").ShouldEqual(\"text/css\");\r\n            MimeTypes.GetMimeType(\".png\").ShouldEqual(\"image/png\");\r\n            MimeTypes.GetMimeType(\".gif\").ShouldEqual(\"image/gif\");\r\n            MimeTypes.GetMimeType(\".jpg\").ShouldEqual(\"image/jpeg\");\r\n            MimeTypes.GetMimeType(\".xml\").ShouldEqual(\"application/xml\");\r\n        }\r\n\r\n        [Fact] \r\n        public void Should_return_octet_stream_if_unknown_mime_type()\r\n        {\r\n            // Given, When, Then\r\n            MimeTypes.GetMimeType(\".crazyext\").ShouldEqual(\"application/octet-stream\");\r\n        }\r\n\r\n        [Fact] \r\n        public void Should_return_appropriate_mime_for_numerical_extensions()\r\n        {\r\n            // Given, When, Then\r\n            MimeTypes.GetMimeType(\".323\").ShouldEqual(\"text/h323\");\r\n        }\r\n\r\n        [Fact] \r\n        public void Should_return_appropriate_mime_for_Special_char_extensions()\r\n        {\r\n            // Given, When, Then\r\n            MimeTypes.GetMimeType(\".c++\").ShouldEqual(\"text/plain\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_support_new_office_formats()\r\n        {\r\n            // Given, When, Then\r\n            MimeTypes.GetMimeType(\".docx\").ShouldEqual(\"application/vnd.openxmlformats-officedocument.wordprocessingml.document\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_support_adding_mime_extensions()\r\n        {\r\n            // Given, When\r\n            MimeTypes.AddType(\"php\", \"text/plain\");\r\n\r\n            // Then\r\n            MimeTypes.GetMimeType(\".php\").ShouldEqual(\"text/plain\");\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/ModelBinding/BindingMemberInfoFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.ModelBinding\r\n{\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using System.Xml.Serialization;\r\n\r\n    using Nancy.ModelBinding;\r\n    using Nancy.Testing;\r\n    using Xunit;\r\n\r\n    public class BindingMemberInfoFixture\r\n    {\r\n        [Fact]\r\n        public void Should_return_MemberInfo_for_properties_or_fields()\r\n        {\r\n            // Given\r\n            var type = typeof(TestModel);\r\n            var underlyingFieldInfo = type.GetFields().First();\r\n            var underlyingPropertyInfo = type.GetProperties().First();\r\n\r\n            // When\r\n            var fieldInfo = new BindingMemberInfo(underlyingFieldInfo);\r\n            var propertyInfo = new BindingMemberInfo(underlyingPropertyInfo);\r\n\r\n            // Then\r\n            fieldInfo.MemberInfo.ShouldEqual(underlyingFieldInfo);\r\n            propertyInfo.MemberInfo.ShouldEqual(underlyingPropertyInfo);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_Name_for_properties_or_fields()\r\n        {\r\n            // Given\r\n            var type = typeof(TestModel);\r\n            var underlyingFieldInfo = type.GetFields().First();\r\n            var underlyingPropertyInfo = type.GetProperties().First();\r\n\r\n            // When\r\n            var fieldInfo = new BindingMemberInfo(underlyingFieldInfo);\r\n            var propertyInfo = new BindingMemberInfo(underlyingPropertyInfo);\r\n\r\n            // Then\r\n            fieldInfo.Name.ShouldEqual(underlyingFieldInfo.Name);\r\n            propertyInfo.Name.ShouldEqual(underlyingPropertyInfo.Name);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_PropertyType_for_properties_or_fields()\r\n        {\r\n            // Given\r\n            var properties = BindingMemberInfo.Collect<TestModel>();\r\n\r\n            // When\r\n\r\n            // Then\r\n            properties.ShouldHaveCount(4);\r\n\r\n            foreach (var propInfo in properties)\r\n            {\r\n                if (propInfo.Name.StartsWith(\"Int\"))\r\n                {\r\n                    propInfo.PropertyType.ShouldEqual(typeof(int));\r\n                }\r\n                else if (propInfo.Name.StartsWith(\"String\"))\r\n                {\r\n                    propInfo.PropertyType.ShouldEqual(typeof(string));\r\n                }\r\n                else\r\n                {\r\n                    throw new AssertException(\"Internal error in unit test: Test model property/field name does not follow the expected convention: \" + propInfo.Name);\r\n                }\r\n            }\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_get_fields()\r\n        {\r\n            // Given\r\n            var propInfo = BindingMemberInfo.Collect<TestModel>().Where(prop => prop.Name.EndsWith(\"Field\"));\r\n            var model = new TestModel();\r\n\r\n            // When\r\n            model.IntField = 669;\r\n            model.StringField = \"testing\";\r\n\r\n            // Then\r\n            propInfo.Single(prop => prop.PropertyType == typeof(int))\r\n                .GetValue(model)\r\n                .ShouldEqual(669);\r\n\r\n            propInfo.Single(prop => prop.PropertyType == typeof(string))\r\n                .GetValue(model)\r\n                .ShouldEqual(\"testing\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_fields()\r\n        {\r\n            // Given\r\n            var propInfo = BindingMemberInfo.Collect<TestModel>().Where(prop => prop.Name.EndsWith(\"Field\"));\r\n            var model = new TestModel();\r\n\r\n            // When\r\n            propInfo.Single(prop => prop.PropertyType == typeof(int))\r\n                .SetValue(model, 42);\r\n\r\n            propInfo.Single(prop => prop.PropertyType == typeof(string))\r\n                .SetValue(model, \"nineteen\");\r\n\r\n            // Then\r\n            model.IntField.ShouldEqual(42);\r\n            model.StringField.ShouldEqual(\"nineteen\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_get_properties()\r\n        {\r\n            // Given\r\n            var propInfo = BindingMemberInfo.Collect<TestModel>().Where(prop => prop.Name.EndsWith(\"Property\"));\r\n            var model = new TestModel();\r\n\r\n            // When\r\n            model.IntProperty = 1701;\r\n            model.StringProperty = \"NancyFX Unit Testing\";\r\n\r\n            // Then\r\n            propInfo.Single(prop => prop.PropertyType == typeof(int))\r\n                .GetValue(model)\r\n                .ShouldEqual(1701);\r\n\r\n            propInfo.Single(prop => prop.PropertyType == typeof(string))\r\n                .GetValue(model)\r\n                .ShouldEqual(\"NancyFX Unit Testing\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_properties()\r\n        {\r\n            // Given\r\n            var propInfo = BindingMemberInfo.Collect<TestModel>().Where(prop => prop.Name.EndsWith(\"Property\"));\r\n            var model = new TestModel();\r\n\r\n            // When\r\n            propInfo.Single(prop => prop.PropertyType == typeof(int))\r\n                .SetValue(model, 2600);\r\n\r\n            propInfo.Single(prop => prop.PropertyType == typeof(string))\r\n                .SetValue(model, \"R2D2\");\r\n\r\n            // Then\r\n            model.IntProperty.ShouldEqual(2600);\r\n            model.StringProperty.ShouldEqual(\"R2D2\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_collect_all_bindable_members_and_skip_all_others()\r\n        {\r\n            // Given\r\n\r\n            // When\r\n            var properties = BindingMemberInfo.Collect<BiggerTestModel>();\r\n\r\n            // Then\r\n            properties.ShouldHaveCount(16);\r\n\r\n            foreach (var property in properties)\r\n                property.Name.ShouldStartWith(\"Bindable\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_use_except_on_two_lists_of_bindingMemberInfos()\r\n        {\r\n            // Given\r\n            var properties = BindingMemberInfo.Collect<TestModel>();\r\n            var except = BindingMemberInfo.Collect<TestModel>().Where(i => i.Name.Contains(\"Property\"));\r\n\r\n            // When\r\n            var res = properties.Except(except).ToList();\r\n\r\n            // Then\r\n            res.Count.ShouldEqual(2);\r\n            res[0].Name.ShouldEqual(\"IntField\");\r\n            res[1].Name.ShouldEqual(\"StringField\");\r\n        }\r\n\r\n        public class TestModel\r\n        {\r\n            public int IntField;\r\n            public string StringField;\r\n\r\n            public int IntProperty { get; set; }\r\n            public string StringProperty { get; set; }\r\n        }\r\n\r\n        public class BiggerTestModel\r\n        {\r\n            public int BindableIntField;\r\n            public int BindableIntProperty { get; set; }\r\n            public string BindableStringField;\r\n            public string BindableStringProperty { get; set; }\r\n            public TestModel BindableTestModelField;\r\n            public TestModel BindableTestModelProperty { get; set; }\r\n            public BiggerTestModel BindableBiggerTestModelField;\r\n            public BiggerTestModel BindableBiggerTestModelProperty { get; set; }\r\n            [XmlIgnore]\r\n            public IEnumerable<int> BindableEnumerableField;\r\n            [XmlIgnore]\r\n            public IEnumerable<int> BindableEnumerableProperty { get; set; }\r\n            public List<string> BindableListField;\r\n            public List<string> BindableListProperty { get; set; }\r\n            public double[] BindableArrayField;\r\n            public double[] BindableArrayProperty { get; set; }\r\n            public TestModel[] BindableArrayOfObjectsField;\r\n            public TestModel[] BindableArrayOfObjectsProperty { get; set; }\r\n\r\n            public int this[int index]\r\n            {\r\n                get { return 0; }\r\n                set { }\r\n            }\r\n\r\n            public int this[string index, int index2]\r\n            {\r\n                get { return 0; }\r\n                set { }\r\n            }\r\n\r\n            public readonly int UnbindableReadOnlyField = 74205;\r\n\r\n            public string UnbindableReadOnlyProperty\r\n            {\r\n                get { return \"hi\"; }\r\n            }\r\n\r\n            public string UnbindableWriteOnlyProperty\r\n            {\r\n                set { }\r\n            }\r\n\r\n#pragma warning disable 169\r\n            // ReSharper disable once InconsistentNaming\r\n            private int UnbindablePrivateField;\r\n#pragma warning restore 169\r\n\r\n            public static int UnbindableStaticField;\r\n\r\n            public static int UnbindableStaticProperty\r\n            {\r\n                get { return 0; }\r\n                set { }\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/ModelBinding/DefaultBinderFixture.cs",
    "content": "namespace Nancy.Tests.Unit.ModelBinding\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Globalization;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using System.Text;\r\n    using System.Xml.Serialization;\r\n    using FakeItEasy;\r\n    using Nancy.Configuration;\r\n    using Nancy.IO;\r\n    using Nancy.Json;\r\n    using Nancy.ModelBinding;\r\n    using Nancy.ModelBinding.DefaultBodyDeserializers;\r\n    using Nancy.ModelBinding.DefaultConverters;\r\n    using Nancy.Responses.Negotiation;\r\n    using Nancy.Tests.Fakes;\r\n    using Nancy.Tests.Unit.ModelBinding.DefaultBodyDeserializers;\r\n    using Xunit;\r\n\r\n    public class DefaultBinderFixture\r\n    {\r\n        private readonly IFieldNameConverter passthroughNameConverter;\r\n        private readonly BindingDefaults emptyDefaults;\r\n        private readonly JavaScriptSerializer serializer;\r\n        private readonly BindingDefaults bindingDefaults;\r\n\r\n        public DefaultBinderFixture()\r\n        {\r\n            var environment = new DefaultNancyEnvironment();\r\n            environment.AddValue(JsonConfiguration.Default);\r\n            environment.AddValue(GlobalizationConfiguration.Default);\r\n\r\n            this.passthroughNameConverter = A.Fake<IFieldNameConverter>();\r\n            A.CallTo(() => this.passthroughNameConverter.Convert(null)).WithAnyArguments()\r\n                .ReturnsLazily(f => (string)f.Arguments[0]);\r\n\r\n            this.serializer = new JavaScriptSerializer();\r\n            this.serializer.RegisterConverters(JsonConfiguration.Default.Converters);\r\n            this.bindingDefaults = new BindingDefaults(environment);\r\n\r\n            this.emptyDefaults = A.Fake<BindingDefaults>(options => options.WithArgumentsForConstructor(new[] { environment }));\r\n            A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(ArrayCache.Empty<IBodyDeserializer>());\r\n            A.CallTo(() => this.emptyDefaults.DefaultTypeConverters).Returns(ArrayCache.Empty<ITypeConverter>());\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_if_type_converters_is_null()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => new DefaultBinder(null, ArrayCache.Empty<IBodyDeserializer>(), A.Fake<IFieldNameConverter>(), this.bindingDefaults));\r\n\r\n            // Then\r\n            result.ShouldBeOfType(typeof(ArgumentNullException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_if_body_deserializers_is_null()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => new DefaultBinder(ArrayCache.Empty<ITypeConverter>(), null, A.Fake<IFieldNameConverter>(), this.bindingDefaults));\r\n\r\n            // Then\r\n            result.ShouldBeOfType(typeof(ArgumentNullException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_if_body_deserializer_fails_and_IgnoreErrors_is_false()\r\n        {\r\n            // Given\r\n            var deserializer = new ThrowingBodyDeserializer<FormatException>();\r\n            var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n\r\n            var config = new BindingConfig { IgnoreErrors = false };\r\n\r\n            // When\r\n            var result = Record.Exception(() => binder.Bind(context, this.GetType(), null, config));\r\n\r\n            // Then\r\n            result.ShouldBeOfType<ModelBindingException>();\r\n            result.InnerException.ShouldBeOfType<FormatException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_throw_if_body_deserializer_fails_and_IgnoreErrors_is_true()\r\n        {\r\n            // Given\r\n            var deserializer = new ThrowingBodyDeserializer<FormatException>();\r\n            var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n\r\n            var config = new BindingConfig { IgnoreErrors = true };\r\n\r\n            // When, Then\r\n            binder.Bind(context, this.GetType(), null, config);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_if_field_name_converter_is_null()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => new DefaultBinder(ArrayCache.Empty<ITypeConverter>(), ArrayCache.Empty<IBodyDeserializer>(), null, this.bindingDefaults));\r\n\r\n            // Then\r\n            result.ShouldBeOfType(typeof(ArgumentNullException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_if_defaults_is_null()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => new DefaultBinder(ArrayCache.Empty<ITypeConverter>(), ArrayCache.Empty<IBodyDeserializer>(), A.Fake<IFieldNameConverter>(), null));\r\n\r\n            // Then\r\n            result.ShouldBeOfType(typeof(ArgumentNullException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_call_body_deserializer_if_one_matches()\r\n        {\r\n            // Given\r\n            var deserializer = A.Fake<IBodyDeserializer>();\r\n            A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);\r\n            var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n\r\n            // When\r\n            binder.Bind(context, this.GetType(), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments()\r\n                .MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_call_body_deserializer_if_doesnt_match()\r\n        {\r\n            // Given\r\n            var deserializer = A.Fake<IBodyDeserializer>();\r\n            A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(false);\r\n            var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n\r\n            // When\r\n            binder.Bind(context, this.GetType(), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments()\r\n                .MustNotHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_pass_request_content_type_to_can_deserialize()\r\n        {\r\n            // Then\r\n            var deserializer = A.Fake<IBodyDeserializer>();\r\n            var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n\r\n            // When\r\n            binder.Bind(context, this.GetType(), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            A.CallTo(() => deserializer.CanDeserialize(A<MediaRange>.That.Matches(x => x.Matches(\"application/xml\")), A<BindingContext>._))\r\n                .MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_pass_binding_context_to_can_deserialize()\r\n        {\r\n            // Then\r\n            var deserializer = A.Fake<IBodyDeserializer>();\r\n            var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n\r\n            // When\r\n            binder.Bind(context, this.GetType(), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            A.CallTo(() => deserializer.CanDeserialize(A<MediaRange>.That.Matches(x => x.Matches(\"application/xml\")), A<BindingContext>.That.Not.IsNull()))\r\n                .MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_object_from_deserializer_if_one_returned()\r\n        {\r\n            // Given\r\n            var modelObject = new TestModel { StringProperty = \"Hello!\" };\r\n            var deserializer = A.Fake<IBodyDeserializer>();\r\n            A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);\r\n            A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments().Returns(modelObject);\r\n            var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n\r\n            // When\r\n            var result = binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.ShouldBeOfType<TestModel>();\r\n            ((TestModel)result).StringProperty.ShouldEqual(\"Hello!\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_object_from_deserializer_if_one_returned_and_overwrite_when_allowed()\r\n        {\r\n            // Given\r\n            var modelObject = new TestModel { StringPropertyWithDefaultValue = \"Hello!\" };\r\n            var deserializer = A.Fake<IBodyDeserializer>();\r\n            A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);\r\n            A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments().Returns(modelObject);\r\n            var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n\r\n            // When\r\n            var result = binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.ShouldBeOfType<TestModel>();\r\n            ((TestModel)result).StringPropertyWithDefaultValue.ShouldEqual(\"Hello!\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_object_from_deserializer_if_one_returned_and_not_overwrite_when_not_allowed()\r\n        {\r\n            // Given\r\n            var modelObject =\r\n                new TestModel()\r\n                {\r\n                    StringPropertyWithDefaultValue = \"Hello!\",\r\n                    StringFieldWithDefaultValue = \"World!\",\r\n                };\r\n\r\n            var deserializer = A.Fake<IBodyDeserializer>();\r\n            A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);\r\n            A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments().Returns(modelObject);\r\n            var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n\r\n            // When\r\n            var result = binder.Bind(context, typeof(TestModel), null, BindingConfig.NoOverwrite);\r\n\r\n            // Then\r\n            result.ShouldBeOfType<TestModel>();\r\n            ((TestModel)result).StringPropertyWithDefaultValue.ShouldEqual(\"Default Property Value\");\r\n            ((TestModel)result).StringFieldWithDefaultValue.ShouldEqual(\"Default Field Value\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_see_if_a_type_converter_is_available_for_each_property_on_the_model_where_incoming_value_exists()\r\n        {\r\n            // Given\r\n            var typeConverter = A.Fake<ITypeConverter>();\r\n            A.CallTo(() => typeConverter.CanConvertTo(null, null)).WithAnyArguments().Returns(false);\r\n            var binder = this.GetBinder(typeConverters: new[] { typeConverter });\r\n            var context = new NancyContext { Request = new FakeRequest(\"GET\", \"/\") };\r\n            context.Request.Form[\"StringProperty\"] = \"Test\";\r\n            context.Request.Form[\"IntProperty\"] = \"12\";\r\n\r\n            // When\r\n            binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            A.CallTo(() => typeConverter.CanConvertTo(null, null)).WithAnyArguments()\r\n                .MustHaveHappenedTwiceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_call_convert_on_type_converter_if_available()\r\n        {\r\n            // Given\r\n            var typeConverter = A.Fake<ITypeConverter>();\r\n            A.CallTo(() => typeConverter.CanConvertTo(typeof(string), null)).WithAnyArguments().Returns(true);\r\n            A.CallTo(() => typeConverter.Convert(null, null, null)).WithAnyArguments().Returns(null);\r\n            var binder = this.GetBinder(typeConverters: new[] { typeConverter });\r\n            var context = new NancyContext { Request = new FakeRequest(\"GET\", \"/\") };\r\n            context.Request.Form[\"StringProperty\"] = \"Test\";\r\n\r\n            // When\r\n            binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            A.CallTo(() => typeConverter.Convert(null, null, null)).WithAnyArguments()\r\n                .MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_ignore_properties_that_cannot_be_converted()\r\n        {\r\n            // Given\r\n            var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });\r\n            var context = new NancyContext { Request = new FakeRequest(\"GET\", \"/\") };\r\n            context.Request.Form[\"StringProperty\"] = \"Test\";\r\n            context.Request.Form[\"IntProperty\"] = \"12\";\r\n            context.Request.Form[\"DateProperty\"] = \"Broken\";\r\n\r\n            // When\r\n            var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.StringProperty.ShouldEqual(\"Test\");\r\n            result.IntProperty.ShouldEqual(12);\r\n            result.DateProperty.ShouldEqual(default(DateTime));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_ModelBindingException_if_convertion_of_a_property_fails()\r\n        {\r\n            // Given\r\n            var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });\r\n            var context = new NancyContext { Request = new FakeRequest(\"GET\", \"/\") };\r\n            context.Request.Form[\"IntProperty\"] = \"badint\";\r\n            context.Request.Form[\"AnotherIntProperty\"] = \"morebad\";\r\n\r\n            // Then\r\n            Type modelType = typeof(TestModel);\r\n            Assert.Throws<ModelBindingException>(() => binder.Bind(context, modelType, null, BindingConfig.Default))\r\n                .ShouldMatch(exception =>\r\n                             exception.BoundType == modelType\r\n                             && exception.PropertyBindingExceptions.Any(pe =>\r\n                                                                        pe.PropertyName == \"IntProperty\"\r\n                                                                        && pe.AttemptedValue == \"badint\")\r\n                             && exception.PropertyBindingExceptions.Any(pe =>\r\n                                                                        pe.PropertyName == \"AnotherIntProperty\"\r\n                                                                        && pe.AttemptedValue == \"morebad\")\r\n                             && exception.PropertyBindingExceptions.All(pe =>\r\n                                                                        pe.InnerException.Message.Contains(pe.AttemptedValue)\r\n                                                                        && pe.InnerException.Message.Contains(modelType.GetProperty(pe.PropertyName).PropertyType.Name)));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_throw_ModelBindingException_if_convertion_of_property_fails_and_ignore_error_is_true()\r\n        {\r\n            // Given\r\n            var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });\r\n            var context = new NancyContext { Request = new FakeRequest(\"GET\", \"/\") };\r\n            context.Request.Form[\"IntProperty\"] = \"badint\";\r\n            context.Request.Form[\"AnotherIntProperty\"] = \"morebad\";\r\n\r\n            var config = new BindingConfig {IgnoreErrors = true};\r\n\r\n            // When\r\n            // Then\r\n            Record.Exception(() => binder.Bind(context, typeof(TestModel), null, config)).ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_remaining_properties_when_one_fails_and_ignore_error_is_enabled()\r\n        {\r\n            // Given\r\n            var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });\r\n            var context = new NancyContext { Request = new FakeRequest(\"GET\", \"/\") };\r\n            context.Request.Form[\"IntProperty\"] = \"badint\";\r\n            context.Request.Form[\"AnotherIntProperty\"] = 10;\r\n\r\n            var config = new BindingConfig { IgnoreErrors = true };\r\n\r\n            // When\r\n            var model = binder.Bind(context, typeof(TestModel), null, config) as TestModel;\r\n\r\n            // Then\r\n            model.AnotherIntProperty.ShouldEqual(10);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_ignore_indexer_properties()\r\n        {\r\n            // Given\r\n            var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n\r\n            var validProperties = 0;\r\n            var deserializer = A.Fake<IBodyDeserializer>();\r\n            A.CallTo(() => deserializer.CanDeserialize(A<MediaRange>._, A<BindingContext>._)).Returns(true);\r\n            A.CallTo(() => deserializer.Deserialize(A<MediaRange>._, A<Stream>.Ignored, A<BindingContext>.Ignored))\r\n                                       .Invokes(f =>\r\n                                           {\r\n                                               validProperties = f.Arguments.Get<BindingContext>(2).ValidModelBindingMembers.Count();\r\n                                           })\r\n                                       .Returns(new TestModel());\r\n\r\n            A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(new[] { deserializer });\r\n\r\n            // When\r\n            binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            validProperties.ShouldEqual(22);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_pass_binding_context_to_default_deserializer()\r\n        {\r\n            // Given\r\n            var deserializer = A.Fake<IBodyDeserializer>();\r\n            var binder = this.GetBinder();\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n            A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(new[] { deserializer });\r\n\r\n            // When\r\n            binder.Bind(context, this.GetType(), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            A.CallTo(() => deserializer.CanDeserialize(A<MediaRange>.That.Matches(x => x.Matches(\"application/xml\")), A<BindingContext>.That.Not.IsNull()))\r\n                .MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_field_name_converter_for_each_field()\r\n        {\r\n            // Given\r\n            var binder = this.GetBinder();\r\n            var context = new NancyContext { Request = new FakeRequest(\"GET\", \"/\") };\r\n            context.Request.Form[\"StringProperty\"] = \"Test\";\r\n            context.Request.Form[\"IntProperty\"] = \"12\";\r\n\r\n            // When\r\n            binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            A.CallTo(() => this.passthroughNameConverter.Convert(null)).WithAnyArguments()\r\n                .MustHaveHappenedTwiceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_bind_anything_on_blacklist()\r\n        {\r\n            // Given\r\n            var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });\r\n            var context = new NancyContext { Request = new FakeRequest(\"GET\", \"/\") };\r\n            context.Request.Form[\"StringProperty\"] = \"Test\";\r\n            context.Request.Form[\"IntProperty\"] = \"12\";\r\n\r\n            // When\r\n            var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default, \"IntProperty\");\r\n\r\n            // Then\r\n            result.StringProperty.ShouldEqual(\"Test\");\r\n            result.IntProperty.ShouldEqual(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_bind_anything_on_blacklist_when_the_blacklist_is_specified_by_expressions()\r\n        {\r\n            // Given\r\n            var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });\r\n            var context = new NancyContext { Request = new FakeRequest(\"GET\", \"/\") };\r\n            context.Request.Form[\"StringProperty\"] = \"Test\";\r\n            context.Request.Form[\"IntProperty\"] = \"12\";\r\n\r\n            var fakeModule = A.Fake<INancyModule>();\r\n            var fakeModelBinderLocator = A.Fake<IModelBinderLocator>();\r\n            A.CallTo(() => fakeModule.Context).Returns(context);\r\n            A.CallTo(() => fakeModule.ModelBinderLocator).Returns(fakeModelBinderLocator);\r\n            A.CallTo(() => fakeModelBinderLocator.GetBinderForType(typeof (TestModel), context)).Returns(binder);\r\n\r\n            // When\r\n            var result = fakeModule.Bind<TestModel>(tm => tm.IntProperty);\r\n\r\n            // Then\r\n            result.StringProperty.ShouldEqual(\"Test\");\r\n            result.IntProperty.ShouldEqual(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_default_body_deserializer_if_one_found()\r\n        {\r\n            // Given\r\n            var deserializer = A.Fake<IBodyDeserializer>();\r\n            A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);\r\n            A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(new[] { deserializer });\r\n            var binder = this.GetBinder();\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n\r\n            // When\r\n            binder.Bind(context, this.GetType(), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments()\r\n                .MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_default_type_converter_if_one_found()\r\n        {\r\n            // Given\r\n            var typeConverter = A.Fake<ITypeConverter>();\r\n            A.CallTo(() => typeConverter.CanConvertTo(typeof(string), null)).WithAnyArguments().Returns(true);\r\n            A.CallTo(() => typeConverter.Convert(null, null, null)).WithAnyArguments().Returns(null);\r\n            A.CallTo(() => this.emptyDefaults.DefaultTypeConverters).Returns(new[] { typeConverter });\r\n            var binder = this.GetBinder(ArrayCache.Empty<ITypeConverter>());\r\n            var context = new NancyContext { Request = new FakeRequest(\"GET\", \"/\") };\r\n            context.Request.Form[\"StringProperty\"] = \"Test\";\r\n\r\n            // When\r\n            binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            A.CallTo(() => typeConverter.Convert(null, null, null)).WithAnyArguments()\r\n                .MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void User_body_serializer_should_take_precedence_over_default_one()\r\n        {\r\n            // Given\r\n            var userDeserializer = A.Fake<IBodyDeserializer>();\r\n            A.CallTo(() => userDeserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);\r\n\r\n            var defaultDeserializer = A.Fake<IBodyDeserializer>();\r\n            A.CallTo(() => defaultDeserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);\r\n\r\n            A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(new[] { defaultDeserializer });\r\n            var binder = this.GetBinder(bodyDeserializers: new[] { userDeserializer });\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n\r\n            // When\r\n            binder.Bind(context, this.GetType(), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            A.CallTo(() => userDeserializer.Deserialize(null, null, null)).WithAnyArguments()\r\n                .MustHaveHappenedOnceExactly();\r\n            A.CallTo(() => defaultDeserializer.Deserialize(null, null, null)).WithAnyArguments()\r\n                .MustNotHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void User_type_converter_should_take_precedence_over_default_one()\r\n        {\r\n            // Given\r\n            var userTypeConverter = A.Fake<ITypeConverter>();\r\n            A.CallTo(() => userTypeConverter.CanConvertTo(typeof(string), null)).WithAnyArguments().Returns(true);\r\n            A.CallTo(() => userTypeConverter.Convert(null, null, null)).WithAnyArguments().Returns(null);\r\n            var defaultTypeConverter = A.Fake<ITypeConverter>();\r\n            A.CallTo(() => defaultTypeConverter.CanConvertTo(typeof(string), null)).WithAnyArguments().Returns(true);\r\n            A.CallTo(() => defaultTypeConverter.Convert(null, null, null)).WithAnyArguments().Returns(null);\r\n            A.CallTo(() => this.emptyDefaults.DefaultTypeConverters).Returns(new[] { defaultTypeConverter });\r\n            var binder = this.GetBinder(new[] { userTypeConverter });\r\n            var context = new NancyContext { Request = new FakeRequest(\"GET\", \"/\") };\r\n            context.Request.Form[\"StringProperty\"] = \"Test\";\r\n\r\n            // When\r\n            binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            A.CallTo(() => userTypeConverter.Convert(null, null, null)).WithAnyArguments()\r\n                .MustHaveHappenedOnceExactly();\r\n            A.CallTo(() => defaultTypeConverter.Convert(null, null, null)).WithAnyArguments()\r\n                .MustNotHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_bind_model_from_request()\r\n        {\r\n            // Given\r\n            var binder = this.GetBinder();\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n            context.Request.Query[\"StringProperty\"] = \"Test\";\r\n            context.Request.Query[\"IntProperty\"] = \"3\";\r\n\r\n            // When\r\n            var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.StringProperty.ShouldEqual(\"Test\");\r\n            result.IntProperty.ShouldEqual(3);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_bind_inherited_model_from_request()\r\n        {\r\n            // Given\r\n            var binder = this.GetBinder();\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n            context.Request.Query[\"StringProperty\"] = \"Test\";\r\n            context.Request.Query[\"IntProperty\"] = \"3\";\r\n            context.Request.Query[\"AnotherProperty\"] = \"Hello\";\r\n\r\n            // When\r\n            var result = (InheritedTestModel)binder.Bind(context, typeof(InheritedTestModel), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.StringProperty.ShouldEqual(\"Test\");\r\n            result.IntProperty.ShouldEqual(3);\r\n            result.AnotherProperty.ShouldEqual(\"Hello\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_bind_model_from_context_parameters()\r\n        {\r\n            // Given\r\n            var binder = this.GetBinder();\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n            context.Parameters[\"StringProperty\"] = \"Test\";\r\n            context.Parameters[\"IntProperty\"] = \"3\";\r\n\r\n            // When\r\n            var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.StringProperty.ShouldEqual(\"Test\");\r\n            result.IntProperty.ShouldEqual(3);\r\n        }\r\n\r\n        [Fact]\r\n        public void Form_properties_should_take_precendence_over_request_properties()\r\n        {\r\n            // Given\r\n            var binder = this.GetBinder();\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n            context.Request.Form[\"StringProperty\"] = \"Test\";\r\n            context.Request.Form[\"IntProperty\"] = \"3\";\r\n            context.Request.Query[\"StringProperty\"] = \"Test2\";\r\n            context.Request.Query[\"IntProperty\"] = \"1\";\r\n\r\n            // When\r\n            var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.StringProperty.ShouldEqual(\"Test\");\r\n            result.IntProperty.ShouldEqual(3);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_bind_multiple_Form_properties_to_list()\r\n        {\r\n            //Given\r\n            var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };\r\n            var binder = this.GetBinder(typeConverters);\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/x-www-form-urlencoded\" });\r\n            context.Request.Form[\"StringProperty_0\"] = \"Test\";\r\n            context.Request.Form[\"IntProperty_0\"] = \"1\";\r\n            context.Request.Form[\"StringProperty_1\"] = \"Test2\";\r\n            context.Request.Form[\"IntProperty_1\"] = \"2\";\r\n\r\n            // When\r\n            var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.First().StringProperty.ShouldEqual(\"Test\");\r\n            result.First().IntProperty.ShouldEqual(1);\r\n            result.Last().StringProperty.ShouldEqual(\"Test2\");\r\n            result.Last().IntProperty.ShouldEqual(2);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_bind_more_than_10_multiple_Form_properties_to_list()\r\n        {\r\n            //Given\r\n            var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };\r\n            var binder = this.GetBinder(typeConverters);\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/x-www-form-urlencoded\" });\r\n            context.Request.Form[\"IntProperty_0\"] = \"1\";\r\n            context.Request.Form[\"IntProperty_01\"] = \"2\";\r\n            context.Request.Form[\"IntProperty_02\"] = \"3\";\r\n            context.Request.Form[\"IntProperty_03\"] = \"4\";\r\n            context.Request.Form[\"IntProperty_04\"] = \"5\";\r\n            context.Request.Form[\"IntProperty_05\"] = \"6\";\r\n            context.Request.Form[\"IntProperty_06\"] = \"7\";\r\n            context.Request.Form[\"IntProperty_07\"] = \"8\";\r\n            context.Request.Form[\"IntProperty_08\"] = \"9\";\r\n            context.Request.Form[\"IntProperty_09\"] = \"10\";\r\n            context.Request.Form[\"IntProperty_10\"] = \"11\";\r\n            context.Request.Form[\"IntProperty_11\"] = \"12\";\r\n            context.Request.Form[\"IntProperty_12\"] = \"13\";\r\n\r\n            // When\r\n            var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.First().IntProperty.ShouldEqual(1);\r\n            result.ElementAt(1).IntProperty.ShouldEqual(2);\r\n            result.Last().IntProperty.ShouldEqual(13);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_bind_more_than_10_multiple_Form_properties_to_list_should_work_with_padded_zeros()\r\n        {\r\n            //Given\r\n            var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };\r\n            var binder = this.GetBinder(typeConverters);\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/x-www-form-urlencoded\" });\r\n            context.Request.Form[\"IntProperty_00\"] = \"1\";\r\n            context.Request.Form[\"IntProperty_01\"] = \"2\";\r\n            context.Request.Form[\"IntProperty_02\"] = \"3\";\r\n            context.Request.Form[\"IntProperty_03\"] = \"4\";\r\n            context.Request.Form[\"IntProperty_04\"] = \"5\";\r\n            context.Request.Form[\"IntProperty_05\"] = \"6\";\r\n            context.Request.Form[\"IntProperty_06\"] = \"7\";\r\n            context.Request.Form[\"IntProperty_07\"] = \"8\";\r\n            context.Request.Form[\"IntProperty_08\"] = \"9\";\r\n            context.Request.Form[\"IntProperty_09\"] = \"10\";\r\n            context.Request.Form[\"IntProperty_10\"] = \"11\";\r\n            context.Request.Form[\"IntProperty_11\"] = \"12\";\r\n            context.Request.Form[\"IntProperty_12\"] = \"13\";\r\n\r\n            // When\r\n            var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.First().IntProperty.ShouldEqual(1);\r\n            result.Last().IntProperty.ShouldEqual(13);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_bind_more_than_10_multiple_Form_properties_to_list_starting_counting_from_1()\r\n        {\r\n            //Given\r\n            var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };\r\n            var binder = this.GetBinder(typeConverters);\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/x-www-form-urlencoded\" });\r\n            context.Request.Form[\"IntProperty_01\"] = \"1\";\r\n            context.Request.Form[\"IntProperty_02\"] = \"2\";\r\n            context.Request.Form[\"IntProperty_03\"] = \"3\";\r\n            context.Request.Form[\"IntProperty_04\"] = \"4\";\r\n            context.Request.Form[\"IntProperty_05\"] = \"5\";\r\n            context.Request.Form[\"IntProperty_06\"] = \"6\";\r\n            context.Request.Form[\"IntProperty_07\"] = \"7\";\r\n            context.Request.Form[\"IntProperty_08\"] = \"8\";\r\n            context.Request.Form[\"IntProperty_09\"] = \"9\";\r\n            context.Request.Form[\"IntProperty_10\"] = \"10\";\r\n            context.Request.Form[\"IntProperty_11\"] = \"11\";\r\n            context.Request.Form[\"IntProperty_12\"] = \"12\";\r\n\r\n            // When\r\n            var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.First().IntProperty.ShouldEqual(1);\r\n            result.Last().IntProperty.ShouldEqual(12);\r\n        }\r\n\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_bind_more_than_once_should_ignore_non_list_properties_when_binding_to_a_list()\r\n        {\r\n            // Given\r\n            var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };\r\n            var binder = this.GetBinder(typeConverters);\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/x-www-form-urlencoded\" });\r\n\r\n            context.Request.Form[\"StringProperty\"] = \"Test\";\r\n            context.Request.Form[\"IntProperty\"] = \"3\";\r\n\r\n            context.Request.Form[\"NestedIntProperty[0]\"] = \"1\";\r\n            context.Request.Form[\"NestedIntField[0]\"] = \"2\";\r\n            context.Request.Form[\"NestedStringProperty[0]\"] = \"one\";\r\n            context.Request.Form[\"NestedStringField[0]\"] = \"two\";\r\n\r\n            context.Request.Form[\"NestedIntProperty[1]\"] = \"3\";\r\n            context.Request.Form[\"NestedIntField[1]\"] = \"4\";\r\n            context.Request.Form[\"NestedStringProperty[1]\"] = \"three\";\r\n            context.Request.Form[\"NestedStringField[1]\"] = \"four\";\r\n\r\n            // When\r\n            var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);\r\n            var result2 = (List<AnotherTestModel>)binder.Bind(context, typeof(List<AnotherTestModel>), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.StringProperty.ShouldEqual(\"Test\");\r\n            result.IntProperty.ShouldEqual(3);\r\n\r\n            result2.ShouldHaveCount(2);\r\n            result2.First().NestedIntProperty.ShouldEqual(1);\r\n            result2.First().NestedIntField.ShouldEqual(2);\r\n            result2.First().NestedStringProperty.ShouldEqual(\"one\");\r\n            result2.First().NestedStringField.ShouldEqual(\"two\");\r\n            result2.Last().NestedIntProperty.ShouldEqual(3);\r\n            result2.Last().NestedIntField.ShouldEqual(4);\r\n            result2.Last().NestedStringProperty.ShouldEqual(\"three\");\r\n            result2.Last().NestedStringField.ShouldEqual(\"four\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_bind_more_than_10_multiple_Form_properties_to_list_starting_with_jagged_ids()\r\n        {\r\n            //Given\r\n            var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };\r\n            var binder = this.GetBinder(typeConverters);\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/x-www-form-urlencoded\" });\r\n            context.Request.Form[\"IntProperty_01\"] = \"1\";\r\n            context.Request.Form[\"IntProperty_04\"] = \"2\";\r\n            context.Request.Form[\"IntProperty_05\"] = \"3\";\r\n            context.Request.Form[\"IntProperty_06\"] = \"4\";\r\n            context.Request.Form[\"IntProperty_09\"] = \"5\";\r\n            context.Request.Form[\"IntProperty_11\"] = \"6\";\r\n            context.Request.Form[\"IntProperty_57\"] = \"7\";\r\n            context.Request.Form[\"IntProperty_199\"] = \"8\";\r\n            context.Request.Form[\"IntProperty_1599\"] = \"9\";\r\n            context.Request.Form[\"StringProperty_1599\"] = \"nine\";\r\n            context.Request.Form[\"IntProperty_233\"] = \"10\";\r\n            context.Request.Form[\"IntProperty_14\"] = \"11\";\r\n            context.Request.Form[\"IntProperty_12\"] = \"12\";\r\n\r\n            // When\r\n            var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.First().IntProperty.ShouldEqual(1);\r\n            result.Last().IntProperty.ShouldEqual(9);\r\n            result.Last().StringProperty.ShouldEqual(\"nine\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_bind_to_IEnumerable_from_Form()\r\n        {\r\n            //Given\r\n            var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };\r\n            var binder = this.GetBinder(typeConverters);\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/x-www-form-urlencoded\" });\r\n\r\n            context.Request.Form[\"IntValuesProperty\"] = \"1,2,3,4\";\r\n            context.Request.Form[\"IntValuesField\"] = \"5,6,7,8\";\r\n\r\n            // When\r\n            var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.IntValuesProperty.ShouldHaveCount(4);\r\n            result.IntValuesProperty.ShouldEqualSequence(new[] { 1, 2, 3, 4 });\r\n            result.IntValuesField.ShouldHaveCount(4);\r\n            result.IntValuesField.ShouldEqualSequence(new[] { 5, 6, 7, 8 });\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_bind_to_IEnumerable_from_Form_with_multiple_inputs()\r\n        {\r\n            // Given\r\n            var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };\r\n            var binder = this.GetBinder(typeConverters);\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/x-www-form-urlencoded\" });\r\n\r\n            context.Request.Form[\"IntValuesProperty_0\"] = \"1,2,3,4\";\r\n            context.Request.Form[\"IntValuesField_0\"] = \"5,6,7,8\";\r\n            context.Request.Form[\"IntValuesProperty_1\"] = \"9,10,11,12\";\r\n            context.Request.Form[\"IntValuesField_1\"] = \"13,14,15,16\";\r\n\r\n            // When\r\n            var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.ShouldHaveCount(2);\r\n            result.First().IntValuesProperty.ShouldHaveCount(4);\r\n            result.First().IntValuesProperty.ShouldEqualSequence(new[] { 1, 2, 3, 4 });\r\n            result.First().IntValuesField.ShouldHaveCount(4);\r\n            result.First().IntValuesField.ShouldEqualSequence(new[] { 5, 6, 7, 8 });\r\n            result.Last().IntValuesProperty.ShouldHaveCount(4);\r\n            result.Last().IntValuesProperty.ShouldEqualSequence(new[] { 9, 10, 11, 12 });\r\n            result.Last().IntValuesField.ShouldHaveCount(4);\r\n            result.Last().IntValuesField.ShouldEqualSequence(new[] { 13, 14, 15, 16 });\r\n        }\r\n\r\n\r\n        [Fact]\r\n        public void Should_bind_to_IEnumerable_from_Form_with_multiple_inputs_using_brackets_and_specifying_an_instance()\r\n        {\r\n            // Given\r\n            var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };\r\n            var binder = this.GetBinder(typeConverters);\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/x-www-form-urlencoded\" });\r\n\r\n            context.Request.Form[\"IntValuesProperty[0]\"] = \"1,2,3,4\";\r\n            context.Request.Form[\"IntValuesField[0]\"] = \"5,6,7,8\";\r\n            context.Request.Form[\"IntValuesProperty[1]\"] = \"9,10,11,12\";\r\n            context.Request.Form[\"IntValuesField[1]\"] = \"13,14,15,16\";\r\n\r\n            // When\r\n            var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), new List<TestModel> { new TestModel {AnotherStringProperty = \"Test\"} }, new BindingConfig { Overwrite = false});\r\n\r\n            // Then\r\n            result.ShouldHaveCount(2);\r\n            result.First().AnotherStringProperty.ShouldEqual(\"Test\");\r\n            result.First().IntValuesProperty.ShouldHaveCount(4);\r\n            result.First().IntValuesProperty.ShouldEqualSequence(new[] { 1, 2, 3, 4 });\r\n            result.First().IntValuesField.ShouldHaveCount(4);\r\n            result.First().IntValuesField.ShouldEqualSequence(new[] { 5, 6, 7, 8 });\r\n            result.Last().AnotherStringProperty.ShouldBeNull();\r\n            result.Last().IntValuesProperty.ShouldHaveCount(4);\r\n            result.Last().IntValuesProperty.ShouldEqualSequence(new[] { 9, 10, 11, 12 });\r\n            result.Last().IntValuesField.ShouldHaveCount(4);\r\n            result.Last().IntValuesField.ShouldEqualSequence(new[] { 13, 14, 15, 16 });\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_bind_to_IEnumerable_from_Form_with_multiple_inputs_using_brackets()\r\n        {\r\n            // Given\r\n            var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };\r\n            var binder = this.GetBinder(typeConverters);\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/x-www-form-urlencoded\" });\r\n\r\n            context.Request.Form[\"IntValuesProperty[0]\"] = \"1,2,3,4\";\r\n            context.Request.Form[\"IntValuesField[0]\"] = \"5,6,7,8\";\r\n            context.Request.Form[\"IntValuesProperty[1]\"] = \"9,10,11,12\";\r\n            context.Request.Form[\"IntValuesField[1]\"] = \"13,14,15,16\";\r\n\r\n            // When\r\n            var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.ShouldHaveCount(2);\r\n            result.First().IntValuesProperty.ShouldHaveCount(4);\r\n            result.First().IntValuesProperty.ShouldEqualSequence(new[] { 1, 2, 3, 4 });\r\n            result.First().IntValuesField.ShouldHaveCount(4);\r\n            result.First().IntValuesField.ShouldEqualSequence(new[] { 5, 6, 7, 8 });\r\n            result.Last().IntValuesProperty.ShouldHaveCount(4);\r\n            result.Last().IntValuesProperty.ShouldEqualSequence(new[] { 9, 10, 11, 12 });\r\n            result.Last().IntValuesField.ShouldHaveCount(4);\r\n            result.Last().IntValuesField.ShouldEqualSequence(new[] { 13, 14, 15, 16 });\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_bind_collections_regardless_of_case()\r\n        {\r\n            // Given\r\n            var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };\r\n            var binder = this.GetBinder(typeConverters);\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/x-www-form-urlencoded\" });\r\n\r\n            context.Request.Form[\"lowercaseintproperty[0]\"] = \"1\";\r\n            context.Request.Form[\"lowercaseintproperty[1]\"] = \"2\";\r\n            context.Request.Form[\"lowercaseIntproperty[2]\"] = \"3\";\r\n            context.Request.Form[\"lowercaseIntproperty[3]\"] = \"4\";\r\n            context.Request.Form[\"Lowercaseintproperty[4]\"] = \"5\";\r\n            context.Request.Form[\"Lowercaseintproperty[5]\"] = \"6\";\r\n            context.Request.Form[\"LowercaseIntproperty[6]\"] = \"7\";\r\n            context.Request.Form[\"LowercaseIntproperty[7]\"] = \"8\";\r\n\r\n            context.Request.Form[\"lowercaseintfield[0]\"] = \"9\";\r\n            context.Request.Form[\"lowercaseintfield[1]\"] = \"10\";\r\n            context.Request.Form[\"lowercaseIntfield[2]\"] = \"11\";\r\n            context.Request.Form[\"lowercaseIntfield[3]\"] = \"12\";\r\n            context.Request.Form[\"Lowercaseintfield[4]\"] = \"13\";\r\n            context.Request.Form[\"Lowercaseintfield[5]\"] = \"14\";\r\n            context.Request.Form[\"LowercaseIntfield[6]\"] = \"15\";\r\n            context.Request.Form[\"LowercaseIntfield[7]\"] = \"16\";\r\n\r\n            // When\r\n            var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.ShouldHaveCount(8);\r\n            result.First().lowercaseintproperty.ShouldEqual(1);\r\n            result.Last().lowercaseintproperty.ShouldEqual(8);\r\n            result.First().lowercaseintfield.ShouldEqual(9);\r\n            result.Last().lowercaseintfield.ShouldEqual(16);\r\n        }\r\n\r\n        [Fact]\r\n        public void Form_properties_should_take_precendence_over_request_properties_and_context_properties()\r\n        {\r\n            // Given\r\n            var binder = this.GetBinder();\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n            context.Request.Form[\"StringProperty\"] = \"Test\";\r\n            context.Request.Form[\"IntProperty\"] = \"3\";\r\n            context.Request.Query[\"StringProperty\"] = \"Test2\";\r\n            context.Request.Query[\"IntProperty\"] = \"1\";\r\n            context.Parameters[\"StringProperty\"] = \"Test3\";\r\n            context.Parameters[\"IntProperty\"] = \"2\";\r\n\r\n            // When\r\n            var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);\r\n            // Then\r\n            result.StringProperty.ShouldEqual(\"Test\");\r\n            result.IntProperty.ShouldEqual(3);\r\n        }\r\n\r\n        [Fact]\r\n        public void Request_properties_should_take_precendence_over_context_properties()\r\n        {\r\n            // Given\r\n            var binder = this.GetBinder();\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n\r\n            context.Request.Query[\"StringProperty\"] = \"Test\";\r\n            context.Request.Query[\"IntProperty\"] = \"12\";\r\n            context.Parameters[\"StringProperty\"] = \"Test2\";\r\n            context.Parameters[\"IntProperty\"] = \"13\";\r\n\r\n            // When\r\n            var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);\r\n            // Then\r\n            result.StringProperty.ShouldEqual(\"Test\");\r\n            result.IntProperty.ShouldEqual(12);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_bind_from_form_and_request_simultaneously()\r\n        {\r\n            // Given\r\n            var binder = this.GetBinder();\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n            context.Request.Form[\"StringProperty\"] = \"Test\";\r\n            context.Request.Query[\"IntProperty\"] = \"12\";\r\n\r\n            // When\r\n            var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.StringProperty.ShouldEqual(\"Test\");\r\n            result.IntProperty.ShouldEqual(12);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"de-DE\", 4.50)]\r\n        [InlineData(\"en-GB\", 450)]\r\n        [InlineData(\"en-US\", 450)]\r\n        [InlineData(\"sv-SE\", 4.50)]\r\n        [InlineData(\"ru-RU\", 4.50)]\r\n        [InlineData(\"zh-TW\", 450)]\r\n        public void Should_be_able_to_bind_culturally_aware_form_properties_if_numeric(string culture, double expected)\r\n        {\r\n            // Given\r\n            var binder = this.GetBinder();\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n            context.Culture = new CultureInfo(culture);\r\n            context.Request.Form[\"DoubleProperty\"] = \"4,50\";\r\n\r\n            // When\r\n            var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.DoubleProperty.ShouldEqual(expected);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"12/25/2012\", 12, 25, 2012, \"en-US\")]\r\n        [InlineData(\"12/12/2012\", 12, 12, 2012, \"en-US\")]\r\n        [InlineData(\"25/12/2012\", 12, 25, 2012, \"en-GB\")]\r\n        [InlineData(\"12/12/2012\", 12, 12, 2012, \"en-GB\")]\r\n        [InlineData(\"12/12/2012\", 12, 12, 2012, \"ru-RU\")]\r\n        [InlineData(\"25/12/2012\", 12, 25, 2012, \"ru-RU\")]\r\n        [InlineData(\"2012-12-25\", 12, 25, 2012, \"zh-TW\")]\r\n        [InlineData(\"2012-12-12\", 12, 12, 2012, \"zh-TW\")]\r\n        public void Should_be_able_to_bind_culturally_aware_form_properties_if_datetime(string date, int month, int day, int year, string culture)\r\n        {\r\n            // Given\r\n            var binder = this.GetBinder();\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n            context.Culture = new CultureInfo(culture);\r\n            context.Request.Form[\"DateProperty\"] = date;\r\n\r\n            // When\r\n            var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.DateProperty.Date.Month.ShouldEqual(month);\r\n            result.DateProperty.Date.Day.ShouldEqual(day);\r\n            result.DateProperty.Date.Year.ShouldEqual(year);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_bind_from_request_and_context_simultaneously()\r\n        {\r\n            // Given\r\n            var binder = this.GetBinder();\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n            context.Request.Query[\"StringProperty\"] = \"Test\";\r\n            context.Parameters[\"IntProperty\"] = \"12\";\r\n\r\n            // When\r\n            var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.StringProperty.ShouldEqual(\"Test\");\r\n            result.IntProperty.ShouldEqual(12);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_overwrite_nullable_property_if_already_set_and_overwriting_is_not_allowed()\r\n        {\r\n            // Given\r\n            var binder = this.GetBinder();\r\n            var existing = new TestModel { StringProperty = \"Existing Value\" };\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n\r\n            context.Request.Query[\"StringProperty\"] = \"Test\";\r\n            context.Request.Query[\"IntProperty\"] = \"12\";\r\n            context.Parameters[\"StringProperty\"] = \"Test2\";\r\n            context.Parameters[\"IntProperty\"] = \"1\";\r\n\r\n            // When\r\n            var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.NoOverwrite);\r\n\r\n            // Then\r\n            result.StringProperty.ShouldEqual(\"Existing Value\");\r\n            result.IntProperty.ShouldEqual(12);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_overwrite_non_nullable_property_if_already_set_and_overwriting_is_not_allowed()\r\n        {\r\n            // Given\r\n            var binder = this.GetBinder();\r\n            var existing = new TestModel { IntProperty = 27 };\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n\r\n            context.Request.Query[\"StringProperty\"] = \"Test\";\r\n            context.Request.Query[\"IntProperty\"] = \"12\";\r\n            context.Parameters[\"StringProperty\"] = \"Test2\";\r\n            context.Parameters[\"IntProperty\"] = \"1\";\r\n\r\n            // When\r\n            var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.NoOverwrite);\r\n\r\n            // Then\r\n            result.StringProperty.ShouldEqual(\"Test\");\r\n            result.IntProperty.ShouldEqual(27);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_overwrite_nullable_property_if_already_set_and_overwriting_is_allowed()\r\n        {\r\n            // Given\r\n            var binder = this.GetBinder();\r\n            var existing = new TestModel { StringProperty = \"Existing Value\" };\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n\r\n            context.Parameters[\"StringProperty\"] = \"Test2\";\r\n            context.Parameters[\"IntProperty\"] = \"1\";\r\n\r\n            // When\r\n            var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.StringProperty.ShouldEqual(\"Test2\");\r\n            result.IntProperty.ShouldEqual(1);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_overwrite_non_nullable_property_if_already_set_and_overwriting_is_allowed()\r\n        {\r\n            // Given\r\n            var binder = this.GetBinder();\r\n            var existing = new TestModel { IntProperty = 27 };\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n\r\n            context.Parameters[\"StringProperty\"] = \"Test2\";\r\n            context.Parameters[\"IntProperty\"] = \"1\";\r\n\r\n            // When\r\n            var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.StringProperty.ShouldEqual(\"Test2\");\r\n            result.IntProperty.ShouldEqual(1);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_bind_list_model_from_body()\r\n        {\r\n            //Given\r\n            var binder = this.GetBinder(null, new List<IBodyDeserializer> { new XmlBodyDeserializer() });\r\n            var body = XmlBodyDeserializerFixture.ToXmlString(new List<TestModel>(new[] { new TestModel { StringProperty = \"Test\" }, new TestModel { StringProperty = \"AnotherTest\" } }));\r\n\r\n            var context = CreateContextWithHeaderAndBody(\"Content-Type\", new[] { \"application/xml\" }, body);\r\n\r\n            // When\r\n            var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.First().StringProperty.ShouldEqual(\"Test\");\r\n            result.Last().StringProperty.ShouldEqual(\"AnotherTest\");\r\n        }\r\n\r\n\r\n        [Fact]\r\n        public void Should_bind_array_model_from_body()\r\n        {\r\n            //Given\r\n            var binder = this.GetBinder(null, new List<IBodyDeserializer> { new XmlBodyDeserializer() });\r\n            var body = XmlBodyDeserializerFixture.ToXmlString(new List<TestModel>(new[] { new TestModel { StringProperty = \"Test\" }, new TestModel { StringProperty = \"AnotherTest\" } }));\r\n\r\n            var context = CreateContextWithHeaderAndBody(\"Content-Type\", new[] { \"application/xml\" }, body);\r\n\r\n            // When\r\n            var result = (TestModel[])binder.Bind(context, typeof(TestModel[]), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.First().StringProperty.ShouldEqual(\"Test\");\r\n            result.Last().StringProperty.ShouldEqual(\"AnotherTest\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_bind_string_array_model_from_body()\r\n        {\r\n            //Given\r\n            var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) });\r\n            var body = serializer.Serialize(new[] { \"Test\",\"AnotherTest\"});\r\n\r\n            var context = CreateContextWithHeaderAndBody(\"Content-Type\", new[] { \"application/json\" }, body);\r\n\r\n            // When\r\n            var result = (string[])binder.Bind(context, typeof(string[]), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.First().ShouldEqual(\"Test\");\r\n            result.Last().ShouldEqual(\"AnotherTest\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_bind_ienumerable_model_from_body()\r\n        {\r\n            //Given\r\n            var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) });\r\n            var body = serializer.Serialize(new List<TestModel>(new[] { new TestModel { StringProperty = \"Test\" }, new TestModel { StringProperty = \"AnotherTest\" } }));\r\n\r\n            var context = CreateContextWithHeaderAndBody(\"Content-Type\", new[] { \"application/json\" }, body);\r\n\r\n            // When\r\n            var result = (IEnumerable<TestModel>)binder.Bind(context, typeof(IEnumerable<TestModel>), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.First().StringProperty.ShouldEqual(\"Test\");\r\n            result.Last().StringProperty.ShouldEqual(\"AnotherTest\");\r\n        }\r\n\r\n\r\n        [Fact]\r\n        public void Should_bind_ienumerable_model_with_instance_from_body()\r\n        {\r\n            //Given\r\n            var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) });\r\n            var body = serializer.Serialize(new List<TestModel>(new[] { new TestModel { StringProperty = \"Test\" }, new TestModel { StringProperty = \"AnotherTest\" } }));\r\n\r\n            var context = CreateContextWithHeaderAndBody(\"Content-Type\", new[] { \"application/json\" }, body);\r\n\r\n            var then = DateTime.Now;\r\n            var instance = new List<TestModel> { new TestModel{ DateProperty = then }, new TestModel { IntProperty = 9, AnotherStringProperty = \"Bananas\" } };\r\n\r\n            // When\r\n            var result = (IEnumerable<TestModel>)binder.Bind(context, typeof(IEnumerable<TestModel>), instance, new BindingConfig{Overwrite = false});\r\n\r\n            // Then\r\n            result.First().StringProperty.ShouldEqual(\"Test\");\r\n            result.First().DateProperty.ShouldEqual(then);\r\n            result.Last().StringProperty.ShouldEqual(\"AnotherTest\");\r\n            result.Last().IntProperty.ShouldEqual(9);\r\n            result.Last().AnotherStringProperty.ShouldEqual(\"Bananas\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_bind_model_with_instance_from_body()\r\n        {\r\n            //Given\r\n            var binder = this.GetBinder(null, new List<IBodyDeserializer> { new XmlBodyDeserializer() });\r\n            var body = XmlBodyDeserializerFixture.ToXmlString(new TestModel { StringProperty = \"Test\" });\r\n\r\n            var context = CreateContextWithHeaderAndBody(\"Content-Type\", new[] { \"application/xml\" }, body);\r\n\r\n            var then = DateTime.Now;\r\n            var instance = new TestModel { DateProperty = then, IntProperty = 6, AnotherStringProperty = \"Beers\" };\r\n\r\n            // Wham\r\n            var result = (TestModel)binder.Bind(context, typeof(TestModel), instance, new BindingConfig { Overwrite = false });\r\n\r\n            // Then\r\n            result.StringProperty.ShouldEqual(\"Test\");\r\n            result.DateProperty.ShouldEqual(then);\r\n            result.IntProperty.ShouldEqual(6);\r\n            result.AnotherStringProperty.ShouldEqual(\"Beers\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_bind_model_from_body_that_contains_an_array()\r\n        {\r\n            //Given\r\n            var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };\r\n            var binder = this.GetBinder(typeConverters, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) });\r\n            var body = serializer.Serialize(\r\n                new TestModel\r\n                {\r\n                  StringProperty = \"Test\",\r\n                  SomeStringsProperty = new[] { \"E\", \"A\", \"D\", \"G\", \"B\", \"E\" },\r\n                  SomeStringsField = new[] { \"G\", \"D\", \"A\", \"E\" },\r\n                });\r\n\r\n            var context = CreateContextWithHeaderAndBody(\"Content-Type\", new[] { \"application/json\" }, body);\r\n\r\n            // When\r\n            var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.SomeStringsProperty.ShouldHaveCount(6);\r\n            result.SomeStringsProperty.ShouldEqualSequence(new[] { \"E\", \"A\", \"D\", \"G\", \"B\", \"E\" });\r\n            result.SomeStringsField.ShouldHaveCount(4);\r\n            result.SomeStringsField.ShouldEqualSequence(new[] { \"G\", \"D\", \"A\", \"E\" });\r\n        }\r\n\r\n\r\n        [Fact]\r\n        public void Should_bind_array_model_from_body_that_contains_an_array()\r\n        {\r\n            //Given\r\n            var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) });\r\n            var body =\r\n                serializer.Serialize(new[]\r\n                {\r\n                    new TestModel()\r\n                    {\r\n                        StringProperty = \"Test\",\r\n                        SomeStringsProperty = new[] {\"E\", \"A\", \"D\", \"G\", \"B\", \"E\"},\r\n                        SomeStringsField = new[] { \"G\", \"D\", \"A\", \"E\" },\r\n                    },\r\n                    new TestModel()\r\n                    {\r\n                        StringProperty = \"AnotherTest\",\r\n                        SomeStringsProperty = new[] {\"E\", \"A\", \"D\", \"G\", \"B\", \"E\"},\r\n                        SomeStringsField = new[] { \"G\", \"D\", \"A\", \"E\" },\r\n                    }\r\n                });\r\n\r\n            var context = CreateContextWithHeaderAndBody(\"Content-Type\", new[] { \"application/json\" }, body);\r\n\r\n            // When\r\n            var result = (TestModel[])binder.Bind(context, typeof(TestModel[]), null, BindingConfig.Default, \"SomeStringsProperty\", \"SomeStringsField\");\r\n\r\n            // Then\r\n            result.ShouldHaveCount(2);\r\n            result.First().SomeStringsProperty.ShouldBeNull();\r\n            result.First().SomeStringsField.ShouldBeNull();\r\n            result.Last().SomeStringsProperty.ShouldBeNull();\r\n            result.Last().SomeStringsField.ShouldBeNull();\r\n        }\r\n\r\n\r\n        [Fact]\r\n        public void Form_request_and_context_properties_should_take_precedence_over_body_properties()\r\n        {\r\n            // Given\r\n            var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };\r\n            var bodyDeserializers = new IBodyDeserializer[] { new XmlBodyDeserializer() };\r\n            var binder = this.GetBinder(typeConverters, bodyDeserializers);\r\n            var body = XmlBodyDeserializerFixture.ToXmlString(new TestModel { IntProperty = 0, StringProperty = \"From body\" });\r\n\r\n            var context = CreateContextWithHeaderAndBody(\"Content-Type\", new[] { \"application/xml\" }, body);\r\n\r\n            context.Request.Form[\"StringProperty\"] = \"From form\";\r\n            context.Request.Query[\"IntProperty\"] = \"1\";\r\n            context.Parameters[\"AnotherStringProperty\"] = \"From context\";\r\n\r\n            // When\r\n            var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.StringProperty.ShouldEqual(\"From form\");\r\n            result.AnotherStringProperty.ShouldEqual(\"From context\");\r\n            result.IntProperty.ShouldEqual(1);\r\n        }\r\n\r\n        [Fact]\r\n        public void Form_request_and_context_properties_should_be_ignored_in_body_only_mode_when_there_is_a_body()\r\n        {\r\n            // Given\r\n            var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };\r\n            var bodyDeserializers = new IBodyDeserializer[] { new XmlBodyDeserializer() };\r\n            var binder = GetBinder(typeConverters, bodyDeserializers);\r\n            var body = XmlBodyDeserializerFixture.ToXmlString(new TestModel { IntProperty = 2, StringProperty = \"From body\" });\r\n\r\n            var context = CreateContextWithHeaderAndBody(\"Content-Type\", new[] { \"application/xml\" }, body);\r\n\r\n            context.Request.Form[\"StringProperty\"] = \"From form\";\r\n            context.Request.Query[\"IntProperty\"] = \"1\";\r\n            context.Parameters[\"AnotherStringProperty\"] = \"From context\";\r\n\r\n            // When\r\n            var result = (TestModel)binder.Bind(context, typeof(TestModel), null, new BindingConfig { BodyOnly = true });\r\n\r\n            // Then\r\n            result.StringProperty.ShouldEqual(\"From body\");\r\n            result.AnotherStringProperty.ShouldBeNull(); // not in body, so default value\r\n            result.IntProperty.ShouldEqual(2);\r\n        }\r\n\r\n        [Fact]\r\n        public void Form_request_and_context_properties_should_NOT_be_used_in_body_only_mode_if_there_is_no_body()\r\n        {\r\n            // Given\r\n            var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };\r\n            var binder = GetBinder(typeConverters);\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n            context.Request.Form[\"StringProperty\"] = \"From form\";\r\n            context.Request.Query[\"IntProperty\"] = \"1\";\r\n            context.Parameters[\"AnotherStringProperty\"] = \"From context\";\r\n\r\n            // When\r\n            var result = (TestModel)binder.Bind(context, typeof(TestModel), null, new BindingConfig { BodyOnly = true });\r\n\r\n            // Then\r\n            result.StringProperty.ShouldEqual(null);\r\n            result.AnotherStringProperty.ShouldEqual(null);\r\n            result.IntProperty.ShouldEqual(0);\r\n        }\r\n\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_bind_body_request_form_and_context_properties()\r\n        {\r\n            //Given\r\n            var binder = this.GetBinder(null, new List<IBodyDeserializer> { new XmlBodyDeserializer() });\r\n            var body = XmlBodyDeserializerFixture.ToXmlString(new TestModel { DateProperty = new DateTime(2012, 8, 16) });\r\n\r\n            var context = CreateContextWithHeaderAndBody(\"Content-Type\", new[] { \"application/xml\" }, body);\r\n\r\n            context.Request.Form[\"IntProperty\"] = \"0\";\r\n            context.Request.Query[\"StringProperty\"] = \"From Query\";\r\n            context.Parameters[\"AnotherStringProperty\"] = \"From Context\";\r\n\r\n            // When\r\n            var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.StringProperty.ShouldEqual(\"From Query\");\r\n            result.IntProperty.ShouldEqual(0);\r\n            result.DateProperty.ShouldEqual(new DateTime(2012, 8, 16));\r\n            result.AnotherStringProperty.ShouldEqual(\"From Context\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_ignore_existing_instance_if_type_doesnt_match()\r\n        {\r\n            //Given\r\n            var binder = this.GetBinder();\r\n            var existing = new object();\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/xml\" });\r\n\r\n            // When\r\n            var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.ShouldNotBeSameAs(existing);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_bind_to_valuetype_from_body()\r\n        {\r\n            //Given\r\n            var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) });\r\n            var body = serializer.Serialize(1);\r\n\r\n            var context = CreateContextWithHeaderAndBody(\"Content-Type\", new[] { \"application/json\" }, body);\r\n\r\n            // When\r\n            var result = (int)binder.Bind(context, typeof(int), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.ShouldEqual(1);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_bind_ienumerable_model__of_valuetype_from_body()\r\n        {\r\n            //Given\r\n            var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer(GetTestingEnvironment()) });\r\n            var body = serializer.Serialize(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 });\r\n\r\n            var context = CreateContextWithHeaderAndBody(\"Content-Type\", new[] { \"application/json\" }, body);\r\n\r\n            // When\r\n            var result = (IEnumerable<int>)binder.Bind(context, typeof(IEnumerable<int>), null, BindingConfig.Default);\r\n\r\n            // Then\r\n            result.ShouldEqualSequence(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 });\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_bind_to_model_with_non_public_default_constructor()\r\n        {\r\n            var binder = this.GetBinder();\r\n\r\n            var context = CreateContextWithHeader(\"Content-Type\", new[] { \"application/json\" });\r\n            context.Request.Form[\"IntProperty\"] = \"10\";\r\n\r\n            var result = (TestModelWithHiddenDefaultConstructor)binder.Bind(context, typeof (TestModelWithHiddenDefaultConstructor), null, BindingConfig.Default);\r\n\r\n            result.ShouldNotBeNull();\r\n            result.IntProperty.ShouldEqual(10);\r\n        }\r\n\r\n        private IBinder GetBinder(IEnumerable<ITypeConverter> typeConverters = null, IEnumerable<IBodyDeserializer> bodyDeserializers = null, IFieldNameConverter nameConverter = null, BindingDefaults bindingDefaults = null)\r\n        {\r\n            var converters = typeConverters ?? new ITypeConverter[] { new DateTimeConverter(), new NumericConverter(), new FallbackConverter() };\r\n            var deserializers = bodyDeserializers ?? ArrayCache.Empty<IBodyDeserializer>();\r\n            var converter = nameConverter ?? this.passthroughNameConverter;\r\n            var defaults = bindingDefaults ?? this.emptyDefaults;\r\n\r\n            return new DefaultBinder(converters, deserializers, converter, defaults);\r\n        }\r\n\r\n        private static NancyContext CreateContextWithHeader(string name, IEnumerable<string> values)\r\n        {\r\n            var header = new Dictionary<string, IEnumerable<string>>\r\n            {\r\n                { name, values }\r\n            };\r\n\r\n            return new NancyContext\r\n            {\r\n                Request = new FakeRequest(\"GET\", \"/\", header),\r\n                Parameters = DynamicDictionary.Empty\r\n            };\r\n        }\r\n\r\n        private static NancyContext CreateContextWithHeaderAndBody(string name, IEnumerable<string> values, string body)\r\n        {\r\n            var header = new Dictionary<string, IEnumerable<string>>\r\n            {\r\n                { name, values }\r\n            };\r\n\r\n            byte[] byteArray = Encoding.UTF8.GetBytes(body);\r\n            var bodyStream = RequestStream.FromStream(new MemoryStream(byteArray));\r\n\r\n            return new NancyContext\r\n            {\r\n                Request = new FakeRequest(\"GET\", \"/\", header, bodyStream, \"http\", string.Empty),\r\n                Parameters = DynamicDictionary.Empty\r\n            };\r\n        }\r\n\r\n        private static INancyEnvironment GetTestingEnvironment()\r\n        {\r\n            var envionment =\r\n                new DefaultNancyEnvironment();\r\n\r\n            envionment.AddValue(JsonConfiguration.Default);\r\n            envionment.AddValue(GlobalizationConfiguration.Default);\r\n            return envionment;\r\n        }\r\n\r\n        public class TestModel\r\n        {\r\n            public TestModel()\r\n            {\r\n                this.StringPropertyWithDefaultValue = \"Default Property Value\";\r\n                this.StringFieldWithDefaultValue = \"Default Field Value\";\r\n            }\r\n\r\n            public string StringProperty { get; set; }\r\n\r\n            public string AnotherStringProperty { get; set; }\r\n\r\n            public string StringField;\r\n\r\n            public string AnotherStringField;\r\n\r\n            public int IntProperty { get; set; }\r\n\r\n            public int AnotherIntProperty { get; set; }\r\n\r\n            public int IntField;\r\n\r\n            public int AnotherIntField;\r\n\r\n            public int lowercaseintproperty { get; set; }\r\n\r\n            public int lowercaseintfield;\r\n\r\n            public DateTime DateProperty { get; set; }\r\n\r\n            public DateTime DateField;\r\n\r\n            public string StringPropertyWithDefaultValue { get; set; }\r\n\r\n            public string StringFieldWithDefaultValue;\r\n\r\n            public double DoubleProperty { get; set; }\r\n\r\n            public double DoubleField;\r\n\r\n            [XmlIgnore]\r\n            public IEnumerable<int> IntValuesProperty { get; set; }\r\n\r\n            [XmlIgnore]\r\n            public IEnumerable<int> IntValuesField;\r\n\r\n            public string[] SomeStringsProperty { get; set; }\r\n\r\n            public string[] SomeStringsField;\r\n\r\n            public int this[int index]\r\n            {\r\n                get { return 0; }\r\n                set { }\r\n            }\r\n\r\n            public List<AnotherTestModel> ModelsProperty { get; set; }\r\n\r\n            public List<AnotherTestModel> ModelsField;\r\n        }\r\n\r\n        public class InheritedTestModel : TestModel\r\n        {\r\n            public string AnotherProperty { get; set; }\r\n        }\r\n\r\n        public class AnotherTestModel\r\n        {\r\n            public string NestedStringProperty { get; set; }\r\n            public int NestedIntProperty { get; set; }\r\n            public double NestedDoubleProperty { get; set; }\r\n\r\n            public string NestedStringField;\r\n            public int NestedIntField;\r\n            public double NestedDoubleField;\r\n        }\r\n\r\n        private class ThrowingBodyDeserializer<T> : IBodyDeserializer where T : Exception, new()\r\n        {\r\n            public bool CanDeserialize(MediaRange mediaRange, BindingContext context)\r\n            {\r\n                return true;\r\n            }\r\n\r\n            public object Deserialize(MediaRange mediaRange, Stream bodyStream, BindingContext context)\r\n            {\r\n                throw new T();\r\n            }\r\n        }\r\n\r\n        public class TestModelWithHiddenDefaultConstructor\r\n        {\r\n            public int IntProperty { get; private set; }\r\n\r\n            private TestModelWithHiddenDefaultConstructor() { }\r\n        }\r\n    }\r\n\r\n    public class BindingConfigFixture\r\n    {\r\n        [Fact]\r\n        public void Should_allow_overwrite_on_new_instance()\r\n        {\r\n            // Given\r\n            // When\r\n            var instance = new BindingConfig();\r\n\r\n            // Then\r\n            instance.Overwrite.ShouldBeTrue();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/ModelBinding/DefaultBodyDeserializers/JsonBodyDeserializerFixture.cs",
    "content": "namespace Nancy.Tests.Unit.ModelBinding.DefaultBodyDeserializers\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Globalization;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Text;\r\n    using System.Threading;\r\n    using FakeItEasy;\r\n    using Nancy.Configuration;\r\n    using Nancy.Json;\r\n    using Nancy.ModelBinding;\r\n    using Nancy.ModelBinding.DefaultBodyDeserializers;\r\n    using Nancy.Tests.xUnitExtensions;\r\n    using Xunit;\r\n    using Xunit.Extensions;\r\n\r\n    public class JsonBodyDeserializerFixture\r\n    {\r\n        private readonly JavaScriptSerializer serializer;\r\n        private readonly JsonBodyDeserializer deserialize;\r\n        private readonly TestModel testModel;\r\n\r\n        public JsonBodyDeserializerFixture()\r\n        {\r\n            var environment = new DefaultNancyEnvironment();\r\n            environment.AddValue(JsonConfiguration.Default);\r\n            environment.AddValue(GlobalizationConfiguration.Default);\r\n\r\n            this.deserialize = new JsonBodyDeserializer(environment);\r\n\r\n            this.testModel = new TestModel()\r\n                {\r\n                    IntProperty = 12,\r\n                    StringProperty = \"More cowbell\",\r\n                    DateProperty = DateTime.Parse(\"2011/12/25\"),\r\n                    ArrayProperty = new[] { \"Ping\", \"Pong\" }\r\n                };\r\n\r\n            this.serializer = new JavaScriptSerializer();\r\n            this.serializer.RegisterConverters(JsonConfiguration.Default.Converters);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_report_false_for_can_deserialize_for_non_json_format()\r\n        {\r\n            // Given\r\n            const string contentType = \"application/xml\";\r\n\r\n            // When\r\n            var result = this.deserialize.CanDeserialize(contentType, A.Dummy<BindingContext>());\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_report_true_for_can_deserialize_for_application_json()\r\n        {\r\n            // Given\r\n            const string contentType = \"application/json\";\r\n\r\n            // When\r\n            var result = this.deserialize.CanDeserialize(contentType, A.Dummy<BindingContext>());\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_report_true_for_can_deserialize_for_text_json()\r\n        {\r\n            // Given\r\n            const string contentType = \"text/json\";\r\n\r\n            // When\r\n            var result = this.deserialize.CanDeserialize(contentType, A.Dummy<BindingContext>());\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_report_true_for_can_deserialize_for_custom_json_format()\r\n        {\r\n            // Given\r\n            const string contentType = \"application/vnd.org.nancyfx.mything+json\";\r\n\r\n            // When\r\n            var result = this.deserialize.CanDeserialize(contentType, A.Dummy<BindingContext>());\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_case_insensitive_in_can_deserialize()\r\n        {\r\n            // Given\r\n            const string contentType = \"appLicaTion/jsOn\";\r\n\r\n            // When\r\n            var result = this.deserialize.CanDeserialize(contentType, A.Dummy<BindingContext>());\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_deserialize_timespan()\r\n        {\r\n            // Given\r\n            var json = this.serializer.Serialize(TimeSpan.FromDays(14));\r\n            var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(json));\r\n            var context = new BindingContext()\r\n            {\r\n                DestinationType = typeof(TimeSpan),\r\n                ValidModelBindingMembers = BindingMemberInfo.Collect<TimeSpan>().ToList(),\r\n            };\r\n\r\n            // When\r\n            var result = (TimeSpan)this.deserialize.Deserialize(\r\n                            \"application/json\",\r\n                            bodyStream,\r\n                            context);\r\n\r\n            // Then\r\n            result.Days.ShouldEqual(14);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_deserialize_enum()\r\n        {\r\n            // Given\r\n            var json = this.serializer.Serialize(TestEnum.One);\r\n            var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(json));\r\n            var context = new BindingContext()\r\n            {\r\n                DestinationType = typeof (TestEnum),\r\n                ValidModelBindingMembers = BindingMemberInfo.Collect<TestEnum>().ToList(),\r\n            };\r\n\r\n            // When\r\n            var result = (TestEnum)this.deserialize.Deserialize(\r\n                \"application/json\",\r\n                bodyStream,\r\n                context);\r\n\r\n            // Then\r\n            result.ShouldEqual(TestEnum.One);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(TestEnum.Hundred)]\r\n        [InlineData(null)]\r\n        public void Should_deserialize_nullable_enum(TestEnum? propertyValue)\r\n        {\r\n            var context = new BindingContext()\r\n            {\r\n                DestinationType = typeof(TestModel),\r\n                ValidModelBindingMembers = BindingMemberInfo.Collect<TestModel>().ToList(),\r\n            };\r\n\r\n            var model = new TestModel { NullableEnumProperty = propertyValue };\r\n\r\n            var s = new JavaScriptSerializer();\r\n            var serialized = s.Serialize(model);\r\n            var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(serialized));\r\n\r\n            // When\r\n            var result = (TestModel)this.deserialize.Deserialize(\r\n                \"application/json\",\r\n                bodyStream,\r\n                context);\r\n\r\n            // Then\r\n            result.NullableEnumProperty.ShouldEqual(propertyValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_deserialize_list_of_primitives()\r\n        {\r\n            // Given\r\n            var context = new BindingContext()\r\n            {\r\n                DestinationType = typeof (TestModel),\r\n                ValidModelBindingMembers = BindingMemberInfo.Collect<TestModel>().ToList(),\r\n            };\r\n\r\n            var model =\r\n                new TestModel\r\n                {\r\n                    ListOfPrimitivesProperty = new List<int> { 1, 3, 5 },\r\n                    ListOfPrimitivesField = new List<int> { 2, 4, 6 },\r\n                };\r\n\r\n            var s = new JavaScriptSerializer();\r\n            var serialized = s.Serialize(model);\r\n            var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(serialized));\r\n\r\n            // When\r\n            var result = (TestModel)this.deserialize.Deserialize(\r\n                            \"application/json\",\r\n                            bodyStream,\r\n                            context);\r\n\r\n            // Then\r\n            result.ListOfPrimitivesProperty.ShouldHaveCount(3);\r\n            result.ListOfPrimitivesProperty[0].ShouldEqual(1);\r\n            result.ListOfPrimitivesProperty[1].ShouldEqual(3);\r\n            result.ListOfPrimitivesProperty[2].ShouldEqual(5);\r\n\r\n            result.ListOfPrimitivesField.ShouldHaveCount(3);\r\n            result.ListOfPrimitivesField[0].ShouldEqual(2);\r\n            result.ListOfPrimitivesField[1].ShouldEqual(4);\r\n            result.ListOfPrimitivesField[2].ShouldEqual(6);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_deserialize_list_of_complex_objects()\r\n        {\r\n            // Given\r\n            var context = new BindingContext()\r\n            {\r\n                DestinationType = typeof(TestModel),\r\n                ValidModelBindingMembers = BindingMemberInfo.Collect<TestModel>().ToList(),\r\n            };\r\n\r\n            var model =\r\n                new TestModel\r\n                {\r\n                    ListOfComplexObjectsProperty = new List<ModelWithStringValues>\r\n                    {\r\n                        new ModelWithStringValues() { Value1 = \"one\", Value2 = \"two\"},\r\n                        new ModelWithStringValues() { Value1 = \"three\", Value2 = \"four\"}\r\n                    },\r\n                    ListOfComplexObjectsField = new List<ModelWithStringValues>\r\n                    {\r\n                        new ModelWithStringValues() { Value1 = \"five\", Value2 = \"six\"},\r\n                        new ModelWithStringValues() { Value1 = \"seven\", Value2 = \"eight\"}\r\n                    }\r\n                };\r\n\r\n            var s = new JavaScriptSerializer();\r\n            var serialized = s.Serialize(model);\r\n            var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(serialized));\r\n\r\n            // When\r\n            var result = (TestModel)this.deserialize.Deserialize(\r\n                            \"application/json\",\r\n                            bodyStream,\r\n                            context);\r\n\r\n            // Then\r\n            result.ListOfComplexObjectsProperty.ShouldHaveCount(2);\r\n            result.ListOfComplexObjectsProperty[0].Value1.ShouldEqual(\"one\");\r\n            result.ListOfComplexObjectsProperty[0].Value2.ShouldEqual(\"two\");\r\n            result.ListOfComplexObjectsProperty[1].Value1.ShouldEqual(\"three\");\r\n            result.ListOfComplexObjectsProperty[1].Value2.ShouldEqual(\"four\");\r\n            result.ListOfComplexObjectsField.ShouldHaveCount(2);\r\n            result.ListOfComplexObjectsField[0].Value1.ShouldEqual(\"five\");\r\n            result.ListOfComplexObjectsField[0].Value2.ShouldEqual(\"six\");\r\n            result.ListOfComplexObjectsField[1].Value1.ShouldEqual(\"seven\");\r\n            result.ListOfComplexObjectsField[1].Value2.ShouldEqual(\"eight\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_Deserialize_Signed_And_Unsigned_Nullable_Numeric_Types()\r\n        {\r\n            //Given\r\n            const string json = \"{\\\"P1\\\": 1, \\\"P2\\\": 2, \\\"P3\\\": 3, \\\"F1\\\": 4, \\\"F2\\\": 5, \\\"F3\\\": 6}\";\r\n\r\n            //When\r\n            var model = this.serializer.Deserialize<ModelWithNullables> (json);\r\n\r\n            //Should\r\n            Assert.Equal (1, model.P1);\r\n            Assert.Equal ((uint)2, model.P2);\r\n            Assert.Equal ((uint)3, model.P3);\r\n            Assert.Equal (4, model.F1);\r\n            Assert.Equal ((uint)5, model.F2);\r\n            Assert.Equal ((uint)6, model.F3);\r\n        }\r\n\r\n#if !MONO\r\n        [Fact]\r\n        [UsingCulture(\"de-DE\")]\r\n        public void Should_Serialize_Doubles_In_Different_Cultures()\r\n        {\r\n            // TODO - fixup on mono, seems to throw inside double.parse\r\n            // Given\r\n            var modelWithDoubleValues =\r\n                new ModelWithDoubleValues\r\n                    {\r\n                        Latitude = 50.933984,\r\n                        Longitude = 7.330627\r\n                    };\r\n\r\n            var s = new JavaScriptSerializer();\r\n            var serialized = s.Serialize(modelWithDoubleValues);\r\n\r\n            // When\r\n            var deserializedModelWithDoubleValues = s.Deserialize<ModelWithDoubleValues>(serialized);\r\n\r\n            // Then\r\n            Assert.Equal(modelWithDoubleValues.Latitude, deserializedModelWithDoubleValues.Latitude);\r\n            Assert.Equal(modelWithDoubleValues.Longitude, deserializedModelWithDoubleValues.Longitude);\r\n        }\r\n\r\n#endif\r\n\r\n        [Theory]\r\n        [InlineData(\"\\n\")]\r\n        [InlineData(\"\\n\\r\")]\r\n        [InlineData(\"\\r\\n\")]\r\n        [InlineData(\"\\r\")]\r\n        public void Should_Serialize_Last_Prop_is_Bool_And_Trailing_NewLine(string lineEndings)\r\n        {\r\n            // Given\r\n            var json = string.Concat(\"{\\\"Property\\\": true\", lineEndings, \"}\");\r\n\r\n            // When\r\n            var s = new JavaScriptSerializer();\r\n            var deserialized = (dynamic)s.DeserializeObject(json);\r\n\r\n            // Then\r\n            Assert.True(deserialized[\"Property\"]);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_Serialize_Last_Prop_is_Bool()\r\n        {\r\n            // Given\r\n            var json = \"{\\\"Property\\\": true}\";\r\n\r\n            // When\r\n            var s = new JavaScriptSerializer();\r\n            var deserialized = (dynamic)s.DeserializeObject(json);\r\n\r\n            // Then\r\n            Assert.True(deserialized[\"Property\"]);\r\n        }\r\n\r\n        public class TestModel : IEquatable<TestModel>\r\n        {\r\n            public string StringProperty { get; set; }\r\n\r\n            public int IntProperty { get; set; }\r\n\r\n            public DateTime DateProperty { get; set; }\r\n\r\n            public string[] ArrayProperty { get; set; }\r\n\r\n            public TestEnum? NullableEnumProperty { get; set; }\r\n\r\n            public List<int> ListOfPrimitivesProperty { get; set; }\r\n\r\n            public List<int> ListOfPrimitivesField;\r\n\r\n            public List<ModelWithStringValues> ListOfComplexObjectsProperty { get; set; }\r\n\r\n            public List<ModelWithStringValues> ListOfComplexObjectsField { get; set; }\r\n\r\n            public bool Equals(TestModel other)\r\n            {\r\n                if (ReferenceEquals(null, other))\r\n                {\r\n                    return false;\r\n                }\r\n\r\n                if (ReferenceEquals(this, other))\r\n                {\r\n                    return true;\r\n                }\r\n\r\n                return other.StringProperty == this.StringProperty &&\r\n                       other.IntProperty == this.IntProperty &&\r\n                       !other.ArrayProperty.Except(this.ArrayProperty).Any() &&\r\n                       other.DateProperty.ToString(\"d\") == this.DateProperty.ToString(\"d\");\r\n            }\r\n\r\n            public override bool Equals(object obj)\r\n            {\r\n                if (ReferenceEquals(null, obj))\r\n                {\r\n                    return false;\r\n                }\r\n\r\n                if (ReferenceEquals(this, obj))\r\n                {\r\n                    return true;\r\n                }\r\n\r\n                if (obj.GetType() != typeof(TestModel))\r\n                {\r\n                    return false;\r\n                }\r\n\r\n                return Equals((TestModel)obj);\r\n            }\r\n\r\n            public override int GetHashCode()\r\n            {\r\n                unchecked\r\n                {\r\n                    int result = (this.StringProperty != null ? this.StringProperty.GetHashCode() : 0);\r\n                    result = (result * 397) ^ this.IntProperty;\r\n                    result = (result * 397) ^ this.DateProperty.GetHashCode();\r\n                    result = (result * 397) ^ (this.ArrayProperty != null ? this.ArrayProperty.GetHashCode() : 0);\r\n                    return result;\r\n                }\r\n            }\r\n\r\n            public static bool operator ==(TestModel left, TestModel right)\r\n            {\r\n                return Equals(left, right);\r\n            }\r\n\r\n            public static bool operator !=(TestModel left, TestModel right)\r\n            {\r\n                return !Equals(left, right);\r\n            }\r\n        }\r\n\r\n        public enum TestEnum\r\n        {\r\n            One = 1,\r\n            Hundred = 100\r\n        }\r\n    }\r\n\r\n    public class ModelWithStringValues\r\n    {\r\n        public string Value1 { get; set; }\r\n\r\n        public string Value2;\r\n    }\r\n\r\n    public class ModelWithDoubleValues\r\n    {\r\n        public double Latitude { get; set; }\r\n\r\n        public double Longitude;\r\n    }\r\n\r\n    public class ModelWithNullables\r\n    {\r\n        public int? P1 { get; set; }\r\n        public uint P2 { get; set; }\r\n        public uint? P3 { get; set; }\r\n\r\n        public int? F1;\r\n        public uint F2;\r\n        public uint? F3;\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/ModelBinding/DefaultBodyDeserializers/XmlBodyDeserializerfixture.cs",
    "content": "namespace Nancy.Tests.Unit.ModelBinding.DefaultBodyDeserializers\r\n{\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Text;\r\n    using System.Xml.Serialization;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Nancy.ModelBinding;\r\n    using Nancy.ModelBinding.DefaultBodyDeserializers;\r\n\r\n    using Xunit;\r\n\r\n    public class XmlBodyDeserializerFixture\r\n    {\r\n        private readonly XmlBodyDeserializer deserialize;\r\n        private readonly TestModel testModel;\r\n        private readonly string testModelXml;\r\n\r\n        public XmlBodyDeserializerFixture()\r\n        {\r\n            deserialize = new XmlBodyDeserializer();\r\n            testModel = new TestModel { Bar = 13, Foo = \"lil\" };\r\n            testModelXml = ToXmlString(testModel);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_report_true_for_can_deserialize_for_application_xml()\r\n        {\r\n            // Given\r\n            const string contentType = \"application/xml\";\r\n\r\n            // When\r\n            var result = this.deserialize.CanDeserialize(contentType, A.Dummy<BindingContext>());\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_report_true_for_can_deserialize_for_text_xml()\r\n        {\r\n            // Given\r\n            const string contentType = \"text/xml\";\r\n\r\n            // When\r\n            var result = this.deserialize.CanDeserialize(contentType, A.Dummy<BindingContext>());\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_report_true_for_can_deserialize_for_custom_xml()\r\n        {\r\n            // Given\r\n            const string contentType = \"application/vnd.org.nancyfx.mything+xml\";\r\n\r\n            // When\r\n            var result = this.deserialize.CanDeserialize(contentType, A.Dummy<BindingContext>());\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_report_false_for_can_deserialize_for_json_format()\r\n        {\r\n            // Given\r\n            const string contentType = \"text/json\";\r\n\r\n            // When\r\n            var result = this.deserialize.CanDeserialize(contentType, A.Dummy<BindingContext>());\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_deserialize_if_body_stream_accessed_before_bind()\r\n        {\r\n            // Given\r\n            var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(this.testModelXml));\r\n            var context = new BindingContext()\r\n            {\r\n                DestinationType = typeof(TestModel),\r\n                ValidModelBindingMembers = BindingMemberInfo.Collect<TestModel>(),\r\n            };\r\n\r\n            var reader = new StreamReader(bodyStream);\r\n            var dataThatDoesntResetStreamPosition = reader.ReadToEnd();\r\n\r\n            // When\r\n            var result = (TestModel)this.deserialize.Deserialize(\r\n                            \"application/xml\",\r\n                            bodyStream,\r\n                            context);\r\n\r\n            // Then\r\n            result.ShouldNotBeNull();\r\n            result.ShouldBeOfType(typeof(TestModel));\r\n            result.ShouldEqual(this.testModel);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_deserialize_xml_model()\r\n        {\r\n            // Given\r\n            var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(this.testModelXml));\r\n            var context = new BindingContext()\r\n            {\r\n                DestinationType = typeof(TestModel),\r\n                ValidModelBindingMembers = BindingMemberInfo.Collect<TestModel>().ToArray(),\r\n            };\r\n\r\n            // When\r\n            var result = (TestModel)this.deserialize.Deserialize(\r\n                            \"application/xml\",\r\n                            bodyStream,\r\n                            context);\r\n\r\n            // Then\r\n            result.ShouldNotBeNull();\r\n            result.ShouldBeOfType(typeof(TestModel));\r\n            result.ShouldEqual(this.testModel);\r\n        }\r\n\r\n        public static string ToXmlString<T>(T input)\r\n        {\r\n            string xml;\r\n            var ser = new XmlSerializer(typeof(T));\r\n            using (var ms = new MemoryStream())\r\n            {\r\n                ser.Serialize(ms, input);\r\n                // codepage 0 represents the system's default encoding\r\n                xml = Encoding.GetEncoding(0).GetString(ms.ToArray());\r\n            }\r\n            return xml;\r\n        }\r\n\r\n        public class TestModel\r\n        {\r\n            [XmlElement(\"fooProp\")]\r\n            public string Foo { get; set; }\r\n            [XmlElement()]\r\n            public int Bar { get; set; }\r\n\r\n            public bool Equals(TestModel other)\r\n            {\r\n                if (ReferenceEquals(null, other)) return false;\r\n                if (ReferenceEquals(this, other)) return true;\r\n                return Equals(other.Foo, Foo) && other.Bar == Bar;\r\n            }\r\n\r\n            public override bool Equals(object obj)\r\n            {\r\n                if (ReferenceEquals(null, obj)) return false;\r\n                if (ReferenceEquals(this, obj)) return true;\r\n                if (obj.GetType() != typeof(TestModel)) return false;\r\n                return Equals((TestModel)obj);\r\n            }\r\n\r\n            public override int GetHashCode()\r\n            {\r\n                unchecked\r\n                {\r\n                    return ((Foo != null ? Foo.GetHashCode() : 0) * 397) ^ Bar;\r\n                }\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/ModelBinding/DefaultConverters/CollectionConverterFixture.cs",
    "content": "namespace Nancy.Tests.Unit.ModelBinding.DefaultConverters\r\n{\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Nancy.ModelBinding;\r\n    using Nancy.ModelBinding.DefaultConverters;\r\n\r\n    using Xunit;\r\n\r\n    public class CollectionConverterFixture\r\n    {\r\n        private ITypeConverter converter;\r\n        private BindingContext context;\r\n        private ITypeConverter mockStringTypeConverter;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"T:System.Object\"/> class.\r\n        /// </summary>\r\n        public CollectionConverterFixture()\r\n        {\r\n            this.converter = new CollectionConverter();\r\n            this.context = new BindingContext() { TypeConverters = new[] { new FallbackConverter() } };\r\n\r\n            this.mockStringTypeConverter = A.Fake<ITypeConverter>();\r\n            A.CallTo(() => mockStringTypeConverter.CanConvertTo(null, null)).WithAnyArguments().Returns(true);\r\n            A.CallTo(() => mockStringTypeConverter.Convert(null, null, null)).WithAnyArguments().Returns(string.Empty);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_handle_array_types()\r\n        {\r\n            const string input = \"one,two,three\";\r\n\r\n            var output = (string[])converter.Convert(input, typeof(string[]), this.context);\r\n\r\n            output.ShouldNotBeNull();\r\n            output.Length.ShouldEqual(3);\r\n        }\r\n\r\n        [Fact]\r\n        public void Array_type_conversion_should_use_type_converter()\r\n        {\r\n            const string input = \"one,two,three\";\r\n            var mockContext = new BindingContext() { TypeConverters = new[] { this.mockStringTypeConverter } };\r\n\r\n            converter.Convert(input, typeof(string[]), mockContext);\r\n\r\n            A.CallTo(() => this.mockStringTypeConverter.Convert(null, null, null)).WithAnyArguments()\r\n                .MustHaveHappened(3, Times.Exactly);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_handle_collection_types()\r\n        {\r\n            const string input = \"one,two,three\";\r\n\r\n            var output = (List<string>)converter.Convert(input, typeof(List<string>), this.context);\r\n\r\n            output.ShouldNotBeNull();\r\n            output.Count.ShouldEqual(3);\r\n        }\r\n\r\n        [Fact]\r\n        public void Collection_type_conversion_should_use_type_converter()\r\n        {\r\n            const string input = \"one,two,three\";\r\n            var mockContext = new BindingContext() { TypeConverters = new[] { this.mockStringTypeConverter } };\r\n\r\n            converter.Convert(input, typeof(List<string>), mockContext);\r\n\r\n            A.CallTo(() => this.mockStringTypeConverter.Convert(null, null, null)).WithAnyArguments()\r\n                .MustHaveHappened(3, Times.Exactly);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_handle_IEnumerable_types()\r\n        {\r\n            const string input = \"one,two,three\";\r\n\r\n            var output = (IEnumerable<string>)converter.Convert(input, typeof(IEnumerable<string>), this.context);\r\n\r\n            output.ShouldNotBeNull();\r\n            output.Count().ShouldEqual(3);\r\n        }\r\n\r\n        [Fact]\r\n        public void IEnumerable_type_conversion_should_use_type_converter()\r\n        {\r\n            const string input = \"one,two,three\";\r\n            var mockContext = new BindingContext() { TypeConverters = new[] { this.mockStringTypeConverter } };\r\n\r\n            converter.Convert(input, typeof(IEnumerable<string>), mockContext);\r\n\r\n            A.CallTo(() => this.mockStringTypeConverter.Convert(null, null, null)).WithAnyArguments()\r\n                .MustHaveHappened(3, Times.Exactly);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/ModelBinding/DefaultConverters/FallbackConverterFixture.cs",
    "content": "namespace Nancy.Tests.Unit.ModelBinding.DefaultConverters\r\n{\r\n    using System;\r\n\r\n    using Nancy.ModelBinding;\r\n    using Nancy.ModelBinding.DefaultConverters;\r\n\r\n    using Xunit;\r\n    using Xunit.Extensions;\r\n\r\n    public class FallbackConverterFixture\r\n    {\r\n        private ITypeConverter converter;\r\n\r\n        public FallbackConverterFixture()\r\n        {\r\n            this.converter = new FallbackConverter();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_respond_true_for_any_type()\r\n        {\r\n            var result = converter.CanConvertTo(null, null);\r\n\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_convert_int()\r\n        {\r\n            var input = \"12\";\r\n\r\n            var result = (int)converter.Convert(input, typeof(int), null);\r\n\r\n            result.ShouldEqual(12);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_convert_double()\r\n        {\r\n            var input = 12.34.ToString();\r\n\r\n            var result = (double)converter.Convert(input, typeof(double), null);\r\n\r\n            result.ShouldEqual(12.34);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_convert_datetime()\r\n        {\r\n            var now = DateTime.Now;\r\n            var input = now.ToString();\r\n\r\n            var result = (DateTime)converter.Convert(input, typeof(DateTime), null);\r\n\r\n            result.ShouldEqual(now);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"on\")]\r\n        [InlineData(\"On\")]\r\n        [InlineData(\"oN\")]\r\n        [InlineData(\"ON\")]\r\n        public void Should_convert_on_to_true_for_bool(string value)\r\n        {\r\n            string input = \"on\";\r\n\r\n            var result = (bool)converter.Convert(input, typeof(bool), null);\r\n\r\n            result.ShouldBeTrue();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/ModelBinding/DefaultFieldNameConverterFixture.cs",
    "content": "namespace Nancy.Tests.Unit.ModelBinding\r\n{\r\n    using Nancy.ModelBinding;\r\n\r\n    using Xunit;\r\n\r\n    public class DefaultFieldNameConverterFixture\r\n    {\r\n        private readonly DefaultFieldNameConverter converter;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"T:System.Object\"/> class.\r\n        /// </summary>\r\n        public DefaultFieldNameConverterFixture()\r\n        {\r\n            this.converter = new DefaultFieldNameConverter();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_just_return_name_if_pascal_cased()\r\n        {\r\n            var input = \"FieldName\";\r\n\r\n            var result = this.converter.Convert(input);\r\n\r\n            result.ShouldEqual(input);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_pascal_case_camel_case_field()\r\n        {\r\n            var input = \"fieldName\";\r\n\r\n            var result = this.converter.Convert(input);\r\n\r\n            result.ShouldEqual(\"FieldName\");\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/ModelBinding/DefaultModelBinderLocatorFixture.cs",
    "content": "namespace Nancy.Tests.Unit.ModelBinding\r\n{\r\n    using System;\r\n    using System.Reflection;\r\n\r\n    using FakeItEasy;\r\n    using Nancy.Configuration;\r\n    using Nancy.Json;\r\n    using Nancy.ModelBinding;\r\n    using Nancy.Tests.Fakes;\r\n\r\n    using Xunit;\r\n\r\n    public class DefaultModelBinderLocatorFixture\r\n    {\r\n        private readonly DefaultBinder defaultBinder;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"T:System.Object\"/> class.\r\n        /// </summary>\r\n        public DefaultModelBinderLocatorFixture()\r\n        {\r\n            var environment = new DefaultNancyEnvironment();\r\n            environment.AddValue(JsonConfiguration.Default);\r\n            environment.AddValue(GlobalizationConfiguration.Default);\r\n\r\n            var bindingDefaults =\r\n                new BindingDefaults(environment);\r\n\r\n            this.defaultBinder = new DefaultBinder(ArrayCache.Empty<ITypeConverter>(), ArrayCache.Empty<IBodyDeserializer>(), A.Fake<IFieldNameConverter>(), bindingDefaults);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_throw_if_null_binders_collection_is_passed()\r\n        {\r\n            var result = Record.Exception(() => new DefaultModelBinderLocator(null, this.defaultBinder));\r\n\r\n            result.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_default_binder_if_no_specific_binder_exists()\r\n        {\r\n            var fakeBinder = A.Fake<IModelBinder>();\r\n            A.CallTo(() => fakeBinder.CanBind(A<Type>.Ignored)).Returns(false);\r\n            var locator = new DefaultModelBinderLocator(new IModelBinder[] { fakeBinder }, this.defaultBinder);\r\n\r\n            var result = locator.GetBinderForType(typeof(Model), A.Dummy<NancyContext>());\r\n\r\n            result.ShouldBeSameAs(this.defaultBinder);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_return_a_binder_that_returns_false_for_canbind()\r\n        {\r\n            var fakeBinder = A.Fake<IModelBinder>();\r\n            A.CallTo(() => fakeBinder.CanBind(A<Type>.Ignored)).Returns(false);\r\n            var locator = new DefaultModelBinderLocator(new IModelBinder[] { fakeBinder }, this.defaultBinder);\r\n\r\n            var result = locator.GetBinderForType(typeof(Model), A.Dummy<NancyContext>());\r\n\r\n            result.ShouldNotBeSameAs(fakeBinder);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_a_binder_that_returns_true_for_canbind()\r\n        {\r\n            var fakeBinder = A.Fake<IModelBinder>();\r\n            A.CallTo(() => fakeBinder.CanBind(A<Type>.Ignored)).Returns(true);\r\n            var locator = new DefaultModelBinderLocator(new IModelBinder[] { fakeBinder }, this.defaultBinder);\r\n\r\n            var result = locator.GetBinderForType(typeof(Model), A.Dummy<NancyContext>());\r\n\r\n            result.ShouldBeSameAs(fakeBinder);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_bind_interfaces()\r\n        {\r\n            var binder = new InterfaceModelBinder();\r\n            var locator = new DefaultModelBinderLocator(new IModelBinder[] { binder }, this.defaultBinder);\r\n            var locatedBinder = locator.GetBinderForType(typeof(Concrete), A.Dummy<NancyContext>());\r\n\r\n            var result = locatedBinder.Bind(null, typeof(Concrete), null, new BindingConfig()) as IAmAnInterface;\r\n\r\n            result.ShouldNotBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_bind_interfaces_using_module_extensions()\r\n        {\r\n            var binder =\r\n                new InterfaceModelBinder();\r\n\r\n            var locator =\r\n                new DefaultModelBinderLocator(new IModelBinder[] { binder }, this.defaultBinder);\r\n\r\n            var module = new TestBindingModule\r\n            {\r\n                Context = new NancyContext() { Request = new FakeRequest(\"GET\", \"/\") },\r\n                ModelBinderLocator = locator\r\n            };\r\n\r\n            var result = module.TestBindInterface();\r\n            var result2 = module.TestBindConcrete();\r\n\r\n            result.ShouldNotBeNull();\r\n            result2.ShouldNotBeNull();\r\n        }\r\n\r\n        private class TestBindingModule : NancyModule\r\n        {\r\n            public IAmAnInterface TestBindInterface()\r\n            {\r\n                var result = this.Bind<IAmAnInterface>();\r\n\r\n                return result;\r\n            }\r\n\r\n            public IAmAnInterface TestBindConcrete()\r\n            {\r\n                var result = this.Bind<Concrete>();\r\n\r\n                return result;\r\n            }\r\n        }\r\n\r\n        interface IAmAnInterface\r\n        {\r\n\r\n        }\r\n\r\n        class Concrete : IAmAnInterface\r\n        {\r\n\r\n        }\r\n\r\n        class InterfaceModelBinder : IModelBinder\r\n        {\r\n            public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList)\r\n            {\r\n                return new Concrete() as IAmAnInterface;\r\n            }\r\n\r\n            public bool CanBind(Type modelType)\r\n            {\r\n                return typeof(IAmAnInterface).IsAssignableFrom(modelType);\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/ModelBinding/DynamicModelBinderAdapterFixture.cs",
    "content": "namespace Nancy.Tests.Unit.ModelBinding\r\n{\r\n    using System;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Nancy.ModelBinding;\r\n\r\n    using Xunit;\r\n\r\n    public class DynamicModelBinderAdapterFixture\r\n    {\r\n        [Fact]\r\n        public void Should_throw_if_locator_is_null()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => new DynamicModelBinderAdapter(null, new NancyContext(), null, A.Dummy<BindingConfig>()));\r\n\r\n            // Then\r\n            result.ShouldBeOfType(typeof(ArgumentNullException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_if_context_is_null()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => new DynamicModelBinderAdapter(A.Fake<IModelBinderLocator>(), null, null, A.Dummy<BindingConfig>()));\r\n\r\n            // Then\r\n            result.ShouldBeOfType(typeof(ArgumentNullException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_if_configuration_is_null()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => new DynamicModelBinderAdapter(A.Fake<IModelBinderLocator>(), A.Dummy<NancyContext>(), null, null));\r\n\r\n            // Then\r\n            result.ShouldBeOfType(typeof(ArgumentNullException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_pass_type_to_locator_when_cast_implicitly()\r\n        {\r\n            // Given\r\n            var fakeModelBinder = A.Fake<IModelBinder>();\r\n            var returnModel = new Model();\r\n            A.CallTo(() => fakeModelBinder.Bind(null, null, null, null)).WithAnyArguments().Returns(returnModel);\r\n\r\n            var fakeLocator = A.Fake<IModelBinderLocator>();\r\n            A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, A<NancyContext>.Ignored)).Returns(fakeModelBinder);\r\n            dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, new NancyContext(), null, A.Dummy<BindingConfig>());\r\n\r\n            // When\r\n            Model result = adapter;\r\n\r\n            // Then\r\n            A.CallTo(() => fakeLocator.GetBinderForType(typeof(Model), A<NancyContext>.Ignored)).MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_binder_with_context()\r\n        {\r\n            // Given\r\n            var context = new NancyContext();\r\n\r\n            var fakeModelBinder = A.Fake<IModelBinder>();\r\n            var returnModel = new Model();\r\n            A.CallTo(() => fakeModelBinder.Bind(null, null, null, null)).WithAnyArguments().Returns(returnModel);\r\n\r\n            var fakeLocator = A.Fake<IModelBinderLocator>();\r\n            A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, context)).Returns(fakeModelBinder);\r\n            dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, context, null, A.Dummy<BindingConfig>());\r\n\r\n            // When\r\n            Model result = adapter;\r\n\r\n            // Then\r\n            A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, context)).MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_pass_type_to_locator_when_cast_explicitly()\r\n        {\r\n            // Given\r\n            var fakeModelBinder = A.Fake<IModelBinder>();\r\n            var returnModel = new Model();\r\n            A.CallTo(() => fakeModelBinder.Bind(null, null, null, null)).WithAnyArguments().Returns(returnModel);\r\n\r\n            var fakeLocator = A.Fake<IModelBinderLocator>();\r\n            A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, A<NancyContext>.Ignored)).Returns(fakeModelBinder);\r\n            dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, new NancyContext(), null, A.Dummy<BindingConfig>());\r\n\r\n            // When\r\n            var result = (Model)adapter;\r\n\r\n            // Then\r\n            A.CallTo(() => fakeLocator.GetBinderForType(typeof(Model), A<NancyContext>.Ignored)).MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_object_from_binder_if_binder_doesnt_return_null()\r\n        {\r\n            // Given\r\n            var fakeModelBinder = A.Fake<IModelBinder>();\r\n            var returnModel = new Model();\r\n            A.CallTo(() => fakeModelBinder.Bind(null, null, null, null)).WithAnyArguments().Returns(returnModel);\r\n\r\n            var fakeLocator = A.Fake<IModelBinderLocator>();\r\n            A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, A<NancyContext>.Ignored)).Returns(fakeModelBinder);\r\n            dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, new NancyContext(), null, A.Dummy<BindingConfig>());\r\n\r\n            // When\r\n            Model result = adapter;\r\n\r\n            // Then\r\n            result.ShouldNotBeNull();\r\n            result.ShouldBeSameAs(returnModel);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_if_locator_does_not_return_binder()\r\n        {\r\n            // Given\r\n            var fakeLocator = A.Fake<IModelBinderLocator>();\r\n            A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, A<NancyContext>.Ignored)).Returns(null);\r\n            dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, new NancyContext(), null, A.Dummy<BindingConfig>());\r\n\r\n            // When\r\n            var result = Record.Exception(() => (Model)adapter);\r\n\r\n            // Then\r\n            result.ShouldBeOfType(typeof(ModelBindingException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_pass_context_to_binder()\r\n        {\r\n            // Given\r\n            var context = new NancyContext();\r\n\r\n            var fakeModelBinder = A.Fake<IModelBinder>();\r\n            var returnModel = new Model();\r\n            A.CallTo(() => fakeModelBinder.Bind(null, null, null, null)).WithAnyArguments().Returns(returnModel);\r\n\r\n            var fakeLocator = A.Fake<IModelBinderLocator>();\r\n            A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, A<NancyContext>.Ignored)).Returns(fakeModelBinder);\r\n            dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, context , null, A.Dummy<BindingConfig>());\r\n\r\n            // When\r\n            Model result = adapter;\r\n\r\n            // Then\r\n            A.CallTo(() => fakeModelBinder.Bind(context, A<Type>._, A<object>._, A<BindingConfig>._, A<string[]>._)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_pass_type_to_binder()\r\n        {\r\n            // Given\r\n            var context = new NancyContext();\r\n\r\n            var fakeModelBinder = A.Fake<IModelBinder>();\r\n            var returnModel = new Model();\r\n            A.CallTo(() => fakeModelBinder.Bind(null, null, null, null)).WithAnyArguments().Returns(returnModel);\r\n\r\n            var fakeLocator = A.Fake<IModelBinderLocator>();\r\n            A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, A<NancyContext>.Ignored)).Returns(fakeModelBinder);\r\n            dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, context, null, A.Dummy<BindingConfig>());\r\n\r\n            // When\r\n            Model result = adapter;\r\n\r\n            // Then\r\n            A.CallTo(() => fakeModelBinder.Bind(A<NancyContext>._, typeof(Model), A<object>._, A<BindingConfig>._, A<string[]>._)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_pass_instance_to_binder()\r\n        {\r\n            // Given\r\n            var context = new NancyContext();\r\n            var instance = new Model();\r\n\r\n            var fakeModelBinder = A.Fake<IModelBinder>();\r\n            var returnModel = new Model();\r\n            A.CallTo(() => fakeModelBinder.Bind(null, null, null, null)).WithAnyArguments().Returns(returnModel);\r\n\r\n            var fakeLocator = A.Fake<IModelBinderLocator>();\r\n            A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, A<NancyContext>.Ignored)).Returns(fakeModelBinder);\r\n            dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, context, instance, A.Dummy<BindingConfig>());\r\n\r\n            // When\r\n            Model result = adapter;\r\n\r\n            // Then\r\n            A.CallTo(() => fakeModelBinder.Bind(A<NancyContext>._, A<Type>._, instance, A<BindingConfig>._, A<string[]>._)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_pass_binding_configuration_to_binder()\r\n        {\r\n            // Given\r\n            var context = new NancyContext();\r\n            var instance = new Model();\r\n            var config = BindingConfig.Default;\r\n            var blacklist = new[] {\"foo\", \"bar\"};\r\n\r\n            var fakeModelBinder = A.Fake<IModelBinder>();\r\n            var returnModel = new Model();\r\n            A.CallTo(() => fakeModelBinder.Bind(null, null, null, null)).WithAnyArguments().Returns(returnModel);\r\n\r\n            var fakeLocator = A.Fake<IModelBinderLocator>();\r\n            A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, A<NancyContext>.Ignored)).Returns(fakeModelBinder);\r\n            dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, context, instance, config, blacklist);\r\n\r\n            // When\r\n            Model result = adapter;\r\n\r\n            // Then\r\n            A.CallTo(() => fakeModelBinder.Bind(A<NancyContext>._, A<Type>._, A<object>._, A<BindingConfig>._, blacklist)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_pass_blacklist_to_binder()\r\n        {\r\n            // Given\r\n            var context = new NancyContext();\r\n            var instance = new Model();\r\n            var config = BindingConfig.Default;\r\n\r\n            var fakeModelBinder = A.Fake<IModelBinder>();\r\n            var returnModel = new Model();\r\n            A.CallTo(() => fakeModelBinder.Bind(null, null, null, null)).WithAnyArguments().Returns(returnModel);\r\n\r\n            var fakeLocator = A.Fake<IModelBinderLocator>();\r\n            A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, A<NancyContext>.Ignored)).Returns(fakeModelBinder);\r\n            dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, context, instance, config);\r\n\r\n            // When\r\n            Model result = adapter;\r\n\r\n            // Then\r\n            A.CallTo(() => fakeModelBinder.Bind(A<NancyContext>._, A<Type>._, A<object>._, config, A<string[]>._)).MustHaveHappened();\r\n        }\r\n    }\r\n\r\n    public class Model\r\n    {\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/ModelBinding/ModelBindingExceptionFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.ModelBinding\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    using Nancy.ModelBinding;\r\n\r\n    using Xunit;\r\n\r\n    public class ModelBindingExceptionFixture\r\n    {\r\n        [Fact]\r\n        public void Ctor_should_set_property_exceptions_and_bound_type()\r\n        {\r\n            //When\r\n            var propertyExceptions = new List<PropertyBindingException>();\r\n            var exception = new ModelBindingException(typeof (string), propertyExceptions);\r\n\r\n            //Then\r\n            exception.BoundType.ShouldBeOfType<string>();\r\n            exception.PropertyBindingExceptions.ShouldBeSameAs(propertyExceptions);\r\n        }\r\n\r\n        [Fact]\r\n        public void Ctor_should_set_empty_property_exceptions_list_if_null_is_provided()\r\n        {\r\n            //When\r\n            var exception = new ModelBindingException(typeof(string), null);\r\n\r\n            //Then\r\n            exception.PropertyBindingExceptions.Any().ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Ctor_should_set_empty_property_exceptions_list_if_none_are_provided()\r\n        {\r\n            //When\r\n            var exception = new ModelBindingException(typeof (string));\r\n\r\n            //Then\r\n            exception.PropertyBindingExceptions.Any().ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Ctor_should_throw_on_null_type()\r\n        {\r\n            Assert.Throws<ArgumentNullException>(() => new ModelBindingException(null))\r\n                .ParamName.ShouldEqual(\"boundType\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Message_should_contain_bound()\r\n        {\r\n            //When\r\n            var exception = new ModelBindingException(typeof (string));\r\n\r\n            //then\r\n            exception.Message.ShouldEqual(String.Format(\"Unable to bind to type: {0}\", typeof(string)));\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/ModelBinding/PropertyBindingExceptionFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.ModelBinding\r\n{\r\n    using System;\r\n\r\n    using Nancy.ModelBinding;\r\n\r\n    using Xunit;\r\n\r\n    public class PropertyBindingExceptionFixture\r\n    {\r\n        const string PROPERTY_NAME = \"PropName\";\r\n        const string ATTEMPTED_VALUE = \"wrong value\";\r\n\r\n        [Fact]\r\n        public void Ctor_should_set_property_name_and_attempted_value_and_inner_exception()\r\n        {\r\n            //When\r\n            var innerException = new Exception();\r\n            \r\n            var exception = new PropertyBindingException(PROPERTY_NAME, ATTEMPTED_VALUE, innerException);\r\n\r\n            //Then\r\n            exception.PropertyName.ShouldEqual(PROPERTY_NAME);\r\n            exception.AttemptedValue.ShouldEqual(ATTEMPTED_VALUE);\r\n            exception.InnerException.ShouldBeSameAs(innerException);\r\n        }\r\n\r\n        [Fact]\r\n        public void Message_should_contain_property_name_and_attempted_value()\r\n        {\r\n            //When\r\n            var exception = new PropertyBindingException(PROPERTY_NAME, ATTEMPTED_VALUE);\r\n\r\n            //then\r\n            exception.Message.ShouldEqual(String.Format(\"Unable to bind property: {0}; Attempted value: {1}\", PROPERTY_NAME, ATTEMPTED_VALUE));\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/ModuleNameFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit\r\n{\r\n    using Nancy.Extensions;\r\n\r\n    using Xunit;\r\n\r\n    public class ModuleNameFixture\r\n    {\r\n        class FakeModule : NancyModule\r\n        {\r\n            \r\n        }\r\n\r\n        class SuperDuperHappyModule : NancyModule\r\n        {\r\n            \r\n        }\r\n\r\n        class ThisIsNoJoke : NancyModule\r\n        {\r\n            \r\n        }\r\n\r\n        class ModuleForNancy : NancyModule\r\n        {\r\n            \r\n        }\r\n\r\n        [Fact]\r\n        public void Should_strip_module_from_name()\r\n        {\r\n            // Given\r\n            NancyModule module = new FakeModule();\r\n\r\n            // When\r\n            var name = module.GetModuleName();\r\n\r\n            // Then\r\n            name.ShouldEqual(\"Fake\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_strip_module_from_really_long_name()\r\n        {\r\n            // Given\r\n            NancyModule module = new SuperDuperHappyModule();\r\n\r\n            // When\r\n            var name = module.GetModuleName();\r\n\r\n            // Then\r\n            name.ShouldEqual(\"SuperDuperHappy\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_fullname_if_module_doesnt_exist()\r\n        {\r\n            // Given\r\n            NancyModule module = new ThisIsNoJoke();\r\n\r\n            // When\r\n            var name = module.GetModuleName();\r\n\r\n            // Then\r\n            name.ShouldEqual(\"ThisIsNoJoke\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_fullname_if_module_is_not_at_the_end()\r\n        {\r\n            // Given\r\n            NancyModule module = new ModuleForNancy();\r\n\r\n            // When\r\n            var name = module.GetModuleName();\r\n\r\n            // Then\r\n            name.ShouldEqual(\"ModuleForNancy\");\r\n        }\r\n\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/NamedPipelineBaseFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    using Xunit;\r\n\r\n    public class NamedPipelineBaseFixture\r\n    {\r\n        private class TestPipeline :  NamedPipelineBase<Action<string>>\r\n        {\r\n            public IEnumerable<PipelineItem<Action<string>>> Items\r\n            {\r\n                get { return pipelineItems; }\r\n            }\r\n        }\r\n\r\n        private readonly TestPipeline pipeline;\r\n\r\n        public NamedPipelineBaseFixture()\r\n        {\r\n            this.pipeline = new TestPipeline();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_add_to_start_of_pipeline()\r\n        {\r\n            var item1 = new PipelineItem<Action<string>>(\"item1\", s => { });\r\n            var item2 = new PipelineItem<Action<string>>(\"item2\", s => { });\r\n            pipeline.AddItemToEndOfPipeline(item2);\r\n\r\n            pipeline.AddItemToStartOfPipeline(item1);\r\n\r\n            Assert.Equal(2, pipeline.Items.Count());\r\n            Assert.Same(item1, pipeline.Items.First());\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_add_to_end_of_pipeline()\r\n        {\r\n            var item1 = new PipelineItem<Action<string>>(\"item1\", s => { });\r\n            var item2 = new PipelineItem<Action<string>>(\"item2\", s => { });\r\n            pipeline.AddItemToEndOfPipeline(item2);\r\n\r\n            pipeline.AddItemToEndOfPipeline(item1);\r\n\r\n            Assert.Equal(2, pipeline.Items.Count());\r\n            Assert.Same(item1, pipeline.Items.Last());\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_add_at_specific_index()\r\n        {\r\n            var item1 = new PipelineItem<Action<string>>(\"item1\", s => { });\r\n            var item2 = new PipelineItem<Action<string>>(\"item2\", s => { });\r\n            var item3 = new PipelineItem<Action<string>>(\"item3\", s => { });\r\n            pipeline.AddItemToEndOfPipeline(item1);\r\n            pipeline.AddItemToEndOfPipeline(item3);\r\n\r\n            pipeline.InsertItemAtPipelineIndex(1, item2);\r\n\r\n            Assert.Same(item1, pipeline.Items.ElementAt(0));\r\n            Assert.Same(item2, pipeline.Items.ElementAt(1));\r\n            Assert.Same(item3, pipeline.Items.ElementAt(2));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_remove_item_with_same_name_when_adding_to_start()\r\n        {\r\n            var existingItem = new PipelineItem<Action<string>>(\"item1\", s => { });\r\n            var item1 = new PipelineItem<Action<string>>(\"item1\", s => { });\r\n            var item2 = new PipelineItem<Action<string>>(\"item2\", s => { });\r\n            pipeline.AddItemToStartOfPipeline(existingItem);\r\n            pipeline.AddItemToEndOfPipeline(item2);\r\n\r\n            pipeline.AddItemToStartOfPipeline(item1);\r\n\r\n            Assert.Equal(2, pipeline.Items.Count());\r\n            Assert.Same(item1, pipeline.Items.First());\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_remove_item_with_same_name_when_adding_to_end()\r\n        {\r\n            var existingItem = new PipelineItem<Action<string>>(\"item1\", s => { });\r\n            var item1 = new PipelineItem<Action<string>>(\"item1\", s => { });\r\n            var item2 = new PipelineItem<Action<string>>(\"item2\", s => { });\r\n            pipeline.AddItemToEndOfPipeline(item2);\r\n            pipeline.AddItemToEndOfPipeline(existingItem);\r\n\r\n            pipeline.AddItemToEndOfPipeline(item1);\r\n\r\n            Assert.Equal(2, pipeline.Items.Count());\r\n            Assert.Same(item1, pipeline.Items.Last());\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_remove_item_with_same_name_when_adding_at_index()\r\n        {\r\n            var existingItem = new PipelineItem<Action<string>>(\"item2\", s => { });\r\n            var item1 = new PipelineItem<Action<string>>(\"item1\", s => { });\r\n            var item2 = new PipelineItem<Action<string>>(\"item2\", s => { });\r\n            var item3 = new PipelineItem<Action<string>>(\"item3\", s => { });\r\n            pipeline.AddItemToEndOfPipeline(item1);\r\n            pipeline.AddItemToEndOfPipeline(item3);\r\n            pipeline.AddItemToEndOfPipeline(existingItem);\r\n\r\n            pipeline.InsertItemAtPipelineIndex(1, item2);\r\n\r\n            Assert.Same(item1, pipeline.Items.ElementAt(0));\r\n            Assert.Same(item2, pipeline.Items.ElementAt(1));\r\n            Assert.Same(item3, pipeline.Items.ElementAt(2));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_insert_before_a_named_item()\r\n        {\r\n            var item1 = new PipelineItem<Action<string>>(\"item1\", s => { });\r\n            var item2 = new PipelineItem<Action<string>>(\"item2\", s => { });\r\n            var item3 = new PipelineItem<Action<string>>(\"item3\", s => { });\r\n            pipeline.AddItemToEndOfPipeline(item1);\r\n            pipeline.AddItemToEndOfPipeline(item3);\r\n\r\n            pipeline.InsertBefore(\"item3\", item2);\r\n\r\n            Assert.Same(item1, pipeline.Items.ElementAt(0));\r\n            Assert.Same(item2, pipeline.Items.ElementAt(1));\r\n            Assert.Same(item3, pipeline.Items.ElementAt(2));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_insert_after_a_named_item()\r\n        {\r\n            var item1 = new PipelineItem<Action<string>>(\"item1\", s => { });\r\n            var item2 = new PipelineItem<Action<string>>(\"item2\", s => { });\r\n            var item3 = new PipelineItem<Action<string>>(\"item3\", s => { });\r\n            pipeline.AddItemToEndOfPipeline(item1);\r\n            pipeline.AddItemToEndOfPipeline(item3);\r\n\r\n            pipeline.InsertAfter(\"item1\", item2);\r\n\r\n            Assert.Same(item1, pipeline.Items.ElementAt(0));\r\n            Assert.Same(item2, pipeline.Items.ElementAt(1));\r\n            Assert.Same(item3, pipeline.Items.ElementAt(2));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_to_start_if_inserting_before_and_item_doesnt_exist()\r\n        {\r\n            var item1 = new PipelineItem<Action<string>>(\"item1\", s => { });\r\n            var item2 = new PipelineItem<Action<string>>(\"item2\", s => { });\r\n            var item3 = new PipelineItem<Action<string>>(\"item3\", s => { });\r\n            pipeline.AddItemToEndOfPipeline(item1);\r\n            pipeline.AddItemToEndOfPipeline(item3);\r\n\r\n            pipeline.InsertBefore(\"nonexistant\", item2);\r\n\r\n            Assert.Same(item2, pipeline.Items.ElementAt(0));\r\n            Assert.Same(item1, pipeline.Items.ElementAt(1));\r\n            Assert.Same(item3, pipeline.Items.ElementAt(2));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_to_end_if_inserting_after_and_item_doesnt_exist()\r\n        {\r\n            var item1 = new PipelineItem<Action<string>>(\"item1\", s => { });\r\n            var item2 = new PipelineItem<Action<string>>(\"item2\", s => { });\r\n            var item3 = new PipelineItem<Action<string>>(\"item3\", s => { });\r\n            pipeline.AddItemToEndOfPipeline(item1);\r\n            pipeline.AddItemToEndOfPipeline(item3);\r\n\r\n            pipeline.InsertAfter(\"nonexistant\", item2);\r\n\r\n            Assert.Same(item1, pipeline.Items.ElementAt(0));\r\n            Assert.Same(item3, pipeline.Items.ElementAt(1));\r\n            Assert.Same(item2, pipeline.Items.ElementAt(2));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_replace_in_place_if_set_when_adding_to_start()\r\n        {\r\n            var existingItem = new PipelineItem<Action<string>>(\"item1\", s => { });\r\n            var item1 = new PipelineItem<Action<string>>(\"item1\", s => { });\r\n            var item2 = new PipelineItem<Action<string>>(\"item2\", s => { });\r\n            pipeline.AddItemToEndOfPipeline(item2);\r\n            pipeline.AddItemToEndOfPipeline(existingItem);\r\n\r\n            pipeline.AddItemToStartOfPipeline(item1, true);\r\n\r\n            Assert.Equal(2, pipeline.Items.Count());\r\n            Assert.Same(item1, pipeline.Items.Last());\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_replace_in_place_if_set_when_adding_to_end()\r\n        {\r\n            var existingItem = new PipelineItem<Action<string>>(\"item1\", s => { });\r\n            var item1 = new PipelineItem<Action<string>>(\"item1\", s => { });\r\n            var item2 = new PipelineItem<Action<string>>(\"item2\", s => { });\r\n            pipeline.AddItemToEndOfPipeline(existingItem);\r\n            pipeline.AddItemToEndOfPipeline(item2);\r\n\r\n            pipeline.AddItemToEndOfPipeline(item1, true);\r\n\r\n            Assert.Equal(2, pipeline.Items.Count());\r\n            Assert.Same(item1, pipeline.Items.First());\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_replace_in_place_if_set_when_adding_at_index()\r\n        {\r\n            var existingItem = new PipelineItem<Action<string>>(\"item1\", s => { });\r\n            var item1 = new PipelineItem<Action<string>>(\"item1\", s => { });\r\n            var item2 = new PipelineItem<Action<string>>(\"item2\", s => { });\r\n            pipeline.AddItemToEndOfPipeline(item2);\r\n            pipeline.AddItemToEndOfPipeline(existingItem);\r\n\r\n            pipeline.InsertItemAtPipelineIndex(0, item1, true);\r\n\r\n            Assert.Equal(2, pipeline.Items.Count());\r\n            Assert.Same(item1, pipeline.Items.Last());\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_remove_a_named_item()\r\n        {\r\n            var item1 = new PipelineItem<Action<string>>(\"item1\", s => { });\r\n            var item2 = new PipelineItem<Action<string>>(\"item2\", s => { });\r\n            pipeline.AddItemToEndOfPipeline(item1);\r\n            pipeline.AddItemToEndOfPipeline(item2);\r\n\r\n            pipeline.RemoveByName(\"item2\");\r\n\r\n            Assert.Equal(1, pipeline.Items.Count());\r\n            Assert.Same(item1, pipeline.Items.First());\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_add_unnamed_item_to_end_of_pipeline()\r\n        {\r\n            // Given\r\n            Action<string> firstAction = r => { };\r\n            Action<string> secondAction = r => { };\r\n\r\n            // When\r\n            pipeline.AddItemToEndOfPipeline(firstAction);\r\n            pipeline.AddItemToEndOfPipeline(secondAction);\r\n\r\n            // Then\r\n            pipeline.PipelineDelegates.ShouldHaveCount(2);\r\n            pipeline.PipelineDelegates.First().ShouldBeSameAs(firstAction);\r\n            pipeline.PipelineDelegates.Last().ShouldBeSameAs(secondAction);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/NancyContextFixture.cs",
    "content": "namespace Nancy.Tests.Unit\r\n{\r\n    using System;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Xunit;\r\n\r\n    public class NancyContextFixture\r\n    {\r\n        private readonly NancyContext context;\r\n\r\n        public NancyContextFixture()\r\n        {\r\n            this.context = new NancyContext();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_dispose_request_when_not_set()\r\n        {\r\n            // Given, When\r\n            var exception = Record.Exception(() => this.context.Dispose());\r\n\r\n            // Then\r\n            exception.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_dispose_request_when_being_disposed()\r\n        {\r\n            // Given\r\n            var request = A.Fake<Request>(x => {\r\n                x.Implements(typeof (IDisposable));;\r\n                x.WithArgumentsForConstructor(new[] {\"GET\", \"/\", \"http\"});\r\n            });\r\n\r\n            this.context.Request = request;\r\n\r\n            // When\r\n            this.context.Dispose();\r\n\r\n            // Then\r\n            A.CallTo(() => ((IDisposable)request).Dispose()).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_dispose_disposable_items_when_disposed()\r\n        {\r\n            // Given\r\n            var disposable = A.Fake<IDisposable>();\r\n            this.context.Items.Add(\"Disposable\", disposable);\r\n            this.context.Items.Add(\"Test\", new object());\r\n\r\n            // When\r\n            this.context.Dispose();\r\n\r\n            // Then\r\n            A.CallTo(() => disposable.Dispose()).MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_clear_items_collection_when_disposed()\r\n        {\r\n            // Given\r\n            this.context.Items.Add(\"Test\", new object());\r\n\r\n            // When\r\n            this.context.Dispose();\r\n\r\n            // Then\r\n            this.context.Items.Count.ShouldEqual(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_dispose_response_if_set_when_context_is_disposed()\r\n        {\r\n            // Given\r\n            var response = new DisposableResponse();\r\n            this.context.Response = response;\r\n\r\n            // When\r\n            this.context.Dispose();\r\n\r\n            // Then\r\n            response.HasBeenDisposed.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_dispose_response_when_not_set()\r\n        {\r\n            // Given\r\n            this.context.Response = null;\r\n\r\n            // When\r\n            var exception = Record.Exception(() => this.context.Dispose());\r\n\r\n            // Then\r\n            exception.ShouldBeNull();\r\n        }\r\n\r\n        private class DisposableResponse : Response\r\n        {\r\n            public bool HasBeenDisposed { get; private set; }\r\n\r\n            public override void Dispose()\r\n            {\r\n                this.HasBeenDisposed = true;\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/NancyCookieFixture.cs",
    "content": "namespace Nancy.Tests.Unit\r\n{\r\n    using System;\r\n    using System.Globalization;\r\n    using System.Threading;\r\n\r\n    using Nancy.Cookies;\r\n    using Nancy.Tests.xUnitExtensions;\r\n    using Xunit;\r\n\r\n    public class NancyCookieFixture\r\n    {\r\n        [Fact]\r\n        public void Should_stringify_a_simple_name_value()\r\n        {\r\n            // Given\r\n            var cookie = new NancyCookie(\"leto\", \"worm\");\r\n\r\n            // When\r\n            var stringified = cookie.ToString();\r\n\r\n            // Then\r\n            stringified.ShouldEqual(\"leto=worm; path=/\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_stringify_an_expiry_to_gmt_and_stupid_format()\r\n        {\r\n            // Given\r\n            var date = new DateTime(2015, 10, 8, 9, 10, 11, DateTimeKind.Utc);\r\n\r\n            // When\r\n            var cookie = new NancyCookie(\"leto\", \"worm\") { Expires = date }.ToString();\r\n\r\n            // Then\r\n            cookie.ShouldEqual(\"leto=worm; path=/; expires=Thu, 08-Oct-2015 09:10:11 GMT\");\r\n        }\r\n\r\n        [Fact]\r\n        [UsingCulture(\"fr-FR\")]\r\n        public void Should_stringify_an_expiry_to_english()\r\n        {\r\n            // Given\r\n            var date = new DateTime(2015, 10, 8, 9, 10, 11, DateTimeKind.Utc);\r\n\r\n            // When\r\n            var cookie = new NancyCookie(\"leto\", \"worm\") { Expires = date }.ToString();\r\n\r\n            // Then\r\n            cookie.ShouldEqual(\"leto=worm; path=/; expires=Thu, 08-Oct-2015 09:10:11 GMT\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_stringify_a_domain()\r\n        {\r\n            // Given\r\n            var cookie = new NancyCookie(\"leto\", \"worm\") { Domain = \"google.com\" };\r\n\r\n            // When\r\n            var stringified = cookie.ToString();\r\n\r\n            // Then\r\n            stringified.ShouldEqual(\"leto=worm; path=/; domain=google.com\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_stringify_a_path()\r\n        {\r\n            // Given\r\n            var cookie = new NancyCookie(\"leto\", \"worm\") { Path = \"/nancy\" };\r\n\r\n            // When\r\n            var stringified = cookie.ToString();\r\n\r\n            // Then\r\n            stringified.ShouldEqual(\"leto=worm; path=/nancy\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_stringify_everyting()\r\n        {\r\n            // Given\r\n            var date = new DateTime(2016, 11, 8, 9, 10, 11, DateTimeKind.Utc);\r\n            var tuesday = GetInvariantAbbreviatedWeekdayName(date);\r\n            var november = GetInvariantAbbreviatedMonthName(date);\r\n            var cookie = new NancyCookie(\"paul\", \"blind\", true, true, date) { Path = \"/frank\", Domain = \"gmail.com\" };\r\n\r\n            // When\r\n            var stringified = cookie.ToString();\r\n\r\n            // Then\r\n            stringified.ShouldEqual(string.Format(\"paul=blind; path=/frank; expires={0}, 08-{1}-2016 09:10:11 GMT; domain=gmail.com; Secure; HttpOnly\", tuesday, november));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_add_secure_if_set_to_false()\r\n        {\r\n            var cookie = new NancyCookie(\"Test\", \"Value\");\r\n\r\n            var result = cookie.ToString();\r\n\r\n            result.ShouldNotContain(\"Secure\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_secure_if_set_to_true()\r\n        {\r\n            var cookie = new NancyCookie(\"Test\", \"Value\", true, true, null);\r\n\r\n            var result = cookie.ToString();\r\n\r\n            result.ShouldContain(\"Secure\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_add_http_only_if_set_to_false()\r\n        {\r\n            var cookie = new NancyCookie(\"Test\", \"Value\", false);\r\n\r\n            var result = cookie.ToString();\r\n\r\n            result.ShouldNotContain(\"HttpOnly\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_http_only_if_set_to_true()\r\n        {\r\n            var cookie = new NancyCookie(\"Test\", \"Value\", true);\r\n\r\n            var result = cookie.ToString();\r\n\r\n            result.ShouldContain(\"HttpOnly\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_encode_key_and_value_when_stringified()\r\n        {\r\n            var cookie = new NancyCookie(\"Key with spaces\", \"Value with spaces\");\r\n\r\n            var result = cookie.ToString();\r\n\r\n            result.ShouldEqual(\"Key+with+spaces=Value+with+spaces; path=/\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_encode_key_if_necessary()\r\n        {\r\n            var cookie = new NancyCookie(\"with spaces\", \"Value\");\r\n\r\n            var result = cookie.EncodedName;\r\n\r\n            result.ShouldEqual(\"with+spaces\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_encode_value_if_necessary()\r\n        {\r\n            var cookie = new NancyCookie(\"Test\", \"Value with spaces\");\r\n\r\n            var result = cookie.EncodedValue;\r\n\r\n            result.ShouldEqual(\"Value+with+spaces\");\r\n        }\r\n\r\n        public static string GetInvariantAbbreviatedMonthName(DateTime dateTime)\r\n        {\r\n            return CultureInfo.InvariantCulture.DateTimeFormat.AbbreviatedMonthNames[dateTime.Month - 1];\r\n        }\r\n\r\n        public static string GetInvariantAbbreviatedWeekdayName(DateTime dateTime)\r\n        {\r\n            return CultureInfo.InvariantCulture.DateTimeFormat.AbbreviatedDayNames[(int)dateTime.DayOfWeek];\r\n        }\r\n\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/NancyEngineFixture.cs",
    "content": "namespace Nancy.Tests.Unit\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Configuration;\r\n    using Nancy.Diagnostics;\r\n    using Nancy.ErrorHandling;\r\n    using Nancy.Extensions;\r\n    using Nancy.Helpers;\r\n    using Nancy.Routing;\r\n    using Nancy.Tests.Fakes;\r\n\r\n    using Xunit;\r\n    using Nancy.Responses.Negotiation;\r\n    using Nancy.Tests.xUnitExtensions;\r\n\r\n    public class NancyEngineFixture\r\n    {\r\n        private readonly INancyEngine engine;\r\n        private readonly IRouteResolver resolver;\r\n        private readonly FakeRoute route;\r\n        private readonly NancyContext context;\r\n        private readonly INancyContextFactory contextFactory;\r\n        private readonly Response response;\r\n        private readonly IStatusCodeHandler statusCodeHandler;\r\n        private readonly IRouteInvoker routeInvoker;\r\n        private readonly IRequestDispatcher requestDispatcher;\r\n        private readonly IResponseNegotiator negotiator;\r\n        private readonly INancyEnvironment environment;\r\n\r\n        public NancyEngineFixture()\r\n        {\r\n            this.environment =\r\n                new DefaultNancyEnvironment();\r\n\r\n            this.environment.Tracing(\r\n                enabled: true,\r\n                displayErrorTraces: true);\r\n\r\n            this.resolver = A.Fake<IRouteResolver>();\r\n            this.response = new Response();\r\n            this.route = new FakeRoute(response);\r\n            this.context = new NancyContext();\r\n            this.statusCodeHandler = A.Fake<IStatusCodeHandler>();\r\n            this.requestDispatcher = A.Fake<IRequestDispatcher>();\r\n            this.negotiator = A.Fake<IResponseNegotiator>();\r\n\r\n            A.CallTo(() => this.requestDispatcher.Dispatch(A<NancyContext>._, A<CancellationToken>._))\r\n                .Returns(Task.FromResult(new Response()));\r\n\r\n            A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).Returns(false);\r\n\r\n            contextFactory = A.Fake<INancyContextFactory>();\r\n            A.CallTo(() => contextFactory.Create(A<Request>._)).Returns(context);\r\n\r\n            var resolveResult = new ResolveResult { Route = route, Parameters = DynamicDictionary.Empty, Before = null, After = null, OnError = null };\r\n            A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolveResult);\r\n\r\n            var applicationPipelines = new Pipelines();\r\n\r\n            this.routeInvoker = A.Fake<IRouteInvoker>();\r\n\r\n            this.engine =\r\n                new NancyEngine(this.requestDispatcher, this.contextFactory, new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator, this.environment)\r\n                {\r\n                    RequestPipelinesFactory = ctx => applicationPipelines\r\n                };\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_argumentnullexception_when_created_with_null_dispatcher()\r\n        {\r\n            // Given, When\r\n            var exception =\r\n                Record.Exception(() => new NancyEngine(null, A.Fake<INancyContextFactory>(), new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator, this.environment));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ArgumentNullException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_argumentnullexception_when_created_with_null_context_factory()\r\n        {\r\n            // Given, When\r\n            var exception =\r\n                Record.Exception(() => new NancyEngine(this.requestDispatcher, null, new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator, this.environment));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ArgumentNullException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_argumentnullexception_when_created_with_null_status_handler()\r\n        {\r\n            // Given, When\r\n            var exception =\r\n                Record.Exception(() => new NancyEngine(this.requestDispatcher, A.Fake<INancyContextFactory>(), null, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator, this.environment));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ArgumentNullException>();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task HandleRequest_Should_Throw_ArgumentNullException_When_Given_A_Null_Request()\r\n        {\r\n            // Given,\r\n            Request request = null;\r\n\r\n            // When\r\n            var exception = await RecordAsync.Exception(async () => await engine.HandleRequest(request));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ArgumentNullException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void HandleRequest_should_get_context_from_context_factory()\r\n        {\r\n            // Given\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n\r\n            // When\r\n            this.engine.HandleRequest(request);\r\n\r\n            // Then\r\n            A.CallTo(() => this.contextFactory.Create(request)).MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task HandleRequest_should_set_correct_response_on_returned_context()\r\n        {\r\n            // Given\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n\r\n            A.CallTo(() => this.requestDispatcher.Dispatch(this.context, A<CancellationToken>._))\r\n                .Returns(Task.FromResult(this.response));\r\n\r\n            // When\r\n            var result = await this.engine.HandleRequest(request);\r\n\r\n            // Then\r\n            result.Response.ShouldBeSameAs(this.response);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_add_nancy_version_number_header_on_returned_response()\r\n        {\r\n            // NOTE: Regression for removal of nancy-version from response headers\r\n            // Given\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n\r\n            // When\r\n            var result = await this.engine.HandleRequest(request);\r\n\r\n            // Then\r\n            result.Response.Headers.ContainsKey(\"Nancy-Version\").ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_throw_exception_when_handlerequest_is_invoked_and_pre_request_hook_is_null()\r\n        {\r\n            // Given\r\n            var pipelines = new Pipelines { BeforeRequest = null };\r\n            engine.RequestPipelinesFactory = (ctx) => pipelines;\r\n\r\n            // When\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n\r\n            // Then\r\n            await this.engine.HandleRequest(request);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_throw_exception_when_handlerequest_is_invoked_and_post_request_hook_is_null()\r\n        {\r\n            // Given\r\n            var pipelines = new Pipelines { AfterRequest = null };\r\n            engine.RequestPipelinesFactory = (ctx) => pipelines;\r\n\r\n            // When\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n\r\n            // Then\r\n            await this.engine.HandleRequest(request);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_call_pre_request_hook_should_be_invoked_with_request_from_context()\r\n        {\r\n            // Given\r\n            Request passedRequest = null;\r\n\r\n            var pipelines = new Pipelines();\r\n            pipelines.BeforeRequest.AddItemToStartOfPipeline((ctx) =>\r\n            {\r\n                passedRequest = ctx.Request;\r\n                return null;\r\n            });\r\n\r\n            engine.RequestPipelinesFactory = (ctx) => pipelines;\r\n\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n\r\n            this.context.Request = request;\r\n\r\n            // When\r\n            await this.engine.HandleRequest(request);\r\n\r\n            // Then\r\n            passedRequest.ShouldBeSameAs(request);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_response_from_pre_request_hook_when_not_null()\r\n        {\r\n            // Given\r\n            var returnedResponse = A.Fake<Response>();\r\n\r\n            var pipelines = new Pipelines();\r\n            pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx => returnedResponse);\r\n\r\n            engine.RequestPipelinesFactory = (ctx) => pipelines;\r\n\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n\r\n            // When\r\n            var result = await this.engine.HandleRequest(request);\r\n\r\n            // Then\r\n            result.Response.ShouldBeSameAs(returnedResponse);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_allow_post_request_hook_to_modify_context_items()\r\n        {\r\n            // Given\r\n            var pipelines = new Pipelines();\r\n            pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx =>\r\n            {\r\n                ctx.Items.Add(\"PostReqTest\", new object());\r\n                return null;\r\n            });\r\n\r\n            engine.RequestPipelinesFactory = (ctx) => pipelines;\r\n\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n\r\n            // When\r\n            var result = await this.engine.HandleRequest(request);\r\n\r\n            // Then\r\n            result.Items.ContainsKey(\"PostReqTest\").ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_allow_post_request_hook_to_replace_response()\r\n        {\r\n            // Given\r\n            var newResponse = new Response();\r\n\r\n            var pipelines = new Pipelines();\r\n            pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx => ctx.Response = newResponse);\r\n            engine.RequestPipelinesFactory = (ctx) => pipelines;\r\n\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n\r\n            // When\r\n            var result = await this.engine.HandleRequest(request);\r\n\r\n            // Then\r\n            result.Response.ShouldBeSameAs(newResponse);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task HandleRequest_prereq_returns_response_should_still_run_postreq()\r\n        {\r\n            // Given\r\n            var returnedResponse = A.Fake<Response>();\r\n            var postReqCalled = false;\r\n\r\n            var pipelines = new Pipelines();\r\n            pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx => returnedResponse);\r\n            pipelines.AfterRequest.AddItemToEndOfPipeline(ctx => postReqCalled = true);\r\n\r\n            engine.RequestPipelinesFactory = (ctx) => pipelines;\r\n\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n\r\n            // When\r\n            await this.engine.HandleRequest(request);\r\n\r\n            // Then\r\n            postReqCalled.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_ask_status_handler_if_it_can_handle_status_code()\r\n        {\r\n            // Given\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n\r\n            // When\r\n            await this.engine.HandleRequest(request);\r\n\r\n            // Then\r\n            A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_invoke_status_handler_if_not_supported_status_code()\r\n        {\r\n            // Given\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n\r\n            // When\r\n            await this.engine.HandleRequest(request);\r\n\r\n            // Then\r\n            A.CallTo(() => this.statusCodeHandler.Handle(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).MustNotHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_invoke_status_handler_if_supported_status_code()\r\n        {\r\n            // Given\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n            A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).Returns(true);\r\n\r\n            // When\r\n            await this.engine.HandleRequest(request);\r\n\r\n            // Then\r\n            A.CallTo(() => this.statusCodeHandler.Handle(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_catch_exception_inside_status_code_handler_and_return_default_error_response()\r\n        {\r\n            // Given\r\n            A.CallTo(() => this.requestDispatcher.Dispatch(A<NancyContext>.Ignored, A<CancellationToken>.Ignored))\r\n                .Returns(new Response() { StatusCode = HttpStatusCode.InternalServerError });\r\n\r\n            var statusCodeHandlers = new[]\r\n            {\r\n                this.statusCodeHandler,\r\n                new DefaultStatusCodeHandler(this.negotiator, this.environment),\r\n            };\r\n\r\n            var engine =\r\n                new NancyEngine(this.requestDispatcher, this.contextFactory, statusCodeHandlers,\r\n                    A.Fake<IRequestTracing>(),\r\n                    new DisabledStaticContentProvider(), this.negotiator, this.environment)\r\n                {\r\n                    RequestPipelinesFactory = ctx => new Pipelines()\r\n                };\r\n\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n\r\n            A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).Returns(true);\r\n            A.CallTo(() => this.statusCodeHandler.Handle(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored))\r\n                .Throws<Exception>();\r\n\r\n            // When\r\n            await engine.HandleRequest(request);\r\n\r\n            // Then\r\n            this.context.Response.StatusCode.ShouldEqual(HttpStatusCode.InternalServerError);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_throw_exception_if_no_default_status_code_handler_present_when_custom_status_code_handler_throws()\r\n        {\r\n            // Given\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n            A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).Returns(true);\r\n            A.CallTo(() => this.statusCodeHandler.Handle(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored))\r\n                .Throws<Exception>();\r\n\r\n            // When,Then\r\n            await AssertAsync.Throws<Exception>(async () => await this.engine.HandleRequest(request));\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_set_status_code_to_500_if_route_throws()\r\n        {\r\n            // Given\r\n            var resolvedRoute = new ResolveResult(\r\n                new FakeRoute(),\r\n                DynamicDictionary.Empty,\r\n                null,\r\n                null,\r\n                null);\r\n\r\n            A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);\r\n\r\n            A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._))\r\n                .Returns(TaskHelpers.GetFaultedTask<Response>(new NotImplementedException()));\r\n\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n\r\n            // When\r\n            var result = await this.engine.HandleRequest(request);\r\n\r\n            // Then\r\n            result.Response.StatusCode.ShouldEqual(HttpStatusCode.InternalServerError);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_store_exception_details_if_dispatcher_throws()\r\n        {\r\n            // Given\r\n            var resolvedRoute = new ResolveResult(\r\n                new FakeRoute(),\r\n                DynamicDictionary.Empty,\r\n                null,\r\n                null,\r\n                null);\r\n\r\n            A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);\r\n\r\n            A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._))\r\n                .Returns(TaskHelpers.GetFaultedTask<Response>(new NotImplementedException()));\r\n\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n\r\n            // When\r\n            var result = await this.engine.HandleRequest(request);\r\n\r\n            // Then\r\n            result.GetExceptionDetails().ShouldContain(\"NotImplementedException\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_invoke_the_error_request_hook_if_one_exists_when_dispatcher_throws()\r\n        {\r\n            // Given\r\n            var testEx = new Exception();\r\n\r\n            var errorRoute =\r\n                new Route<object>(\"GET\", \"/\", null, (x, c) => { throw testEx; });\r\n\r\n            var resolvedRoute = new ResolveResult(\r\n                errorRoute,\r\n                DynamicDictionary.Empty,\r\n                null,\r\n                null,\r\n                null);\r\n\r\n            A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);\r\n\r\n            A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._))\r\n                .Returns(TaskHelpers.GetFaultedTask<Response>(testEx));\r\n\r\n            Exception handledException = null;\r\n            NancyContext handledContext = null;\r\n            var errorResponse = new Response();\r\n\r\n            A.CallTo(() => this.negotiator.NegotiateResponse(A<object>.Ignored, A<NancyContext>.Ignored))\r\n                .Returns(errorResponse);\r\n\r\n            Func<NancyContext, Exception, dynamic> routeErrorHook = (ctx, ex) =>\r\n            {\r\n                handledContext = ctx;\r\n                handledException = ex;\r\n                return errorResponse;\r\n            };\r\n\r\n            var pipelines = new Pipelines();\r\n            pipelines.OnError.AddItemToStartOfPipeline(routeErrorHook);\r\n\r\n            engine.RequestPipelinesFactory = (ctx) => pipelines;\r\n\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n\r\n            // When\r\n            var result = await this.engine.HandleRequest(request);\r\n\r\n            // Then\r\n            Assert.Equal(testEx, handledException);\r\n            Assert.Equal(result, handledContext);\r\n            Assert.Equal(result.Response, errorResponse);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_add_unhandled_exception_to_context_as_requestexecutionexception()\r\n        {\r\n            // Given\r\n            var routeUnderTest =\r\n                new Route<object>(\"GET\", \"/\", null, (x, c) => { throw new Exception(); });\r\n\r\n            var resolved =\r\n                new ResolveResult(routeUnderTest, DynamicDictionary.Empty, null, null, null);\r\n\r\n            A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolved);\r\n\r\n            A.CallTo(() => this.routeInvoker.Invoke(A<Route>._, A<CancellationToken>._, A<DynamicDictionary>._, A<NancyContext>._))\r\n                .Invokes((x) => routeUnderTest.Action.Invoke(DynamicDictionary.Empty, new CancellationToken()));\r\n\r\n            A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._))\r\n                .Returns(TaskHelpers.GetFaultedTask<Response>(new Exception()));\r\n\r\n            var pipelines = new Pipelines();\r\n            pipelines.OnError.AddItemToStartOfPipeline((ctx, exception) => null);\r\n            engine.RequestPipelinesFactory = (ctx) => pipelines;\r\n\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n\r\n            // When\r\n            var result = await this.engine.HandleRequest(request);\r\n\r\n            // Then\r\n            result.Items.Keys.Contains(\"ERROR_EXCEPTION\").ShouldBeTrue();\r\n            result.Items[\"ERROR_EXCEPTION\"].ShouldBeOfType<RequestExecutionException>();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_persist_original_exception_in_requestexecutionexception()\r\n        {\r\n            // Given\r\n            var expectedException = new Exception();\r\n\r\n            var resolvedRoute = new ResolveResult(\r\n               new FakeRoute(),\r\n               DynamicDictionary.Empty,\r\n               null,\r\n               null,\r\n               null);\r\n\r\n            A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);\r\n\r\n            A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._))\r\n                .Returns(TaskHelpers.GetFaultedTask<Response>(expectedException));\r\n\r\n            var pipelines = new Pipelines();\r\n            pipelines.OnError.AddItemToStartOfPipeline((ctx, exception) => null);\r\n            engine.RequestPipelinesFactory = (ctx) => pipelines;\r\n\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n\r\n            // When\r\n            var result = await this.engine.HandleRequest(request);\r\n            var returnedException = result.Items[\"ERROR_EXCEPTION\"] as RequestExecutionException;\r\n\r\n            // Then\r\n            returnedException.InnerException.ShouldBeSameAs(expectedException);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_persist_original_exception_in_requestexecutionexception_when_pipeline_is_null()\r\n        {\r\n            // Given\r\n            var expectedException = new Exception();\r\n\r\n            var resolvedRoute = new ResolveResult(\r\n                new FakeRoute(),\r\n                DynamicDictionary.Empty,\r\n                null,\r\n                null,\r\n                null);\r\n\r\n            A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);\r\n\r\n            A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._))\r\n                .Returns(TaskHelpers.GetFaultedTask<Response>(expectedException));\r\n\r\n            var pipelines = new Pipelines { OnError = null };\r\n            engine.RequestPipelinesFactory = (ctx) => pipelines;\r\n\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n\r\n            // When\r\n            var result = await this.engine.HandleRequest(request);\r\n            var returnedException = result.Items[\"ERROR_EXCEPTION\"] as RequestExecutionException;\r\n\r\n            // Then\r\n            returnedException.InnerException.ShouldBeSameAs(expectedException);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_static_content_response_if_one_returned()\r\n        {\r\n            // Given\r\n            var localResponse = new Response();\r\n            var staticContent = A.Fake<IStaticContentProvider>();\r\n            A.CallTo(() => staticContent.GetContent(A<NancyContext>._))\r\n                        .Returns(localResponse);\r\n\r\n            var localEngine = new NancyEngine(\r\n                                    this.requestDispatcher,\r\n                                    this.contextFactory,\r\n                                    new[] { this.statusCodeHandler },\r\n                                    A.Fake<IRequestTracing>(),\r\n                                    staticContent,\r\n                                    this.negotiator\r\n                                    , this.environment);\r\n\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n\r\n            // When\r\n            var result = await localEngine.HandleRequest(request);\r\n\r\n            // Then\r\n            result.Response.ShouldBeSameAs(localResponse);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_set_status_code_to_500_if_pre_execute_response_throws()\r\n        {\r\n            // Given\r\n            var resolvedRoute = new ResolveResult(\r\n                new FakeRoute(),\r\n                DynamicDictionary.Empty,\r\n                null,\r\n                null,\r\n                null);\r\n\r\n            A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);\r\n\r\n            A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._))\r\n                .Returns(Task.FromResult<Response>(new PreExecuteFailureResponse()));\r\n\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n\r\n            // When\r\n            var result = await this.engine.HandleRequest(request);\r\n\r\n            // Then\r\n            result.Response.StatusCode.ShouldEqual(HttpStatusCode.InternalServerError);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_throw_operationcancelledexception_when_disposed_handling_request()\r\n        {\r\n            // Given\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n            var engine = new NancyEngine(A.Fake<IRequestDispatcher>(), A.Fake<INancyContextFactory>(),\r\n                new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(),\r\n                this.negotiator, this.environment);\r\n\r\n            engine.Dispose();\r\n\r\n            // When\r\n            var exception = await RecordAsync.Exception(async () => await engine.HandleRequest(request));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<OperationCanceledException>();\r\n        }\r\n    }\r\n\r\n    public class PreExecuteFailureResponse : Response\r\n    {\r\n        public override Task PreExecute(NancyContext context)\r\n        {\r\n            return TaskHelpers.GetFaultedTask<object>(new InvalidOperationException());\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/NancyMiddlewareFixture.cs",
    "content": "namespace Nancy.Tests.Unit\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Security.Claims;\r\n    using System.Security.Principal;\r\n    using System.Text;\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Helpers;\r\n    using Nancy.Owin;\r\n\r\n    using Xunit;\r\n\r\n    using AppFunc = System.Func<System.Collections.Generic.IDictionary<string, object>,\r\n       System.Threading.Tasks.Task>;\r\n\r\n    using MidFunc = System.Func<System.Func<System.Collections.Generic.IDictionary<string, object>,\r\n            System.Threading.Tasks.Task>, System.Func<System.Collections.Generic.IDictionary<string, object>,\r\n            System.Threading.Tasks.Task>>;\r\n\r\n    public class NancyMiddlewareFixture\r\n    {\r\n        private readonly Dictionary<string, object> environment;\r\n        private readonly INancyBootstrapper fakeBootstrapper;\r\n        private readonly INancyEngine fakeEngine;\r\n        private readonly AppFunc host;\r\n\r\n        public NancyMiddlewareFixture()\r\n        {\r\n            this.fakeEngine = A.Fake<INancyEngine>();\r\n            this.fakeBootstrapper = A.Fake<INancyBootstrapper>();\r\n            A.CallTo(() => this.fakeBootstrapper.GetEngine()).Returns(this.fakeEngine);\r\n            this.host = NancyMiddleware.UseNancy(new NancyOptions {Bootstrapper = this.fakeBootstrapper})(null);\r\n            this.environment = new Dictionary<string, object>\r\n            {\r\n                {\"owin.RequestMethod\", \"GET\"},\r\n                {\"owin.RequestPath\", \"/test\"},\r\n                {\"owin.RequestPathBase\", \"/root\"},\r\n                {\"owin.RequestQueryString\", \"var=value\"},\r\n                {\"owin.RequestBody\", Stream.Null},\r\n                {\"owin.RequestHeaders\", new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase)},\r\n                {\"owin.RequestScheme\", \"http\"},\r\n                {\"owin.ResponseHeaders\", new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase)},\r\n                {\"owin.ResponseBody\", new MemoryStream()},\r\n                {\"owin.ResponseReasonPhrase\", string.Empty},\r\n                {\"owin.Version\", \"1.0\"},\r\n                {\"owin.CallCancelled\", CancellationToken.None}\r\n            };\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_immediately_invoke_nancy_if_no_request_body_delegate()\r\n        {\r\n            // Given\r\n            var fakeResponse = new Response { StatusCode = HttpStatusCode.OK, Contents = s => { } };\r\n            var fakeContext = new NancyContext { Response = fakeResponse };\r\n            this.SetupFakeNancyCompleteCallback(fakeContext);\r\n\r\n            // When\r\n            this.host(this.environment);\r\n\r\n            // Then\r\n            A.CallTo(() =>  this.fakeEngine.HandleRequest(\r\n                    A<Request>.Ignored,\r\n                    A<Func<NancyContext, NancyContext>>.Ignored,\r\n                    (CancellationToken)this.environment[\"owin.CallCancelled\"]))\r\n             .MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_return_code_in_response_callback()\r\n        {\r\n            // Given\r\n            var fakeResponse = new Response {StatusCode = HttpStatusCode.OK, Contents = s => { }};\r\n            var fakeContext = new NancyContext {Response = fakeResponse};\r\n            this.SetupFakeNancyCompleteCallback(fakeContext);\r\n\r\n            // When\r\n            this.host.Invoke(this.environment);\r\n\r\n            // Then\r\n            ((int)this.environment[\"owin.ResponseStatusCode\"]).ShouldEqual(200);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_headers_in_response_callback()\r\n        {\r\n            // Given\r\n            var fakeResponse = new Response\r\n            {\r\n                StatusCode = HttpStatusCode.OK,\r\n                Headers = new Dictionary<string, string> {{\"TestHeader\", \"TestValue\"}},\r\n                Contents = s => { }\r\n            };\r\n            var fakeContext = new NancyContext {Response = fakeResponse};\r\n            this.SetupFakeNancyCompleteCallback(fakeContext);\r\n\r\n            // When\r\n            this.host.Invoke(this.environment);\r\n            var headers = (IDictionary<string, string[]>)this.environment[\"owin.ResponseHeaders\"];\r\n\r\n            // Then\r\n            // 2 headers because the default content-type is text/html\r\n            headers.Count.ShouldEqual(2);\r\n            headers[\"Content-Type\"][0].ShouldEqual(\"text/html\");\r\n            headers[\"TestHeader\"][0].ShouldEqual(\"TestValue\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_send_entire_body()\r\n        {\r\n            // Given\r\n            var data1 = Encoding.ASCII.GetBytes(\"Some content\");\r\n            var data2 = Encoding.ASCII.GetBytes(\"Some more content\");\r\n            var fakeResponse = new Response\r\n            {\r\n                StatusCode = HttpStatusCode.OK,\r\n                Contents = s =>\r\n                {\r\n                    s.Write(data1, 0, data1.Length);\r\n                    s.Write(data2, 0, data2.Length);\r\n                }\r\n            };\r\n            var fakeContext = new NancyContext {Response = fakeResponse};\r\n            this.SetupFakeNancyCompleteCallback(fakeContext);\r\n\r\n            // When\r\n            this.host.Invoke(this.environment);\r\n\r\n            var data = ((MemoryStream)this.environment[\"owin.ResponseBody\"]).ToArray();\r\n\r\n            // Then\r\n            data.ShouldEqualSequence(data1.Concat(data2));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_dispose_context_on_completion_of_body_delegate()\r\n        {\r\n            // Given\r\n            var data1 = Encoding.ASCII.GetBytes(\"Some content\");\r\n            var fakeResponse = new Response {StatusCode = HttpStatusCode.OK, Contents = s => s.Write(data1, 0, data1.Length)};\r\n            var fakeContext = new NancyContext {Response = fakeResponse};\r\n            var mockDisposable = A.Fake<IDisposable>();\r\n            fakeContext.Items.Add(\"Test\", mockDisposable);\r\n            this.SetupFakeNancyCompleteCallback(fakeContext);\r\n\r\n            // When\r\n            this.host.Invoke(environment);\r\n\r\n            // Then\r\n            A.CallTo(() => mockDisposable.Dispose()).MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_cookie_with_valid_header()\r\n        {\r\n            // Given\r\n            var fakeResponse = new Response {StatusCode = HttpStatusCode.OK};\r\n            fakeResponse.WithCookie(\"test\", \"testvalue\");\r\n            fakeResponse.WithCookie(\"test1\", \"testvalue1\");\r\n            var fakeContext = new NancyContext {Response = fakeResponse};\r\n\r\n            this.SetupFakeNancyCompleteCallback(fakeContext);\r\n\r\n            // When\r\n            this.host.Invoke(this.environment).Wait();\r\n            var respHeaders = Get<IDictionary<string, string[]>>(this.environment, \"owin.ResponseHeaders\");\r\n\r\n            // Then\r\n            respHeaders.ContainsKey(\"Set-Cookie\").ShouldBeTrue();\r\n            (respHeaders[\"Set-Cookie\"][0] == \"test=testvalue; path=/\").ShouldBeTrue();\r\n            (respHeaders[\"Set-Cookie\"][1] == \"test1=testvalue1; path=/\").ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_append_setcookie_headers()\r\n        {\r\n            //Given\r\n            var respHeaders = Get<IDictionary<string, string[]>>(this.environment, \"owin.ResponseHeaders\");\r\n            const string middlewareSetCookie = \"other=othervalue; path=/\";\r\n            respHeaders.Add(\"Set-Cookie\", new[] { middlewareSetCookie });\r\n\r\n            var fakeResponse = new Response { StatusCode = HttpStatusCode.OK };\r\n            fakeResponse.WithCookie(\"test\", \"testvalue\");\r\n            var fakeContext = new NancyContext { Response = fakeResponse };\r\n\r\n            this.SetupFakeNancyCompleteCallback(fakeContext);\r\n\r\n            //When\r\n            this.host.Invoke(this.environment).Wait();\r\n\r\n            //Then\r\n            respHeaders[\"Set-Cookie\"].Length.ShouldEqual(2);\r\n            (respHeaders[\"Set-Cookie\"][0] == middlewareSetCookie).ShouldBeTrue();\r\n            (respHeaders[\"Set-Cookie\"][1] == \"test=testvalue; path=/\").ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_flow_katana_user()\r\n        {\r\n            // Given\r\n            IPrincipal user = new ClaimsPrincipal(new GenericIdentity(\"testuser\"));\r\n            this.environment.Add(\"server.User\", user);\r\n\r\n            var fakeResponse = new Response { StatusCode = HttpStatusCode.OK, Contents = s => { } };\r\n            var fakeContext = new NancyContext { Response = fakeResponse };\r\n            this.SetupFakeNancyCompleteCallback(fakeContext);\r\n\r\n            // When\r\n            await this.host.Invoke(this.environment);\r\n\r\n            // Then\r\n            fakeContext.CurrentUser.ShouldEqual(user);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_flow_owin_user()\r\n        {\r\n            // Given\r\n            var user = new ClaimsPrincipal(new GenericIdentity(\"testuser\"));\r\n            this.environment.Add(\"owin.RequestUser\", user);\r\n\r\n            var fakeResponse = new Response { StatusCode = HttpStatusCode.OK, Contents = s => { } };\r\n            var fakeContext = new NancyContext { Response = fakeResponse };\r\n            this.SetupFakeNancyCompleteCallback(fakeContext);\r\n\r\n            // When\r\n            await this.host.Invoke(this.environment);\r\n\r\n            // Then\r\n            fakeContext.CurrentUser.ShouldEqual(user);\r\n        }\r\n\r\n        /// <summary>\r\n        /// Sets the fake nancy engine to execute the complete callback with the given context\r\n        /// </summary>\r\n        /// <param name=\"context\">Context to return</param>\r\n        private void SetupFakeNancyCompleteCallback(NancyContext context)\r\n        {\r\n            A.CallTo(() => this.fakeEngine.HandleRequest(\r\n                A<Request>.Ignored,\r\n                A<Func<NancyContext, NancyContext>>.Ignored,\r\n                A<CancellationToken>.Ignored))\r\n             .Invokes((Request _, Func<NancyContext, NancyContext> preRequest, CancellationToken __) => preRequest(context))\r\n             .Returns(Task.FromResult(context));\r\n        }\r\n\r\n        private static T Get<T>(IDictionary<string, object> env, string key)\r\n        {\r\n            object value;\r\n            return env.TryGetValue(key, out value) && value is T ? (T)value : default(T);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/NancyModuleFixture.cs",
    "content": "namespace Nancy.Tests.Unit\r\n{\r\n    using System;\r\n    using System.Linq;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Tests.Fakes;\r\n    using Xunit;\r\n\r\n    public class NancyModuleFixture\r\n    {\r\n        private readonly NancyModule module;\r\n\r\n        public NancyModuleFixture()\r\n        {\r\n            this.module = new FakeNancyModuleNoRoutes();\r\n        }\r\n\r\n        [Fact]\r\n        public void Adds_route_when_get_indexer_used()\r\n        {\r\n            // Given, When\r\n            this.module.Get<object>(\"/test\", (_, __) => null);\r\n\r\n            // Then\r\n            this.module.Routes.Count().ShouldEqual(1);\r\n        }\r\n\r\n        [Fact]\r\n        public void Adds_route_when_put_indexer_used()\r\n        {\r\n            // Given, When\r\n            this.module.Put<object>(\"/test\", (_, __) => null);\r\n\r\n            // Then\r\n            this.module.Routes.Count().ShouldEqual(1);\r\n        }\r\n\r\n        [Fact]\r\n        public void Adds_route_when_post_indexer_used()\r\n        {\r\n            // Given, When\r\n            this.module.Post<object>(\"/test\", (_, __) => null);\r\n\r\n            // Then\r\n            this.module.Routes.Count().ShouldEqual(1);\r\n        }\r\n\r\n        [Fact]\r\n        public void Adds_route_when_delete_indexer_used()\r\n        {\r\n            // Given, When\r\n            this.module.Delete<object>(\"/test\", (_, __) => null);\r\n\r\n            // Then\r\n            this.module.Routes.Count().ShouldEqual(1);\r\n        }\r\n\r\n        [Fact]\r\n        public void Adds_route_when_options_indexer_userd()\r\n        {\r\n            // Given, When\r\n            this.module.Options<object>(\"/test\", (_, __) => null);\r\n\r\n            // Then\r\n            this.module.Routes.Count().ShouldEqual(1);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_store_route_with_specified_path_when_route_indexer_is_invoked_with_a_path_but_no_condition()\r\n        {\r\n            // Given, When\r\n            this.module.Get<object>(\"/test\", (_, __) => null);\r\n\r\n            // Then\r\n            module.Routes.First().Description.Path.ShouldEqual(\"/test\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_store_route_with_specified_path_when_route_indexer_is_invoked_with_a_path_and_condition()\r\n        {\r\n            // Given\r\n            Func<NancyContext, bool> condition = r => true;\r\n\r\n            // When\r\n            this.module.Get<object>(\"/test\",\r\n                condition: condition,\r\n                action: (_, __) => null);\r\n\r\n            // Then\r\n            module.Routes.First().Description.Path.ShouldEqual(\"/test\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_store_route_with_null_condition_when_route_indexer_is_invoked_without_a_condition()\r\n        {\r\n            // Given, When\r\n            this.module.Get<object>(\"/test\", (_, __) => null);\r\n\r\n            // Then\r\n            module.Routes.First().Description.Condition.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_store_route_with_condition_when_route_indexer_is_invoked_with_a_condition()\r\n        {\r\n            // Given\r\n            Func<NancyContext, bool> condition = r => true;\r\n\r\n            // When\r\n            this.module.Get<object>(\"/test\",\r\n                condition: condition,\r\n                action: (_, __) => null);\r\n\r\n            // Then\r\n            module.Routes.First().Description.Condition.ShouldBeSameAs(condition);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_route_with_get_method_when_added_using_get_indexer()\r\n        {\r\n            // Given, When\r\n            this.module.Get<object>(\"/test\", (_, __) => null);\r\n\r\n            // Then\r\n            module.Routes.First().Description.Method.ShouldEqual(\"GET\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_route_with_put_method_when_added_using_get_indexer()\r\n        {\r\n            // Given, When\r\n            this.module.Put<object>(\"/test\", (_, __) => null);\r\n\r\n            // Then\r\n            module.Routes.First().Description.Method.ShouldEqual(\"PUT\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_route_with_post_method_when_added_using_get_indexer()\r\n        {\r\n            // Given, When\r\n            this.module.Post<object>(\"/test\", (_, __) => null);\r\n\r\n            // Then\r\n            module.Routes.First().Description.Method.ShouldEqual(\"POST\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_route_with_delete_method_when_added_using_get_indexer()\r\n        {\r\n            // Given, When\r\n            this.module.Delete<object>(\"/test\", (_, __) => null);\r\n\r\n            // Then\r\n            module.Routes.First().Description.Method.ShouldEqual(\"DELETE\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_store_route_combine_with_base_path_if_one_specified()\r\n        {\r\n            // Given\r\n            var moduleWithBasePath = new FakeNancyModuleWithBasePath();\r\n\r\n            // When\r\n            moduleWithBasePath.Get(\"/NewRoute\", args => Task.FromResult<object>(null));\r\n\r\n            // Then\r\n            moduleWithBasePath.Routes.Last().Description.Path.ShouldEqual(\"/fake/NewRoute\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_leading_slash_to_route_if_missing()\r\n        {\r\n            // Given\r\n            var moduleWithBasePath = new FakeNancyModuleWithBasePath();\r\n\r\n            // When\r\n            moduleWithBasePath.Get<object>(\"/test\", (_, __) => null);\r\n\r\n            // Then\r\n            moduleWithBasePath.Routes.Last().Description.Path.ShouldEqual(\"/fake/test\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_store_single_route_when_calling_non_overridden_post_from_sub_module()\r\n        {\r\n            // Given\r\n            var moduleWithBasePath = new CustomNancyModule();\r\n\r\n            // When\r\n            moduleWithBasePath.Post<object>(\"/Test1\", (_, __) => null);\r\n\r\n            // Then\r\n            moduleWithBasePath.Routes.Last().Description.Path.ShouldEqual(\"/Test1\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_throw_when_null_passed_as_modulepath()\r\n        {\r\n            // Given\r\n            var moduleWithNullPath = new CustomModulePathModule(null);\r\n\r\n            // When\r\n            moduleWithNullPath.Post<object>(\"/Test1\", (_, __) => null);\r\n\r\n            // Then\r\n            moduleWithNullPath.Routes.Count().ShouldBeGreaterThan(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Adds_named_route_when_named_indexer_used()\r\n        {\r\n            // Given, When\r\n            this.module.Get<object>(\"/test\",\r\n                name: \"Foo\",\r\n                action: (_, __) => null);\r\n\r\n            // Then\r\n            this.module.Routes.Count().ShouldEqual(1);\r\n            this.module.Routes.First().Description.Name.ShouldEqual(\"Foo\");\r\n        }\r\n\r\n        private class CustomModulePathModule : NancyModule\r\n        {\r\n            public CustomModulePathModule(string modulePath)\r\n                : base(modulePath)\r\n            {\r\n            }\r\n        }\r\n\r\n        private class CustomNancyModule : NancyModule\r\n        {\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/NancyOptionsExtensionsFixture.cs",
    "content": "namespace Nancy.Tests.Unit\r\n{\r\n    using Nancy.Owin;\r\n\r\n    using Xunit;\r\n\r\n    public class NancyOptionsExtensionsFixture\r\n    {\r\n        [Fact]\r\n        public void When_response_status_code_match_then_should_perform_pass_through()\r\n        {\r\n            // Given\r\n            var options = new NancyOptions();\r\n            options.PassThroughWhenStatusCodesAre(HttpStatusCode.NotFound);\r\n            var nancyContext = new NancyContext { Response = new Response {StatusCode = HttpStatusCode.NotFound} };\r\n\r\n            // When\r\n            bool passedThrough = options.PerformPassThrough(nancyContext);\r\n\r\n            // Then\r\n            passedThrough.ShouldBeTrue();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/NancyOptionsFixture.cs",
    "content": "namespace Nancy.Tests.Unit\r\n{\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Owin;\r\n\r\n    using Xunit;\r\n\r\n    public class NancyOptionsFixture\r\n    {\r\n        private readonly NancyOptions nancyOptions;\r\n\r\n        public NancyOptionsFixture()\r\n        {\r\n            this.nancyOptions = new NancyOptions();\r\n        }\r\n\r\n        [Fact]\r\n        public void Bootstrapper_should_use_locator_if_not_specified()\r\n        {\r\n            // Given\r\n            var bootstrapper = new DefaultNancyBootstrapper();\r\n            NancyBootstrapperLocator.Bootstrapper = bootstrapper;\r\n\r\n            //When\r\n            //Then\r\n            this.nancyOptions.Bootstrapper.ShouldNotBeNull();\r\n            this.nancyOptions.Bootstrapper.ShouldBeSameAs(bootstrapper);\r\n        }\r\n\r\n        [Fact]\r\n        public void Bootstrapper_should_use_chosen_bootstrapper_if_specified()\r\n        {\r\n            // Given\r\n            var bootstrapper = new DefaultNancyBootstrapper();\r\n            var specificBootstrapper = new DefaultNancyBootstrapper();\r\n            NancyBootstrapperLocator.Bootstrapper = bootstrapper;\r\n\r\n            //When\r\n            this.nancyOptions.Bootstrapper = specificBootstrapper;\r\n\r\n            //Then\r\n            this.nancyOptions.Bootstrapper.ShouldNotBeNull();\r\n            this.nancyOptions.Bootstrapper.ShouldBeSameAs(specificBootstrapper);\r\n        }\r\n\r\n        [Fact]\r\n        public void PerformPassThrough_should_not_be_null()\r\n        {\r\n            this.nancyOptions.PerformPassThrough.ShouldNotBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void PerformPassThrough_delegate_should_return_false()\r\n        {\r\n            this.nancyOptions.PerformPassThrough(new NancyContext()).ShouldBeFalse();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/RequestFixture.cs",
    "content": "namespace Nancy.Tests.Unit\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Text;\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n    using FakeItEasy;\r\n    using Nancy.Helpers;\r\n    using Nancy.IO;\r\n    using Xunit;\r\n    using Xunit.Extensions;\r\n\r\n    public class RequestFixture\r\n    {\r\n        [Fact]\r\n        public void Should_dispose_request_stream_when_being_disposed()\r\n        {\r\n            // Given\r\n            var stream = A.Fake<RequestStream>(x =>\r\n            {\r\n                x.Implements(typeof(IDisposable));\r\n                x.WithArgumentsForConstructor(() => new RequestStream(0, false));\r\n            });\r\n\r\n            var url = new Url()\r\n            {\r\n                Scheme = \"http\",\r\n                Path = \"localhost\"\r\n            };\r\n\r\n            var request = new Request(\"GET\", url, stream);\r\n\r\n            // When\r\n            request.Dispose();\r\n\r\n            // Then\r\n            A.CallTo(() => ((IDisposable)stream).Dispose()).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_disposable()\r\n        {\r\n            // Given, When, Then\r\n            typeof(Request).ShouldImplementInterface<IDisposable>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_override_request_method_on_post()\r\n        {\r\n            // Given\r\n            const string bodyContent = \"_method=GET\";\r\n            var memory = CreateRequestStream();\r\n            var writer = new StreamWriter(memory);\r\n            writer.Write(bodyContent);\r\n            writer.Flush();\r\n            memory.Position = 0;\r\n\r\n            var headers =\r\n                new Dictionary<string, IEnumerable<string>> { { \"content-type\", new[] { \"application/x-www-form-urlencoded\" } } };\r\n\r\n            // When\r\n            var request = new Request(\"POST\", new Url { Path = \"/\", Scheme = \"http\" }, memory, headers);\r\n\r\n            // Then\r\n            request.Method.ShouldEqual(\"GET\");\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"GET\")]\r\n        [InlineData(\"PUT\")]\r\n        [InlineData(\"DELETE\")]\r\n        [InlineData(\"HEAD\")]\r\n        public void Should_only_override_method_on_post(string method)\r\n        {\r\n            // Given\r\n            const string bodyContent = \"_method=TEST\";\r\n            var memory = CreateRequestStream();\r\n            var writer = new StreamWriter(memory);\r\n            writer.Write(bodyContent);\r\n            writer.Flush();\r\n            memory.Position = 0;\r\n\r\n            var headers =\r\n                new Dictionary<string, IEnumerable<string>> { { \"content-type\", new[] { \"application/x-www-form-urlencoded\" } } };\r\n\r\n            // When\r\n            var request = new Request(method, new Url { Path = \"/\", Scheme = \"http\" }, memory, headers);\r\n\r\n            // Then\r\n            request.Method.ShouldEqual(method);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_argumentoutofrangeexception_when_initialized_with_null_method()\r\n        {\r\n            // Given, When\r\n            var exception =\r\n                Record.Exception(() => new Request(null, \"/\", \"http\"));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ArgumentOutOfRangeException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_argumentoutofrangeexception_when_initialized_with_empty_method()\r\n        {\r\n            // Given, When\r\n            var exception =\r\n                Record.Exception(() => new Request(string.Empty, \"/\", \"http\"));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ArgumentOutOfRangeException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_null_exception_when_initialized_with_null_uri()\r\n        {\r\n            // Given, When\r\n            var exception =\r\n                Record.Exception(() => new Request(\"GET\", null, \"http\"));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ArgumentNullException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_method_parameter_value_to_method_property_when_initialized()\r\n        {\r\n            // Given\r\n            const string method = \"GET\";\r\n\r\n            // When\r\n            var request = new Request(method, \"/\", \"http\");\r\n\r\n            // Then\r\n            request.Method.ShouldEqual(method);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_uri_parameter_value_to_uri_property_when_initialized()\r\n        {\r\n            // Given\r\n            const string path = \"/\";\r\n\r\n            // When\r\n            var request = new Request(\"GET\", path, \"http\");\r\n\r\n            // Then\r\n            request.Path.ShouldEqual(path);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_header_parameter_value_to_header_property_when_initialized()\r\n        {\r\n            // Given\r\n            var headers = new Dictionary<string, IEnumerable<string>>()\r\n                {\r\n                    { \"content-type\", new[] {\"foo/bar\"} }\r\n                };\r\n\r\n            // When\r\n            var request = new Request(\"GET\", new Url { Path = \"/\", Scheme = \"http\" }, CreateRequestStream(), headers);\r\n\r\n            // Then\r\n            request.Headers.ContentType.ShouldNotBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_body_parameter_value_to_body_property_when_initialized()\r\n        {\r\n            // Given\r\n            var body = CreateRequestStream();\r\n\r\n            // When\r\n            var request = new Request(\"GET\", new Url { Path = \"/\", Scheme = \"http\" }, body, new Dictionary<string, IEnumerable<string>>());\r\n\r\n            // Then\r\n            request.Body.ShouldBeSameAs(body);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_extract_form_data_from_body_when_content_type_is_x_www_form_urlencoded()\r\n        {\r\n            // Given\r\n            const string bodyContent = \"name=John+Doe&gender=male&family=5&city=kent&city=miami&other=abc%0D%0Adef&nickname=J%26D\";\r\n            var memory = CreateRequestStream();\r\n            var writer = new StreamWriter(memory);\r\n            writer.Write(bodyContent);\r\n            writer.Flush();\r\n            memory.Position = 0;\r\n\r\n            var headers =\r\n                new Dictionary<string, IEnumerable<string>>\r\n                {\r\n                    { \"content-type\", new[] { \"application/x-www-form-urlencoded\" } }\r\n                };\r\n\r\n            // When\r\n            var request = new Request(\"POST\", new Url { Path = \"/\", Scheme = \"http\" }, memory, headers);\r\n\r\n            // Then\r\n            ((string)request.Form.name).ShouldEqual(\"John Doe\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_extract_form_data_from_body_when_content_type_is_x_www_form_urlencoded_with_character_set()\r\n        {\r\n            // Given\r\n            const string bodyContent = \"name=John+Doe&gender=male&family=5&city=kent&city=miami&other=abc%0D%0Adef&nickname=J%26D\";\r\n            var memory = CreateRequestStream();\r\n            var writer = new StreamWriter(memory);\r\n            writer.Write(bodyContent);\r\n            writer.Flush();\r\n            memory.Position = 0;\r\n\r\n            var headers =\r\n                new Dictionary<string, IEnumerable<string>>\r\n                {\r\n                    { \"content-type\", new[] { \"application/x-www-form-urlencoded; charset=UTF-8\" } }\r\n                };\r\n\r\n            // When\r\n            var request = new Request(\"POST\", new Url { Path = \"/\", Scheme = \"http\" }, memory, headers);\r\n\r\n            // Then\r\n            ((string)request.Form.name).ShouldEqual(\"John Doe\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_extracted_form_data_from_body_when_content_type_is_multipart_form_data()\r\n        {\r\n            // Given\r\n            var memory =\r\n                new MemoryStream(BuildMultipartFormValues(new Dictionary<string, string>\r\n                {\r\n                    { \"name\", \"John Doe\"},\r\n                    { \"age\", \"42\"}\r\n                }));\r\n\r\n            var headers =\r\n                new Dictionary<string, IEnumerable<string>>\r\n                {\r\n                    { \"content-type\", new[] { \"multipart/form-data; boundary=----NancyFormBoundary\" } }\r\n                };\r\n\r\n            // When\r\n            var request = new Request(\"POST\", new Url { Path = \"/\", Scheme = \"http\" }, CreateRequestStream(memory), headers);\r\n\r\n            // Then\r\n            ((string)request.Form.name).ShouldEqual(\"John Doe\");\r\n            ((string)request.Form.age).ShouldEqual(\"42\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_respect_case_insensitivity_when_extracting_form_data_from_body_when_content_type_is_x_www_form_urlencoded()\r\n        {\r\n            // Given\r\n            StaticConfiguration.CaseSensitive = false;\r\n            const string bodyContent = \"key=value&key=value&KEY=VALUE\";\r\n            var memory = CreateRequestStream();\r\n            var writer = new StreamWriter(memory);\r\n            writer.Write(bodyContent);\r\n            writer.Flush();\r\n            memory.Position = 0;\r\n\r\n            var headers =\r\n                new Dictionary<string, IEnumerable<string>>\r\n                {\r\n                    { \"content-type\", new[] { \"application/x-www-form-urlencoded\" } }\r\n                };\r\n\r\n            // When\r\n            var request = new Request(\"POST\", new Url { Path = \"/\", Scheme = \"http\" }, memory, headers);\r\n\r\n            // Then\r\n            ((string)request.Form.key).ShouldEqual(\"value,value,VALUE\");\r\n            ((string)request.Form.KEY).ShouldEqual(\"value,value,VALUE\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_respect_case_sensitivity_when_extracting_form_data_from_body_when_content_type_is_x_www_form_urlencoded()\r\n        {\r\n            // Given\r\n            StaticConfiguration.CaseSensitive = true;\r\n            const string bodyContent = \"key=value&key=value&KEY=VALUE\";\r\n            var memory = CreateRequestStream();\r\n            var writer = new StreamWriter(memory);\r\n            writer.Write(bodyContent);\r\n            writer.Flush();\r\n            memory.Position = 0;\r\n\r\n            var headers =\r\n                new Dictionary<string, IEnumerable<string>>\r\n                {\r\n                    { \"content-type\", new[] { \"application/x-www-form-urlencoded\" } }\r\n                };\r\n\r\n            // When\r\n            var request = new Request(\"POST\", new Url { Path = \"/\", Scheme = \"http\" }, memory, headers);\r\n\r\n            // Then\r\n            ((string)request.Form.key).ShouldEqual(\"value,value\");\r\n            ((string)request.Form.KEY).ShouldEqual(\"VALUE\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_respect_case_insensitivity_when_extracting_form_data_from_body_when_content_type_is_multipart_form_data()\r\n        {\r\n            // Given\r\n            StaticConfiguration.CaseSensitive = false;\r\n            var memory =\r\n                new MemoryStream(BuildMultipartFormValues(new Dictionary<string, string>(StringComparer.Ordinal)\r\n                {\r\n                    { \"key\", \"value\" },\r\n                    { \"KEY\", \"VALUE\" }\r\n                }));\r\n\r\n            var headers =\r\n                new Dictionary<string, IEnumerable<string>>\r\n                {\r\n                    { \"content-type\", new[] { \"multipart/form-data; boundary=----NancyFormBoundary\" } }\r\n                };\r\n\r\n            // When\r\n            var request = new Request(\"POST\", new Url { Path = \"/\", Scheme = \"http\" }, CreateRequestStream(memory), headers);\r\n\r\n            // Then\r\n            ((string)request.Form.key).ShouldEqual(\"value,VALUE\");\r\n            ((string)request.Form.KEY).ShouldEqual(\"value,VALUE\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_respect_case_sensitivity_when_extracting_form_data_from_body_when_content_type_is_multipart_form_data()\r\n        {\r\n            // Given\r\n            StaticConfiguration.CaseSensitive = true;\r\n            var memory =\r\n                new MemoryStream(BuildMultipartFormValues(new Dictionary<string, string>(StringComparer.Ordinal)\r\n                {\r\n                    { \"key\", \"value\" },\r\n                    { \"KEY\", \"VALUE\" }\r\n                }));\r\n\r\n            var headers =\r\n                new Dictionary<string, IEnumerable<string>>\r\n                {\r\n                    { \"content-type\", new[] { \"multipart/form-data; boundary=----NancyFormBoundary\" } }\r\n                };\r\n\r\n            // When\r\n            var request = new Request(\"POST\", new Url { Path = \"/\", Scheme = \"http\" }, CreateRequestStream(memory), headers);\r\n\r\n            // Then\r\n            ((string)request.Form.key).ShouldEqual(\"value\");\r\n            ((string)request.Form.KEY).ShouldEqual(\"VALUE\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_extracted_files_to_files_collection_when_body_content_type_is_multipart_form_data()\r\n        {\r\n            // Given\r\n            var memory =\r\n                new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>>\r\n                {\r\n                    { \"test\", new Tuple<string, string, string>(\"content/type\", \"some test content\", \"whatever\")}\r\n                }));\r\n\r\n            var headers =\r\n                new Dictionary<string, IEnumerable<string>>\r\n                {\r\n                    { \"content-type\", new[] { \"multipart/form-data; boundary=----NancyFormBoundary\" } }\r\n                };\r\n\r\n            // When\r\n            var request = new Request(\"POST\", new Url { Path = \"/\", Scheme = \"http\" }, CreateRequestStream(memory), headers);\r\n\r\n            // Then\r\n            request.Files.ShouldHaveCount(1);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_content_type_on_file_extracted_from_multipart_form_data_body()\r\n        {\r\n            // Given\r\n            var memory =\r\n                new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>>\r\n                {\r\n                    { \"sample.txt\", new Tuple<string, string, string>(\"content/type\", \"some test content\", \"whatever\")}\r\n                }));\r\n\r\n            var headers =\r\n                new Dictionary<string, IEnumerable<string>>\r\n                {\r\n                    { \"content-type\", new[] { \"multipart/form-data; boundary=----NancyFormBoundary\" } }\r\n                };\r\n\r\n            // When\r\n            var request = new Request(\"POST\", new Url { Path = \"/\", Scheme = \"http\" }, CreateRequestStream(memory), headers);\r\n\r\n            // Then\r\n            request.Files.First().ContentType.ShouldEqual(\"content/type\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_name_on_file_extracted_from_multipart_form_data_body()\r\n        {\r\n            // Given\r\n            var memory =\r\n                new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>>\r\n                {\r\n                    { \"sample.txt\", new Tuple<string, string, string>(\"content/type\", \"some test content\", \"whatever\")}\r\n                }));\r\n\r\n            var headers =\r\n                new Dictionary<string, IEnumerable<string>>\r\n                {\r\n                    { \"content-type\", new[] { \"multipart/form-data; boundary=----NancyFormBoundary\" } }\r\n                };\r\n\r\n            // When\r\n            var request = new Request(\"POST\", new Url { Path = \"/\", Scheme = \"http\" }, CreateRequestStream(memory), headers);\r\n\r\n            // Then\r\n            request.Files.First().Name.ShouldEqual(\"sample.txt\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_value_on_file_extracted_from_multipart_form_data_body()\r\n        {\r\n            // Given\r\n            var memory =\r\n                new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>>\r\n                {\r\n                    { \"sample.txt\", new Tuple<string, string, string>(\"content/type\", \"some test content\", \"whatever\")}\r\n                }));\r\n\r\n            var headers =\r\n                new Dictionary<string, IEnumerable<string>>\r\n                {\r\n                    { \"content-type\", new[] { \"multipart/form-data; boundary=----NancyFormBoundary\" } }\r\n                };\r\n\r\n            // When\r\n            var request = new Request(\"POST\", new Url { Path = \"/\", Scheme = \"http\" }, CreateRequestStream(memory), headers);\r\n\r\n            // Then\r\n            GetStringValue(request.Files.First().Value).ShouldEqual(\"some test content\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_key_on_file_extracted_from_multipart_data_body()\r\n        {\r\n            // Given\r\n            var memory =\r\n                new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>>\r\n                {\r\n                    { \"sample.txt\", new Tuple<string, string, string>(\"content/type\", \"some test content\", \"fieldname\")}\r\n                }));\r\n\r\n            var headers =\r\n                new Dictionary<string, IEnumerable<string>>\r\n                {\r\n                    { \"content-type\", new[] { \"multipart/form-data; boundary=----NancyFormBoundary\" } }\r\n                };\r\n\r\n            // When\r\n            var request = new Request(\"POST\", new Url { Path = \"/\", Scheme = \"http\" }, CreateRequestStream(memory), headers);\r\n\r\n            // Then\r\n            request.Files.First().Key.ShouldEqual(\"fieldname\");\r\n        }\r\n\r\n        private static string GetStringValue(Stream stream)\r\n        {\r\n            var reader = new StreamReader(stream);\r\n            return reader.ReadToEnd();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_invoke_form_repeatedly()\r\n        {\r\n            const string bodyContent = \"name=John+Doe&gender=male&family=5&city=kent&city=miami&other=abc%0D%0Adef&nickname=J%26D\";\r\n            var memory = new MemoryStream();\r\n            var writer = new StreamWriter(memory);\r\n            writer.Write(bodyContent);\r\n            writer.Flush();\r\n            memory.Position = 0;\r\n\r\n            var headers =\r\n                new Dictionary<string, IEnumerable<string>>\r\n                {\r\n                    { \"content-type\", new[] { \"application/x-www-form-urlencoded\" } }\r\n                };\r\n\r\n            // When\r\n            var request = new Request(\"POST\", new Url { Path = \"/\", Scheme = \"http\" }, CreateRequestStream(memory), headers);\r\n\r\n            // Then\r\n            ((string)request.Form.name).ShouldEqual(\"John Doe\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_argumentoutofrangeexception_when_initialized_with_null_protocol()\r\n        {\r\n            // Given, When\r\n            var exception =\r\n                Record.Exception(() => new Request(\"GET\", \"/\", null));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ArgumentOutOfRangeException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_argumentoutofrangeexception_when_initialized_with_an_empty_protocol()\r\n        {\r\n            // Given, When\r\n            var exception =\r\n                Record.Exception(() => new Request(\"GET\", \"/\", string.Empty));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ArgumentOutOfRangeException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_protocol_parameter_value_to_protocol_property_when_initialized()\r\n        {\r\n            // Given\r\n            const string protocol = \"http\";\r\n\r\n            // When\r\n            var request = new Request(\"GET\", \"/\", protocol);\r\n\r\n            // Then\r\n            request.Url.Scheme.ShouldEqual(protocol);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_split_cookie_in_two_parts_only()\r\n        {\r\n            // Given, when\r\n            var cookieName = \"_nc\";\r\n            var cookieData = \"Y+M3rcC/7ssXvHTx9pwCbwQVV4g=sp0hUZVApYgGbKZIU4bvXbBCVl9fhSEssEXSGdrt4jVag6PO1oed8lSd+EJD1nzWx4OTTCTZKjYRWeHE97QVND4jJIl+DuKRgJnSl3hWI5gdgGjcxqCSTvMOMGmW3NHLVyKpajGD8tq1DXhXMyXHjTzrCAYl8TGzwyJJGx/gd7VMJeRbAy9JdHOxEUlCKUnPneWN6q+/ITFryAa5hAdfcjXmh4Fgym75whKOMkWO+yM2icdsciX0ShcvnEQ/bXcTHTya6d7dJVfZl7qQ8AgIQv8ucQHxD3NxIvHNPBwms2ClaPds0HG5N+7pu7eMSFZjUHpDrrCnFvYN+JDiG3GMpf98LuCCvxemvipJo2MUkY4J1LvaDFoWA5tIxAfItZJkSIW2d8JPDwFk8OHJy8zhyn8AjD2JFqWaUZr4y9KZOtgI0V0Qlq0mS3mDSlLn29xapgoPHBvykwQjR6TwF2pBLpStsfZa/tXbEv2mc3VO3CnErIA1lEfKNqn9C/Dw6hqW\";\r\n            var headers = new Dictionary<string, IEnumerable<string>>();\r\n            var cookies = new List<string>();\r\n            cookies.Add(string.Format(\"{0}={1}\", cookieName, HttpUtility.UrlEncode(cookieData)));\r\n            headers.Add(\"cookie\", cookies);\r\n            var newUrl = new Url\r\n            {\r\n                Path = \"/\"\r\n            };\r\n            var request = new Request(\"GET\", newUrl, null, headers);\r\n\r\n            // Then\r\n            request.Cookies[cookieName].ShouldEqual(cookieData);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_split_cookie_in_two_parts_with_secure_attribute()\r\n        {\r\n            // Given, when\r\n            const string cookieName = \"path\";\r\n            const string cookieData = \"/\";\r\n            var headers = new Dictionary<string, IEnumerable<string>>();\r\n            var cookies = new List<string> { string.Format(\"{0}={1}; Secure\", cookieName, cookieData)} ;\r\n            headers.Add(\"cookie\", cookies);\r\n            var newUrl = new Url\r\n            {\r\n                Path = \"/\"\r\n            };\r\n            var request = new Request(\"GET\", newUrl, null, headers);\r\n\r\n            // Then\r\n            request.Cookies[cookieName].ShouldEqual(cookieData);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_split_cookie_in_two_parts_with_httponly_and_secure_attribute()\r\n        {\r\n            // Given, when\r\n            const string cookieName = \"path\";\r\n            const string cookieData = \"/\";\r\n            var headers = new Dictionary<string, IEnumerable<string>>();\r\n            var cookies = new List<string> { string.Format(\"{0}={1}; HttpOnly; Secure\", cookieName, cookieData) };\r\n            headers.Add(\"cookie\", cookies);\r\n            var newUrl = new Url\r\n            {\r\n                Path = \"/\"\r\n            };\r\n            var request = new Request(\"GET\", newUrl, null, headers);\r\n\r\n            // Then\r\n            request.Cookies[cookieName].ShouldEqual(cookieData);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_split_cookie_in_two_parts_with_httponly_and_secure_attribute_ignoring_case()\r\n        {\r\n            // Given, when\r\n            const string cookieName = \"path\";\r\n            const string cookieData = \"/\";\r\n            var headers = new Dictionary<string, IEnumerable<string>>();\r\n            var cookies = new List<string> { string.Format(\"{0}={1}; httponly; secure\", cookieName, cookieData) };\r\n            headers.Add(\"cookie\", cookies);\r\n            var newUrl = new Url\r\n            {\r\n                Path = \"/\"\r\n            };\r\n            var request = new Request(\"GET\", newUrl, null, headers);\r\n\r\n            // Then\r\n            request.Cookies[cookieName].ShouldEqual(cookieData);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_split_cookie_in_two_parts_with_httponly_attribute()\r\n        {\r\n            // Given, when\r\n            const string cookieName = \"path\";\r\n            const string cookieData = \"/\";\r\n            var headers = new Dictionary<string, IEnumerable<string>>();\r\n            var cookies = new List<string> { string.Format(\"{0}={1}; HttpOnly\", cookieName, cookieData) };\r\n            headers.Add(\"cookie\", cookies);\r\n            var newUrl = new Url\r\n            {\r\n                Path = \"/\"\r\n            };\r\n            var request = new Request(\"GET\", newUrl, null, headers);\r\n\r\n            // Then\r\n            request.Cookies[cookieName].ShouldEqual(cookieData);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_attribute_in_cookie_as_empty_value()\r\n        {\r\n          // Given, when\r\n          const string cookieName = \"path\";\r\n          const string cookieData = \"/\";\r\n          const string cookieAttribute = \"SomeAttribute\";\r\n          var headers = new Dictionary<string, IEnumerable<string>>();\r\n          var cookies = new List<string> { string.Format(\"{0}={1}; {2}\", cookieName, cookieData, cookieAttribute) };\r\n          headers.Add(\"cookie\", cookies);\r\n          var newUrl = new Url\r\n          {\r\n            Path = \"/\"\r\n          };\r\n          var request = new Request(\"GET\", newUrl, null, headers);\r\n\r\n          // Then\r\n          request.Cookies[cookieName].ShouldEqual(cookieData);\r\n          request.Cookies[cookieAttribute].ShouldEqual(string.Empty);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_move_request_body_position_to_zero_after_parsing_url_encoded_data()\r\n        {\r\n            // Given\r\n            const string bodyContent = \"name=John+Doe&gender=male&family=5&city=kent&city=miami&other=abc%0D%0Adef&nickname=J%26D\";\r\n            var memory = CreateRequestStream();\r\n            var writer = new StreamWriter(memory);\r\n            writer.Write(bodyContent);\r\n            writer.Flush();\r\n            memory.Position = 0;\r\n\r\n            var headers =\r\n                new Dictionary<string, IEnumerable<string>>\r\n                {\r\n                    { \"content-type\", new[] { \"application/x-www-form-urlencoded; charset=UTF-8\" } }\r\n                };\r\n\r\n            // When\r\n            var request = new Request(\"POST\", new Url { Path = \"/\", Scheme = \"http\" }, memory, headers);\r\n\r\n            // Then\r\n            memory.Position.ShouldEqual(0L);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_move_request_body_position_to_zero_after_parsing_multipart_encoded_data()\r\n        {\r\n            // Given\r\n            var memory =\r\n                new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>>\r\n                {\r\n                    { \"sample.txt\", new Tuple<string, string, string>(\"content/type\", \"some test content\", \"whatever\")}\r\n                }));\r\n\r\n            var headers =\r\n                new Dictionary<string, IEnumerable<string>>\r\n                {\r\n                    { \"content-type\", new[] { \"multipart/form-data; boundary=----NancyFormBoundary\" } }\r\n                };\r\n\r\n            // When\r\n            var request = new Request(\"POST\", new Url { Path = \"/\", Scheme = \"http\" }, CreateRequestStream(memory), headers);\r\n\r\n            // Then\r\n            memory.Position.ShouldEqual(0L);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_preserve_all_values_when_multiple_are_posted_using_same_name_after_parsing_multipart_encoded_data()\r\n        {\r\n            // Given\r\n            var memory =\r\n                new MemoryStream(BuildMultipartFormValues(\r\n                    new KeyValuePair<string, string>(\"age\", \"32\"),\r\n                    new KeyValuePair<string, string>(\"age\", \"42\"),\r\n                    new KeyValuePair<string, string>(\"age\", \"52\")\r\n                ));\r\n\r\n            var headers =\r\n                new Dictionary<string, IEnumerable<string>>\r\n                {\r\n                    { \"content-type\", new[] { \"multipart/form-data; boundary=----NancyFormBoundary\" } }\r\n                };\r\n\r\n            // When\r\n            var request = new Request(\"POST\", new Url { Path = \"/\", Scheme = \"http\" }, CreateRequestStream(memory), headers);\r\n\r\n            // Then\r\n            ((string)request.Form.age).ShouldEqual(\"32,42,52\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_limit_the_amount_of_form_fields_parsed()\r\n        {\r\n            // Given\r\n            var sb = new StringBuilder();\r\n            for (int i = 0; i < StaticConfiguration.RequestQueryFormMultipartLimit + 10; i++)\r\n            {\r\n                if (i > 0)\r\n                {\r\n                    sb.Append('&');\r\n                }\r\n\r\n                sb.AppendFormat(\"Field{0}=Value{0}\", i);\r\n            }\r\n            var memory = CreateRequestStream();\r\n            var writer = new StreamWriter(memory);\r\n            writer.Write(sb.ToString());\r\n            writer.Flush();\r\n            memory.Position = 0;\r\n\r\n            var headers =\r\n                new Dictionary<string, IEnumerable<string>>\r\n                {\r\n                    { \"content-type\", new[] { \"application/x-www-form-urlencoded\" } }\r\n                };\r\n\r\n            // When\r\n            var request = new Request(\"POST\", new Url { Path = \"/\", Scheme = \"http\" }, memory, headers);\r\n\r\n            // Then\r\n            ((IEnumerable<string>)request.Form.GetDynamicMemberNames()).Count().ShouldEqual(StaticConfiguration.RequestQueryFormMultipartLimit);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_limit_the_amount_of_querystring_fields_parsed()\r\n        {\r\n            // Given\r\n            var sb = new StringBuilder();\r\n            for (int i = 0; i < StaticConfiguration.RequestQueryFormMultipartLimit + 10; i++)\r\n            {\r\n                if (i > 0)\r\n                {\r\n                    sb.Append('&');\r\n                }\r\n\r\n                sb.AppendFormat(\"Field{0}=Value{0}\", i);\r\n            }\r\n            var memory = CreateRequestStream();\r\n\r\n            // When\r\n            var request = new Request(\"GET\", new Url { Path = \"/\", Scheme = \"http\", Query = sb.ToString() }, memory, new Dictionary<string, IEnumerable<string>>());\r\n\r\n            // Then\r\n            ((IEnumerable<string>)request.Query.GetDynamicMemberNames()).Count().ShouldEqual(StaticConfiguration.RequestQueryFormMultipartLimit);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_change_empty_path_to_root()\r\n        {\r\n            var request = new Request(\"GET\", \"\", \"http\");\r\n\r\n            request.Path.ShouldEqual(\"/\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_replace_value_of_query_key_without_value_with_true()\r\n        {\r\n            // Given\r\n            var memory = CreateRequestStream();\r\n\r\n            // When\r\n            var request = new Request(\"GET\", new Url { Path = \"/\", Scheme = \"http\", Query = \"key1\" }, memory);\r\n\r\n            // Then\r\n            ((bool)request.Query.key1).ShouldBeTrue();\r\n            ((string)request.Query.key1).ShouldEqual(\"key1\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_replace_equal_key_value_query_with_bool()\r\n        {\r\n            // Given\r\n            var memory = CreateRequestStream();\r\n\r\n            // When\r\n            var request = new Request(\"GET\", new Url { Path = \"/\", Scheme = \"http\", Query = \"key1=key1\" }, memory);\r\n\r\n            // Then\r\n            ShouldAssertExtensions.ShouldBeOfType<string>(request.Query[\"key1\"].Value);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_flush_underlying_stream_if_it_is_not_writable()\r\n        {\r\n            var largeStream = new NonWriteableStream(\r\n                new MemoryStream(new byte[1025]));\r\n            // Given\r\n            var memory = new RequestStream(largeStream, 1025, 1024, false);\r\n\r\n            // When\r\n            var exception = Record.Exception(() => new Request(\"POST\", new Url { Path = \"/\", Scheme = \"http\" }, memory));\r\n\r\n            // Then\r\n            exception.ShouldBeNull();\r\n        }\r\n\r\n        private static RequestStream CreateRequestStream()\r\n        {\r\n            return CreateRequestStream(new MemoryStream());\r\n        }\r\n\r\n        private static RequestStream CreateRequestStream(Stream stream)\r\n        {\r\n            return RequestStream.FromStream(stream);\r\n        }\r\n\r\n        private static byte[] BuildMultipartFormValues(params KeyValuePair<string, string>[] values)\r\n        {\r\n            var boundaryBuilder = new StringBuilder();\r\n\r\n            foreach (var pair in values)\r\n            {\r\n                boundaryBuilder.Append('\\r');\r\n                boundaryBuilder.Append('\\n');\r\n                boundaryBuilder.Append(\"--\");\r\n                boundaryBuilder.Append(\"----NancyFormBoundary\");\r\n                boundaryBuilder.Append('\\r');\r\n                boundaryBuilder.Append('\\n');\r\n                boundaryBuilder.AppendFormat(\"Content-Disposition: form-data; name=\\\"{0}\\\"\", pair.Key);\r\n                boundaryBuilder.Append('\\r');\r\n                boundaryBuilder.Append('\\n');\r\n                boundaryBuilder.Append('\\r');\r\n                boundaryBuilder.Append('\\n');\r\n                boundaryBuilder.Append(pair.Value);\r\n            }\r\n\r\n            boundaryBuilder.Append('\\r');\r\n            boundaryBuilder.Append('\\n');\r\n            boundaryBuilder.Append(\"------NancyFormBoundary--\");\r\n\r\n            var bytes =\r\n                Encoding.ASCII.GetBytes(boundaryBuilder.ToString());\r\n\r\n            return bytes;\r\n        }\r\n\r\n        private static byte[] BuildMultipartFormValues(Dictionary<string, string> formValues)\r\n        {\r\n            var pairs =\r\n                formValues.Keys.Select(key => new KeyValuePair<string, string>(key, formValues[key]));\r\n\r\n            return BuildMultipartFormValues(pairs.ToArray());\r\n        }\r\n\r\n        private static byte[] BuildMultipartFileValues(Dictionary<string, Tuple<string, string, string>> formValues)\r\n        {\r\n            var boundaryBuilder = new StringBuilder();\r\n\r\n            foreach (var key in formValues.Keys)\r\n            {\r\n                boundaryBuilder.Append('\\r');\r\n                boundaryBuilder.Append('\\n');\r\n                boundaryBuilder.Append(\"--\");\r\n                boundaryBuilder.Append(\"----NancyFormBoundary\");\r\n                boundaryBuilder.Append('\\r');\r\n                boundaryBuilder.Append('\\n');\r\n                boundaryBuilder.AppendFormat(\"Content-Disposition: form-data; name=\\\"{1}\\\"; filename=\\\"{0}\\\"\", key, formValues[key].Item3);\r\n                boundaryBuilder.Append('\\r');\r\n                boundaryBuilder.Append('\\n');\r\n                boundaryBuilder.AppendFormat(\"Content-Type: {0}\", formValues[key].Item1);\r\n                boundaryBuilder.Append('\\r');\r\n                boundaryBuilder.Append('\\n');\r\n                boundaryBuilder.Append('\\r');\r\n                boundaryBuilder.Append('\\n');\r\n                boundaryBuilder.Append(formValues[key].Item2);\r\n            }\r\n\r\n            boundaryBuilder.Append('\\r');\r\n            boundaryBuilder.Append('\\n');\r\n            boundaryBuilder.Append(\"------NancyFormBoundary--\");\r\n\r\n            var bytes =\r\n                Encoding.ASCII.GetBytes(boundaryBuilder.ToString());\r\n\r\n            return bytes;\r\n        }\r\n\r\n        private class NonWriteableStream : Stream\r\n        {\r\n            private readonly MemoryStream inner;\r\n\r\n            public NonWriteableStream(MemoryStream inner)\r\n            {\r\n                this.inner = inner;\r\n            }\r\n\r\n            public override void Flush()\r\n            {\r\n                throw new NotSupportedException();\r\n            }\r\n\r\n            public override Task FlushAsync(CancellationToken cancellationToken)\r\n            {\r\n                throw new NotSupportedException();\r\n            }\r\n\r\n            public override int Read(byte[] buffer, int offset, int count)\r\n            {\r\n                return this.inner.Read(buffer, offset, count);\r\n            }\r\n\r\n            public override long Seek(long offset, SeekOrigin origin)\r\n            {\r\n                return this.inner.Seek(offset, origin);\r\n            }\r\n\r\n            public override void SetLength(long value)\r\n            {\r\n                throw new NotSupportedException();\r\n            }\r\n\r\n            public override void Write(byte[] buffer, int offset, int count)\r\n            {\r\n                throw new NotSupportedException();\r\n            }\r\n\r\n            public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)\r\n            {\r\n                throw new NotSupportedException();\r\n            }\r\n\r\n            public override void WriteByte(byte value)\r\n            {\r\n                throw new NotSupportedException();\r\n            }\r\n\r\n            public override bool CanRead\r\n            {\r\n                get { return this.inner.CanRead; }\r\n            }\r\n\r\n            public override bool CanSeek\r\n            {\r\n                get { return this.inner.CanSeek; }\r\n            }\r\n\r\n            public override bool CanWrite\r\n            {\r\n                get { return false; }\r\n            }\r\n\r\n            public override long Length\r\n            {\r\n                get { return this.inner.Length; }\r\n            }\r\n\r\n            public override long Position\r\n            {\r\n                get { return this.inner.Position; }\r\n                set { this.inner.Position = value; }\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/RequestHeadersFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    using Nancy.Cookies;\r\n    using Nancy.Responses.Negotiation;\r\n    using Xunit;\r\n    using Xunit.Extensions;\r\n\r\n    public class RequestHeadersFixture\r\n    {\r\n        [Fact]\r\n        public void Should_return_all_header_values_when_values_are_retrieved()\r\n        {\r\n            // Given\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>>\r\n                {\r\n                    {\"accept\", new[] {\"text/plain\", \"text/html\"}},\r\n                    {\"charset\", new[] {\"utf-8\"}}\r\n                };\r\n\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // When\r\n            var values = headers.Values.ToList();\r\n\r\n            // Then\r\n            values.ShouldHaveCount(2);\r\n            values.First().ShouldHaveCount(2);\r\n            values.First().First().ShouldEqual(\"text/plain\");\r\n            values.First().Last().ShouldEqual(\"text/html\");\r\n            values.Last().First().ShouldEqual(\"utf-8\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_all_header_names_when_keys_are_retrieved()\r\n        {\r\n            // Given\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>>\r\n                {\r\n                    {\"accept\", null},\r\n                    {\"charset\", null}\r\n                };\r\n\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // When\r\n            var keys = headers.Keys.ToList();\r\n\r\n            // Then\r\n            keys.ShouldHaveCount(2);\r\n            keys.First().ShouldEqual(\"accept\");\r\n            keys.Last().ShouldEqual(\"charset\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_enumerable_when_accept_headers_are_not_available()\r\n        {\r\n            // Given\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>>();\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.Accept.ShouldHaveCount(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_all_accept_headers_when_multiple_are_available()\r\n        {\r\n            // Given\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>>\r\n                {\r\n                    { \"Accept\", new[] { \"text/plain\", \"text/ninja\" } }\r\n                };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).Accept.ToList();\r\n\r\n            // Then\r\n            headers.ShouldHaveCount(2);\r\n            headers[0].Item1.ShouldEqual(\"text/plain\");\r\n            headers[1].Item1.ShouldEqual(\"text/ninja\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_parse_accept_header_values_when_containing_multiple_values()\r\n        {\r\n            // Given\r\n            var values = new[] { \"text/plain, text/ninja\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Accept\", values } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).Accept.ToList();\r\n\r\n            // Then\r\n            headers.ShouldHaveCount(2);\r\n            headers[0].Item1.ShouldEqual(\"text/plain\");\r\n            headers[1].Item1.ShouldEqual(\"text/ninja\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_parse_accept_header_value_quality_when_available()\r\n        {\r\n            // Given\r\n            var values = new[] { \"text/plain;q=0.3\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Accept\", values } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).Accept.ToList();\r\n\r\n            // Then\r\n            headers.ShouldHaveCount(1);\r\n            headers[0].Item1.ShouldEqual(\"text/plain\");\r\n            headers[0].Item2.ShouldEqual(0.3m);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_default_accept_header_values_to_quality_one_if_not_explicitly_defined()\r\n        {\r\n            // Given\r\n            var values = new[] { \"text/plain\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Accept\", values } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).Accept.ToList();\r\n\r\n            // Then\r\n            headers.ShouldHaveCount(1);\r\n            headers[0].Item1.ShouldEqual(\"text/plain\");\r\n            headers[0].Item2.ShouldEqual(1m);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_ignore_accept_header_values_with_invalid_quality()\r\n        {\r\n            // Given\r\n            var values = new[] { \"text/plain, text/ninja;q=a\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Accept\", values } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).Accept.ToList();\r\n\r\n            // Then\r\n            headers.ShouldHaveCount(2);\r\n            headers.ShouldHave(t => t.Item1 == \"text/plain\" && t.Item2 == 1.0m);\r\n            headers.ShouldHave(t => t.Item1 == \"text/ninja\" && t.Item2 == 1.0m);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_strip_additional_accept_header_parameters()\r\n        {\r\n            // Given\r\n            var values = new[] { \"text/plain, text/ninja;q=0.3;a=1;b=2\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Accept\", values } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).Accept.ToList();\r\n\r\n            // Then\r\n            headers.ShouldHaveCount(2);\r\n            headers.ShouldHave(t => t.Item1 == \"text/plain\" && t.Item2 == 1.0m);\r\n            headers.ShouldHave(t => t.Item1 == \"text/ninja;a=1;b=2\" && t.Item2 == 0.3m);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_sort_accept_header_values_decending_based_on_quality()\r\n        {\r\n            // Given\r\n            var values = new[] { \"text/plain;q=0.3, text/ninja, text/html;q=0.7\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Accept\", values } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).Accept.ToList();\r\n\r\n            // Then\r\n            headers.ShouldHaveCount(3);\r\n            headers[0].Item1.ShouldEqual(\"text/ninja\");\r\n            headers[1].Item1.ShouldEqual(\"text/html\");\r\n            headers[2].Item1.ShouldEqual(\"text/plain\");\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"accept\")]\r\n        [InlineData(\"AcCepT\")]\r\n        public void Should_ignore_case_of_accept_header_name_when_retrieving_values(string headerName)\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"text/plain\", \"text/ninja\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { headerName, expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).Accept.ToList();\r\n\r\n            // Then\r\n            headers[0].Item1.ShouldEqual(\"text/plain\");\r\n            headers[1].Item1.ShouldEqual(\"text/ninja\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_enumerable_when_accept_charset_headers_are_not_available()\r\n        {\r\n            // Given\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>>();\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.AcceptCharset.ShouldHaveCount(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_accept_charset_headers_when_available()\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"utf-8\", \"iso-8859-5\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Accept-Charset\", expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).AcceptCharset.ToList();\r\n\r\n            // Then\r\n            headers.ShouldHaveCount(2);\r\n            headers[0].Item1.ShouldEqual(\"utf-8\");\r\n            headers[1].Item1.ShouldEqual(\"iso-8859-5\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_parse_accept_charset_header_values_when_containing_multiple_values()\r\n        {\r\n            // Given\r\n            var values = new[] { \"utf-8, iso-8859-5\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Accept-Charset\", values } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).AcceptCharset.ToList();\r\n\r\n            // Then\r\n            headers.ShouldHaveCount(2);\r\n            headers[0].Item1.ShouldEqual(\"utf-8\");\r\n            headers[1].Item1.ShouldEqual(\"iso-8859-5\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_parse_accept_charset_header_value_quality_when_available()\r\n        {\r\n            // Given\r\n            var values = new[] { \"utf-8;q=0.3\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Accept-Charset\", values } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).AcceptCharset.ToList();\r\n\r\n            // Then\r\n            headers.ShouldHaveCount(1);\r\n            headers[0].Item1.ShouldEqual(\"utf-8\");\r\n            headers[0].Item2.ShouldEqual(0.3m);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_default_accept_charset_header_values_to_quality_one_if_not_explicitly_defined()\r\n        {\r\n            // Given\r\n            var values = new[] { \"utf-8\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Accept-Charset\", values } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).AcceptCharset.ToList();\r\n\r\n            // Then\r\n            headers.ShouldHaveCount(1);\r\n            headers[0].Item1.ShouldEqual(\"utf-8\");\r\n            headers[0].Item2.ShouldEqual(1m);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_ignore_accept_charset_header_values_with_invalid_quality()\r\n        {\r\n            // Given\r\n            var values = new[] { \"utf-8, iso-8859-5;q=a\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Accept-Charset\", values } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).AcceptCharset.ToList();\r\n\r\n            // Then\r\n            headers.ShouldHaveCount(2);\r\n            headers.ShouldHave(t => t.Item1 == \"utf-8\" && t.Item2 == 1.0m);\r\n            headers.ShouldHave(t => t.Item1 == \"iso-8859-5\" && t.Item2 == 1.0m);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_sort_accept_charset_header_values_decending_based_on_quality()\r\n        {\r\n            // Given\r\n            var values = new[] { \"utf-8;q=0.3, iso-8859-5, iso-8859-15;q=0.7\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Accept-Charset\", values } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).AcceptCharset.ToList();\r\n\r\n            // Then\r\n            headers.ShouldHaveCount(3);\r\n            headers[0].Item1.ShouldEqual(\"iso-8859-5\");\r\n            headers[1].Item1.ShouldEqual(\"iso-8859-15\");\r\n            headers[2].Item1.ShouldEqual(\"utf-8\");\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"accept-charset\")]\r\n        [InlineData(\"AcCepT-cHaRsET\")]\r\n        public void Should_ignore_case_of_accept_charset_header_name_when_retrieving_values(string headerName)\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"utf-8\", \"iso-8859-5\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { headerName, expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).AcceptCharset.ToList();\r\n\r\n            // Then\r\n            headers[0].Item1.ShouldEqual(\"utf-8\");\r\n            headers[1].Item1.ShouldEqual(\"iso-8859-5\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_enumerable_when_accept_encoding_headers_are_not_available()\r\n        {\r\n            // Given\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>>();\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.AcceptEncoding.ShouldHaveCount(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_accept_encoding_headers_when_available()\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"compress\", \"sdch\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Accept-Encoding\", expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).AcceptEncoding.ToList();\r\n\r\n            // Then\r\n            headers.ShouldHaveCount(2);\r\n            headers[0].ShouldEqual(\"compress\");\r\n            headers[1].ShouldEqual(\"sdch\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_parse_accept_encoding_header_values_when_containing_multiple_values()\r\n        {\r\n            // Given\r\n            var values = new[] { \"compress, sdch\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Accept-Encoding\", values } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).AcceptEncoding.ToList();\r\n\r\n            // Then\r\n            headers.ShouldHaveCount(2);\r\n            headers[0].ShouldEqual(\"compress\");\r\n            headers[1].ShouldEqual(\"sdch\");\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"accept-encoding\")]\r\n        [InlineData(\"AcCepT-ENcOdinG\")]\r\n        public void Should_ignore_case_of_accept_encoding_header_name_when_retrieving_values(string headerName)\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"compress\", \"sdch\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { headerName, expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).AcceptEncoding.ToList();\r\n\r\n            // Then\r\n            headers.ShouldHaveCount(2);\r\n            headers[0].ShouldEqual(\"compress\");\r\n            headers[1].ShouldEqual(\"sdch\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_enumerable_when_accept_language_headers_are_not_available()\r\n        {\r\n            // Given\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>>();\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).AcceptLanguage.ToList();\r\n\r\n            // Then\r\n            headers.ShouldHaveCount(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_accept_language_headers_when_available()\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"en-US\", \"sv-SE\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Accept-Language\", expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).AcceptLanguage.ToList();\r\n\r\n            // Then\r\n            headers.ShouldHaveCount(2);\r\n            headers[0].Item1.ShouldEqual(\"en-US\");\r\n            headers[1].Item1.ShouldEqual(\"sv-SE\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_parse_accept_language_header_values_when_containing_multiple_values()\r\n        {\r\n            // Given\r\n            var values = new[] { \"en-US, sv-SE\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Accept-Language\", values } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).AcceptLanguage.ToList();\r\n\r\n            // Then\r\n            headers.ShouldHaveCount(2);\r\n            headers[0].Item1.ShouldEqual(\"en-US\");\r\n            headers[1].Item1.ShouldEqual(\"sv-SE\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_parse_accept_language_header_value_quality_when_available()\r\n        {\r\n            // Given\r\n            var values = new[] { \"en-US;q=0.3\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Accept-Language\", values } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).AcceptLanguage.ToList();\r\n\r\n            // Then\r\n            headers.ShouldHaveCount(1);\r\n            headers[0].Item1.ShouldEqual(\"en-US\");\r\n            headers[0].Item2.ShouldEqual(0.3m);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_default_accept_language_header_values_to_quality_one_if_not_explicitly_defined()\r\n        {\r\n            // Given\r\n            var values = new[] { \"en-US\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Accept-Language\", values } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).AcceptLanguage.ToList();\r\n\r\n            // Then\r\n            headers.ShouldHaveCount(1);\r\n            headers[0].Item1.ShouldEqual(\"en-US\");\r\n            headers[0].Item2.ShouldEqual(1m);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_ignore_accept_language_header_values_with_invalid_quality()\r\n        {\r\n            // Given\r\n            var values = new[] { \"en-US, sv-SE;q=a\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Accept-Language\", values } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).AcceptLanguage.ToList();\r\n\r\n            // Then\r\n            headers.ShouldHaveCount(2);\r\n            headers.ShouldHave(t => t.Item1 == \"en-US\" && t.Item2 == 1.0m);\r\n            headers.ShouldHave(t => t.Item1 == \"sv-SE\" && t.Item2 == 1.0m);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_sort_accept_language_header_values_decending_based_on_quality()\r\n        {\r\n            // Given\r\n            var values = new[] { \"en-US;q=0.3, da, sv-SE;q=0.7\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Accept-Language\", values } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).AcceptLanguage.ToList();\r\n\r\n            // Then\r\n            headers.ShouldHaveCount(3);\r\n            headers[0].Item1.ShouldEqual(\"da\");\r\n            headers[1].Item1.ShouldEqual(\"sv-SE\");\r\n            headers[2].Item1.ShouldEqual(\"en-US\");\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"accept-language\")]\r\n        [InlineData(\"AcCepT-LaNGUage\")]\r\n        public void Should_ignore_case_of_accept_language_header_name_when_retrieving_values(string headerName)\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"en-US\", \"sv-SE\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { headerName, expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).AcceptLanguage.ToList();\r\n\r\n            // Then\r\n            headers.ShouldHaveCount(2);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_string_when_authorization_headers_are_not_available()\r\n        {\r\n            // Given\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>>();\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.Authorization.ShouldBeEmpty();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_authorization_headers_when_available()\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Authorization\", expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.Authorization.ShouldBeSameAs(expectedValues[0]);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"authorization\")]\r\n        [InlineData(\"AutHORizaTion\")]\r\n        public void Should_ignore_case_of_authorization_header_name_when_retrieving_values(string headerName)\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { headerName, expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.Authorization.ShouldBeSameAs(expectedValues[0]);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_enumerable_when_cache_control_headers_are_not_available()\r\n        {\r\n            // Given\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>>();\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.CacheControl.ShouldHaveCount(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_cache_control_headers_when_available()\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"public\", \"max-age=123445\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Cache-Control\", expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.CacheControl.ShouldBeSameAs(expectedValues);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"cache-control\")]\r\n        [InlineData(\"CaCHe-ContROL\")]\r\n        public void Should_ignore_case_of_cache_control_header_name_when_retrieving_values(string headerName)\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"public\", \"max-age=123445\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { headerName, expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.CacheControl.ShouldBeSameAs(expectedValues);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_string_when_connection_headers_are_not_available()\r\n        {\r\n            // Given\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>>();\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.Connection.ShouldBeEmpty();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_connection_headers_when_available()\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"closed\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Connection\", expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.Connection.ShouldBeSameAs(expectedValues[0]);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"connection\")]\r\n        [InlineData(\"CONNecTION\")]\r\n        public void Should_ignore_case_of_connection_header_name_when_retrieving_values(string headerName)\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"closed\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { headerName, expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.Connection.ShouldBeSameAs(expectedValues[0]);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_zero_when_content_length_headers_are_not_available()\r\n        {\r\n            // Given\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>>();\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.ContentLength.ShouldEqual(0L);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_content_length_headers_when_available()\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"12345\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Content-Length\", expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.ContentLength.ShouldEqual(12345L);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"content-length\")]\r\n        [InlineData(\"CoNTEnt-LENGth\")]\r\n        public void Should_ignore_case_of_content_length_header_name_when_retrieving_values(string headerName)\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"12345\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { headerName, expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.ContentLength.ShouldEqual(12345L);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_string_when_content_type_headers_are_not_available()\r\n        {\r\n            // Given\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>>();\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.ContentType.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_content_type_header_when_available()\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"text/ninja\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Content-Type\", expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.ContentType.Matches(\"text/ninja\").ShouldBeTrue();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"content-type\")]\r\n        [InlineData(\"CoNTEnt-tYPe\")]\r\n        public void Should_ignore_case_of_content_type_header_name_when_retrieving_values(string headerName)\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"text/ninja\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { headerName, expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.ContentType.Matches(\"text/ninja\").ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_date_when_date_headers_are_not_available()\r\n        {\r\n            // Given\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>>();\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.Date.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_date_when_date_headers_available()\r\n        {\r\n            // Given\r\n            var expectedDate = new DateTime(2011, 11, 15, 8, 12, 31);\r\n            var expectedValues = new[] { \"Tue, 15 Nov 2011 08:12:31 GMT\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Date\", expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.Date.ShouldEqual(expectedDate);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_null_when_date_headers_are_invalid()\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"Bad Date Header\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Date\", expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.Date.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_enumerable_when_cookie_headers_are_not_available()\r\n        {\r\n            // Given\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>>();\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.Cookie.ShouldHaveCount(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_cookie_headers_when_available()\r\n        {\r\n            // Given\r\n            var rawValues = new[] { \"foo=bar\", \"name=value\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Cookie\", rawValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            ValidateCookie(headers.Cookie.First(), \"foo\", \"bar\");\r\n            ValidateCookie(headers.Cookie.Last(), \"name\", \"value\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_parse_cookie_headers_when_delimited_by_semicolon()\r\n        {\r\n            // Given\r\n            var rawValues = new[] { \"foo=bar\", \"name=value ; third=  something=stuff  \" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Cookie\", rawValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            ValidateCookie(headers.Cookie.ElementAt(0), \"foo\", \"bar\");\r\n            ValidateCookie(headers.Cookie.ElementAt(1), \"name\", \"value\");\r\n            ValidateCookie(headers.Cookie.ElementAt(2), \"third\", \"  something=stuff\");\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"cookie\")]\r\n        [InlineData(\"COokIE\")]\r\n        public void Should_ignore_case_of_cookie_header_name_when_retrieving_values(string headerName)\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"foo=bar\", \"name=value\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { headerName, expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            ValidateCookie(headers.Cookie.First(), \"foo\", \"bar\");\r\n            ValidateCookie(headers.Cookie.Last(), \"name\", \"value\");\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"date\")]\r\n        [InlineData(\"daTE\")]\r\n        public void Should_ignore_case_of_date_header_name_when_retrieving_values(string headerName)\r\n        {\r\n            // Given\r\n            var expectedDate = new DateTime(2011, 11, 15, 8, 12, 31);\r\n            var expectedValues = new[] { \"Tue, 15 Nov 2011 08:12:31 GMT\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { headerName, expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.Date.ShouldEqual(expectedDate);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_string_when_host_headers_are_not_available()\r\n        {\r\n            // Given\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>>();\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.Host.ShouldBeEmpty();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_host_headers_when_available()\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"en.wikipedia.org\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Host\", expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.Host.ShouldBeSameAs(expectedValues[0]);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"host\")]\r\n        [InlineData(\"hOsT\")]\r\n        public void Should_ignore_case_of_host_header_name_when_retrieving_values(string headerName)\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"en.wikipedia.org\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { headerName, expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.Host.ShouldBeSameAs(expectedValues[0]);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_enumerable_when_ifmatch_headers_are_not_available()\r\n        {\r\n            // Given\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>>();\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.IfMatch.ShouldHaveCount(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_ifmatch_headers_when_available()\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"xyzzy\", \"c3piozzzz\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"If-Match\", expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.IfMatch.ShouldBeSameAs(expectedValues);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_parse_ifmatch_header_values_when_containing_multiple_values()\r\n        {\r\n            // Given\r\n            var values = new[] { \"xyzzy\", \"c3piozzzz\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"If-Match\", values } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).IfMatch.ToList();\r\n\r\n            // Then\r\n            headers.ShouldHaveCount(2);\r\n            headers[0].ShouldEqual(\"xyzzy\");\r\n            headers[1].ShouldEqual(\"c3piozzzz\");\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"if-match\")]\r\n        [InlineData(\"If-MaTCH\")]\r\n        public void Should_ignore_case_of_ifmatch_header_name_when_retrieving_values(string headerName)\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"xyzzy\", \"c3piozzzz\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { headerName, expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.IfMatch.ShouldBeSameAs(expectedValues);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_when_ifmodifiedsince_headers_are_not_available()\r\n        {\r\n            // Given\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>>();\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.IfModifiedSince.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_ifmodifiedsince_when_available()\r\n        {\r\n            // Given\r\n            var expectedDate = new DateTime(2011, 11, 15, 8, 12, 31);\r\n            var expectedValues = new[] { \"Tue, 15 Nov 2011 08:12:31 GMT\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"If-Modified-Since\", expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.IfModifiedSince.ShouldEqual(expectedDate);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_when_ifmodifiedsince_when_invalid()\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"Bad Date\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"If-Modified-Since\", expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.IfModifiedSince.ShouldBeNull();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"if-modified-since\")]\r\n        [InlineData(\"IF-MODIFIED-SINCE\")]\r\n        public void Should_ignore_case_of_ifmodifiedsince_header_name_when_retrieving_values(string headerName)\r\n        {\r\n            // Given\r\n            var expectedDate = new DateTime(2011, 11, 15, 8, 12, 31);\r\n            var expectedValues = new[] { \"Tue, 15 Nov 2011 08:12:31 GMT\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { headerName, expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.IfModifiedSince.ShouldEqual(expectedDate);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_enumerable_when_ifnonematch_headers_are_not_available()\r\n        {\r\n            // Given\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>>();\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.IfNoneMatch.ShouldHaveCount(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_ifnonematch_headers_when_available()\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"xyzzy\", \"c3piozzzz\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"If-None-Match\", expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.IfNoneMatch.ShouldBeSameAs(expectedValues);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_parse_ifnonematch_header_values_when_containing_multiple_values()\r\n        {\r\n            // Given\r\n            var values = new[] { \"xyzzy\", \"c3piozzzz\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"If-None-Match\", values } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders).IfNoneMatch.ToList();\r\n\r\n            // Then\r\n            headers.ShouldHaveCount(2);\r\n            headers[0].ShouldEqual(\"xyzzy\");\r\n            headers[1].ShouldEqual(\"c3piozzzz\");\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"if-none-match\")]\r\n        [InlineData(\"If-NONe-MaTCH\")]\r\n        public void Should_ignore_case_of_ifnonematch_header_name_when_retrieving_values(string headerName)\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"xyzzy\", \"c3piozzzz\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { headerName, expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.IfNoneMatch.ShouldBeSameAs(expectedValues);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_string_when_ifrange_headers_are_not_available()\r\n        {\r\n            // Given\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>>();\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.IfRange.ShouldBeEmpty();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_ifrange_header_when_available()\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"737060cd8c284d8af7ad3082f209582d\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"If-Range\", expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.IfRange.ShouldEqual(expectedValues[0]);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"if-range\")]\r\n        [InlineData(\"IF-RANGe\")]\r\n        public void Should_ignore_case_of_ifrange_header_name_when_retrieving_values(string headerName)\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"737060cd8c284d8af7ad3082f209582d\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { headerName, expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.IfRange.ShouldEqual(expectedValues[0]);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_when_ifunmodifiedsince_headers_are_not_available()\r\n        {\r\n            // Given\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>>();\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.IfUnmodifiedSince.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_date_ifunmodifiedsince_when_available()\r\n        {\r\n            // Given\r\n            var expectedDate = new DateTime(2011, 11, 15, 8, 12, 31);\r\n            var expectedValues = new[] { \"Tue, 15 Nov 2011 08:12:31 GMT\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"If-Unmodified-Since\", expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.IfUnmodifiedSince.ShouldEqual(expectedDate);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_ifunmodifiedsince_is_invalid()\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"Bad Date\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"If-Unmodified-Since\", expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.IfUnmodifiedSince.ShouldBeNull();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"if-unmodified-since\")]\r\n        [InlineData(\"If-UnmoDified-SInce\")]\r\n        public void Should_ignore_case_of_ifunmodifiedsince_header_name_when_retrieving_values(string headerName)\r\n        {\r\n            // Given\r\n            var expectedDate = new DateTime(2011, 11, 15, 8, 12, 31);\r\n            var expectedValues = new[] { \"Tue, 15 Nov 2011 08:12:31 GMT\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { headerName, expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.IfUnmodifiedSince.ShouldEqual(expectedDate);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_zero_when_maxforwards_headers_are_not_available()\r\n        {\r\n            // Given\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>>();\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.MaxForwards.ShouldEqual(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_maxforwards_headers_when_available()\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"12\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Max-Forwards\", expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.MaxForwards.ShouldEqual(12);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"max-forwards\")]\r\n        [InlineData(\"MAX-Forwards\")]\r\n        public void Should_ignore_case_of_maxforwards_header_name_when_retrieving_values(string headerName)\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"12\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { headerName, expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.MaxForwards.ShouldEqual(12);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_string_when_referer_headers_are_not_available()\r\n        {\r\n            // Given\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>>();\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.Referrer.ShouldBeEmpty();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_referer_headers_when_available()\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"http://nancyfx.org\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Referer\", expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.Referrer.ShouldBeSameAs(expectedValues[0]);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"referer\")]\r\n        [InlineData(\"RefERer\")]\r\n        public void Should_ignore_case_of_referer_header_name_when_retrieving_values(string headerName)\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"http://nancyfx.org\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { headerName, expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.Referrer.ShouldBeSameAs(expectedValues[0]);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_string_when_useragent_headers_are_not_available()\r\n        {\r\n            // Given\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>>();\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.UserAgent.ShouldBeEmpty();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_useragent_headers_when_available()\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.815.0 Safari/535.1\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"User-Agent\", expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.UserAgent.ShouldBeSameAs(expectedValues[0]);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"user-agent\")]\r\n        [InlineData(\"user-AGENT\")]\r\n        public void Should_ignore_case_of_useragent_header_name_when_retrieving_values(string headerName)\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.815.0 Safari/535.1\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { headerName, expectedValues } };\r\n\r\n            // When\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // Then\r\n            headers.UserAgent.ShouldBeSameAs(expectedValues[0]);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_enumerable_when_header_not_available_using_indexer()\r\n        {\r\n            // Given\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>>();\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // When\r\n            var result = headers[\"not-found\"];\r\n\r\n            // Then\r\n            result.ShouldHaveCount(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_header_values_when_available_using_indexer()\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"fakeValue1\", \"fakeValue2\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"some-header\", expectedValues } };\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // When\r\n            var result = headers[\"some-header\"];\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(expectedValues);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_ignore_case_when_available_using_indexer()\r\n        {\r\n            // Given\r\n            var expectedValues = new[] { \"fakeValue1\", \"fakeValue2\" };\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"some-header\", expectedValues } };\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            // When\r\n            var result = headers[\"sOme-HeAdEr\"];\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(expectedValues);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_accept_headers_to_be_overwritten()\r\n        {\r\n            // Given\r\n            var expectedValues = new[] {\r\n                new Tuple<string, decimal>(\"text/plain\", 0.8m),\r\n                new Tuple<string, decimal>(\"text/ninja\", 0.5m),\r\n            };\r\n\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"Accept\", new[] { \"initial value\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { Accept = expectedValues };\r\n\r\n            // When\r\n            var values = headers.Accept.ToList();\r\n\r\n            // Then\r\n            values[0].Item1.ShouldEqual(\"text/plain\");\r\n            values[0].Item2.ShouldEqual(0.8m);\r\n            values[1].Item1.ShouldEqual(\"text/ninja\");\r\n            values[1].Item2.ShouldEqual(0.5m);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_remove_accept_if_assigned_null()\r\n        {\r\n            // Given\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"Accept\", new[] { \"text/plain\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { Accept = null };\r\n\r\n            // When\r\n            var values = headers.Keys;\r\n\r\n            // Then\r\n            values.Contains(\"Accept\").ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_accept_charset_headers_to_be_overwritten()\r\n        {\r\n            // Given\r\n            var expectedValues = new[] {\r\n                new Tuple<string, decimal>(\"utf-8\", 0.7m),\r\n                new Tuple<string, decimal>(\"iso-8859-5\", 0.3m),\r\n            };\r\n\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"Accept-Charset\", new[] { \"utf-7\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { AcceptCharset = expectedValues };\r\n\r\n            // When\r\n            var values = headers.AcceptCharset.ToList();\r\n\r\n            // Then\r\n            values[0].Item1.ShouldEqual(\"utf-8\");\r\n            values[0].Item2.ShouldEqual(0.7m);\r\n            values[1].Item1.ShouldEqual(\"iso-8859-5\");\r\n            values[1].Item2.ShouldEqual(0.3m);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_remove_accept_charset_if_assigned_null()\r\n        {\r\n            // Given\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"Accept-Charset\", new[] { \"iso-8859-5\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { AcceptCharset = null };\r\n\r\n            // When\r\n            var values = headers.Keys;\r\n\r\n            // Then\r\n            values.Contains(\"Accept-Charset\").ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_accept_encoding_headers_to_be_overwritten()\r\n        {\r\n            // Given\r\n            var expectedValues = new[] {\r\n                \"compress\",\r\n                \"gzip\",\r\n            };\r\n\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"Accept-Encoding\", new[] { \"sdch\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { AcceptEncoding = expectedValues };\r\n\r\n            // When\r\n            var values = headers.AcceptEncoding.ToList();\r\n\r\n            // Then\r\n            values[0].ShouldEqual(\"compress\");\r\n            values[1].ShouldEqual(\"gzip\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_remove_accept_encoding_if_assigned_null()\r\n        {\r\n            // Given\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"Accept-Encoding\", new[] { \"compress\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { AcceptEncoding = null };\r\n\r\n            // When\r\n            var values = headers.Keys;\r\n\r\n            // Then\r\n            values.Contains(\"Accept-Encoding\").ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_accept_language_headers_to_be_overwritten()\r\n        {\r\n            // Given\r\n            var expectedValues = new[] {\r\n                new Tuple<string, decimal>(\"en-US\", 0.7m),\r\n                new Tuple<string, decimal>(\"sv-SE\", 0.3m)\r\n            };\r\n\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"Accept-Language\", new[] { \"da\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { AcceptLanguage = expectedValues };\r\n\r\n            // When\r\n            var values = headers.AcceptLanguage.ToList();\r\n\r\n            // Then\r\n            values[0].Item1.ShouldEqual(\"en-US\");\r\n            values[0].Item2.ShouldEqual(0.7m);\r\n            values[1].Item1.ShouldEqual(\"sv-SE\");\r\n            values[1].Item2.ShouldEqual(0.3m);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_remove_accept_language_if_assigned_null()\r\n        {\r\n            // Given\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"Accept-Language\", new[] { \"en-US\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { AcceptLanguage = null };\r\n\r\n            // When\r\n            var values = headers.Keys;\r\n\r\n            // Then\r\n            values.Contains(\"Accept-Language\").ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_accept_authorization_to_be_overwritten()\r\n        {\r\n            // Given\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"Authorization\", new[] { \"Basic 12345LDKJDFJDDSFDFvfdf==\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { Authorization = \"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\" };\r\n\r\n            // When\r\n            var values = headers.Authorization;\r\n\r\n            // Then\r\n            values.ShouldEqual(\"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_remove_authorization_if_assigned_null()\r\n        {\r\n            // Given\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"Authorization\", new[] { \"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { Authorization = null };\r\n\r\n            // When\r\n            var values = headers.Keys;\r\n\r\n            // Then\r\n            values.Contains(\"Authorization\").ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_cache_control_headers_to_be_overwritten()\r\n        {\r\n            // Given\r\n            var expectedValues = new[] {\r\n                \"public\",\r\n                \"max-age=123445\",\r\n            };\r\n\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"Cache-Control\", new[] { \"no-transform\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { CacheControl = expectedValues };\r\n\r\n            // When\r\n            var values = headers.CacheControl.ToList();\r\n\r\n            // Then\r\n            values[0].ShouldEqual(\"public\");\r\n            values[1].ShouldEqual(\"max-age=123445\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_remove_cache_control_if_assigned_null()\r\n        {\r\n            // Given\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"Cache-Control\", new[] { \"public\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { CacheControl = null };\r\n\r\n            // When\r\n            var values = headers.Keys;\r\n\r\n            // Then\r\n            values.Contains(\"Cache-Control\").ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_connection_to_be_overwritten()\r\n        {\r\n            // Given\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"Connection\", new[] { \"closed\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { Connection = \"keep-alive\" };\r\n\r\n            // When\r\n            var values = headers.Connection;\r\n\r\n            // Then\r\n            values.ShouldEqual(\"keep-alive\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_remove_connection_if_assigned_null()\r\n        {\r\n            // Given\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"Connection\", new[] { \"text/plain\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { Connection = null };\r\n\r\n            // When\r\n            var values = headers.Keys;\r\n\r\n            // Then\r\n            values.Contains(\"Connection\").ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_content_length_to_be_overwritten()\r\n        {\r\n            // Given\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"Content-Length\", new[] { \"12345\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { ContentLength = 54321 };\r\n\r\n            // When\r\n            var values = headers.ContentLength;\r\n\r\n            // Then\r\n            values.ShouldEqual(54321L);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_remove_content_length_if_assigned_zero()\r\n        {\r\n            // Given\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"Content-Length\", new[] { \"12345\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { ContentLength = 0 };\r\n\r\n            // When\r\n            var values = headers.Keys;\r\n\r\n            // Then\r\n            values.Contains(\"Content-Length\").ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_date_to_be_overwritten()\r\n        {\r\n            // Given\r\n            var expectedValue =\r\n                new DateTime(2012, 12, 15, 8, 12, 31);\r\n\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"Date\", new[] { \"Tue, 15 Nov 2011 08:12:31 GMT\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { Date = expectedValue };\r\n\r\n            // When\r\n            var values = headers.Date;\r\n\r\n            // Then\r\n            values.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_remove_date_if_assigned_null()\r\n        {\r\n            // Given\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"Date\", new[] { \"Tue, 15 Nov 2011 08:12:31 GMT\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { Date = null };\r\n\r\n            // When\r\n            var values = headers.Keys;\r\n\r\n            // Then\r\n            values.Contains(\"Date\").ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_host_to_be_overwritten()\r\n        {\r\n            // Given\r\n            const string expectedValue = \"www.nancyfx.org\";\r\n\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"Host\", new[] { \"en.wikipedia.org\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { Host = expectedValue };\r\n\r\n            // When\r\n            var values = headers.Host;\r\n\r\n            // Then\r\n            values.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_remove_host_if_assigned_null()\r\n        {\r\n            // Given\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"Host\", new[] { \"www.nancyfx.org\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { Host = null };\r\n\r\n            // When\r\n            var values = headers.Keys;\r\n\r\n            // Then\r\n            values.Contains(\"Host\").ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_if_match_headers_to_be_overwritten()\r\n        {\r\n            // Given\r\n            var expectedValues = new[] {\r\n                \"fsdfsd\", \"c3pdfgdfgjiozzzz\"\r\n            };\r\n\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"If-Match\", new[] { \"xyzzy\", \"c3piozzzz\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { IfMatch = expectedValues };\r\n\r\n            // When\r\n            var values = headers.IfMatch.ToArray();\r\n\r\n            // Then\r\n            values.ShouldEqualSequence(expectedValues);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_remove_if_match_if_assigned_null()\r\n        {\r\n            // Given\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"If-Match\", new[] { \"fsdfsd\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { IfMatch = null };\r\n\r\n            // When\r\n            var values = headers.Keys;\r\n\r\n            // Then\r\n            values.Contains(\"If-Match\").ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_if_modified_since_to_be_overwritten()\r\n        {\r\n            // Given\r\n            var expectedValue =\r\n                new DateTime(2012, 12, 15, 8, 12, 31);\r\n\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"If-Modified-Since\", new[] { \"Tue, 15 Nov 2011 08:12:31 GMT\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { IfModifiedSince = expectedValue };\r\n\r\n            // When\r\n            var values = headers.IfModifiedSince;\r\n\r\n            // Then\r\n            values.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_remove_if_modified_since_if_assigned_null()\r\n        {\r\n            // Given\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"If-Modified-Since\", new[] { \"Tue, 15 Nov 2011 08:12:31 GMT\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { IfModifiedSince = null };\r\n\r\n            // When\r\n            var values = headers.Keys;\r\n\r\n            // Then\r\n            values.Contains(\"If-Modified-Since\").ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_if_none_match_to_be_overwritten()\r\n        {\r\n            // Given\r\n            var expectedValues = new[] {\r\n                \"fsdfsd\", \"c3pdfgdfgjiozzzz\"\r\n            };\r\n\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"If-None-Match\", new[] { \"xyzzy\", \"c3piozzzz\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { IfNoneMatch = expectedValues };\r\n\r\n            // When\r\n            var values = headers.IfNoneMatch.ToArray();\r\n\r\n            // Then\r\n            values.ShouldEqualSequence(expectedValues);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_remove_if_none_match_if_assigned_null()\r\n        {\r\n            // Given\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"If-None-Match\", new[] { \"fsdfsd\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { IfNoneMatch = null };\r\n\r\n            // When\r\n            var values = headers.Keys;\r\n\r\n            // Then\r\n            values.Contains(\"If-None-Match\").ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_if_range_to_be_overwritten()\r\n        {\r\n            // Given\r\n            const string expectedValue = \"737060cd8c284d8af7ad3082f209582d\";\r\n\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"If-Range\", new[] { \"737060ed712v4d8af7ad3082f209582d\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { IfRange = expectedValue };\r\n\r\n            // When\r\n            var values = headers.IfRange;\r\n\r\n            // Then\r\n            values.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_remove_if_range_if_assigned_null()\r\n        {\r\n            // Given\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"If-Range\", new[] { \"737060cd8c284d8af7ad3082f209582d\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { IfRange = null };\r\n\r\n            // When\r\n            var values = headers.Keys;\r\n\r\n            // Then\r\n            values.Contains(\"If-Range\").ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_if_unmodified_since_to_be_overwritten()\r\n        {\r\n            // Given\r\n            var expectedValue =\r\n                new DateTime(2012, 12, 15, 8, 12, 31);\r\n\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"If-Unmodified-Since\", new[] { \"Tue, 15 Nov 2011 08:12:31 GMT\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { IfUnmodifiedSince = expectedValue };\r\n\r\n            // When\r\n            var values = headers.IfUnmodifiedSince;\r\n\r\n            // Then\r\n            values.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_remove_if_unmodified_since_if_assigned_null()\r\n        {\r\n            // Given\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"If-Unmodified-Since\", new[] { \"Tue, 15 Nov 2011 08:12:31 GMT\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { IfUnmodifiedSince = null };\r\n\r\n            // When\r\n            var values = headers.Keys;\r\n\r\n            // Then\r\n            values.Contains(\"If-Unmodified-Since\").ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_max_forwards_to_be_overwritten()\r\n        {\r\n            // Given\r\n            const int expectedValue = 10;\r\n\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"Max-Forwards\", new[] { \"3\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { MaxForwards = expectedValue };\r\n\r\n            // When\r\n            var values = headers.MaxForwards;\r\n\r\n            // Then\r\n            values.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_remove_max_forwards_if_assigned_zero()\r\n        {\r\n            // Given\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"Max-Forwards\", new[] { \"2\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { MaxForwards = 0 };\r\n\r\n            // When\r\n            var values = headers.Keys;\r\n\r\n            // Then\r\n            values.Contains(\"Max-Forwards\").ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_referrer_to_be_overwritten()\r\n        {\r\n            // Given\r\n            const string expectedValue = \"www.nancyfx.org\";\r\n\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"Referer\", new[] { \"en.wikipedia.com\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { Referrer = expectedValue };\r\n\r\n            // When\r\n            var values = headers.Referrer;\r\n\r\n            // Then\r\n            values.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_remove_referrer_header_if_assigned_null()\r\n        {\r\n            // Given\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"Referer\", new[] { \"en.wikipedia.com\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { Referrer = null };\r\n\r\n            // When\r\n            var values = headers.Keys;\r\n\r\n            // Then\r\n            values.Contains(\"Referer\").ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_user_agent_to_be_overwritten()\r\n        {\r\n            // Given\r\n            const string expectedValue = \"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20120427 Firefox/15.0a1\";\r\n\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"User-Agent\", new[] { \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.815.0 Safari/535.1\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { UserAgent = expectedValue };\r\n\r\n            // When\r\n            var values = headers.UserAgent;\r\n\r\n            // Then\r\n            values.ShouldEqual(expectedValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_remove_user_agent_header_if_assigned_null()\r\n        {\r\n            // Given\r\n            var rawHeaders =\r\n                new Dictionary<string, IEnumerable<string>> { { \"User-Agent\", new[] { \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.815.0 Safari/535.1\" } } };\r\n\r\n            var headers =\r\n                new RequestHeaders(rawHeaders) { UserAgent = null };\r\n\r\n            // When\r\n            var values = headers.Keys;\r\n\r\n            // Then\r\n            values.Contains(\"User-Agent\").ShouldBeFalse();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"text/html;q=0.8\", \"text/html\", 0.8)]\r\n        [InlineData(\"application/javascript;q=0.9,text/html;q=0.2,text/text\", \"text/html\", 0.2)]\r\n        [InlineData(\"application/xhtml+xml; profile=\\\"http://www.wapforum. org/xhtml\\\"\", \"application/xhtml+xml;profile=\\\"http://www.wapforum. org/xhtml\\\"\", 1.0)]\r\n        [InlineData(\"application/xhtml+xml; q=0.2; profile=\\\"http://www.wapforum. org/xhtml\\\"\", \"application/xhtml+xml;profile=\\\"http://www.wapforum. org/xhtml\\\"\", 0.2)]\r\n        [InlineData(\"application/xhtml+xml; q=.7; profile=\\\"http://www.wapforum. org/xhtml\\\"\", \"application/xhtml+xml;profile=\\\"http://www.wapforum. org/xhtml\\\"\", 0.7)]\r\n        public void Should_retrieve_weighting_for_accept_headers(string header, string typeToCheck, double weighting)\r\n        {\r\n            var rawHeaders = new Dictionary<string, IEnumerable<string>> { { \"Accept\", new[] { header } } };\r\n\r\n            var headers = new RequestHeaders(rawHeaders);\r\n\r\n            headers.Accept.First(a => a.Item1 == typeToCheck).Item2.ShouldEqual((decimal)weighting);\r\n        }\r\n\r\n        private static void ValidateCookie(INancyCookie cookie, string name, string value)\r\n        {\r\n            cookie.Name.ShouldEqual(name);\r\n            cookie.Value.ShouldEqual(value);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/ResponseExtensionsFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using Nancy.Configuration;\r\n    using Nancy.Responses;\r\n    using Xunit;\r\n\r\n    public class ResponseExtensionsFixture\r\n    {\r\n        [Fact]\r\n        public void Should_add_content_disposition_header_for_attachments()\r\n        {\r\n            var response = new Response();\r\n\r\n            var result = response.AsAttachment(\"testing.html\", \"text/html\");\r\n\r\n            result.Headers.ShouldNotBeNull();\r\n            result.Headers.ContainsKey(\"Content-Disposition\").ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_have_filename_in_content_disposition_header()\r\n        {\r\n            var response = new Response();\r\n\r\n            var result = response.AsAttachment(\"testing.html\", \"text/html\");\r\n\r\n            result.Headers[\"Content-Disposition\"].ShouldContain(\"testing.html\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_allow_null_filename_on_generic_responses_as_attachments()\r\n        {\r\n            var response = new Response();\r\n\r\n            var result = Record.Exception(() => response.AsAttachment(null, \"text/html\"));\r\n\r\n            result.ShouldBeOfType(typeof(ArgumentException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_filename_and_content_type_for_attachments_from_file_response_if_not_overridden()\r\n        {\r\n            // Given\r\n            var environment = new DefaultNancyEnvironment();\r\n            environment.StaticContent(safepaths:this.GetLocation());\r\n\r\n            var filename = this.GetFilePath();\r\n            var response = new GenericFileResponse(filename, \"foo/bar\", new NancyContext() {Environment = environment});\r\n\r\n            // When\r\n            var result = response.AsAttachment();\r\n\r\n            // Then\r\n            result.Headers[\"Content-Disposition\"].ShouldContain(Path.GetFileName(filename));\r\n            result.ContentType.ShouldEqual(\"foo/bar\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_overriding_of_content_type_for_attachments()\r\n        {\r\n            var response = new Response();\r\n            response.ContentType = \"test/test\";\r\n\r\n            var result = response.AsAttachment(\"testing.html\", \"text/html\");\r\n\r\n            result.ContentType.ShouldEqual(\"text/html\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_set_content_type_for_attachment_if_null()\r\n        {\r\n            var response = new Response();\r\n            response.ContentType = \"test/test\";\r\n\r\n            var result = response.AsAttachment(\"testing.html\");\r\n\r\n            result.ContentType.ShouldEqual(\"test/test\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_handle_null_response_headers_using_withheaders()\r\n        {\r\n            var response = new Response();\r\n            response.Headers = null;\r\n\r\n            var result = response.WithHeaders(new[] { Tuple.Create(\"test\", \"test\") });\r\n\r\n            result.Headers.ShouldNotBeNull();\r\n            result.Headers.Count.ShouldEqual(1);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_append_to_existing_headers_if_already_in_response()\r\n        {\r\n            var response = new Response();\r\n            response.Headers = new Dictionary<string, string>();\r\n            response.Headers.Add(\"Existing\", \"Test\");\r\n\r\n            var result = response.WithHeaders(new[] { Tuple.Create(\"test\", \"test\") });\r\n\r\n            result.Headers.ShouldNotBeNull();\r\n            result.Headers.Count.ShouldEqual(2);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_all_headers_using_withheaders()\r\n        {\r\n            var response = new Response();\r\n\r\n            var result = response.WithHeaders(\r\n                             Tuple.Create(\"test\", \"testvalue\"),\r\n                             Tuple.Create(\"test2\", \"test2value\"));\r\n\r\n            result.Headers.ShouldNotBeNull();\r\n            result.Headers[\"test\"].ShouldEqual(\"testvalue\");\r\n            result.Headers[\"test2\"].ShouldEqual(\"test2value\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_supply_withHeaders_headers_as_anonymous_types()\r\n        {\r\n            var response = new Response();\r\n\r\n            var result = response.WithHeaders(\r\n                             new { Header = \"test\", Value = \"testvalue\" },\r\n                             new { Header = \"test2\", Value = \"test2value\" });\r\n\r\n            result.Headers.ShouldNotBeNull();\r\n            result.Headers[\"test\"].ShouldEqual(\"testvalue\");\r\n            result.Headers[\"test2\"].ShouldEqual(\"test2value\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_chain_setting_single_headers()\r\n        {\r\n            var response = new Response();\r\n\r\n            var result = response.WithHeader(\"test\", \"testvalue\").WithHeader(\"test2\", \"test2value\");\r\n\r\n            result.Headers.ShouldNotBeNull();\r\n            result.Headers[\"test\"].ShouldEqual(\"testvalue\");\r\n            result.Headers[\"test2\"].ShouldEqual(\"test2value\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_the_content_type_enum()\r\n        {\r\n            var response = new Response();\r\n\r\n            var result = response.WithContentType(\"text/cache-manifest\");\r\n\r\n            result.ContentType.ShouldEqual(\"text/cache-manifest\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_status_code()\r\n        {\r\n            var respone = new Response();\r\n\r\n            var result = respone.WithStatusCode(HttpStatusCode.NotFound);\r\n\r\n            respone.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_status_code_int()\r\n        {\r\n            var respone = new Response();\r\n\r\n            var result = respone.WithStatusCode(404);\r\n\r\n            respone.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        private string GetLocation()\r\n        {\r\n#if CORE\r\n            return Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.ApplicationBasePath;\r\n#else\r\n            return Path.GetDirectoryName(this.GetType().Assembly.Location);\r\n#endif\r\n        }\r\n\r\n        private string GetFilePath()\r\n        {\r\n#if CORE\r\n            return Path.Combine(\"Resources\", \"test.txt\");\r\n#else\r\n            return Path.GetFileName(this.GetType().Assembly.Location);\r\n#endif\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/ResponseFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit\r\n{\r\n    using System;\r\n\r\n    using Nancy.Cookies;\r\n    using Nancy.Tests.Extensions;\r\n\r\n    using Xunit;\r\n\r\n    public class ResponseFixture\r\n    {\r\n        [Fact]\r\n        public void Should_set_empty_content_on_new_instance()\r\n        {\r\n            // Given\r\n            var response = new Response();\r\n\r\n            // When\r\n            var content = response.GetStringContentsFromResponse();\r\n\r\n            // Then\r\n            content.ShouldBeEmpty();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_content_type_to_text_html_on_new_instance()\r\n        {\r\n            // Given, When\r\n            var response = new Response();\r\n\r\n            // Then\r\n            response.ContentType.ShouldEqual(\"text/html\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_status_code_ok_on_new_instance()\r\n        {\r\n            // Given, When\r\n            var response = new Response();\r\n\r\n            // Then\r\n            response.StatusCode.ShouldEqual(HttpStatusCode.OK);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_make_headers_null_on_new_instance()\r\n        {\r\n            // Given, When\r\n            var response = new Response();\r\n\r\n            // Then\r\n            response.Headers.ShouldNotBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_status_code_when_implicitly_cast_from_int()\r\n        {\r\n            // Given, When\r\n            Response response = 200;\r\n\r\n            // Then\r\n            response.StatusCode.ShouldEqual(HttpStatusCode.OK);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_empty_content_when_implicitly_cast_from_int()\r\n        {\r\n            // Arrange\r\n            Response response = 200;\r\n\r\n            // Act\r\n            var output = response.GetStringContentsFromResponse();\r\n\r\n            // Assert\r\n            output.ShouldBeEmpty();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_content_type_to_text_html_when_implicitly_cast_from_int()\r\n        {\r\n            // Arrange, Act\r\n            Response response = 200;\r\n\r\n            // Assert\r\n            response.ContentType.ShouldEqual(\"text/html\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_status_code_when_implicitly_cast_from_http_status_code()\r\n        {\r\n            // Given, When\r\n            Response response = HttpStatusCode.NotFound;\r\n\r\n            // Then\r\n            response.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_empty_content_when_implicitly_cast_from_http_status_code()\r\n        {\r\n            // Arrange\r\n            Response response = HttpStatusCode.OK;\r\n\r\n            // Act\r\n            var output = response.GetStringContentsFromResponse();\r\n\r\n            // Assert\r\n            output.ShouldBeEmpty();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_content_type_to_text_html_when_implicitly_cast_from_http_status_code()\r\n        {\r\n            // Arrange, Act\r\n            Response response = HttpStatusCode.OK;\r\n\r\n            // Assert\r\n            response.ContentType.ShouldEqual(\"text/html\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_status_code_to_ok_when_implicitly_cast_from_string()\r\n        {\r\n            // Given, When\r\n            const string value = \"test value\";\r\n            Response response = value;\r\n\r\n            // Then\r\n            response.StatusCode.ShouldEqual(HttpStatusCode.OK);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_content_when_implicitly_cast_from_string()\r\n        {\r\n            // Given\r\n            const string value = \"test value\";\r\n            Response response = value;\r\n\r\n            // When\r\n            var output = response.GetStringContentsFromResponse();\r\n\r\n            // Then\r\n            output.ShouldEqual(value);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_content_type_to_text_plain_when_implicitly_cast_from_string()\r\n        {\r\n            // Given, When\r\n            const string value = \"test value\";\r\n            Response response = value;\r\n\r\n            // Then\r\n            response.ContentType.ShouldEqual(\"text/plain; charset=utf-8\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_overwrite_content_type_from_headers()\r\n        {\r\n            // Given\r\n            const string value = \"test value\";\r\n            Response response = value;\r\n\r\n            // When\r\n            response.Headers.Add(\"contenT-typE\", \"application/json\");\r\n\r\n            // Then\r\n            response.ContentType.ShouldEqual(\"application/json\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_a_cookie_with_name_and_value()\r\n        {\r\n\t\t\t// Given\r\n            var response = new Response();\r\n\r\n\t\t\t// When\r\n            response.WithCookie(\"itsover\", \"9000\");\r\n\r\n\t\t\t// Then\r\n            response.Cookies.Count.ShouldEqual(1);\r\n            ValidateCookie(response.Cookies[0], \"itsover\", \"9000\", null, null, null);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_a_cookie_with_name_and_value_and_expiry()\r\n        {\r\n\t\t\t// Given\r\n            var response = new Response();\r\n            var date = DateTime.Now;\r\n\r\n\t\t\t// When\r\n            response.WithCookie(\"itsover\", \"9000\", date);\r\n\r\n\t\t\t// Then\r\n            response.Cookies.Count.ShouldEqual(1);\r\n            ValidateCookie(response.Cookies[0], \"itsover\", \"9000\", date, null, null);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_a_cookie_with_everything()\r\n        {\r\n\t\t\t// Given\r\n            var response = new Response();\r\n            var date = DateTime.Now;\r\n\r\n\t\t\t// When\r\n            response.WithCookie(\"itsover\", \"9000\", date, \"life\", \"/andeverything\");\r\n\r\n\t\t\t// Then\r\n            response.Cookies.Count.ShouldEqual(1);\r\n            ValidateCookie(response.Cookies[0], \"itsover\", \"9000\", date, \"life\", \"/andeverything\");\r\n        }\r\n\r\n\t\tprivate static void ValidateCookie(INancyCookie cookie, string name, string value, DateTime? expires, string domain, string path)\r\n        {\r\n            cookie.Name.ShouldEqual(name);\r\n            cookie.Value.ShouldEqual(value);\r\n            cookie.Expires.ShouldEqual(expires);\r\n            cookie.Domain.ShouldEqual(domain);\r\n            cookie.Path.ShouldEqual(path);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Responses/DefaultJsonSerializerFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Responses\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Text;\r\n    using Nancy.Configuration;\r\n    using Nancy.Json;\r\n    using Nancy.Responses;\r\n    using Xunit;\r\n\r\n    public class DefaultJsonSerializerFixture\r\n    {\r\n        [Fact]\r\n        public void Should_camel_case_property_names_by_default()\r\n        {\r\n            // Given\r\n            var input = new { FirstName = \"Joe\", lastName = \"Doe\" };\r\n            var serializer = new DefaultJsonSerializer(GetTestableEnvironment());\r\n\r\n            // When\r\n            var output = new MemoryStream();\r\n            serializer.Serialize(\"application/json\", input, output);\r\n            var actual = Encoding.UTF8.GetString(output.ToArray());\r\n\r\n            // Then\r\n            actual.ShouldEqual(\"{\\\"firstName\\\":\\\"Joe\\\",\\\"lastName\\\":\\\"Doe\\\"}\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_camel_case_field_names_by_default()\r\n        {\r\n            // Given\r\n            var input = new PersonWithFields { FirstName = \"Joe\", LastName = \"Doe\" };\r\n            var serializer = new DefaultJsonSerializer(GetTestableEnvironment());\r\n\r\n            // When\r\n            var output = new MemoryStream();\r\n            serializer.Serialize(\"application/json\", input, output);\r\n            var actual = Encoding.UTF8.GetString(output.ToArray());\r\n\r\n            // Then\r\n            actual.ShouldEqual(\"{\\\"firstName\\\":\\\"Joe\\\",\\\"lastName\\\":\\\"Doe\\\"}\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_camel_case_dictionary_keys_by_default()\r\n        {\r\n            // Given\r\n            var input = new Dictionary<string, object>\r\n            {\r\n                { \"Joe\", new PersonWithFields { FirstName = \"Joe\" } },\r\n                { \"John\", new PersonWithFields { FirstName = \"John\" } }\r\n            };\r\n\r\n            var serializer = new DefaultJsonSerializer(GetTestableEnvironment());\r\n\r\n            // When\r\n            var output = new MemoryStream();\r\n            serializer.Serialize(\"application/json\", input, output);\r\n            var actual = Encoding.UTF8.GetString(output.ToArray());\r\n\r\n            // Then\r\n            actual.ShouldEqual(\"{\\\"joe\\\":{\\\"firstName\\\":\\\"Joe\\\",\\\"lastName\\\":null},\\\"john\\\":{\\\"firstName\\\":\\\"John\\\",\\\"lastName\\\":null}}\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_change_casing_when_retain_casing_is_true()\r\n        {\r\n            // Given\r\n            var input = new {FirstName = \"Joe\", lastName = \"Doe\"};\r\n            var environment = GetTestableEnvironment(x =>\r\n            {\r\n                x.Json(retainCasing: true);\r\n                x.Globalization(new []{ \"en-US\" });\r\n            });\r\n            var serializer = new DefaultJsonSerializer(environment);\r\n\r\n            // When\r\n            var output = new MemoryStream();\r\n            serializer.Serialize(\"application/json\", input, output);\r\n            var actual = Encoding.UTF8.GetString(output.ToArray());\r\n\r\n            // Then\r\n            actual.ShouldEqual(\"{\\\"FirstName\\\":\\\"Joe\\\",\\\"lastName\\\":\\\"Doe\\\"}\");\r\n        }\r\n\r\n        public class PersonWithFields\r\n        {\r\n            public string FirstName;\r\n            public string LastName;\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_iso8601_datetimes_by_default()\r\n        {\r\n            // Given\r\n            var serializer = new DefaultJsonSerializer(GetTestableEnvironment());\r\n            var input = new\r\n            {\r\n                UnspecifiedDateTime = new DateTime(2014, 3, 9, 17, 03, 25).AddMilliseconds(234),\r\n                LocalDateTime = new DateTime(2014, 3, 9, 17, 03, 25, DateTimeKind.Local).AddMilliseconds(234),\r\n                UtcDateTime = new DateTime(2014, 3, 9, 16, 03, 25, DateTimeKind.Utc).AddMilliseconds(234)\r\n            };\r\n\r\n            // When\r\n            var output = new MemoryStream();\r\n            serializer.Serialize(\"application/json\", input, output);\r\n            var actual = Encoding.UTF8.GetString(output.ToArray());\r\n\r\n            // Then\r\n            actual.ShouldEqual(string.Format(@\"{{\"\"unspecifiedDateTime\"\":\"\"2014-03-09T17:03:25.2340000{0}\"\",\"\"localDateTime\"\":\"\"2014-03-09T17:03:25.2340000{0}\"\",\"\"utcDateTime\"\":\"\"2014-03-09T16:03:25.2340000Z\"\"}}\",\r\n                GetTimezoneSuffix(input.LocalDateTime, \":\")));\r\n        }\r\n\r\n        private static INancyEnvironment GetTestableEnvironment()\r\n        {\r\n            return GetTestableEnvironment(env =>\r\n            {\r\n                env.Json();\r\n                env.Globalization(new []{\"en-US\"});\r\n            });\r\n        }\r\n\r\n        private static INancyEnvironment GetTestableEnvironment(Action<INancyEnvironment> closure)\r\n        {\r\n            var environment =\r\n                new DefaultNancyEnvironment();\r\n\r\n            environment.Tracing(\r\n                enabled: true,\r\n                displayErrorTraces: true);\r\n\r\n            closure.Invoke(environment);\r\n\r\n            return environment;\r\n        }\r\n\r\n        private static string GetTimezoneSuffix(DateTime value, string separator = \"\")\r\n        {\r\n            string suffix;\r\n\t\t    var time = value.ToUniversalTime();\r\n\t\t    TimeSpan localTZOffset;\r\n\t\t    if (value >= time)\r\n\t\t    {\r\n\t\t        localTZOffset = value - time;\r\n\t\t        suffix = \"+\";\r\n\t\t    }\r\n\t\t    else\r\n\t\t    {\r\n\t\t        localTZOffset = time - value;\r\n\t\t        suffix = \"-\";\r\n\t\t    }\r\n            return suffix + localTZOffset.ToString(\"hh\") + separator + localTZOffset.ToString(\"mm\");\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Responses/EmbeddedFileResponseFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Responses\r\n{\r\n    using System.IO;\r\n\r\n    using Nancy.Extensions;\r\n    using Nancy.Responses;\r\n\r\n    using Xunit;\r\n\r\n    public class EmbeddedFileResponseFixture\r\n    {\r\n        [Fact]\r\n        public void Should_contain_etag_in_response_header_if_embedded_resource_exists()\r\n        {\r\n            // Given, when\r\n            var response =\r\n                new EmbeddedFileResponse(this.GetType().GetAssembly(), \"Nancy.Tests\", \"Resources.Views.staticviewresource.html\");\r\n\r\n            // Then\r\n            response.Headers[\"ETag\"].ShouldEqual(\"\\\"B9D9DC2B50ADFD0867749D4837C63556339080CE\\\"\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_contain_etag_in_response_header_if_embedded_resource_exists_when_invoking()\r\n        {\r\n            // Given\r\n            var response =\r\n                new EmbeddedFileResponse(this.GetType().GetAssembly(), \"Nancy.Tests\", \"Resources.Views.staticviewresource.html\");\r\n\r\n            var outputStream = new MemoryStream();\r\n\r\n            // when\r\n            response.Contents.Invoke(outputStream);\r\n\r\n            // Then\r\n            response.Headers[\"ETag\"].ShouldEqual(\"\\\"B9D9DC2B50ADFD0867749D4837C63556339080CE\\\"\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_contain_etag_in_response_header_if_embedded_resource_does_not_exists()\r\n        {\r\n            // Given, when\r\n            var response =\r\n                new EmbeddedFileResponse(this.GetType().GetAssembly(), \"Nancy.Tests\", \"i_dont_exist.jpg\");\r\n\r\n            // Then\r\n            response.Headers.ContainsKey(\"ETag\").ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_contain_etag_in_response_header_if_embedded_resource_does_not_exists_when_invoking()\r\n        {\r\n            // Given\r\n            var response =\r\n                new EmbeddedFileResponse(this.GetType().GetAssembly(), \"Nancy.Tests\", \"i_dont_exist.jpg\");\r\n\r\n            var outputStream = new MemoryStream();\r\n\r\n            // when\r\n            response.Contents.Invoke(outputStream);\r\n\r\n            // Then\r\n            response.Headers.ContainsKey(\"ETag\").ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_ignore_casing_in_resource_name_if_embedded_resource_exists()\r\n        {\r\n            // Given, when\r\n            var response =\r\n                new EmbeddedFileResponse(this.GetType().GetAssembly(), \"nancy.tests\", \"Resources.Views.staticviewresource.html\");\r\n\r\n            // Then\r\n            response.Headers[\"ETag\"].ShouldEqual(\"\\\"B9D9DC2B50ADFD0867749D4837C63556339080CE\\\"\");\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Responses/GenericFileResponseFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Responses\r\n{\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using Nancy.Configuration;\r\n    using Nancy.Responses;\r\n    using Xunit;\r\n    using Xunit.Abstractions;\r\n\r\n    public class GenericFileResponseFixture\r\n    {\r\n        private readonly string filePath;\r\n        private readonly string fileContentType = \"foo/bar\";\r\n        private readonly NancyContext context;\r\n\r\n        public GenericFileResponseFixture(ITestOutputHelper output)\r\n        {\r\n            var environment = new DefaultNancyEnvironment();\r\n            environment.StaticContent(safepaths: this.GetLocation());\r\n\r\n            this.context = new NancyContext { Environment = environment };\r\n\r\n            this.filePath = this.GetFilePath();\r\n        }\r\n\r\n        private string GetLocation()\r\n        {\r\n#if CORE\r\n            return Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.ApplicationBasePath;\r\n#else\r\n            return Path.GetDirectoryName(this.GetType().Assembly.Location);\r\n#endif\r\n        }\r\n\r\n        private string GetFilePath()\r\n        {\r\n#if CORE\r\n            return Path.Combine(\"Resources\", \"test.txt\");\r\n#else\r\n            return Path.GetFileName(this.GetType().Assembly.Location);\r\n#endif\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_status_code_to_not_found_when_file_name_is_empty()\r\n        {\r\n            // Given, When\r\n            var response = new GenericFileResponse(string.Empty, this.fileContentType, this.context);\r\n\r\n            // Then\r\n            response.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_status_code_to_not_found_when_file_name_is_null()\r\n        {\r\n            // Given, When\r\n            var response = new GenericFileResponse(null, this.fileContentType, this.context);\r\n\r\n            // Then\r\n            response.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_status_code_to_not_found_when_file_name_does_not_contain_extension()\r\n        {\r\n            // Given\r\n            var fileNameWithoutExtensions = Path.GetFileNameWithoutExtension(this.filePath);\r\n\r\n            // When\r\n            var response = new GenericFileResponse(fileNameWithoutExtensions, this.fileContentType, this.context);\r\n\r\n            // Then\r\n            response.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_status_code_to_not_found_when_file_does_not_exist()\r\n        {\r\n            // Given\r\n            // When\r\n            var response = new GenericFileResponse(\"nancy\", this.fileContentType, this.context);\r\n\r\n            // Then\r\n            response.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_status_code_to_not_found_when_file_is_above_root_path()\r\n        {\r\n            // Given\r\n            var path =\r\n                Path.Combine(this.filePath, \"..\", \"..\");\r\n\r\n            // When\r\n            var response = new GenericFileResponse(path, this.fileContentType, this.context);\r\n\r\n            // Then\r\n            response.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_status_code_to_ok()\r\n        {\r\n            // Given\r\n            // When\r\n            var response = new GenericFileResponse(this.filePath, \"text/plain\", this.context);\r\n\r\n            // Then\r\n            response.StatusCode.ShouldEqual(HttpStatusCode.OK);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_file_unchanged()\r\n        {\r\n            // Given\r\n            var path = Path.Combine(this.GetLocation(), this.filePath);\r\n            var expected = File.ReadAllBytes(path);\r\n            var response = new GenericFileResponse(this.filePath, this.fileContentType, this.context);\r\n\r\n            // When\r\n            var result = GetResponseContents(response);\r\n\r\n            // Then\r\n            result.ShouldEqualSequence(expected);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_filename_property_to_filename()\r\n        {\r\n            // Given\r\n            // When\r\n            var response = new GenericFileResponse(this.filePath, this.fileContentType, this.context);\r\n\r\n            // Then\r\n            response.Filename.ShouldEqual(Path.GetFileName(this.filePath));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_contain_etag_in_response_header()\r\n        {\r\n            // Given\r\n            // When\r\n            var response = new GenericFileResponse(this.filePath, this.fileContentType, this.context);\r\n\r\n            // Then\r\n            response.Headers[\"ETag\"].ShouldStartWith(\"\\\"\");\r\n            response.Headers[\"ETag\"].ShouldEndWith(\"\\\"\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_content_length_in_response_header()\r\n        {\r\n            // Given, when\r\n            var path = Path.Combine(this.GetLocation(), this.filePath);\r\n            var expected = new FileInfo(path).Length.ToString();\r\n            var response = new GenericFileResponse(this.filePath, this.fileContentType, this.context);\r\n\r\n            // Then\r\n            response.Headers[\"Content-Length\"].ShouldEqual(expected);\r\n        }\r\n\r\n        private static IEnumerable<byte> GetResponseContents(Response response)\r\n        {\r\n            var ms = new MemoryStream();\r\n            response.Contents(ms);\r\n            ms.Flush();\r\n\r\n            return ms.ToArray();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Responses/Negotiation/DefaultResponseNegotiatorFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Responses.Negotiation\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    using Nancy.Responses.Negotiation;\r\n\r\n    using Xunit;\r\n\r\n    public class DefaultResponseNegotiatorFixture\r\n    {\r\n        [Fact]\r\n        public void Should_encode_URL_in_Link_response_header()\r\n        {\r\n            // Given\r\n            var negotiator = new DefaultResponseNegotiatorWrapper();\r\n            var requestUrl = new Uri(\"http://localhost:80/george-å\");\r\n            var range = new MediaRange(\"application/vnd.nancy\");\r\n            var linkProcessor = new KeyValuePair<string, MediaRange>(\"nancy\", range);\r\n\r\n            // When\r\n            var linkHeader = negotiator.CreateLinkHeaderWrapper(requestUrl, new[] { linkProcessor }, null);\r\n\r\n            // Then\r\n            Assert.DoesNotContain(\"å\", linkHeader, StringComparison.InvariantCultureIgnoreCase);\r\n            Assert.Contains(\"%C3%A5\", linkHeader, StringComparison.InvariantCultureIgnoreCase);\r\n        }\r\n\r\n        private class DefaultResponseNegotiatorWrapper : DefaultResponseNegotiator\r\n        {\r\n            public DefaultResponseNegotiatorWrapper()\r\n                : base(Enumerable.Empty<IResponseProcessor>(), null)\r\n            {\r\n            }\r\n\r\n            public string CreateLinkHeaderWrapper(Url requestUrl, IEnumerable<KeyValuePair<string, MediaRange>> linkProcessors, string existingLinkHeader)\r\n            {\r\n                return base.CreateLinkHeader(requestUrl, linkProcessors, existingLinkHeader);\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Responses/Negotiation/MediaRangeFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Responses.Negotiation\r\n{\r\n    using System.Linq;\r\n\r\n    using Nancy.Responses.Negotiation;\r\n\r\n    using Xunit;\r\n\r\n    public class MediaRangeFixture\r\n    {\r\n        [Fact]\r\n        public void Should_parse_media_range_parameters()\r\n        {\r\n            // When\r\n            var range = new MediaRange(\"application/vnd.nancy;a=1;b=2\");\r\n\r\n            // Then\r\n            range.Parameters.Keys.ElementAt(0).ShouldEqual(\"a\");\r\n            range.Parameters.Keys.ElementAt(1).ShouldEqual(\"b\");\r\n            range.Parameters.Values.ElementAt(0).ShouldEqual(\"1\");\r\n            range.Parameters.Values.ElementAt(1).ShouldEqual(\"2\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_match_with_parameters_if_parameters_match()\r\n        {\r\n            // Given\r\n            var range1 = new MediaRange(\"application/vnd.nancy;a=1;b=2\");\r\n            var range2 = new MediaRange(\"application/vnd.nancy;a=1;b=2\");\r\n\r\n            // Then\r\n            range1.MatchesWithParameters(range2).ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_match_with_parameters_if_parameters_do_not_match()\r\n        {\r\n            // Given\r\n            var range1 = new MediaRange(\"application/vnd.nancy;a=1;b=2\");\r\n            var range2 = new MediaRange(\"application/vnd.nancy;a=1;b=2;c=3\");\r\n\r\n            // Then\r\n            range1.MatchesWithParameters(range2).ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_match_with_parameters_if_parameters_match_in_any_order()\r\n        {\r\n            // Given\r\n            var range1 = new MediaRange(\"application/vnd.nancy;a=1;b=2\");\r\n            var range2 = new MediaRange(\"application/vnd.nancy;b=2;a=1\");\r\n\r\n            // Then\r\n            range1.MatchesWithParameters(range2).ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_handle_no_parameters_when_calling_tostring()\r\n        {\r\n            // Given\r\n            var range = new MediaRange(\"application/vnd.nancy\");\r\n\r\n            // Then\r\n            range.ToString().ShouldEqual(\"application/vnd.nancy\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_include_parameters_when_calling_tostring()\r\n        {\r\n            // Given\r\n            var range = new MediaRange(\"application/vnd.nancy;a=1;b=2\");\r\n\r\n            // Then\r\n            range.ToString().ShouldEqual(\"application/vnd.nancy;a=1;b=2\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_strip_whitespace_when_calling_tostring()\r\n        {\r\n            // Given\r\n            var range = new MediaRange(\"application/vnd.nancy ; a=1; b=2\");\r\n\r\n            // Then\r\n            range.ToString().ShouldEqual(\"application/vnd.nancy;a=1;b=2\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_cast_to_null_string()\r\n        {\r\n            // Given\r\n            MediaRange range = null;\r\n\r\n            // When\r\n            string cast = (string)range;\r\n\r\n            // Then\r\n            Assert.Null(cast);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Responses/RedirectResponseFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Responses\r\n{\r\n    using Nancy.Responses;\r\n\r\n    using Xunit;\r\n\r\n    public class RedirectResponseFixture\r\n    {\r\n        [Fact]\r\n        public void Permanent_redirect_should_return_status_code_301()\r\n        {\r\n            var response = new RedirectResponse(\"/\", RedirectResponse.RedirectType.Permanent);\r\n            response.StatusCode.ShouldEqual(HttpStatusCode.MovedPermanently);\r\n        }\r\n\r\n        [Fact]\r\n        public void Temporary_redirect_should_return_status_code_307()\r\n        {\r\n            var response = new RedirectResponse(\"/\", RedirectResponse.RedirectType.Temporary);\r\n            response.StatusCode.ShouldEqual(HttpStatusCode.TemporaryRedirect);\r\n        }\r\n\r\n        [Fact]\r\n        public void SeeOther_redirect_should_return_status_code_303()\r\n        {\r\n            var response = new RedirectResponse(\"/\", RedirectResponse.RedirectType.SeeOther);\r\n            response.StatusCode.ShouldEqual(HttpStatusCode.SeeOther);\r\n        }\r\n\r\n        [Fact]\r\n        public void Default_redirect_should_return_status_code_303()\r\n        {\r\n            var response = new RedirectResponse(\"/\");\r\n            response.StatusCode.ShouldEqual(HttpStatusCode.SeeOther);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Responses/StreamResponseFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Responses\r\n{\r\n    using System;\r\n    using System.IO;\r\n    using FakeItEasy;\r\n    using Nancy.Responses;\r\n    using Xunit;\r\n\r\n    public class StreamResponseFixture\r\n    {\r\n        [Fact]\r\n        public void Should_copy_stream_to_output_when_body_invoked()\r\n        {\r\n            // Given\r\n            var streamContent =\r\n                new byte[] { 1, 2, 3, 4, 5 };\r\n\r\n            var inputStream =\r\n                new MemoryStream(streamContent);\r\n\r\n            var response =\r\n                new StreamResponse(() => inputStream, \"test\");\r\n\r\n            var outputStream = new MemoryStream();\r\n\r\n            // When\r\n            response.Contents.Invoke(outputStream);\r\n\r\n            // Then\r\n            outputStream.ToArray().ShouldEqualSequence(streamContent);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_content_of_stream_from_current_location_of_stream()\r\n        {\r\n            // Given\r\n            var streamContent =\r\n                new byte[] { 1, 2, 3, 4, 5 };\r\n\r\n            var inputStream =\r\n                new MemoryStream(streamContent) { Position = 2 };\r\n\r\n            var response =\r\n                new StreamResponse(() => inputStream, \"test\");\r\n\r\n            var outputStream = new MemoryStream();\r\n\r\n            var expectedContent =\r\n                new byte[] { 3, 4, 5 };\r\n\r\n            // When\r\n            response.Contents.Invoke(outputStream);\r\n\r\n            // Then\r\n            outputStream.ToArray().ShouldEqualSequence(expectedContent);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_exception_when_stream_is_non_readable()\r\n        {\r\n            // Given\r\n            var inputStream =\r\n                new TestStream(canRead: false);\r\n\r\n            var response =\r\n                new StreamResponse(() => inputStream, \"test\");\r\n\r\n            var outputStream = new MemoryStream();\r\n\r\n            // When\r\n            var exception = Record.Exception(() => response.Contents.Invoke(outputStream));\r\n\r\n            // Then\r\n            exception.ShouldNotBeNull();\r\n        }\r\n\r\n        public class TestStream : Stream\r\n        {\r\n            public TestStream(bool canRead = true, bool canWrite = true)\r\n            {\r\n                this.CanRead = canRead;\r\n                this.CanWrite = canWrite;\r\n            }\r\n\r\n            public override bool CanRead { get; }\r\n\r\n            public override bool CanSeek\r\n            {\r\n                get { return true; }\r\n            }\r\n\r\n            public override bool CanWrite  { get; }\r\n\r\n            public override long Length\r\n            {\r\n                get { return 0; }\r\n            }\r\n\r\n            public override long Position\r\n            {\r\n                get { return 0; }\r\n                set { }\r\n            }\r\n\r\n            public override void Flush()\r\n            {\r\n            }\r\n            public override int Read(byte[] buffer, int offset, int count)\r\n            {\r\n                return 0;\r\n            }\r\n\r\n            public override long Seek(long offset, SeekOrigin origin)\r\n            {\r\n                return 0;\r\n            }\r\n\r\n            public override void SetLength(long value)\r\n            {\r\n            }\r\n\r\n            public override void Write(byte[] buffer, int offset, int count)\r\n            {\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Responses/TextResponseFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Responses\r\n{\r\n    using System.IO;\r\n    using System.Text;\r\n\r\n    using Nancy.Responses;\r\n\r\n    using Xunit;\r\n\r\n    public class TextResponseFixture\r\n    {\r\n        [Fact]\r\n        public void Should_copy_text_when_body_invoked()\r\n        {\r\n            // Given\r\n            var text\r\n                = \"sample text\";\r\n\r\n            var response =\r\n                new TextResponse(text);\r\n\r\n            var outputStream = new MemoryStream();\r\n\r\n            // When\r\n            response.Contents.Invoke(outputStream);\r\n\r\n            // Then\r\n            outputStream.ToArray().ShouldEqualSequence(Encoding.UTF8.GetBytes(text));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_0_when_text_is_null_and_body_invoked()\r\n        {\r\n            // Given\r\n            string text\r\n                = null;\r\n\r\n            var response =\r\n                new TextResponse(text);\r\n\r\n            var outputStream = new MemoryStream();\r\n\r\n            // When\r\n            response.Contents.Invoke(outputStream);\r\n\r\n            // then\r\n            outputStream.ToArray().Length.ShouldEqual(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_0_when_text_is_empty_and_body_invoked()\r\n        {\r\n            // Given\r\n            string text\r\n                = string.Empty;\r\n\r\n            var response =\r\n                new TextResponse(text);\r\n\r\n            var outputStream = new MemoryStream();\r\n\r\n            // When\r\n            response.Contents.Invoke(outputStream);\r\n\r\n            // then\r\n            outputStream.ToArray().Length.ShouldEqual(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_content_type_to_text_plain()\r\n        {\r\n            // Given\r\n            string text =\r\n                \"sample text\";\r\n\r\n            var response =\r\n                new TextResponse(text);\r\n\r\n            var outputStream = new MemoryStream();\r\n\r\n            // When\r\n            response.Contents.Invoke(outputStream);\r\n\r\n            // Then\r\n            response.ContentType.ShouldEqual(\"text/plain; charset=utf-8\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_override_content_type()\r\n        {\r\n            // Given\r\n            const string text = \"sample text\";\r\n\r\n            var response =\r\n                new TextResponse(text, \"text/cache-manifest\");\r\n\r\n            var outputStream = new MemoryStream();\r\n\r\n            // When\r\n            response.Contents.Invoke(outputStream);\r\n\r\n            // Then\r\n            response.ContentType.ShouldEqual(\"text/cache-manifest; charset=utf-8\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_include_webname_for_custom_encoding()\r\n        {\r\n            // Given\r\n            string text =\r\n                \"sample text\";\r\n\r\n            var response =\r\n                new TextResponse(text, encoding: Encoding.Unicode);\r\n\r\n            var outputStream = new MemoryStream();\r\n\r\n            // When\r\n            response.Contents.Invoke(outputStream);\r\n\r\n            // Then\r\n            response.ContentType.ShouldEqual(\"text/plain; charset=utf-16\");\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Routing/ConstraintNodeRouteResolverFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Routing\r\n{\r\n    using System;\r\n    using System.Globalization;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Helpers;\r\n    using Nancy.Testing;\r\n\r\n    using Xunit;\r\n\r\n    public class ConstraintNodeRouteResolverFixture\r\n    {\r\n        private readonly Browser browser;\r\n\r\n        public ConstraintNodeRouteResolverFixture()\r\n        {\r\n            // Given\r\n            this.browser = new Browser(with => with.Module<TestModule>());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_resolve_int_constraint()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/intConstraint/1\");\r\n\r\n            // Then\r\n            result.Body.AsString().ShouldEqual(\"IntConstraint\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task When_int_is_larger_than_max_int_should_has_no_match()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/intConstraint/\" + long.MaxValue);\r\n\r\n            // Then\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n            result.Body.AsString().ShouldEqual(\"\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_resolve_long_constraint()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/longConstraint/\" + long.MaxValue);\r\n\r\n            // Then\r\n            result.Body.AsString().ShouldEqual(\"LongConstraint\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_resolve_int_constraint()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/intConstraint/foo\");\r\n\r\n            // Then\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_resolve_decimal_constraint()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/decimalConstraint/1.1\");\r\n\r\n            // Then\r\n            result.Body.AsString().ShouldEqual(\"DecimalConstraint\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_resolve_decimal_constraint()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/decimalConstraint/foo\");\r\n\r\n            // Then\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_resolve_guid_constraint()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/guidConstraint/87f8df5d-3c08-49fd-8961-d85b0984e006\");\r\n\r\n            // Then\r\n            result.Body.AsString().ShouldEqual(\"GuidConstraint\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_resolve_guid_constraint()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/guidConstraint/87f8df5d-3c08-49fd-8961-d85b0984e006d\");\r\n\r\n            // Then\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_resolve_bool_constraint()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/boolConstraint/true\");\r\n\r\n            // Then\r\n            result.Body.AsString().ShouldEqual(\"BoolConstraint\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_resolve_bool_constraint()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/boolConstraint/foo\");\r\n\r\n            // Then\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_resolve_alpha_constraint()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/alphaConstraint/foo\");\r\n\r\n            // Then\r\n            result.Body.AsString().ShouldEqual(\"AlphaConstraint\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_resolve_alpha_constraint()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/alphaConstraint/1\");\r\n\r\n            // Then\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_resolve_datetime_constraint()\r\n        {\r\n            // When\r\n            var dateTime = new DateTime(2010, 1, 2, 3, 4, 5, 6);\r\n            var urlEncodeDateTime = HttpUtility.UrlEncode(dateTime.ToString(\"yyyy-MM-dd hh:mm:ss\", CultureInfo.InvariantCulture));\r\n            var result = await this.browser.Get(\"/datetimeConstraint/\" + urlEncodeDateTime);\r\n\r\n            // Then\r\n            result.Body.AsString().ShouldEqual(\"2010-01-02 03:04:05\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_resolve_datetime_constraint()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/DateTimeConstraint/1\");\r\n\r\n            // Then\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_resolve_min_constraint()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/minConstraint/5\");\r\n\r\n            // Then\r\n            result.Body.AsString().ShouldEqual(\"MinConstraint\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_resolve_min_constraint()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/minConstraint/1\");\r\n\r\n            // Then\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_resolve_custom_datetime_constraint()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/customDatetimeConstraint/2013-10-02\");\r\n\r\n            // Then\r\n            result.Body.AsString().ShouldEqual(\"CustomDateTimeConstraint\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_resolve_custom_datetime_constraint()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/customDatetimeConstraint/2013-20-02\");\r\n\r\n            // Then\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_resolve_min_constraint_as_string()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/minConstraint/foo\");\r\n\r\n            // Then\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_resolve_max_constraint()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/maxConstraint/4\");\r\n\r\n            // Then\r\n            result.Body.AsString().ShouldEqual(\"MaxConstraint\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_resolve_max_constraint()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/maxConstraint/7\");\r\n\r\n            // Then\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_resolve_max_constraint_as_string()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/maxConstraint/foo\");\r\n\r\n            // Then\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_resolve_range_constraint()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/rangeConstraint/15\");\r\n\r\n            // Then\r\n            result.Body.AsString().ShouldEqual(\"RangeConstraint\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_resolve_range_constraint_as_too_low()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/rangeConstraint/1\");\r\n\r\n            // Then\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_resolve_range_constraint_as_too_high()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/rangeConstraint/30\");\r\n\r\n            // Then\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_resolve_range_constraint_as_string()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/rangeConstraint/foo\");\r\n\r\n            // Then\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_resolve_minlength_constraint()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/minlengthConstraint/foobar\");\r\n\r\n            // Then\r\n            result.Body.AsString().ShouldEqual(\"MinLengthConstraint\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_resolve_minlength_constraint()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/minLengthConstraint/foo\");\r\n\r\n            // Then\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_resolve_maxlength_constraint()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/maxlengthConstraint/foobar\");\r\n\r\n            // Then\r\n            result.Body.AsString().ShouldEqual(\"MaxLengthConstraint\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_resolve_maxlength_constraint()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/maxlengthConstraint/foobarfoobar\");\r\n\r\n            // Then\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_resolve_length_constraint_max_only()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/lengthMaxOnlyConstraint/foobarfoobar\");\r\n\r\n            // Then\r\n            result.Body.AsString().ShouldEqual(\"LengthMaxOnlyConstraint\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_resolve_range_constraint_max_only_as_too_high()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/lengthMaxOnlyConstraint/foobarfoobarfoobarfoobar\");\r\n\r\n            // Then\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_resolve_length_constraint()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/lengthConstraint/foobar\");\r\n\r\n            // Then\r\n            result.Body.AsString().ShouldEqual(\"LengthConstraint\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_resolve_length_constraint_as_too_low()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/lengthConstraint/foo\");\r\n\r\n            // Then\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_resolve_length_constraint_as_too_high()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/lengthConstraint/foobarfoobarfoobarfoobar\");\r\n\r\n            // Then\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_be_case_insensitive()\r\n        {\r\n            // When\r\n            var result = await this.browser.Get(\"/caseInsensitive/foobarfoobar\");\r\n\r\n            // Then\r\n            result.Body.AsString().ShouldEqual(\"CaseInsensitive\");\r\n        }\r\n\r\n        private class TestModule : NancyModule\r\n        {\r\n            public TestModule()\r\n            {\r\n                Get(\"/intConstraint/{value:int}\", args => \"IntConstraint\");\r\n\r\n                Get(\"/longConstraint/{value:long}\", args => \"LongConstraint\");\r\n\r\n                Get(\"/decimalConstraint/{value:decimal}\", args => \"DecimalConstraint\");\r\n\r\n                Get(\"/guidConstraint/{value:guid}\", args => \"GuidConstraint\");\r\n\r\n                Get(\"/boolConstraint/{value:bool}\", args => \"BoolConstraint\");\r\n\r\n                Get(\"/alphaConstraint/{value:alpha}\", args => \"AlphaConstraint\");\r\n\r\n                Get(\"/datetimeConstraint/{value:datetime}\", args => DateTime.Parse(args.value).ToString(\"yyyy-MM-dd hh:mm:ss\", CultureInfo.InvariantCulture));\r\n\r\n                Get(\"/customDatetimeConstraint/{value:datetime(yyyy-MM-dd)}\", args => \"CustomDateTimeConstraint\");\r\n\r\n                Get(\"/minConstraint/{value:min(4)}\", args => \"MinConstraint\");\r\n\r\n                Get(\"/maxConstraint/{value:max(6)}\", args => \"MaxConstraint\");\r\n\r\n                Get(\"/rangeConstraint/{value:range(10, 20)}\", args => \"RangeConstraint\");\r\n\r\n                Get(\"/minlengthConstraint/{value:minlength(4)}\", args => \"MinLengthConstraint\");\r\n\r\n                Get(\"/maxlengthConstraint/{value:maxlength(10)}\", args => \"MaxLengthConstraint\");\r\n\r\n                Get(\"/lengthMaxOnlyConstraint/{value:length(20)}\", args => \"LengthMaxOnlyConstraint\");\r\n\r\n                Get(\"/lengthConstraint/{value:length(5, 20)}\", args => \"LengthConstraint\");\r\n\r\n                Get(\"/caseInsensitive/{vAlUe:LeNgTh(5, 20)}\", args => \"CaseInsensitive\");\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Routing/ConstraintNodeRouteScoringFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Routing\r\n{\r\n    using System.Threading.Tasks;\r\n    using Nancy.Testing;\r\n\r\n    using Xunit;\r\n\r\n    public class ConstraintNodeRouteScoringFixture\r\n    {\r\n        private readonly Browser browser;\r\n\r\n        public ConstraintNodeRouteScoringFixture()\r\n        {\r\n            this.browser = new Browser(with => with.Module<TestModule>());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_constraint_route_when_satisfying_the_constraint()\r\n        {\r\n            var result = await this.browser.Get(\"/123\");\r\n\r\n            result.Body.AsString().ShouldEqual(\"constraint\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_normal_capture_route_when_constraint_is_not_satisfied()\r\n        {\r\n            var result = await this.browser.Get(\"/banana\");\r\n\r\n            result.Body.AsString().ShouldEqual(\"capture\");\r\n        }\r\n\r\n        private class TestModule : NancyModule\r\n        {\r\n            public TestModule()\r\n            {\r\n                Get(\"{value:int}\", args => \"constraint\");\r\n                Get(\"{value}\", args => \"capture\");\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Routing/DefaultNancyModuleBuilderFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Routing\r\n{\r\n    using FakeItEasy;\r\n\r\n    using Nancy.ModelBinding;\r\n    using Nancy.Routing;\r\n    using Nancy.Tests.Fakes;\r\n    using Nancy.Validation;\r\n    using Nancy.ViewEngines;\r\n\r\n    using Xunit;\r\n\r\n    public class DefaultNancyModuleBuilderFixture\r\n    {\r\n        private readonly DefaultNancyModuleBuilder builder;\r\n        private readonly IResponseFormatterFactory responseFormatterFactory;\r\n        private readonly IViewFactory viewFactory;\r\n        private readonly FakeNancyModule module;\r\n        private readonly IModelBinderLocator modelBinderLocator;\r\n        private readonly IModelValidatorLocator validatorLocator;\r\n\r\n        public DefaultNancyModuleBuilderFixture()\r\n        {\r\n            this.module = new FakeNancyModule();\r\n\r\n            this.responseFormatterFactory =\r\n                A.Fake<IResponseFormatterFactory>();\r\n\r\n            this.viewFactory = A.Fake<IViewFactory>();\r\n            this.modelBinderLocator = A.Fake<IModelBinderLocator>();\r\n            this.validatorLocator = A.Fake<IModelValidatorLocator>();\r\n\r\n            this.builder = new DefaultNancyModuleBuilder(this.viewFactory, this.responseFormatterFactory, this.modelBinderLocator, this.validatorLocator);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_instance_that_was_returned_by_module_catalog()\r\n        {\r\n            // Given\r\n            var context = new NancyContext();\r\n\r\n            // When\r\n            var result = this.builder.BuildModule(this.module, context);\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(this.module);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_context_on_module_to_provided_context_instance()\r\n        {\r\n            // Given\r\n            var context = new NancyContext();\r\n\r\n            // When\r\n            var result = this.builder.BuildModule(this.module, context);\r\n\r\n            // Then\r\n            result.Context.ShouldBeSameAs(context);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_view_factory_on_module_to_resolved_view_factory()\r\n        {\r\n            // Given\r\n            var context = new NancyContext();\r\n\r\n            // When\r\n            var result = this.builder.BuildModule(this.module, context);\r\n\r\n            // Then\r\n            result.ViewFactory.ShouldBeSameAs(this.viewFactory);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_pass_context_to_response_formatter_factory()\r\n        {\r\n            // Given\r\n            var context = new NancyContext();\r\n\r\n            // When\r\n            this.builder.BuildModule(this.module, context);\r\n\r\n            // Then\r\n            A.CallTo(() => this.responseFormatterFactory.Create(context)).MustHaveHappened();\r\n        }\r\n        \r\n        [Fact]\r\n        public void Should_set_response_on_module_to_resolved_response_formatter()\r\n        {\r\n            // Given\r\n            var context = new NancyContext();\r\n            var formatter = A.Fake<IResponseFormatter>();\r\n            A.CallTo(() => this.responseFormatterFactory.Create(context)).Returns(formatter);\r\n\r\n            // When\r\n            var result = this.builder.BuildModule(this.module, context);\r\n\r\n            // Then\r\n            result.Response.ShouldBeSameAs(formatter);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_binder_locator_on_module_to_resolved_binder_locator()\r\n        {\r\n            // Given\r\n            var context = new NancyContext();\r\n\r\n            // When\r\n            var result = this.builder.BuildModule(this.module, context);\r\n\r\n            // Then\r\n            result.ModelBinderLocator.ShouldBeSameAs(this.modelBinderLocator);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Routing/DefaultRequestDispatcherFixture.cs",
    "content": "namespace Nancy.Tests.Unit.Routing\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n    using FakeItEasy;\r\n    using Nancy.Helpers;\r\n    using Nancy.Responses.Negotiation;\r\n    using Nancy.Routing;\r\n    using Nancy.Tests.Fakes;\r\n    using Nancy.Tests.xUnitExtensions;\r\n    using Xunit;\r\n\r\n    public class DefaultRequestDispatcherFixture\r\n    {\r\n        private readonly DefaultRequestDispatcher requestDispatcher;\r\n        private readonly IRouteResolver routeResolver;\r\n        private readonly IRouteInvoker routeInvoker;\r\n        private readonly IList<IResponseProcessor> responseProcessors;\r\n        private IResponseNegotiator negotiator;\r\n\r\n        public DefaultRequestDispatcherFixture()\r\n        {\r\n            this.responseProcessors = new List<IResponseProcessor>();\r\n            this.routeResolver = A.Fake<IRouteResolver>();\r\n            this.routeInvoker = A.Fake<IRouteInvoker>();\r\n            this.negotiator = A.Fake<IResponseNegotiator>();\r\n\r\n            A.CallTo(() => this.routeInvoker.Invoke(A<Route>._, A<CancellationToken>._, A<DynamicDictionary>._, A<NancyContext>._))\r\n                .ReturnsLazily(async arg =>\r\n                {\r\n                    var routeResult = ((Route)arg.Arguments[0]).Invoke((DynamicDictionary)arg.Arguments[2], new CancellationToken()).ConfigureAwait(false);\r\n                    var x = await routeResult;\r\n\r\n                    return (Response)x;\r\n                });\r\n\r\n            this.requestDispatcher =\r\n                new DefaultRequestDispatcher(this.routeResolver, this.responseProcessors, this.routeInvoker, this.negotiator);\r\n\r\n            var resolvedRoute = new ResolveResult\r\n            {\r\n                Route = new FakeRoute(),\r\n                Parameters = DynamicDictionary.Empty,\r\n                Before = null,\r\n                After = null,\r\n                OnError = null\r\n            };\r\n\r\n            A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>._)).Returns(resolvedRoute);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_invoke_module_before_hook_followed_by_resolved_route_followed_by_module_after_hook()\r\n        {\r\n            // Given\r\n            var capturedExecutionOrder = new List<string>();\r\n            var expectedExecutionOrder = new[] { \"Prehook\", \"RouteInvoke\", \"Posthook\" };\r\n\r\n            var route = new FakeRoute\r\n            {\r\n                Action = (parameters, token) =>\r\n                {\r\n                    capturedExecutionOrder.Add(\"RouteInvoke\");\r\n                    return Task.FromResult<object>(null);\r\n                }\r\n            };\r\n\r\n            var before = new BeforePipeline();\r\n            before += (ctx) =>\r\n            {\r\n                capturedExecutionOrder.Add(\"Prehook\");\r\n                return null;\r\n            };\r\n\r\n            var after = new AfterPipeline();\r\n            after += (ctx) =>\r\n            {\r\n                capturedExecutionOrder.Add(\"Posthook\");\r\n            };\r\n\r\n            var resolvedRoute = new ResolveResult\r\n            {\r\n                Route = route,\r\n                Parameters = DynamicDictionary.Empty,\r\n                Before = before,\r\n                After = after,\r\n                OnError = null\r\n            };\r\n\r\n            A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);\r\n\r\n            var context =\r\n                new NancyContext { Request = new Request(\"GET\", \"/\", \"http\") };\r\n\r\n            // When\r\n            await this.requestDispatcher.Dispatch(context, new CancellationToken());\r\n\r\n            // Then\r\n            capturedExecutionOrder.Count().ShouldEqual(3);\r\n            capturedExecutionOrder.SequenceEqual(expectedExecutionOrder).ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_invoke_resolved_route_if_module_before_hook_returns_response_but_should_invoke_module_after_hook()\r\n        {\r\n            // Given\r\n            var capturedExecutionOrder = new List<string>();\r\n            var expectedExecutionOrder = new[] { \"Prehook\", \"Posthook\" };\r\n\r\n            var route = new FakeRoute\r\n            {\r\n                Action = (parameters, token) =>\r\n                {\r\n                    capturedExecutionOrder.Add(\"RouteInvoke\");\r\n                    return null;\r\n                }\r\n            };\r\n\r\n            var before = new BeforePipeline();\r\n            before += ctx =>\r\n                          {\r\n                              capturedExecutionOrder.Add(\"Prehook\");\r\n                              return new Response();\r\n                          };\r\n\r\n            var after = new AfterPipeline();\r\n            after += ctx => capturedExecutionOrder.Add(\"Posthook\");\r\n\r\n            var resolvedRoute = new ResolveResult(\r\n                route,\r\n                DynamicDictionary.Empty,\r\n                before,\r\n                after,\r\n                null);\r\n\r\n            A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);\r\n\r\n            var context =\r\n                new NancyContext { Request = new Request(\"GET\", \"/\", \"http\") };\r\n\r\n            // When\r\n            await this.requestDispatcher.Dispatch(context, new CancellationToken());\r\n\r\n            // Then\r\n            capturedExecutionOrder.Count().ShouldEqual(2);\r\n            capturedExecutionOrder.SequenceEqual(expectedExecutionOrder).ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_response_from_module_before_hook_when_not_null()\r\n        {\r\n            // Given\r\n            var expectedResponse = new Response();\r\n            Func<NancyContext, Response> moduleBeforeHookResponse = ctx => expectedResponse;\r\n\r\n            var before = new BeforePipeline();\r\n            before += moduleBeforeHookResponse;\r\n\r\n            var after = new AfterPipeline();\r\n            after += ctx => { };\r\n\r\n            var route = new FakeRoute();\r\n\r\n            var resolvedRoute = new ResolveResult(\r\n                route,\r\n                DynamicDictionary.Empty,\r\n                before,\r\n                after,\r\n                null);\r\n\r\n            A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);\r\n\r\n            var context =\r\n                new NancyContext { Request = new Request(\"GET\", \"/\", \"http\") };\r\n\r\n            // When\r\n            await this.requestDispatcher.Dispatch(context, new CancellationToken());\r\n\r\n            // Then\r\n            context.Response.ShouldBeSameAs(expectedResponse);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_allow_module_after_hook_to_change_response()\r\n        {\r\n            // Given\r\n            var before = new BeforePipeline();\r\n            before += ctx => null;\r\n\r\n            var response = new Response();\r\n\r\n            Func<NancyContext, Response> moduleAfterHookResponse = ctx => response;\r\n\r\n            var after = new AfterPipeline();\r\n            after += ctx =>\r\n            {\r\n                ctx.Response = moduleAfterHookResponse(ctx);\r\n            };\r\n\r\n            var route = new FakeRoute();\r\n\r\n            var resolvedRoute = new ResolveResult(\r\n                route,\r\n                DynamicDictionary.Empty,\r\n                before,\r\n                after,\r\n                null);\r\n\r\n            A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);\r\n\r\n            var context =\r\n                new NancyContext { Request = new Request(\"GET\", \"/\", \"http\") };\r\n\r\n            // When\r\n            await this.requestDispatcher.Dispatch(context, new CancellationToken());\r\n\r\n            // Then\r\n            context.Response.ShouldBeSameAs(response);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task HandleRequest_should_allow_module_after_hook_to_add_items_to_context()\r\n        {\r\n            // Given\r\n            var route = new FakeRoute();\r\n\r\n            var before = new BeforePipeline();\r\n            before += ctx => null;\r\n\r\n            var after = new AfterPipeline();\r\n            after += ctx => ctx.Items.Add(\"RoutePostReq\", new object());\r\n\r\n            var resolvedRoute = new ResolveResult(\r\n                route,\r\n                DynamicDictionary.Empty,\r\n                before,\r\n                after,\r\n                null);\r\n\r\n            A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);\r\n\r\n            var context =\r\n                new NancyContext { Request = new Request(\"GET\", \"/\", \"http\") };\r\n\r\n            // When\r\n            await this.requestDispatcher.Dispatch(context, new CancellationToken());\r\n\r\n            // Then\r\n            context.Items.ContainsKey(\"RoutePostReq\").ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_set_the_route_parameters_from_resolved_route()\r\n        {\r\n            // Given\r\n            const string expectedPath = \"/the/path\";\r\n\r\n            var context =\r\n                new NancyContext\r\n                {\r\n                    Request = new FakeRequest(\"GET\", expectedPath)\r\n                };\r\n\r\n            var parameters = new DynamicDictionary();\r\n\r\n            var resolvedRoute = new ResolveResult(\r\n               new FakeRoute(),\r\n               parameters,\r\n               null,\r\n               null,\r\n               null);\r\n\r\n            A.CallTo(() => this.routeResolver.Resolve(context)).Returns(resolvedRoute);\r\n\r\n            // When\r\n            await this.requestDispatcher.Dispatch(context, new CancellationToken());\r\n\r\n            // Then\r\n            ((DynamicDictionary)context.Parameters).ShouldBeSameAs(parameters);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_set_the_context_resolved_route_from_resolve_result()\r\n        {\r\n            // Given\r\n            const string expectedPath = \"/the/path\";\r\n\r\n            var context =\r\n                new NancyContext\r\n                {\r\n                    Request = new FakeRequest(\"GET\", expectedPath)\r\n                };\r\n\r\n            var expectedRoute = new FakeRoute();\r\n\r\n            var resolveResult = new ResolveResult(\r\n               expectedRoute,\r\n               new DynamicDictionary(),\r\n               null,\r\n               null,\r\n               null);\r\n\r\n            A.CallTo(() => this.routeResolver.Resolve(context)).Returns(resolveResult);\r\n\r\n            // When\r\n            await this.requestDispatcher.Dispatch(context, new CancellationToken());\r\n\r\n            // Then\r\n            context.ResolvedRoute.ShouldBeSameAs(expectedRoute);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_invoke_route_resolver_with_context_for_current_request()\r\n        {\r\n            // Given\r\n            var context =\r\n                new NancyContext\r\n                {\r\n                    Request = new FakeRequest(\"GET\", \"/\")\r\n                };\r\n\r\n            // When\r\n            await this.requestDispatcher.Dispatch(context, new CancellationToken());\r\n\r\n            // Then\r\n            A.CallTo(() => this.routeResolver.Resolve(context)).MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_invoke_route_resolver_with_path_when_path_does_not_contain_file_extension()\r\n        {\r\n            // Given\r\n            const string expectedPath = \"/the/path\";\r\n            var requestedPath = string.Empty;\r\n\r\n            var context =\r\n                new NancyContext\r\n                {\r\n                    Request = new FakeRequest(\"GET\", expectedPath)\r\n                };\r\n\r\n            var resolvedRoute = new ResolveResult(\r\n               new FakeRoute(),\r\n               DynamicDictionary.Empty,\r\n               null,\r\n               null,\r\n               null);\r\n\r\n            A.CallTo(() => this.routeResolver.Resolve(context))\r\n                .Invokes(x => requestedPath = ((NancyContext)x.Arguments[0]).Request.Path)\r\n                .Returns(resolvedRoute);\r\n\r\n            // When\r\n            await this.requestDispatcher.Dispatch(context, new CancellationToken());\r\n\r\n            // Then\r\n            requestedPath.ShouldEqual(expectedPath);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_invoke_route_resolver_with_passed_in_accept_headers_when_path_does_not_contain_file_extensions()\r\n        {\r\n            // Given\r\n            var expectedAcceptHeaders = new List<Tuple<string, decimal>>\r\n            {\r\n                { new Tuple<string, decimal>(\"application/json\", 0.8m) },\r\n                { new Tuple<string, decimal>(\"application/xml\", 0.4m) }\r\n            };\r\n\r\n            var requestedAcceptHeaders =\r\n                new List<Tuple<string, decimal>>();\r\n\r\n            var request = new FakeRequest(\"GET\", \"/\")\r\n            {\r\n                Headers = { Accept = expectedAcceptHeaders }\r\n            };\r\n\r\n            var context =\r\n                new NancyContext { Request = request };\r\n\r\n            var resolvedRoute = new ResolveResult(\r\n               new FakeRoute(),\r\n               DynamicDictionary.Empty,\r\n               null,\r\n               null,\r\n               null);\r\n\r\n            A.CallTo(() => this.routeResolver.Resolve(context))\r\n                .Invokes(x => requestedAcceptHeaders = ((NancyContext)x.Arguments[0]).Request.Headers.Accept.ToList())\r\n                .Returns(resolvedRoute);\r\n\r\n            // When\r\n            await this.requestDispatcher.Dispatch(context, new CancellationToken());\r\n\r\n            // Then\r\n            requestedAcceptHeaders.ShouldHaveCount(2);\r\n            requestedAcceptHeaders[0].Item1.ShouldEqual(\"application/json\");\r\n            requestedAcceptHeaders[0].Item2.ShouldEqual(0.8m);\r\n            requestedAcceptHeaders[1].Item1.ShouldEqual(\"application/xml\");\r\n            requestedAcceptHeaders[1].Item2.ShouldEqual(0.4m);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_invoke_route_resolver_with_extension_stripped_from_path_when_path_does_contain_file_extension_and_mapped_response_processor_exists()\r\n        {\r\n            // Given\r\n            var requestedPath = string.Empty;\r\n\r\n            var context =\r\n                new NancyContext\r\n                {\r\n                    Request = new FakeRequest(\"GET\", \"/user.json\")\r\n                };\r\n\r\n            var processor =\r\n                A.Fake<IResponseProcessor>();\r\n\r\n            this.responseProcessors.Add(processor);\r\n\r\n            var mappings = new List<Tuple<string, MediaRange>>\r\n            {\r\n                { new Tuple<string, MediaRange>(\"json\", \"application/json\") }\r\n            };\r\n\r\n            A.CallTo(() => processor.ExtensionMappings).Returns(mappings);\r\n\r\n            var resolvedRoute = new ResolveResult(\r\n               new FakeRoute(),\r\n               DynamicDictionary.Empty,\r\n               null,\r\n               null,\r\n               null);\r\n\r\n            A.CallTo(() => this.routeResolver.Resolve(context))\r\n                .Invokes(x => requestedPath = ((NancyContext)x.Arguments[0]).Request.Path)\r\n                .Returns(resolvedRoute);\r\n\r\n            // When\r\n            await this.requestDispatcher.Dispatch(context, new CancellationToken());\r\n\r\n            // Then\r\n            requestedPath.ShouldEqual(\"/user\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_invoke_route_resolver_with_extension_stripped_only_at_the_end_from_path_when_path_does_contain_file_extension_and_mapped_response_processor_exists()\r\n        {\r\n            // Given\r\n            var requestedPath = string.Empty;\r\n\r\n            var context =\r\n                new NancyContext\r\n                {\r\n                    Request = new FakeRequest(\"GET\", \"/directory.jsonfiles/user.json\")\r\n                };\r\n\r\n            var processor =\r\n                A.Fake<IResponseProcessor>();\r\n\r\n            this.responseProcessors.Add(processor);\r\n\r\n            var mappings = new List<Tuple<string, MediaRange>>\r\n            {\r\n                { new Tuple<string, MediaRange>(\"json\", \"application/json\") }\r\n            };\r\n\r\n            A.CallTo(() => processor.ExtensionMappings).Returns(mappings);\r\n\r\n            var resolvedRoute = new ResolveResult(\r\n               new FakeRoute(),\r\n               DynamicDictionary.Empty,\r\n               null,\r\n               null,\r\n               null);\r\n\r\n            A.CallTo(() => this.routeResolver.Resolve(context))\r\n                .Invokes(x => requestedPath = ((NancyContext)x.Arguments[0]).Request.Path)\r\n                .Returns(resolvedRoute);\r\n\r\n            // When\r\n            await this.requestDispatcher.Dispatch(context, new CancellationToken());\r\n\r\n            // Then\r\n            requestedPath.ShouldEqual(\"/directory.jsonfiles/user\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_invoke_route_resolver_with_path_containing_when_path_does_contain_file_extension_and_no_mapped_response_processor_exists()\r\n        {\r\n            // Given\r\n            var requestedPath = string.Empty;\r\n\r\n            var context =\r\n                new NancyContext\r\n                {\r\n                    Request = new FakeRequest(\"GET\", \"/user.json\")\r\n                };\r\n\r\n            var resolvedRoute = new ResolveResult(\r\n               new FakeRoute(),\r\n               DynamicDictionary.Empty,\r\n               null,\r\n               null,\r\n               null);\r\n\r\n            A.CallTo(() => this.routeResolver.Resolve(context))\r\n                .Invokes(x => requestedPath = ((NancyContext)x.Arguments[0]).Request.Path)\r\n                .Returns(resolvedRoute);\r\n\r\n            // When\r\n            await this.requestDispatcher.Dispatch(context, new CancellationToken());\r\n\r\n            // Then\r\n            requestedPath.ShouldEqual(\"/user.json\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_invoke_route_resolver_with_distinct_mapped_media_ranged_when_path_contains_extension_and_mapped_response_processors_exists()\r\n        {\r\n            // Given\r\n            var requestedAcceptHeaders =\r\n                new List<Tuple<string, decimal>>();\r\n\r\n            var context =\r\n                new NancyContext\r\n                {\r\n                    Request = new FakeRequest(\"GET\", \"/user.json\")\r\n                };\r\n\r\n            var jsonProcessor =\r\n                A.Fake<IResponseProcessor>();\r\n\r\n            var jsonProcessormappings =\r\n                new List<Tuple<string, MediaRange>> { { new Tuple<string, MediaRange>(\"json\", \"application/json\") } };\r\n\r\n            A.CallTo(() => jsonProcessor.ExtensionMappings).Returns(jsonProcessormappings);\r\n\r\n            var otherProcessor =\r\n                A.Fake<IResponseProcessor>();\r\n\r\n            var otherProcessormappings =\r\n                new List<Tuple<string, MediaRange>>\r\n                    {\r\n                        { new Tuple<string, MediaRange>(\"json\", \"application/json\") },\r\n                        { new Tuple<string, MediaRange>(\"xml\", \"application/xml\") }\r\n                    };\r\n\r\n            A.CallTo(() => otherProcessor.ExtensionMappings).Returns(otherProcessormappings);\r\n\r\n            this.responseProcessors.Add(jsonProcessor);\r\n            this.responseProcessors.Add(otherProcessor);\r\n\r\n            var resolvedRoute = new ResolveResult(\r\n               new FakeRoute(),\r\n               DynamicDictionary.Empty,\r\n               null,\r\n               null,\r\n               null);\r\n\r\n            A.CallTo(() => this.routeResolver.Resolve(context))\r\n                .Invokes(x => requestedAcceptHeaders = ((NancyContext)x.Arguments[0]).Request.Headers.Accept.ToList())\r\n                .Returns(resolvedRoute);\r\n\r\n            // When\r\n            await this.requestDispatcher.Dispatch(context, new CancellationToken());\r\n\r\n            // Then\r\n            requestedAcceptHeaders.ShouldHaveCount(1);\r\n            requestedAcceptHeaders[0].Item1.ShouldEqual(\"application/json\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_set_quality_to_high_for_mapped_media_ranges_before_invoking_route_resolver_when_path_contains_extension_and_mapped_response_processors_exists()\r\n        {\r\n            // Given\r\n            var requestedAcceptHeaders =\r\n                new List<Tuple<string, decimal>>();\r\n\r\n            var context =\r\n                new NancyContext\r\n                {\r\n                    Request = new FakeRequest(\"GET\", \"/user.json\")\r\n                };\r\n\r\n            var jsonProcessor =\r\n                A.Fake<IResponseProcessor>();\r\n\r\n            var jsonProcessormappings =\r\n                new List<Tuple<string, MediaRange>> { { new Tuple<string, MediaRange>(\"json\", \"application/json\") } };\r\n\r\n            A.CallTo(() => jsonProcessor.ExtensionMappings).Returns(jsonProcessormappings);\r\n\r\n            this.responseProcessors.Add(jsonProcessor);\r\n\r\n            var resolvedRoute = new ResolveResult(\r\n               new FakeRoute(),\r\n               DynamicDictionary.Empty,\r\n               null,\r\n               null,\r\n               null);\r\n\r\n            A.CallTo(() => this.routeResolver.Resolve(context))\r\n                .Invokes(x => requestedAcceptHeaders = ((NancyContext)x.Arguments[0]).Request.Headers.Accept.ToList())\r\n                .Returns(resolvedRoute);\r\n\r\n            // When\r\n            await this.requestDispatcher.Dispatch(context, new CancellationToken());\r\n\r\n            // Then\r\n            requestedAcceptHeaders.ShouldHaveCount(1);\r\n            Assert.True(requestedAcceptHeaders[0].Item2 > 1.0m);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_call_route_invoker_with_resolved_route()\r\n        {\r\n            // Given\r\n            var context =\r\n                new NancyContext\r\n                {\r\n                    Request = new FakeRequest(\"GET\", \"/user.json\")\r\n                };\r\n\r\n            var resolvedRoute = new ResolveResult(\r\n               new FakeRoute(),\r\n               DynamicDictionary.Empty,\r\n               null,\r\n               null,\r\n               null);\r\n\r\n            A.CallTo(() => this.routeResolver.Resolve(context)).Returns(resolvedRoute);\r\n\r\n            // When\r\n            await this.requestDispatcher.Dispatch(context, new CancellationToken());\r\n\r\n            // Then\r\n            A.CallTo(() => this.routeInvoker.Invoke(resolvedRoute.Route, A<CancellationToken>._, A<DynamicDictionary>._, A<NancyContext>._)).MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_invoke_route_resolver_with_path_containing_extension_when_mapped_response_processor_existed_but_no_route_match_was_found()\r\n        {\r\n            // Given\r\n            var requestedAcceptHeaders =\r\n                new List<Tuple<string, decimal>>();\r\n\r\n            var context =\r\n                new NancyContext\r\n                {\r\n                    Request = new FakeRequest(\"GET\", \"/user.json\")\r\n                };\r\n\r\n            var jsonProcessor =\r\n                A.Fake<IResponseProcessor>();\r\n\r\n            var jsonProcessormappings =\r\n                new List<Tuple<string, MediaRange>> { { new Tuple<string, MediaRange>(\"json\", \"application/json\") } };\r\n\r\n            A.CallTo(() => jsonProcessor.ExtensionMappings).Returns(jsonProcessormappings);\r\n\r\n            this.responseProcessors.Add(jsonProcessor);\r\n\r\n            var resolvedRoute = new ResolveResult(\r\n               new NotFoundRoute(\"GET\", \"/\"),\r\n               DynamicDictionary.Empty,\r\n               null,\r\n               null,\r\n               null);\r\n\r\n            A.CallTo(() => this.routeResolver.Resolve(context))\r\n                .Invokes(x => requestedAcceptHeaders = ((NancyContext)x.Arguments[0]).Request.Headers.Accept.ToList())\r\n                .Returns(resolvedRoute);\r\n\r\n            // When\r\n            await this.requestDispatcher.Dispatch(context, new CancellationToken());\r\n\r\n            // Then\r\n            A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>._)).MustHaveHappenedTwiceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_call_route_invoker_with_captured_parameters()\r\n        {\r\n            // Given\r\n            var context =\r\n                new NancyContext\r\n                {\r\n                    Request = new FakeRequest(\"GET\", \"/user.json\")\r\n                };\r\n\r\n            var parameters = new DynamicDictionary();\r\n\r\n            var resolvedRoute = new ResolveResult(\r\n               new FakeRoute(),\r\n               parameters,\r\n               null,\r\n               null,\r\n               null);\r\n\r\n            A.CallTo(() => this.routeResolver.Resolve(context)).Returns(resolvedRoute);\r\n\r\n            // When\r\n            await this.requestDispatcher.Dispatch(context, new CancellationToken());\r\n\r\n            // Then\r\n            A.CallTo(() => this.routeInvoker.Invoke(A<Route>._, A<CancellationToken>._, parameters, A<NancyContext>._)).MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_call_route_invoker_with_context()\r\n        {\r\n            // Given\r\n            var context =\r\n                new NancyContext\r\n                {\r\n                    Request = new FakeRequest(\"GET\", \"/user.json\")\r\n                };\r\n\r\n            var resolvedRoute = new ResolveResult(\r\n               new FakeRoute(),\r\n               DynamicDictionary.Empty,\r\n               null,\r\n               null,\r\n               null);\r\n\r\n            A.CallTo(() => this.routeResolver.Resolve(context)).Returns(resolvedRoute);\r\n\r\n            // When\r\n            await this.requestDispatcher.Dispatch(context, new CancellationToken());\r\n\r\n            // Then\r\n            A.CallTo(() => this.routeInvoker.Invoke(A<Route>._, A<CancellationToken>._, A<DynamicDictionary>._, context)).MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_invoke_module_onerror_hook_when_module_before_hook_throws_exception()\r\n        {\r\n            // Given\r\n            var capturedExecutionOrder = new List<string>();\r\n            var expectedExecutionOrder = new[] { \"Prehook\", \"OnErrorHook\" };\r\n\r\n            var before = new BeforePipeline();\r\n            before += ctx =>\r\n                          {\r\n                              capturedExecutionOrder.Add(\"Prehook\");\r\n                              throw new Exception(\"Prehook\");\r\n                          };\r\n\r\n            var after = new AfterPipeline();\r\n            after += ctx => capturedExecutionOrder.Add(\"Posthook\");\r\n\r\n            var route = new FakeRoute((parameters, ct) =>\r\n            {\r\n                capturedExecutionOrder.Add(\"RouteInvoke\");\r\n                return null;\r\n            });\r\n\r\n            var resolvedRoute = new ResolveResult(\r\n                route,\r\n                DynamicDictionary.Empty,\r\n                before,\r\n                after,\r\n                (ctx, ex) => { capturedExecutionOrder.Add(\"OnErrorHook\"); return new Response(); });\r\n\r\n            A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);\r\n\r\n            var context =\r\n                new NancyContext { Request = new Request(\"GET\", \"/\", \"http\") };\r\n\r\n            // When\r\n            await this.requestDispatcher.Dispatch(context, new CancellationToken());\r\n\r\n            // Then\r\n            capturedExecutionOrder.Count().ShouldEqual(2);\r\n            capturedExecutionOrder.SequenceEqual(expectedExecutionOrder).ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_invoke_module_onerror_hook_when_route_invoker_throws_exception()\r\n        {\r\n            // Given\r\n            var capturedExecutionOrder = new List<string>();\r\n            var expectedExecutionOrder = new[] { \"RouteInvoke\", \"OnErrorHook\" };\r\n\r\n            var route = new FakeRoute\r\n            {\r\n                Action = (parameters, ct) =>\r\n                {\r\n                    capturedExecutionOrder.Add(\"RouteInvoke\");\r\n                    return TaskHelpers.GetFaultedTask<dynamic>(new Exception(\"RouteInvoke\"));\r\n                }\r\n            };\r\n\r\n            var before = new BeforePipeline();\r\n            before += ctx => null;\r\n\r\n            var after = new AfterPipeline();\r\n            after += ctx => capturedExecutionOrder.Add(\"Posthook\");\r\n\r\n            var resolvedRoute = new ResolveResult(\r\n                route,\r\n                DynamicDictionary.Empty,\r\n                before,\r\n                after,\r\n                (ctx, ex) => { capturedExecutionOrder.Add(\"OnErrorHook\"); return new Response(); });\r\n\r\n            A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);\r\n\r\n            var context =\r\n                new NancyContext { Request = new Request(\"GET\", \"/\", \"http\") };\r\n\r\n            // When\r\n            await this.requestDispatcher.Dispatch(context, new CancellationToken());\r\n\r\n            // Then\r\n            capturedExecutionOrder.Count().ShouldEqual(2);\r\n            capturedExecutionOrder.SequenceEqual(expectedExecutionOrder).ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_invoke_module_onerror_hook_when_module_after_hook_throws_exception()\r\n        {\r\n            // Given\r\n            var capturedExecutionOrder = new List<string>();\r\n            var expectedExecutionOrder = new[] { \"Posthook\", \"OnErrorHook\" };\r\n\r\n            var route = new FakeRoute\r\n            {\r\n                Action = (parameters, ct) => Task.FromResult<object>(null)\r\n            };\r\n\r\n            var before = new BeforePipeline();\r\n            before += ctx => null;\r\n\r\n            var after = new AfterPipeline();\r\n            after += ctx =>\r\n                         {\r\n                             capturedExecutionOrder.Add(\"Posthook\");\r\n                             throw new Exception(\"Posthook\");\r\n                         };\r\n\r\n            var resolvedRoute = new ResolveResult(\r\n                route,\r\n                DynamicDictionary.Empty,\r\n                before,\r\n                after,\r\n                (ctx, ex) => { capturedExecutionOrder.Add(\"OnErrorHook\"); return new Response(); });\r\n\r\n            A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);\r\n\r\n            var context =\r\n                new NancyContext { Request = new Request(\"GET\", \"/\", \"http\") };\r\n\r\n            // When\r\n            await this.requestDispatcher.Dispatch(context, new CancellationToken());\r\n\r\n            // Then\r\n            capturedExecutionOrder.Count().ShouldEqual(2);\r\n            capturedExecutionOrder.SequenceEqual(expectedExecutionOrder).ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_rethrow_exception_when_onerror_hook_does_return_response()\r\n        {\r\n            // Given\r\n            var route = new FakeRoute\r\n            {\r\n                Action = (parameters, ct) => { throw new Exception(); }\r\n            };\r\n\r\n            var before = new BeforePipeline();\r\n            before += ctx => null;\r\n\r\n            var after = new AfterPipeline();\r\n            after += ctx => { };\r\n\r\n            var resolvedRoute = new ResolveResult(\r\n                route,\r\n                DynamicDictionary.Empty,\r\n                before,\r\n                after,\r\n                (ctx, ex) => null);\r\n\r\n            A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);\r\n\r\n            var context =\r\n                new NancyContext { Request = new Request(\"GET\", \"/\", \"http\") };\r\n\r\n            //When\r\n            var exception = await RecordAsync.Exception(async () => await this.requestDispatcher.Dispatch(context, new CancellationToken()));\r\n\r\n            // Then\r\n            exception.ShouldNotBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_rethrow_exception_when_onerror_hook_returns_response()\r\n        {\r\n            // Given\r\n            var route = new FakeRoute\r\n            {\r\n                Action = (parameters, ct) => TaskHelpers.GetFaultedTask<dynamic>(new Exception())\r\n            };\r\n\r\n            var before = new BeforePipeline();\r\n            before += ctx => null;\r\n\r\n            var after = new AfterPipeline();\r\n            after += ctx => { };\r\n\r\n            var resolvedRoute = new ResolveResult(\r\n                route,\r\n                DynamicDictionary.Empty,\r\n                before,\r\n                after,\r\n                (ctx, ex) => new Response());\r\n\r\n            A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);\r\n\r\n            var context =\r\n                new NancyContext { Request = new Request(\"GET\", \"/\", \"http\") };\r\n\r\n            //When\r\n            var exception = await RecordAsync.Exception(async () => await this.requestDispatcher.Dispatch(context, new CancellationToken()));\r\n\r\n            // Then\r\n            exception.ShouldBeNull();\r\n        }\r\n\r\n#if !MONO\r\n        [Fact]\r\n        public async Task should_preserve_stacktrace_when_rethrowing_the_excption()\r\n        {\r\n            // Given\r\n            var route = new FakeRoute\r\n            {\r\n                Action = (o, ct) => BrokenMethod()\r\n            };\r\n\r\n            var before = new BeforePipeline();\r\n            before += ctx => null;\r\n\r\n            var after = new AfterPipeline();\r\n            after += ctx => { };\r\n\r\n            var resolvedRoute = new ResolveResult(\r\n                route,\r\n                DynamicDictionary.Empty,\r\n                before,\r\n                after,\r\n                (ctx, ex) => null);\r\n\r\n            A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);\r\n\r\n            var context =\r\n                new NancyContext { Request = new Request(\"GET\", \"/\", \"http\") };\r\n\r\n            var exception = await RecordAsync.Exception(async () => await this.requestDispatcher.Dispatch(context, new CancellationToken()));\r\n\r\n            exception.StackTrace.ShouldContain(\"BrokenMethod\");\r\n        }\r\n#endif\r\n\r\n        private static Task<dynamic> CreateResponseTask(dynamic response)\r\n        {\r\n            var tcs =\r\n                new TaskCompletionSource<dynamic>();\r\n\r\n            tcs.SetResult(response);\r\n\r\n            return tcs.Task;\r\n        }\r\n\r\n        private static Task<dynamic> BrokenMethod()\r\n        {\r\n            throw new Exception(\"You called the broken method!\");\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Routing/DefaultRouteCacheProviderFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Routing\r\n{\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Routing;\r\n\r\n    using Xunit;\r\n\r\n    public class DefaultRouteCacheProviderFixture\r\n    {\r\n        private IRouteCacheProvider _Provider;\r\n        private IRouteCache _RouteCache;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the DefaultRouteCacheProviderFixture class.\r\n        /// </summary>\r\n        public DefaultRouteCacheProviderFixture()\r\n        {\r\n            _RouteCache = A.Fake<IRouteCache>();\r\n            _Provider = new DefaultRouteCacheProvider(() => _RouteCache);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_Return_Instance_Supplied_By_Func()\r\n        {\r\n            var result = _Provider.GetCache();\r\n\r\n            result.ShouldBeSameAs(_RouteCache);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Routing/DefaultRouteInvokerFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Routing\r\n{\r\n    using System.Threading;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Diagnostics;\r\n    using Nancy.ErrorHandling;\r\n    using Nancy.Responses.Negotiation;\r\n    using Nancy.Routing;\r\n    using Nancy.Tests.Fakes;\r\n\r\n    using Xunit;\r\n\r\n    public class DefaultRouteInvokerFixture\r\n    {\r\n        private readonly DefaultRouteInvoker invoker;\r\n        private readonly IResponseNegotiator responseNegotiator;\r\n\r\n        public DefaultRouteInvokerFixture()\r\n        {\r\n            this.responseNegotiator = A.Fake<IResponseNegotiator>();\r\n            this.invoker = new DefaultRouteInvoker(responseNegotiator);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_route_with_provided_parameters()\r\n        {\r\n            // Given\r\n            var parameters = new DynamicDictionary();\r\n            var route = new FakeRoute(10);\r\n            var context = new NancyContext\r\n            {\r\n                Trace = new DefaultRequestTrace\r\n                {\r\n                    TraceLog = new DefaultTraceLog()\r\n                }\r\n            };\r\n\r\n            // When\r\n            this.invoker.Invoke(route, new CancellationToken(), parameters, context);\r\n\r\n            // Then\r\n            Assert.Same(route.ParametersUsedToInvokeAction, parameters);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_handle_RouteExecutionEarlyExitException_gracefully()\r\n        {\r\n            // Given\r\n            var response = new Response();\r\n            var route = new FakeRoute((c, t) => { throw new RouteExecutionEarlyExitException(response); });\r\n            var parameters = new DynamicDictionary();\r\n            var context = new NancyContext\r\n            {\r\n                Trace = new DefaultRequestTrace\r\n                {\r\n                    TraceLog = new DefaultTraceLog()\r\n                }\r\n            };\r\n\r\n            // When\r\n            var result = this.invoker.Invoke(route, new CancellationToken(), parameters, context).Result;\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(response);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_log_the_reason_for_early_exits()\r\n        {\r\n            // Given\r\n            var response = new Response();\r\n            var route = new FakeRoute((c, t) => { throw new RouteExecutionEarlyExitException(response, \"Reason Testing\"); });\r\n            var parameters = new DynamicDictionary();\r\n            var context = new NancyContext\r\n            {\r\n                Trace = new DefaultRequestTrace\r\n                {\r\n                    TraceLog = new DefaultTraceLog()\r\n                }\r\n            };\r\n\r\n            // When\r\n            var result = this.invoker.Invoke(route, new CancellationToken(), parameters, context).Result;\r\n\r\n            // Then\r\n            context.Trace.TraceLog.ToString().ShouldContain(\"Reason Testing\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_response_negotiator_for_reference_model()\r\n        {\r\n            // Given\r\n            var model = new Person { FirstName = \"First\", LastName = \"Last\" };\r\n            var route = new FakeRoute(model);\r\n            var parameters = new DynamicDictionary();\r\n            var context = new NancyContext\r\n            {\r\n                Trace = new DefaultRequestTrace()\r\n            };\r\n\r\n            // When\r\n            var result = this.invoker.Invoke(route, new CancellationToken(), parameters, context).Result;\r\n\r\n            // Then\r\n            A.CallTo(() => this.responseNegotiator.NegotiateResponse(model, context)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_response_negotiator_for_value_type_model()\r\n        {\r\n            // Given\r\n            var model = new StructModel();\r\n            var route = new FakeRoute(model);\r\n            var parameters = new DynamicDictionary();\r\n            var context = new NancyContext\r\n            {\r\n                Trace = new DefaultRequestTrace()\r\n            };\r\n\r\n            // When\r\n            var result = this.invoker.Invoke(route, new CancellationToken(), parameters, context).Result;\r\n\r\n            // Then\r\n            A.CallTo(() => this.responseNegotiator.NegotiateResponse(model, context)).MustHaveHappened();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Routing/DefaultRouteResolverFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Routing\r\n{\r\n    using System.Threading.Tasks;\r\n    using Nancy.Testing;\r\n    using Xunit;\r\n\r\n    public class DefaultRouteResolverFixture\r\n    {\r\n        [Fact]\r\n        public async Task Should_resolve_root()\r\n        {\r\n            //Given, When\r\n            var browser = InitBrowser(caseSensitive: false);\r\n            var result = await browser.Get(\"/\");\r\n\r\n            //Then\r\n            result.Body.AsString().ShouldEqual(\"Root\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_resolve_correct_route_based_on_method()\r\n        {\r\n            //Given, When\r\n            var browser = InitBrowser(caseSensitive: false);\r\n            var result = await browser.Post(\"/\");\r\n\r\n            //Then\r\n            result.Body.AsString().ShouldEqual(\"PostRoot\");\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"/foo\", true)]\r\n        [InlineData(\"/foo\", false)]\r\n        [InlineData(\"/FOO\", true)]\r\n        [InlineData(\"/FOO\", false)]\r\n        public async Task Should_resolve_single_literal(string path, bool caseSensitive)\r\n        {\r\n            //Given, When\r\n            var browser = InitBrowser(caseSensitive);\r\n            var result = await browser.Get(path);\r\n\r\n            //Then\r\n            if (ShouldBeFound(path, caseSensitive))\r\n            {\r\n                result.Body.AsString().ShouldEqual(\"SingleLiteral\");\r\n            }\r\n            else\r\n            {\r\n                result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n            }\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"/foo/bar/baz\", true)]\r\n        [InlineData(\"/foo/bar/baz\", false)]\r\n        [InlineData(\"/FOO/BAR/BAZ\", true)]\r\n        [InlineData(\"/FOO/BAR/BAZ\", false)]\r\n        public async Task Should_resolve_multi_literal(string path, bool caseSensitive)\r\n        {\r\n            //Given, When\r\n            var browser = InitBrowser(caseSensitive);\r\n            var result = await browser.Get(path);\r\n\r\n            //Then\r\n            if (ShouldBeFound(path, caseSensitive))\r\n            {\r\n                result.Body.AsString().ShouldEqual(\"MultipleLiteral\");\r\n            }\r\n            else\r\n            {\r\n                result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n            }\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"/foo/testing/plop\", true, \"testing\")]\r\n        [InlineData(\"/foo/testing/plop\", false, \"testing\")]\r\n        [InlineData(\"/FOO/TESTING/PLOP\", true, \"NA\")]\r\n        [InlineData(\"/FOO/TESTING/PLOP\", false, \"TESTING\")]\r\n        public async Task Should_resolve_single_capture(string path, bool caseSensitive, string expected)\r\n        {\r\n            //Given, When\r\n            var browser = InitBrowser(caseSensitive);\r\n            var result = await browser.Get(path);\r\n\r\n            //Then\r\n            if (ShouldBeFound(path, caseSensitive))\r\n            {\r\n                result.Body.AsString().ShouldEqual(\"Captured \" + expected);\r\n            }\r\n            else\r\n            {\r\n                result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n            }\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"/moo/hoo/moo\", true, \"hoo\")]\r\n        [InlineData(\"/moo/hoo/moo\", false, \"hoo\")]\r\n        [InlineData(\"/MOO/HOO/MOO\", true, \"NA\")]\r\n        [InlineData(\"/MOO/HOO/MOO\", false, \"HOO\")]\r\n        public async Task Should_resolve_optional_capture_with_optional_specified(string path, bool caseSensitive, string expected)\r\n        {\r\n            //Given, When\r\n            var browser = InitBrowser(caseSensitive);\r\n            var result = await browser.Get(path);\r\n\r\n            //Then\r\n            if (ShouldBeFound(path, caseSensitive))\r\n            {\r\n                result.Body.AsString().ShouldEqual(\"OptionalCapture \" + expected);\r\n            }\r\n            else\r\n            {\r\n                result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n            }\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"/moo/moo\", true)]\r\n        [InlineData(\"/moo/moo\", false)]\r\n        [InlineData(\"/MOO/MOO\", true)]\r\n        [InlineData(\"/MOO/MOO\", false)]\r\n        public async Task Should_resolve_optional_capture_with_optional_not_specified(string path, bool caseSensitive)\r\n        {\r\n            //Given, When\r\n            var browser = InitBrowser(caseSensitive);\r\n            var result = await browser.Get(path);\r\n\r\n            //Then\r\n            if (ShouldBeFound(path, caseSensitive))\r\n            {\r\n                result.Body.AsString().ShouldEqual(\"OptionalCapture default\");\r\n            }\r\n            else\r\n            {\r\n                result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n            }\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"/boo/badger/laa\", true, \"badger\")]\r\n        [InlineData(\"/boo/badger/laa\", false, \"badger\")]\r\n        [InlineData(\"/BOO/BADGER/LAA\", true, \"NA\")]\r\n        [InlineData(\"/BOO/BADGER/LAA\", false, \"BADGER\")]\r\n        public async Task Should_resolve_optional_capture_with_default_with_optional_specified(string path, bool caseSensitive, string expected)\r\n        {\r\n            //Given, When\r\n            var browser = InitBrowser(caseSensitive);\r\n            var result = await browser.Get(path);\r\n\r\n            //Then\r\n            if (ShouldBeFound(path, caseSensitive))\r\n            {\r\n              result.Body.AsString().ShouldEqual(\"OptionalCaptureWithDefault \" + expected);\r\n            }\r\n            else\r\n            {\r\n              result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n            }\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"/boo/laa\", true)]\r\n        [InlineData(\"/boo/laa\", false)]\r\n        [InlineData(\"/BOO/LAA\", true)]\r\n        [InlineData(\"/BOO/LAA\", false)]\r\n        public async Task Should_resolve_optional_capture_with_default_with_optional_not_specified(string path, bool caseSensitive)\r\n        {\r\n            //Given, When\r\n            var browser = InitBrowser(caseSensitive);\r\n            var result = await browser.Get(path);\r\n\r\n            //Then\r\n            if (ShouldBeFound(path, caseSensitive))\r\n            {\r\n              result.Body.AsString().ShouldEqual(\"OptionalCaptureWithDefault test\");\r\n            }\r\n            else\r\n            {\r\n              result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n            }\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"/bleh/this/is/some/stuff\", true, \"this/is/some/stuff\")]\r\n        [InlineData(\"/bleh/this/is/some/stuff\", false, \"this/is/some/stuff\")]\r\n        [InlineData(\"/BLEH/THIS/IS/SOME/STUFF\", true, \"NA\")]\r\n        [InlineData(\"/BLEH/THIS/IS/SOME/STUFF\", false, \"THIS/IS/SOME/STUFF\")]\r\n        public async Task Should_capture_greedy_on_end(string path, bool caseSensitive, string expected)\r\n        {\r\n            //Given, When\r\n            var browser = InitBrowser(caseSensitive);\r\n            var result = await browser.Get(path);\r\n\r\n            //Then\r\n            if (ShouldBeFound(path, caseSensitive))\r\n            {\r\n              result.Body.AsString().ShouldEqual(\"GreedyOnEnd \" + expected);\r\n            }\r\n            else\r\n            {\r\n              result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n            }\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"/bleh/this/is/some/stuff/bar\", true, \"this/is/some/stuff\")]\r\n        [InlineData(\"/bleh/this/is/some/stuff/bar\", false, \"this/is/some/stuff\")]\r\n        [InlineData(\"/BLEH/THIS/IS/SOME/STUFF/BAR\", true, \"NA\")]\r\n        [InlineData(\"/BLEH/THIS/IS/SOME/STUFF/BAR\", false, \"THIS/IS/SOME/STUFF\")]\r\n        public async Task Should_capture_greedy_in_middle(string path, bool caseSensitive, string expected)\r\n        {\r\n            //Given, When\r\n            var browser = InitBrowser(caseSensitive);\r\n            var result = await browser.Get(path);\r\n\r\n            //Then\r\n            if (ShouldBeFound(path, caseSensitive))\r\n            {\r\n              result.Body.AsString().ShouldEqual(\"GreedyInMiddle \" + expected);\r\n            }\r\n            else\r\n            {\r\n              result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n            }\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"/greedy/this/is/some/stuff/badger/blah\", true, \"this/is/some/stuff blah\")]\r\n        [InlineData(\"/greedy/this/is/some/stuff/badger/blah\", false, \"this/is/some/stuff blah\")]\r\n        [InlineData(\"/GREEDY/THIS/IS/SOME/STUFF/BADGER/BLAH\", true, \"NA\")]\r\n        [InlineData(\"/GREEDY/THIS/IS/SOME/STUFF/BADGER/BLAH\", false, \"THIS/IS/SOME/STUFF BLAH\")]\r\n        public async Task Should_capture_greedy_and_normal_capture(string path, bool caseSensitive, string expected)\r\n        {\r\n            //Given, When\r\n            var browser = InitBrowser(caseSensitive);\r\n            var result = await browser.Get(path);\r\n\r\n            //Then\r\n            if (ShouldBeFound(path, caseSensitive))\r\n            {\r\n              result.Body.AsString().ShouldEqual(\"GreedyAndCapture \" + expected);\r\n            }\r\n            else\r\n            {\r\n              result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n            }\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"/multipleparameters/file.extension\", true, \"file.extension\")]\r\n        [InlineData(\"/multipleparameters/file.extension\", false, \"file.extension\")]\r\n        [InlineData(\"/MULTIPLEPARAMETERS/FILE.EXTENSION\", true, \"NA\")]\r\n        [InlineData(\"/MULTIPLEPARAMETERS/FILE.EXTENSION\", false, \"FILE.EXTENSION\")]\r\n        public async Task Should_capture_node_with_multiple_parameters(string path, bool caseSensitive, string expected)\r\n        {\r\n            //Given, When\r\n            var browser = InitBrowser(caseSensitive);\r\n            var result = await browser.Get(path);\r\n\r\n            //Then\r\n            if (ShouldBeFound(path, caseSensitive))\r\n            {\r\n              result.Body.AsString().ShouldEqual(\"Multiple parameters \" + expected);\r\n            }\r\n            else\r\n            {\r\n              result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n            }\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"/capturenodewithliteral/testing.html\", true, \"testing\")]\r\n        [InlineData(\"/capturenodewithliteral/testing.html\", false, \"testing\")]\r\n        [InlineData(\"/CAPTURENODEWITHLITERAL/TESTING.HTML\", true, \"NA\")]\r\n        [InlineData(\"/CAPTURENODEWITHLITERAL/TESTING.HTML\", false, \"TESTING\")]\r\n        public async Task Should_capture_node_with_literal(string path, bool caseSensitive, string expected)\r\n        {\r\n            //Given, When\r\n            var browser = InitBrowser(caseSensitive);\r\n            var result = await browser.Get(path);\r\n\r\n            //Then\r\n            if (ShouldBeFound(path, caseSensitive))\r\n            {\r\n              result.Body.AsString().ShouldEqual(\"CaptureNodeWithLiteral \" + expected + \".html\");\r\n            }\r\n            else\r\n            {\r\n              result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n            }\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"/regex/123/moo\", true, \"123 moo\")]\r\n        [InlineData(\"/regex/123/moo\", false, \"123 moo\")]\r\n        [InlineData(\"/REGEX/123/MOO\", true, \"NA\")]\r\n        [InlineData(\"/REGEX/123/MOO\", false, \"123 MOO\")]\r\n        public async Task Should_capture_regex(string path, bool caseSensitive, string expected)\r\n        {\r\n            //Given, When\r\n            var browser = InitBrowser(caseSensitive);\r\n            var result = await browser.Get(path);\r\n\r\n            //Then\r\n            if (ShouldBeFound(path, caseSensitive))\r\n            {\r\n              result.Body.AsString().ShouldEqual(\"RegEx \" + expected);\r\n            }\r\n            else\r\n            {\r\n              result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n            }\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_handle_head_requests()\r\n        {\r\n            //Given, When\r\n            var browser = InitBrowser(caseSensitive: false);\r\n            var result = await browser.Head(\"/\");\r\n\r\n            //Then\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.OK);\r\n            result.Body.AsString().ShouldEqual(string.Empty);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_handle_options_requests()\r\n        {\r\n            //Given, When\r\n            var browser = InitBrowser(caseSensitive: false);\r\n            var result = await browser.Options(\"/\");\r\n\r\n            //Then\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.OK);\r\n            result.Headers[\"Allow\"].ShouldContain(\"GET\");\r\n            result.Headers[\"Allow\"].ShouldContain(\"POST\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_404_if_no_root_found_when_requesting_it()\r\n        {\r\n            //Given\r\n            var browser = new Browser(with => with.Module<NoRootModule>());\r\n\r\n            //When\r\n            var result = await browser.Get(\"/\");\r\n\r\n            //Then\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_405_if_requested_method_is_not_permitted_but_others_are_available_and_not_disabled()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.Module<MethodNotAllowedModule>();\r\n                with.Configure(env =>\r\n                {\r\n                    env.Routing(disableMethodNotAllowedResponses: false);\r\n                });\r\n            });\r\n\r\n            // When\r\n            var result = await browser.Get(\"/\");\r\n\r\n            // Then\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.MethodNotAllowed);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_return_405_if_requested_method_is_not_permitted_but_others_are_available_and_disabled()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.Module<MethodNotAllowedModule>();\r\n                with.Configure(env =>\r\n                {\r\n                    env.Routing(disableMethodNotAllowedResponses: true);\r\n                });\r\n            });\r\n\r\n            // When\r\n            var result = await browser.Get(\"/\");\r\n\r\n            // Then\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_set_allowed_method_on_response_when_returning_405()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.Module<MethodNotAllowedModule>();\r\n                with.Configure(env =>\r\n                {\r\n                    env.Routing(disableMethodNotAllowedResponses: false);\r\n                });\r\n            });\r\n\r\n            // When\r\n            var result = await browser.Get(\"/\");\r\n\r\n            // Then\r\n            result.Headers[\"Allow\"].ShouldEqual(\"DELETE, POST\");\r\n        }\r\n\r\n        private Browser InitBrowser(bool caseSensitive)\r\n        {\r\n            StaticConfiguration.CaseSensitive = caseSensitive;\r\n            return new Browser(with => with.Module<TestModule>());\r\n        }\r\n\r\n        private bool ShouldBeFound(string path, bool caseSensitive)\r\n        {\r\n            var isUpperCase = path == path.ToUpperInvariant();\r\n            return !caseSensitive || !isUpperCase;\r\n        }\r\n\r\n        private class MethodNotAllowedModule : NancyModule\r\n        {\r\n            public MethodNotAllowedModule()\r\n            {\r\n                Delete(\"/\", args => 200);\r\n\r\n                Post(\"/\", args => 200);\r\n            }\r\n        }\r\n\r\n        private class NoRootModule : NancyModule\r\n        {\r\n            public NoRootModule()\r\n            {\r\n                Get(\"/notroot\", args => \"foo\");\r\n            }\r\n        }\r\n\r\n        private class TestModule : NancyModule\r\n        {\r\n            public TestModule()\r\n            {\r\n                Get(\"/\", args => \"Root\");\r\n\r\n                Post(\"/\", args => \"PostRoot\");\r\n\r\n                Get(\"/foo\", args => \"SingleLiteral\");\r\n\r\n                Get(\"/foo/bar/baz\", args => \"MultipleLiteral\");\r\n\r\n                Get(\"/foo/{bar}/plop\", args => \"Captured \" + args.bar);\r\n\r\n                Get(\"/moo/baa\", args => \"Dummy\");\r\n\r\n                Get(\"/moo/baa/cheese\", args => \"Dummy\");\r\n\r\n                Get(\"/moo/{test?}/moo\", args => \"OptionalCapture \" + args.test.Default(\"default\"));\r\n\r\n                Get(\"/boo/{woo?test}/laa\", args => \"OptionalCaptureWithDefault \" + args.woo);\r\n\r\n                Get(\"/bleh/{test*}\", args => \"GreedyOnEnd \" + args.test);\r\n\r\n                Get(\"/bleh/{test*}/bar\", args => \"GreedyInMiddle \" + args.test);\r\n\r\n                Get(\"/greedy/{test*}/badger/{woo}\", args => \"GreedyAndCapture \" + args.test + \" \" + args.woo);\r\n\r\n                Get(\"/multipleparameters/{file}.{extension}\", args => \"Multiple parameters \" + args.file + \".\" + args.extension);\r\n\r\n                Get(\"/capturenodewithliteral/{file}.html\", args => \"CaptureNodeWithLiteral \" + args.file + \".html\");\r\n\r\n                Get(@\"/regex/(?<foo>\\d{2,4})/{bar}\", args => string.Format(\"RegEx {0} {1}\", args.foo, args.bar));\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Routing/DefaultRouteSegmentExtractorFixture.cs",
    "content": "namespace Nancy.Tests.Unit.Routing\r\n{\r\n    using System.Linq;\r\n\r\n    using Nancy.Routing;\r\n\r\n    using Xunit;\r\n\r\n    public class DefaultRouteSegmentExtractorFixture\r\n    {\r\n        private readonly DefaultRouteSegmentExtractor extractor;\r\n\r\n        public DefaultRouteSegmentExtractorFixture()\r\n        {\r\n            this.extractor = new DefaultRouteSegmentExtractor();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_extract_segments_from_normal_path()\r\n        {\r\n            // Given\r\n            const string path = \"/this/is/the/segments\";\r\n\r\n            // When\r\n            var result = this.extractor.Extract(path).ToArray();\r\n\r\n            // Then\r\n            result.ShouldHaveCount(4);\r\n            result[0].ShouldEqual(\"this\");\r\n            result[1].ShouldEqual(\"is\");\r\n            result[2].ShouldEqual(\"the\");\r\n            result[3].ShouldEqual(\"segments\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_extract_regex_segments()\r\n        {\r\n            // Given\r\n            const string path = \"/normal/(?<name>[A-Z]*)/again\";\r\n\r\n            // When\r\n            var result = this.extractor.Extract(path).ToArray();\r\n\r\n            // Then\r\n            result.ShouldHaveCount(3);\r\n            result[0].ShouldEqual(\"normal\");\r\n            result[1].ShouldEqual(\"(?<name>[A-Z]*)\");\r\n            result[2].ShouldEqual(\"again\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_extract_regex_with_segments_that_contains_paths()\r\n        {\r\n            // Given\r\n            const string path = \"/normal/(?<name>/sub/path/[A-Z]*)/again\";\r\n\r\n            // When\r\n            var result = this.extractor.Extract(path).ToArray();\r\n\r\n            // Then\r\n            result.ShouldHaveCount(3);\r\n            result[0].ShouldEqual(\"normal\");\r\n            result[1].ShouldEqual(\"(?<name>/sub/path/[A-Z]*)\");\r\n            result[2].ShouldEqual(\"again\");\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Routing/NotFoundRouteFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Routing\r\n{\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Routing;\r\n    using Xunit;\r\n\r\n    public class NotFoundRouteFixture\r\n    {\r\n        private readonly Route route;\r\n\r\n        public NotFoundRouteFixture()\r\n        {\r\n            this.route = new NotFoundRoute(\"GET\", \"/test\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_route_property_when_instantiated()\r\n        {\r\n            //Given, When, Then\r\n            this.route.Description.Path.ShouldEqual(\"/test\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_set_action_that_returns_not_found_when_instantiated()\r\n        {\r\n            //Given, When\r\n            var response = await this.route.Invoke(new DynamicDictionary(), new CancellationToken());\r\n\r\n            // Then\r\n            response.ShouldBeOfType<NotFoundResponse>();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Routing/RouteCacheFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Routing\r\n{\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Culture;\r\n    using Nancy.Routing;\r\n    using Nancy.Tests.Fakes;\r\n\r\n    using Xunit;\r\n\r\n    public class RouteCacheFixture\r\n    {\r\n        private readonly INancyModuleCatalog fakeModuleCatalog;\r\n        private readonly IRouteCache routeCache;\r\n        private readonly IRouteSegmentExtractor routeSegmentExtractor;\r\n        private readonly IRouteDescriptionProvider routeDescriptionProvider;\r\n        private readonly IEnumerable<IRouteMetadataProvider> routeMetadataProviders;\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the RouteCacheFixture class.\r\n        /// </summary>\r\n        public RouteCacheFixture()\r\n        {\r\n            this.routeDescriptionProvider = A.Fake<IRouteDescriptionProvider>();\r\n            this.routeSegmentExtractor = A.Fake<IRouteSegmentExtractor>();\r\n            this.routeMetadataProviders = ArrayCache.Empty<IRouteMetadataProvider>();\r\n            this.fakeModuleCatalog = new FakeModuleCatalog();\r\n\r\n            this.routeCache = new RouteCache(\r\n                    this.fakeModuleCatalog,\r\n                    A.Fake<INancyContextFactory>(),\r\n                    this.routeSegmentExtractor,\r\n                    this.routeDescriptionProvider,\r\n                    A.Fake<ICultureService>(),\r\n                    this.routeMetadataProviders);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_Contain_Entries_For_All_Modules()\r\n        {\r\n            // Given, When\r\n            var routes = (from cacheEntry in this.routeCache.Keys\r\n                         select cacheEntry).ToList();\r\n\r\n            // Then\r\n            routes.Contains(typeof(FakeNancyModuleWithBasePath)).ShouldBeTrue();\r\n            routes.Contains(typeof(FakeNancyModuleWithoutBasePath)).ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_Contain_Entries_For_All_Routes()\r\n        {\r\n            // Given\r\n            var total = this.fakeModuleCatalog.GetAllModules(new NancyContext()).Sum(nm => nm.Routes.Count());\r\n\r\n            // When\r\n            var cacheEntriesTotal = this.routeCache.Values.Sum(c => c.Count());\r\n\r\n            // Then\r\n            cacheEntriesTotal.ShouldEqual(total);\r\n        }\r\n\r\n        [Fact]\r\n        public void Sets_Filter_If_Specified()\r\n        {\r\n            // Given\r\n            var routes = from cacheEntry in this.routeCache.Values\r\n                         from route in cacheEntry\r\n                         where route.Item2.Path == \"/filtered\"\r\n                         select route.Item2;\r\n\r\n            // When\r\n            var filteredRoute = routes.First();\r\n\r\n            // Then\r\n            filteredRoute.Condition.ShouldNotBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Filter_Is_Null_If_Not_Specified()\r\n        {\r\n            // Given\r\n            var routes = from cacheEntry in this.routeCache.Values\r\n                         from route in cacheEntry\r\n                         where route.Item2.Path == \"/\"\r\n                         select route.Item2;\r\n\r\n            // When\r\n            var filteredRoute = routes.First();\r\n\r\n            // Then\r\n            filteredRoute.Condition.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Sets_Method()\r\n        {\r\n            // Given, When\r\n            var methods = (from cacheEntry in routeCache.Values\r\n                          from route in cacheEntry\r\n                          select route.Item2.Method).Distinct();\r\n\r\n            // Then\r\n            methods.Count().ShouldEqual(4);\r\n        }\r\n\r\n        [Fact]\r\n        public void Index_Set_Correctly_In_Cache()\r\n        {\r\n            // Given\r\n            var routes = this.fakeModuleCatalog\r\n                .GetModule(typeof(FakeNancyModuleWithBasePath), new NancyContext()).Routes.Select(r => r.Description)\r\n                .ToList();\r\n\r\n            // When\r\n            var cachedRoutes = this.routeCache[typeof(FakeNancyModuleWithBasePath)];\r\n\r\n            // Then\r\n            foreach (var cachedRoute in cachedRoutes)\r\n            {\r\n                var index = cachedRoute.Item1;\r\n                cachedRoute.Item2.ShouldBeSameAs(routes.ElementAt(index));\r\n            }\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_route_description_provider_with_module_that_route_is_defined_in()\r\n        {\r\n            // Given\r\n            var module = new FakeNancyModule(with =>\r\n            {\r\n                with.AddGetRoute(\"/\");\r\n            });\r\n\r\n            var catalog = A.Fake<INancyModuleCatalog>();\r\n            A.CallTo(() => catalog.GetAllModules(A<NancyContext>._)).Returns(new[] { module });\r\n\r\n            var descriptionProvider =\r\n                A.Fake<IRouteDescriptionProvider>();\r\n\r\n            // When\r\n            var cache = new RouteCache(\r\n                catalog,\r\n                A.Fake<INancyContextFactory>(),\r\n                this.routeSegmentExtractor,\r\n                descriptionProvider,\r\n                A.Fake<ICultureService>(),\r\n                ArrayCache.Empty<IRouteMetadataProvider>());\r\n\r\n            // Then\r\n            A.CallTo(() => descriptionProvider.GetDescription(module, A<string>._)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_route_description_provider_with_path_of_route()\r\n        {\r\n            // Given\r\n            const string expectedPath = \"/some/path/{capture}\";\r\n\r\n            var module = new FakeNancyModule(with =>\r\n            {\r\n                with.AddGetRoute(expectedPath);\r\n            });\r\n\r\n            var catalog = A.Fake<INancyModuleCatalog>();\r\n            A.CallTo(() => catalog.GetAllModules(A<NancyContext>._)).Returns(new[] { module });\r\n\r\n            var descriptionProvider =\r\n                A.Fake<IRouteDescriptionProvider>();\r\n\r\n            // When\r\n            var cache = new RouteCache(\r\n                catalog,\r\n                A.Fake<INancyContextFactory>(),\r\n                this.routeSegmentExtractor,\r\n                descriptionProvider,\r\n                A.Fake<ICultureService>(),\r\n                ArrayCache.Empty<IRouteMetadataProvider>());\r\n\r\n            // Then\r\n            A.CallTo(() => descriptionProvider.GetDescription(A<NancyModule>._, expectedPath)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_route_metadata_provider_with_module_that_route_is_defined_in()\r\n        {\r\n            // Given\r\n            var module = new FakeNancyModule(with =>\r\n            {\r\n                with.AddGetRoute(\"/\");\r\n            });\r\n\r\n            var catalog = A.Fake<INancyModuleCatalog>();\r\n            A.CallTo(() => catalog.GetAllModules(A<NancyContext>._)).Returns(new[] { module });\r\n\r\n            var metadataProvider =\r\n                A.Fake<IRouteMetadataProvider>();\r\n\r\n            // When\r\n            new RouteCache(\r\n                catalog,\r\n                A.Fake<INancyContextFactory>(),\r\n                this.routeSegmentExtractor,\r\n                A.Fake<IRouteDescriptionProvider>(),\r\n                A.Fake<ICultureService>(),\r\n                new[] { metadataProvider });\r\n\r\n            // Then\r\n            A.CallTo(() => metadataProvider.GetMetadata(module, A<RouteDescription>._)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_handle_null_metadata()\r\n        {\r\n            // Given\r\n            var module = new FakeNancyModule(with =>\r\n            {\r\n                with.AddGetRoute(\"/\");\r\n            });\r\n\r\n            var catalog = A.Fake<INancyModuleCatalog>();\r\n            A.CallTo(() => catalog.GetAllModules(A<NancyContext>._)).Returns(new[] { module });\r\n\r\n            var metadataProvider = A.Fake<IRouteMetadataProvider>();\r\n            A.CallTo(() => metadataProvider.GetMetadata(null, null)).WithAnyArguments().Returns(null);\r\n\r\n            // When\r\n            var cache = new RouteCache(\r\n                catalog,\r\n                A.Fake<INancyContextFactory>(),\r\n                this.routeSegmentExtractor,\r\n                A.Fake<IRouteDescriptionProvider>(),\r\n                A.Fake<ICultureService>(),\r\n                new[] { metadataProvider });\r\n\r\n            // Then\r\n            cache[module.GetType()][0].Item2.Metadata.Raw.Count.ShouldEqual(0);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Routing/RouteDescriptionFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Routing\r\n{\r\n    using System;\r\n    using Nancy.Routing;\r\n    using Xunit;\r\n\r\n    public class RouteDescriptionFixture\r\n    {\r\n        [Fact]\r\n        public void Should_throw_argumentexception_when_instantiated_with_null_method()\r\n        {\r\n            //Given, When\r\n            var exception =\r\n                Record.Exception(() => new RouteDescription(string.Empty, null, \"/\", null, typeof(object)));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ArgumentException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_argumentexception_when_instantiated_with_empty_method()\r\n        {\r\n            //Given, When\r\n            var exception =\r\n                Record.Exception(() => new RouteDescription(string.Empty, \"\", \"/\", null, typeof(object)));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ArgumentException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_argumentexception_when_instantiated_with_null_path()\r\n        {\r\n            //Given, When\r\n            var exception =\r\n                Record.Exception(() => new RouteDescription(string.Empty, \"GET\", null, null, typeof(object)));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ArgumentException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_argumentexception_when_instantiated_with_empty_path()\r\n        {\r\n            //Given, When\r\n            var exception =\r\n                Record.Exception(() => new RouteDescription(string.Empty, \"GET\", \"\", null, typeof(object)));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ArgumentException>();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(typeof(object))]\r\n        [InlineData(typeof(int))]\r\n        [InlineData(typeof(string))]\r\n        public void Should_set_return_type_property(Type returnType)\r\n        {\r\n            // Given, When\r\n            var description =\r\n                new RouteDescription(string.Empty, \"GET\", \"/\", null, returnType);\r\n\r\n            // Then\r\n            description.ReturnType.ShouldEqual(returnType);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Routing/RouteFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Routing\r\n{\r\n    using System;\r\n    using System.Threading;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Routing;\r\n    using Xunit;\r\n\r\n    public class RouteFixture\r\n    {\r\n        [Fact]\r\n        public void Should_throw_argumentexception_when_instantiated_with_null_method()\r\n        {\r\n            //Given, When\r\n            var exception =\r\n                Record.Exception(() =>\r\n                {\r\n                    return new Route<object>(null, \"\", null, x => true, (args, ct) => null);\r\n                });\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ArgumentException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_argumentexception_when_instantiated_with_empty_method()\r\n        {\r\n            //Given, When\r\n            var exception =\r\n                Record.Exception(() =>\r\n                {\r\n                    return new Route<object>(\"\", \"/\", null, x => true, (args, ct) => null);\r\n                });\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ArgumentException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_argumentexception_when_instantiated_with_null_path()\r\n        {\r\n            //Given, When\r\n            var exception =\r\n                Record.Exception(() =>\r\n                {\r\n                    return new Route<object>(\"GET\", null, null, x => true, (args, ct) => null);\r\n                });\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ArgumentException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_argumentexception_when_instantiated_with_empty_path()\r\n        {\r\n            //Given, When\r\n            var exception =\r\n                Record.Exception(() =>\r\n                {\r\n                    new Route<object>(\"GET\", null, null, x => true, (args, ct) => null);\r\n                });\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ArgumentException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_action_with_parameters_when_invoked()\r\n        {\r\n            //Given\r\n            DynamicDictionary capturedParameters = null;\r\n\r\n            Func<dynamic, CancellationToken, Task<object>> action = (args, ct) =>\r\n            {\r\n                capturedParameters = args;\r\n                return Task.FromResult<object>(null);\r\n            };\r\n\r\n            dynamic parameters = new DynamicDictionary();\r\n            parameters.foo = 10;\r\n            parameters.bar = \"value\";\r\n\r\n            var route = new Route<object>(\"GET\", \"/\", null, action);\r\n\r\n            // When\r\n            route.Invoke(parameters, new CancellationToken());\r\n\r\n            // Then\r\n            capturedParameters.ShouldBeSameAs((object)parameters);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_response_from_action_when_invoked()\r\n        {\r\n            //Given\r\n            var expectedResponse = new Response();\r\n            Func<dynamic, CancellationToken, Task<Response>> action = (args, ct) => Task.FromResult(expectedResponse);\r\n\r\n            var route = new Route<Response>(\"GET\", \"/\", null, action);\r\n\r\n            // When\r\n            var response = await route.Invoke(new DynamicDictionary(), new CancellationToken());\r\n\r\n            // Then\r\n            response.ShouldBeSameAs(expectedResponse);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Security/ClaimsPrincipalExtensionsFixture.cs",
    "content": "namespace Nancy.Tests.Unit.Security\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Security.Claims;\r\n\r\n    using Nancy.Security;\r\n\r\n    using Xunit;\r\n\r\n    public class ClaimsPrincipalExtensionsFixture\r\n    {\r\n        [Fact]\r\n        public void Should_return_false_for_authentication_if_the_user_is_null()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = null;\r\n\r\n            // When\r\n            var result = user.IsAuthenticated();\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_for_authentication_if_the_identity_is_anonymous()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = new ClaimsPrincipal(new ClaimsIdentity());\r\n\r\n            // When\r\n            var result = user.IsAuthenticated();\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_for_required_claim_if_the_claims_are_null()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = GetFakeUser(\"Fake\");\r\n            var requiredClaim = \"not-present-claim\";\r\n\r\n            // When\r\n            var result = user.HasClaim(c => c.Type == requiredClaim);\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n        \r\n        [Fact]\r\n        public void Should_return_false_for_required_claim_if_the_user_does_not_have_claim()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = GetFakeUser(\"Fake\", new Claim(\"present-claim\", string.Empty));\r\n            var requiredClaim = \"not-present-claim\";\r\n\r\n            // When\r\n            var result = user.HasClaim(c => c.Type == requiredClaim);\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_for_required_claim_if_the_user_does_have_claim()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = GetFakeUser(\"Fake\", new Claim(\"present-claim\", string.Empty));\r\n            var requiredClaim = \"present-claim\";\r\n\r\n            // When\r\n            var result = user.HasClaim(c => c.Type == requiredClaim);\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_for_required_claims_if_the_user_is_null()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = null;\r\n            var requiredClaims = new[] { \"not-present-claim1\", \"not-present-claim2\" };\r\n\r\n            // When\r\n            var result = user.HasClaims(c => requiredClaims.Contains(c.Type));\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_for_required_claims_if_the_claims_are_null()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = GetFakeUser(\"Fake\");\r\n            var requiredClaims = new[] { \"not-present-claim1\", \"not-present-claim2\" };\r\n\r\n            // When\r\n            var result = user.HasClaims(c => requiredClaims.Contains(c.Type));\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n        \r\n        [Fact]\r\n        public void Should_return_false_for_required_claims_if_the_user_does_not_have_all_claims()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = GetFakeUser(\"Fake\",\r\n                new Claim(\"present-claim1\", string.Empty),\r\n                new Claim(\"present-claim2\", string.Empty),\r\n                new Claim(\"present-claim3\", string.Empty));\r\n            var requiredClaims = new Predicate<Claim>[]\r\n            {\r\n                c => c.Type == \"present-claim1\",\r\n                c => c.Type == \"not-present-claim1\"\r\n            };\r\n\r\n            // When\r\n            var result = user.HasClaims(requiredClaims);\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_for_required_claims_if_the_user_does_have_all_claims()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = GetFakeUser(\"Fake\",\r\n                new Claim(\"present-claim1\", string.Empty),\r\n                new Claim(\"present-claim2\", string.Empty),\r\n                new Claim(\"present-claim3\", string.Empty));\r\n            var requiredClaims = new Predicate<Claim>[]\r\n            {\r\n                c => c.Type == \"present-claim1\",\r\n                c => c.Type == \"present-claim2\"\r\n            };\r\n\r\n            // When\r\n            var result = user.HasClaims(requiredClaims);\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_for_any_required_claim_if_the_user_is_null()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = null;\r\n            var requiredClaims = new[] { \"not-present-claim1\", \"not-present-claim2\" };\r\n\r\n            // When\r\n            var result = user.HasAnyClaim(c => requiredClaims.Contains(c.Type));\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_for_any_required_claim_if_the_claims_are_null()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = GetFakeUser(\"Fake\");\r\n            var requiredClaims = new[] { \"not-present-claim1\", \"not-present-claim2\" };\r\n\r\n            // When\r\n            var result = user.HasAnyClaim(c => requiredClaims.Contains(c.Type));\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n        \r\n        [Fact]\r\n        public void Should_return_false_for_any_required_claim_if_the_user_does_not_have_any_claim()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = GetFakeUser(\"Fake\",\r\n                new Claim(\"present-claim1\", string.Empty),\r\n                new Claim(\"present-claim2\", string.Empty),\r\n                new Claim(\"present-claim3\", string.Empty));\r\n            var requiredClaims = new[] { \"not-present-claim1\", \"not-present-claim2\" };\r\n\r\n            // When\r\n            var result = user.HasAnyClaim(c => requiredClaims.Contains(c.Type));\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_for_any_required_claim_if_the_user_does_have_any_of_claim()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = GetFakeUser(\"Fake\",\r\n                new Claim(\"present-claim1\", string.Empty),\r\n                new Claim(\"present-claim2\", string.Empty),\r\n                new Claim(\"present-claim3\", string.Empty));\r\n            var requiredClaims = new[] { \"present-claim1\", \"not-present-claim1\" };\r\n\r\n            // When\r\n            var result = user.HasAnyClaim(c => requiredClaims.Contains(c.Type));\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_for_valid_claim_if_the_user_is_null()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = null;\r\n            Func<IEnumerable<Claim>, bool> isValid = claims => true;\r\n\r\n            // When\r\n            var result = user.HasValidClaims(isValid);\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_for_valid_claim_if_the_validation_fails()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = GetFakeUser(\"Fake\",\r\n                new Claim(\"present-claim1\", string.Empty),\r\n                new Claim(\"present-claim2\", string.Empty),\r\n                new Claim(\"present-claim3\", string.Empty));\r\n            Func<IEnumerable<Claim>, bool> isValid = claims => false;\r\n\r\n            // When\r\n            var result = user.HasValidClaims(isValid);\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_for_valid_claim_if_the_validation_succeeds()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = GetFakeUser(\"Fake\",\r\n                new Claim(\"present-claim1\", string.Empty),\r\n                new Claim(\"present-claim2\", string.Empty),\r\n                new Claim(\"present-claim3\", string.Empty));\r\n            Func<IEnumerable<Claim>, bool> isValid = claims => true;\r\n\r\n            // When\r\n            var result = user.HasValidClaims(isValid);\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_call_validation_with_users_claims()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = GetFakeUser(\"Fake\");\r\n\r\n            IEnumerable<Claim> validatedClaims = null;\r\n            Func<IEnumerable<Claim>, bool> isValid = claims =>\r\n            {\r\n                // store passed claims for testing assertion\r\n                validatedClaims = claims;\r\n                return true;\r\n            };\r\n\r\n            // When\r\n            user.HasValidClaims(isValid);\r\n\r\n            // Then\r\n            validatedClaims.ShouldEqualSequence(user.Claims);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_for_required_role_if_the_roles_are_null()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = GetFakeUser(\"Fake\");\r\n            var requiredRole = \"not-present-role\";\r\n\r\n            // When\r\n            var result = user.IsInRole(requiredRole);\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n        \r\n        [Fact]\r\n        public void Should_return_false_for_required_role_if_the_user_does_not_have_role()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = GetFakeUser(\"Fake\", new Claim(ClaimTypes.Role, string.Empty));\r\n            var requiredRole = \"not-present-role\";\r\n\r\n            // When\r\n            var result = user.IsInRole(requiredRole);\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_for_required_role_if_the_user_does_have_role()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = GetFakeUser(\"Fake\", new Claim(ClaimTypes.Role, \"present-role\"));\r\n            var requiredRole = \"present-role\";\r\n\r\n            // When\r\n            var result = user.IsInRole(requiredRole);\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_for_required_roles_if_the_user_is_null()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = null;\r\n            var requiredRoles = new string[] { \"not-present-role1\", \"not-present-role2\" };\r\n\r\n            // When\r\n            var result = user.IsInRoles(requiredRoles);\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_for_required_roles_if_the_roles_are_null()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = GetFakeUser(\"Fake\");\r\n            string[] requiredRoles = null;\r\n\r\n            // When\r\n            var result = user.IsInRoles(requiredRoles);\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n        \r\n        [Fact]\r\n        public void Should_return_false_for_required_roles_if_the_user_does_not_have_all_roles()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = GetFakeUser(\"Fake\",\r\n                new Claim(ClaimTypes.Role, \"present-role1\"),\r\n                new Claim(ClaimTypes.Role, \"present-role2\"),\r\n                new Claim(ClaimTypes.Role, \"present-role3\"));\r\n            var requiredRoles = new string[]\r\n            {\r\n                \"present-role1\",\r\n                \"not-present-role1\"\r\n            };\r\n\r\n            // When\r\n            var result = user.IsInRoles(requiredRoles);\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_for_required_roles_if_the_user_does_have_all_roles()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = GetFakeUser(\"Fake\",\r\n                new Claim(ClaimTypes.Role, \"present-role1\"),\r\n                new Claim(ClaimTypes.Role, \"present-role2\"),\r\n                new Claim(ClaimTypes.Role, \"present-role3\"));\r\n            var requiredRoles = new string[]\r\n            {\r\n                \"present-role1\",\r\n                \"present-role2\"\r\n            };\r\n\r\n            // When\r\n            var result = user.IsInRoles(requiredRoles);\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_for_any_required_role_if_the_user_is_null()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = null;\r\n            var requiredRoles = new string[] { \"not-present-role1\", \"not-present-role2\" };\r\n\r\n            // When\r\n            var result = user.IsInAnyRole(requiredRoles);\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_for_any_required_role_if_the_roles_are_null()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = GetFakeUser(\"Fake\");\r\n            string[] requiredRoles = null;\r\n\r\n            // When\r\n            var result = user.IsInAnyRole(requiredRoles);\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n        \r\n        [Fact]\r\n        public void Should_return_false_for_any_required_role_if_the_user_does_not_have_any_role()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = GetFakeUser(\"Fake\",\r\n                new Claim(ClaimTypes.Role, \"present-role1\"),\r\n                new Claim(ClaimTypes.Role, \"present-role2\"),\r\n                new Claim(ClaimTypes.Role, \"present-role3\"));\r\n            var requiredRoles = new string[] { \"not-present-role1\", \"not-present-role2\" };\r\n\r\n            // When\r\n            var result = user.IsInAnyRole(requiredRoles);\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_for_any_required_role_if_the_user_does_have_any_of_role()\r\n        {\r\n            // Given\r\n            ClaimsPrincipal user = GetFakeUser(\"Fake\",\r\n                new Claim(ClaimTypes.Role, \"present-role1\"),\r\n                new Claim(ClaimTypes.Role, \"present-role2\"),\r\n                new Claim(ClaimTypes.Role, \"present-role3\"));\r\n            var requiredRoles = new string[] { \"present-role1\", \"not-present-role1\" };\r\n\r\n            // When\r\n            var result = user.IsInAnyRole(requiredRoles);\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        private static ClaimsPrincipal GetFakeUser(string userName, params Claim[] claims)\r\n        {\r\n            var claimsList = (claims ?? Enumerable.Empty<Claim>()).ToList();\r\n            claimsList.Add(new Claim(ClaimTypes.NameIdentifier, userName));\r\n\r\n            return new ClaimsPrincipal(new ClaimsIdentity(claimsList));\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Security/CsrfFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Security\r\n{\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using System.Threading;\r\n    using FakeItEasy;\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Cryptography;\r\n    using Nancy.Security;\r\n    using Nancy.Tests.Fakes;\r\n\r\n    using Xunit;\r\n\r\n    public class CsrfFixture\r\n    {\r\n        private readonly IPipelines pipelines;\r\n        private readonly Request request;\r\n        private readonly FakeRequest optionsRequest;\r\n        private readonly Response response;\r\n        private readonly CryptographyConfiguration cryptographyConfiguration;\r\n\r\n        public CsrfFixture()\r\n        {\r\n            this.pipelines = new MockPipelines();\r\n\r\n            this.cryptographyConfiguration = CryptographyConfiguration.Default;\r\n            var csrfStartup = new CsrfApplicationStartup(\r\n                this.cryptographyConfiguration,\r\n                new DefaultCsrfTokenValidator(this.cryptographyConfiguration));\r\n\r\n            csrfStartup.Initialize(this.pipelines);\r\n            Csrf.Enable(this.pipelines);\r\n\r\n            this.request = new FakeRequest(\"GET\", \"/\");\r\n\r\n            this.optionsRequest = new FakeRequest(\"OPTIONS\", \"/\");\r\n\r\n            this.response = new Response();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_create_cookie_in_response_if_token_exists_in_context()\r\n        {\r\n            // Given\r\n            var context = new NancyContext { Request = this.request, Response = this.response };\r\n            context.Items[CsrfToken.DEFAULT_CSRF_KEY] = \"TestingToken\";\r\n\r\n            // When\r\n            this.pipelines.AfterRequest.Invoke(context, new CancellationToken());\r\n\r\n            // Then\r\n            this.response.Cookies.Any(c => c.Name == CsrfToken.DEFAULT_CSRF_KEY).ShouldBeTrue();\r\n            this.response.Cookies.FirstOrDefault(c => c.Name == CsrfToken.DEFAULT_CSRF_KEY).Value.ShouldEqual(\"TestingToken\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_copy_request_cookie_to_context_but_not_response_if_it_exists_and_context_does_not_contain_token()\r\n        {\r\n            // Given\r\n            this.request.Cookies.Add(CsrfToken.DEFAULT_CSRF_KEY, \"ValidToken\");\r\n            var fakeValidator = A.Fake<ICsrfTokenValidator>();\r\n\r\n            A.CallTo(() => fakeValidator.CookieTokenStillValid(A<CsrfToken>.Ignored)).Returns(true);\r\n\r\n            var csrfStartup = new CsrfApplicationStartup(\r\n                this.cryptographyConfiguration,\r\n                fakeValidator);\r\n\r\n            csrfStartup.Initialize(this.pipelines);\r\n            var context = new NancyContext { Request = this.request, Response = this.response };\r\n\r\n            // When\r\n            this.pipelines.AfterRequest.Invoke(context, new CancellationToken());\r\n\r\n            // Then\r\n            this.response.Cookies.Any(c => c.Name == CsrfToken.DEFAULT_CSRF_KEY).ShouldBeFalse();\r\n            context.Items.ContainsKey(CsrfToken.DEFAULT_CSRF_KEY).ShouldBeTrue();\r\n            context.Items[CsrfToken.DEFAULT_CSRF_KEY].ShouldEqual(\"ValidToken\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_generate_a_new_token_on_an_options_request_and_not_add_a_cookie()\r\n        {\r\n            // Given\r\n            this.optionsRequest.Cookies.Add(CsrfToken.DEFAULT_CSRF_KEY, \"ValidToken\");\r\n\r\n            var fakeValidator = A.Fake<ICsrfTokenValidator>();\r\n            A.CallTo(() => fakeValidator.CookieTokenStillValid(A<CsrfToken>.Ignored)).Returns(true);\r\n\r\n            var csrfStartup = new CsrfApplicationStartup(\r\n                this.cryptographyConfiguration,\r\n                fakeValidator);\r\n\r\n            csrfStartup.Initialize(this.pipelines);\r\n            var context = new NancyContext { Request = this.optionsRequest, Response = this.response };\r\n            context.Items[CsrfToken.DEFAULT_CSRF_KEY] = \"ValidToken\";\r\n\r\n            // When\r\n            this.pipelines.AfterRequest.Invoke(context, new CancellationToken());\r\n\r\n            // Then\r\n            this.response.Cookies.Any(c => c.Name == CsrfToken.DEFAULT_CSRF_KEY).ShouldBeFalse();\r\n            context.Items.ContainsKey(CsrfToken.DEFAULT_CSRF_KEY).ShouldBeTrue();\r\n            context.Items[CsrfToken.DEFAULT_CSRF_KEY].ShouldEqual(\"ValidToken\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_regenerage_token_if_invalid()\r\n        {\r\n            // Given\r\n            this.request.Cookies.Add(CsrfToken.DEFAULT_CSRF_KEY, \"InvalidToken\");\r\n            var fakeValidator = A.Fake<ICsrfTokenValidator>();\r\n\r\n            A.CallTo(() => fakeValidator.CookieTokenStillValid(A<CsrfToken>.Ignored)).Returns(false);\r\n\r\n            var csrfStartup = new CsrfApplicationStartup(\r\n                this.cryptographyConfiguration,\r\n                fakeValidator);\r\n\r\n            csrfStartup.Initialize(this.pipelines);\r\n            var context = new NancyContext { Request = this.request, Response = this.response };\r\n\r\n            // When\r\n            this.pipelines.AfterRequest.Invoke(context, new CancellationToken());\r\n\r\n            // Then\r\n            this.response.Cookies.Any(c => c.Name == CsrfToken.DEFAULT_CSRF_KEY).ShouldBeTrue();\r\n            context.Items.ContainsKey(CsrfToken.DEFAULT_CSRF_KEY).ShouldBeTrue();\r\n            context.Items[CsrfToken.DEFAULT_CSRF_KEY].ShouldNotEqual(\"InvalidToken\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_http_decode_cookie_token_when_copied_to_the_context()\r\n        {\r\n            // Given\r\n            var fakeValidator = A.Fake<ICsrfTokenValidator>();\r\n            A.CallTo(() => fakeValidator.CookieTokenStillValid(A<CsrfToken>.Ignored)).Returns(true);\r\n\r\n            var csrfStartup = new CsrfApplicationStartup(\r\n                this.cryptographyConfiguration,\r\n                fakeValidator);\r\n\r\n            csrfStartup.Initialize(this.pipelines);\r\n            this.request.Cookies.Add(CsrfToken.DEFAULT_CSRF_KEY, \"Testing Token\");\r\n            var context = new NancyContext { Request = this.request, Response = this.response };\r\n\r\n            // When\r\n            this.pipelines.AfterRequest.Invoke(context, new CancellationToken());\r\n\r\n            // Then\r\n            this.response.Cookies.Any(c => c.Name == CsrfToken.DEFAULT_CSRF_KEY).ShouldBeFalse();\r\n            context.Items.ContainsKey(CsrfToken.DEFAULT_CSRF_KEY).ShouldBeTrue();\r\n            context.Items[CsrfToken.DEFAULT_CSRF_KEY].ShouldEqual(\"Testing Token\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_create_a_new_token_if_one_doesnt_exist_in_request_or_context()\r\n        {\r\n            // Given\r\n            var context = new NancyContext { Request = this.request, Response = this.response };\r\n\r\n            // When\r\n            this.pipelines.AfterRequest.Invoke(context, new CancellationToken());\r\n\r\n            // Then\r\n            this.response.Cookies.Any(c => c.Name == CsrfToken.DEFAULT_CSRF_KEY).ShouldBeTrue();\r\n            context.Items.ContainsKey(CsrfToken.DEFAULT_CSRF_KEY).ShouldBeTrue();\r\n            var cookieValue = this.response.Cookies.FirstOrDefault(c => c.Name == CsrfToken.DEFAULT_CSRF_KEY).Value;\r\n            var contextValue = context.Items[CsrfToken.DEFAULT_CSRF_KEY];\r\n            cookieValue.ShouldNotBeEmpty();\r\n            cookieValue.ShouldEqual(contextValue);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_disable_csrf()\r\n        {\r\n            // Given\r\n            var context = new NancyContext { Request = this.request, Response = this.response };\r\n            context.Items[CsrfToken.DEFAULT_CSRF_KEY] = \"TestingToken\";\r\n\r\n            Csrf.Disable(this.pipelines);\r\n\r\n            // When\r\n            this.pipelines.AfterRequest.Invoke(context, new CancellationToken());\r\n\r\n            // Then\r\n            this.response.Cookies.Any(c => c.Name == CsrfToken.DEFAULT_CSRF_KEY).ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void ValidateCsrfToken_gets_provided_token_from_form_data()\r\n        {\r\n            // Given\r\n            var token = Csrf.GenerateTokenString();\r\n            var context = new NancyContext { Request = this.request };\r\n            var module = new FakeNancyModule { Context = context };\r\n\r\n            // When\r\n            context.Request.Form[CsrfToken.DEFAULT_CSRF_KEY] = token;\r\n            context.Request.Cookies.Add(CsrfToken.DEFAULT_CSRF_KEY, token);\r\n\r\n            // Then\r\n            module.ValidateCsrfToken();\r\n        }\r\n\r\n        [Fact]\r\n        public void ValidateCsrfToken_gets_provided_token_from_request_header_if_not_present_in_form_data()\r\n        {\r\n            // Given\r\n            var token = Csrf.GenerateTokenString();\r\n            var context = new NancyContext();\r\n            var module = new FakeNancyModule { Context = context };\r\n\r\n            // When\r\n            context.Request = RequestWithHeader(CsrfToken.DEFAULT_CSRF_KEY, token);\r\n            context.Request.Cookies.Add(CsrfToken.DEFAULT_CSRF_KEY, token);\r\n\r\n            // Then\r\n            module.ValidateCsrfToken();\r\n        }\r\n\r\n        private static FakeRequest RequestWithHeader(string header, string value)\r\n        {\r\n            return new FakeRequest(\"GET\", \"/\", new Dictionary<string, IEnumerable<string>> { { header, new[] { value } } });\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Security/DefaultCsrfTokenValidatorFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Security\r\n{\r\n    using System;\r\n\r\n    using Nancy.Cryptography;\r\n    using Nancy.Security;\r\n\r\n    using Xunit;\r\n\r\n    public class DefaultCsrfTokenValidatorFixture\r\n    {\r\n        private readonly ICsrfTokenValidator validator;\r\n        private readonly IHmacProvider hmacProvider;\r\n\r\n        public DefaultCsrfTokenValidatorFixture()\r\n        {\r\n            var cryptoConfig = CryptographyConfiguration.Default;\r\n            this.hmacProvider = cryptoConfig.HmacProvider;\r\n            this.validator = new DefaultCsrfTokenValidator(cryptoConfig);            \r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_token_missing_if_first_token_null()\r\n        {\r\n            var result = this.validator.Validate(null, new CsrfToken());\r\n\r\n            result.ShouldEqual(CsrfTokenValidationResult.TokenMissing);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_token_missing_if_second_token_null()\r\n        {\r\n            var result = this.validator.Validate(new CsrfToken(), null);\r\n\r\n            result.ShouldEqual(CsrfTokenValidationResult.TokenMissing);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_token_mismatch_if_tokens_differ()\r\n        {\r\n            DateTime date = DateTime.Now;\r\n            var tokenOne = new CsrfToken { CreatedDate = date, RandomBytes = new byte[] { 1, 2, 3 } };\r\n            var tokenTwo = new CsrfToken { CreatedDate = date, RandomBytes = new byte[] { 1, 4, 3 } };\r\n            tokenOne.CreateHmac(this.hmacProvider);\r\n            tokenTwo.CreateHmac(this.hmacProvider);\r\n\r\n            var result = this.validator.Validate(tokenOne, tokenTwo);\r\n\r\n            result.ShouldEqual(CsrfTokenValidationResult.TokenMismatch);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_token_ok_if_tokens_match_and_no_expiry_set()\r\n        {\r\n            DateTime date = DateTime.Now;\r\n            var tokenOne = new CsrfToken { CreatedDate = date, RandomBytes = new byte[] { 1, 2, 3 } };\r\n            var tokenTwo = new CsrfToken { CreatedDate = date, RandomBytes = new byte[] { 1, 2, 3 } };\r\n            tokenOne.CreateHmac(this.hmacProvider);\r\n            tokenTwo.CreateHmac(this.hmacProvider);\r\n\r\n            var result = this.validator.Validate(tokenOne, tokenTwo);\r\n\r\n            result.ShouldEqual(CsrfTokenValidationResult.Ok);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_token_mismatch_if_random_bytes_empty()\r\n        {\r\n            DateTime date = DateTime.Now;\r\n            var tokenOne = new CsrfToken { CreatedDate = date, RandomBytes = ArrayCache.Empty<byte>() };\r\n            var tokenTwo = new CsrfToken { CreatedDate = date, RandomBytes = ArrayCache.Empty<byte>() };\r\n            tokenOne.CreateHmac(this.hmacProvider);\r\n            tokenTwo.CreateHmac(this.hmacProvider);\r\n\r\n            var result = this.validator.Validate(tokenOne, tokenTwo);\r\n\r\n            result.ShouldEqual(CsrfTokenValidationResult.TokenTamperedWith);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_token_tampered_with_if_hmac_incorrect()\r\n        {\r\n            DateTime date = DateTime.Now;\r\n            var tokenOne = new CsrfToken { CreatedDate = date, RandomBytes = new byte[] { 1, 2, 3 } };\r\n            var tokenTwo = new CsrfToken { CreatedDate = date, RandomBytes = new byte[] { 1, 2, 3 } };\r\n            tokenOne.CreateHmac(this.hmacProvider);\r\n            tokenTwo.CreateHmac(this.hmacProvider);\r\n            tokenOne.Hmac[0] -= 1;\r\n            tokenTwo.Hmac[0] -= 1;\r\n\r\n            var result = this.validator.Validate(tokenOne, tokenTwo);\r\n\r\n            result.ShouldEqual(CsrfTokenValidationResult.TokenTamperedWith);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_token_expired_if_it_has()\r\n        {\r\n            DateTime date = DateTime.Now.AddHours(-1);\r\n            var tokenOne = new CsrfToken { CreatedDate = date, RandomBytes = new byte[] { 1, 2, 3 } };\r\n            var tokenTwo = new CsrfToken { CreatedDate = date, RandomBytes = new byte[] { 1, 2, 3 } };\r\n            tokenOne.CreateHmac(this.hmacProvider);\r\n            tokenTwo.CreateHmac(this.hmacProvider);\r\n\r\n            var result = this.validator.Validate(tokenOne, tokenTwo, validityPeriod: new TimeSpan(0, 30, 0));\r\n\r\n            result.ShouldEqual(CsrfTokenValidationResult.TokenExpired);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_ok_if_valid_and_not_expired()\r\n        {\r\n            DateTime date = DateTime.Now.AddHours(-1);\r\n            var tokenOne = new CsrfToken { CreatedDate = date, RandomBytes = new byte[] { 1, 2, 3 } };\r\n            var tokenTwo = new CsrfToken { CreatedDate = date, RandomBytes = new byte[] { 1, 2, 3 } };\r\n            tokenOne.CreateHmac(this.hmacProvider);\r\n            tokenTwo.CreateHmac(this.hmacProvider);\r\n\r\n            var result = this.validator.Validate(tokenOne, tokenTwo, validityPeriod: new TimeSpan(1, 30, 0));\r\n\r\n            result.ShouldEqual(CsrfTokenValidationResult.Ok);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_token_ok_if_tokens_match_and_no_salt()\r\n        {\r\n            DateTime date = DateTime.Now;\r\n            var tokenOne = new CsrfToken { CreatedDate = date, RandomBytes = new byte[] { 1, 2, 3 } };\r\n            var tokenTwo = new CsrfToken { CreatedDate = date, RandomBytes = new byte[] { 1, 2, 3 } };\r\n            tokenOne.CreateHmac(this.hmacProvider);\r\n            tokenTwo.CreateHmac(this.hmacProvider);\r\n\r\n            var result = this.validator.Validate(tokenOne, tokenTwo);\r\n\r\n            result.ShouldEqual(CsrfTokenValidationResult.Ok);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Security/ModuleSecurityFixture.cs",
    "content": "\r\nnamespace Nancy.Tests.Unit.Security\r\n{\r\n    using System;\r\n    using System.Linq;\r\n    using System.Security.Claims;\r\n    using System.Threading;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Responses;\r\n    using Nancy.Security;\r\n    using Nancy.Tests.Fakes;\r\n\r\n    using Xunit;\r\n\r\n    public class ModuleSecurityFixture\r\n    {\r\n        [Fact]\r\n        public void Should_add_an_item_to_the_end_of_the_begin_pipeline_when_RequiresAuthentication_enabled()\r\n        {\r\n            var module = new FakeHookedModule(A.Fake<BeforePipeline>());\r\n\r\n            module.RequiresAuthentication();\r\n\r\n            A.CallTo(() => module.Before.AddItemToEndOfPipeline(A<Func<NancyContext, Response>>.Ignored)).MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_two_items_to_the_end_of_the_begin_pipeline_when_RequiresClaims_enabled()\r\n        {\r\n            var module = new FakeHookedModule(A.Fake<BeforePipeline>());\r\n\r\n            module.RequiresClaims(_ => true);\r\n\r\n            A.CallTo(() => module.Before.AddItemToEndOfPipeline(A<Func<NancyContext, Response>>.Ignored)).MustHaveHappenedTwiceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_unauthorized_response_with_RequiresAuthentication_enabled_and_no_user()\r\n        {\r\n            var module = new FakeHookedModule(new BeforePipeline());\r\n            module.RequiresAuthentication();\r\n\r\n            var result = module.Before.Invoke(new NancyContext(), new CancellationToken());\r\n\r\n            result.Result.ShouldNotBeNull();\r\n            result.Result.StatusCode.ShouldEqual(HttpStatusCode.Unauthorized);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_unauthorized_response_with_RequiresAuthentication_enabled_and_no_identity()\r\n        {\r\n            var module = new FakeHookedModule(new BeforePipeline());\r\n            module.RequiresAuthentication();\r\n\r\n            var context = new NancyContext\r\n            {\r\n                CurrentUser = new ClaimsPrincipal()\r\n            };\r\n\r\n            var result = module.Before.Invoke(context, new CancellationToken());\r\n\r\n            result.Result.ShouldNotBeNull();\r\n            result.Result.StatusCode.ShouldEqual(HttpStatusCode.Unauthorized);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_with_RequiresAuthentication_enabled_and_user_provided()\r\n        {\r\n            var module = new FakeHookedModule(new BeforePipeline());\r\n            module.RequiresAuthentication();\r\n\r\n            var context = new NancyContext\r\n            {\r\n                CurrentUser = GetFakeUser(\"Bob\")\r\n            };\r\n\r\n            var result = module.Before.Invoke(context, new CancellationToken());\r\n\r\n            result.Result.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_forbidden_response_with_RequiresClaims_enabled_but_nonmatching_claims()\r\n        {\r\n            var module = new FakeHookedModule(new BeforePipeline());\r\n            module.RequiresClaims(c => c.Type == \"Claim1\");\r\n            var context = new NancyContext\r\n            {\r\n                CurrentUser = GetFakeUser(\r\n                    \"username\",\r\n                    new Claim(\"Claim2\", string.Empty),\r\n                    new Claim(\"Claim3\", string.Empty))\r\n            };\r\n\r\n            var result = module.Before.Invoke(context, new CancellationToken());\r\n\r\n            result.Result.ShouldNotBeNull();\r\n            result.Result.StatusCode.ShouldEqual(HttpStatusCode.Forbidden);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_forbidden_response_with_RequiresClaims_enabled_but_claims_key_missing()\r\n        {\r\n            var module = new FakeHookedModule(new BeforePipeline());\r\n            module.RequiresClaims(c => c.Type == \"Claim1\");\r\n            var context = new NancyContext\r\n            {\r\n                CurrentUser = GetFakeUser(\"username\")\r\n            };\r\n\r\n            var result = module.Before.Invoke(context, new CancellationToken());\r\n\r\n            result.Result.ShouldNotBeNull();\r\n            result.Result.StatusCode.ShouldEqual(HttpStatusCode.Forbidden);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_forbidden_response_with_RequiresClaims_enabled_but_not_all_claims_met()\r\n        {\r\n            var module = new FakeHookedModule(new BeforePipeline());\r\n            module.RequiresClaims(c => c.Type == \"Claim1\", c => c.Type == \"Claim2\");\r\n            var context = new NancyContext\r\n            {\r\n                CurrentUser = GetFakeUser(\r\n                    \"username\",\r\n                    new Claim(\"Claim2\", string.Empty))\r\n            };\r\n\r\n            var result = module.Before.Invoke(context, new CancellationToken());\r\n\r\n            result.Result.ShouldNotBeNull();\r\n            result.Result.StatusCode.ShouldEqual(HttpStatusCode.Forbidden);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_with_RequiresClaims_and_all_claims_met()\r\n        {\r\n            var module = new FakeHookedModule(new BeforePipeline());\r\n            module.RequiresClaims(c => c.Type == \"Claim1\", c => c.Type == \"Claim2\");\r\n            var context = new NancyContext\r\n            {\r\n                CurrentUser = GetFakeUser(\"username\",\r\n                new Claim(\"Claim1\", string.Empty),\r\n                new Claim(\"Claim2\", string.Empty),\r\n                new Claim(\"Claim3\", string.Empty))\r\n            };\r\n\r\n            var result = module.Before.Invoke(context, new CancellationToken());\r\n\r\n            result.Result.ShouldBeNull();\r\n        }\r\n\r\n\r\n        [Fact]\r\n        public void Should_return_forbidden_response_with_RequiresAnyClaim_enabled_but_nonmatching_claims()\r\n        {\r\n            var module = new FakeHookedModule(new BeforePipeline());\r\n            module.RequiresAnyClaim(c => c.Type == \"Claim1\");\r\n            var context = new NancyContext\r\n            {\r\n                CurrentUser = GetFakeUser(\r\n                    \"username\",\r\n                    new Claim(\"Claim2\", string.Empty),\r\n                    new Claim(\"Claim3\", string.Empty))\r\n            };\r\n\r\n            var result = module.Before.Invoke(context, new CancellationToken());\r\n\r\n            result.Result.ShouldNotBeNull();\r\n            result.Result.StatusCode.ShouldEqual(HttpStatusCode.Forbidden);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_forbidden_response_with_RequiresAnyClaim_enabled_but_claims_key_missing()\r\n        {\r\n            var module = new FakeHookedModule(new BeforePipeline());\r\n            module.RequiresAnyClaim(c => c.Type == \"Claim1\");\r\n            var context = new NancyContext\r\n            {\r\n                CurrentUser = GetFakeUser(\"username\")\r\n            };\r\n\r\n            var result = module.Before.Invoke(context, new CancellationToken());\r\n\r\n            result.Result.ShouldNotBeNull();\r\n            result.Result.StatusCode.ShouldEqual(HttpStatusCode.Forbidden);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_with_RequiresAnyClaim_and_any_claim_met()\r\n        {\r\n            var module = new FakeHookedModule(new BeforePipeline());\r\n            module.RequiresAnyClaim(c => c.Type == \"Claim1\", c => c.Type == \"Claim4\");\r\n            var context = new NancyContext\r\n            {\r\n                CurrentUser = GetFakeUser(\"username\",\r\n                    new Claim(\"Claim1\", string.Empty),\r\n                    new Claim(\"Claim2\", string.Empty),\r\n                    new Claim(\"Claim3\", string.Empty))\r\n            };\r\n\r\n            var result = module.Before.Invoke(context, new CancellationToken());\r\n\r\n            result.Result.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_redirect_response_when_request_url_is_non_secure_method_is_get_and_requires_https()\r\n        {\r\n            // Given\r\n            var module = new FakeHookedModule(new BeforePipeline());\r\n            var url = GetFakeUrl(false);\r\n            var context = new NancyContext\r\n            {\r\n                Request = new Request(\"GET\", url)\r\n            };\r\n\r\n            module.RequiresHttps();\r\n\r\n            // When\r\n            var result = module.Before.Invoke(context, new CancellationToken());\r\n\r\n            // Then\r\n            result.Result.ShouldNotBeNull();\r\n            result.Result.ShouldBeOfType<RedirectResponse>();\r\n\r\n            url.Scheme = \"https\";\r\n            url.Port = null;\r\n            result.Result.Headers[\"Location\"].ShouldEqual(url.ToString());\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_redirect_response_with_specific_port_number_when_request_url_is_non_secure_method_is_get_and_requires_https()\r\n        {\r\n            // Given\r\n            var module = new FakeHookedModule(new BeforePipeline());\r\n            var url = GetFakeUrl(false);\r\n            var context = new NancyContext\r\n            {\r\n                Request = new Request(\"GET\", url)\r\n            };\r\n\r\n            module.RequiresHttps(true, 999);\r\n\r\n            // When\r\n            var result = module.Before.Invoke(context, new CancellationToken());\r\n\r\n            // Then\r\n            result.Result.ShouldNotBeNull();\r\n            result.Result.ShouldBeOfType<RedirectResponse>();\r\n\r\n            url.Scheme = \"https\";\r\n            url.Port = 999;\r\n            result.Result.Headers[\"Location\"].ShouldEqual(url.ToString());\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_forbidden_response_when_request_url_is_non_secure_method_is_post_and_requires_https()\r\n        {\r\n            // Given\r\n            var module = new FakeHookedModule(new BeforePipeline());\r\n            var url = GetFakeUrl(false);\r\n            var context = new NancyContext\r\n            {\r\n                Request = new Request(\"POST\", url)\r\n            };\r\n\r\n            module.RequiresHttps();\r\n\r\n            // When\r\n            var result = module.Before.Invoke(context, new CancellationToken());\r\n\r\n            // Then\r\n            result.Result.ShouldNotBeNull();\r\n            result.Result.StatusCode.ShouldEqual(HttpStatusCode.Forbidden);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_forbidden_response_when_request_url_is_non_secure_method_is_delete_and_requires_https()\r\n        {\r\n            // Given\r\n            var module = new FakeHookedModule(new BeforePipeline());\r\n            var url = GetFakeUrl(false);\r\n            var context = new NancyContext\r\n            {\r\n                Request = new Request(\"DELETE\", url)\r\n            };\r\n\r\n            module.RequiresHttps();\r\n\r\n            // When\r\n            var result = module.Before.Invoke(context, new CancellationToken());\r\n\r\n            // Then\r\n            result.Result.ShouldNotBeNull();\r\n            result.Result.StatusCode.ShouldEqual(HttpStatusCode.Forbidden);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_forbidden_response_when_request_url_is_non_secure_method_is_get_and_requires_https_and_redirect_is_false()\r\n        {\r\n            // Given\r\n            var module = new FakeHookedModule(new BeforePipeline());\r\n            var url = GetFakeUrl(false);\r\n            var context = new NancyContext\r\n            {\r\n                Request = new Request(\"GET\", url)\r\n            };\r\n\r\n            module.RequiresHttps(false);\r\n\r\n            // When\r\n            var result = module.Before.Invoke(context, new CancellationToken());\r\n\r\n            // Then\r\n            result.Result.ShouldNotBeNull();\r\n            result.Result.StatusCode.ShouldEqual(HttpStatusCode.Forbidden);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_forbidden_response_when_request_url_is_non_secure_method_is_post_and_requires_https_and_redirect_is_false()\r\n        {\r\n            // Given\r\n            var module = new FakeHookedModule(new BeforePipeline());\r\n            var url = GetFakeUrl(false);\r\n            var context = new NancyContext\r\n            {\r\n                Request = new Request(\"POST\", url)\r\n            };\r\n\r\n            module.RequiresHttps(false);\r\n\r\n            // When\r\n            var result = module.Before.Invoke(context, new CancellationToken());\r\n\r\n            // Then\r\n            result.Result.ShouldNotBeNull();\r\n            result.Result.StatusCode.ShouldEqual(HttpStatusCode.Forbidden);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_response_when_request_url_is_secure_method_is_get_and_requires_https()\r\n        {\r\n            // Given\r\n            var module = new FakeHookedModule(new BeforePipeline());\r\n            var url = GetFakeUrl(true);\r\n            var context = new NancyContext\r\n            {\r\n                Request = new Request(\"GET\", url)\r\n            };\r\n\r\n            module.RequiresHttps();\r\n\r\n            // When\r\n            var result = module.Before.Invoke(context, new CancellationToken());\r\n\r\n            // Then\r\n            result.Result.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_response_when_request_url_is_secure_method_is_post_and_requires_https()\r\n        {\r\n            // Given\r\n            var module = new FakeHookedModule(new BeforePipeline());\r\n            var url = GetFakeUrl(true);\r\n            var context = new NancyContext\r\n            {\r\n                Request = new Request(\"POST\", url)\r\n            };\r\n\r\n            module.RequiresHttps();\r\n\r\n            // When\r\n            var result = module.Before.Invoke(context, new CancellationToken());\r\n\r\n            // Then\r\n            result.Result.ShouldBeNull();\r\n        }\r\n\r\n        private static ClaimsPrincipal GetFakeUser(string userName, params Claim[] claims)\r\n        {\r\n            var claimsList = claims.ToList();\r\n            claimsList.Add(new Claim(ClaimTypes.NameIdentifier, userName));\r\n            \r\n            return new ClaimsPrincipal(new ClaimsIdentity(claimsList, \"test\"));\r\n        }\r\n\r\n        private static Url GetFakeUrl(bool https)\r\n        {\r\n            return new Url\r\n            {\r\n                BasePath = null,\r\n                HostName = \"localhost\",\r\n                Path = \"/\",\r\n                Port = 80,\r\n                Query = string.Empty,\r\n                Scheme = https ? \"https\" : \"http\"\r\n            };\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Security/SSLProxyFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Security\r\n{\r\n    using System.Collections.Generic;\r\n    using System.Threading;\r\n\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Security;\r\n    using Nancy.Tests.Fakes;\r\n\r\n    using Xunit;\r\n\r\n    public class SSLProxyFixture\r\n    {\r\n        private readonly IPipelines pipelines;\r\n\r\n        public SSLProxyFixture()\r\n        {\r\n            this.pipelines = new MockPipelines();\r\n\r\n            SSLProxy.RewriteSchemeUsingForwardedHeaders(this.pipelines);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_url_scheme_to_https_if_X_Forwarded_Proto_header_exists()\r\n        {\r\n            var request = new FakeRequest(\"GET\", \"/\",\r\n                new Dictionary<string, IEnumerable<string>> { { \"X-Forwarded-Proto\", new[] { \"https\" } } });\r\n\r\n            var context = new NancyContext { Request = request };\r\n\r\n            this.pipelines.BeforeRequest.Invoke(context, new CancellationToken());\r\n\r\n            request.Url.Scheme.ShouldEqual(\"https\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_url_scheme_to_https_if_Forwarded_header_exists()\r\n        {\r\n            var request = new FakeRequest(\"GET\", \"/\",\r\n               new Dictionary<string, IEnumerable<string>> { { \"Forwarded\", new[] { \"for=192.0.2.60\", \"proto=https\", \"by=203.0.113.43\" } } });\r\n\r\n            var context = new NancyContext { Request = request };\r\n\r\n            this.pipelines.BeforeRequest.Invoke(context, new CancellationToken());\r\n\r\n            request.Url.Scheme.ShouldEqual(\"https\");\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Sessions/CookieBasedSessionsConfigurationFixture.cs",
    "content": "namespace Nancy.Testing.Tests\r\n{\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Cryptography;\r\n    using Nancy.Session;\r\n    using Nancy.Tests;\r\n\r\n    using Xunit;\r\n\r\n    public class CookieBasesSessionsConfigurationFixture\r\n    {\r\n        private readonly CookieBasedSessionsConfiguration config;\r\n\r\n        public CookieBasesSessionsConfigurationFixture()\r\n        {\r\n            var cryptographyConfiguration = new CryptographyConfiguration(\r\n                new AesEncryptionProvider(new PassphraseKeyGenerator(\"SuperSecretPass\", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 })),\r\n                new DefaultHmacProvider(new PassphraseKeyGenerator(\"UberSuperSecure\", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 })));\r\n\r\n            this.config = new CookieBasedSessionsConfiguration()\r\n            {\r\n                CryptographyConfiguration = cryptographyConfiguration,\r\n                Serializer = A.Fake<IObjectSerializer>()\r\n            };\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_valid_with_all_properties_set()\r\n        {\r\n            var result = this.config.IsValid;\r\n\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_be_valid_with_empty_cookiename()\r\n        {\r\n            this.config.CookieName = \"\";\r\n\r\n            var result = this.config.IsValid;\r\n\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_be_valid_with_null_serializer()\r\n        {\r\n            this.config.Serializer = null;\r\n\r\n            var result = this.config.IsValid;\r\n\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_be_valid_with_null_cryptography_configuration()\r\n        {\r\n            this.config.CryptographyConfiguration = null;\r\n\r\n            var result = this.config.IsValid;\r\n\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_be_valid_with_null_encryption_provider()\r\n        {\r\n            this.config.CryptographyConfiguration = new CryptographyConfiguration(null, this.config.CryptographyConfiguration.HmacProvider);\r\n\r\n            var result = this.config.IsValid;\r\n\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_be_valid_with_null_hmac_provider()\r\n        {\r\n            this.config.CryptographyConfiguration = new CryptographyConfiguration(this.config.CryptographyConfiguration.EncryptionProvider, null);\r\n\r\n            var result = this.config.IsValid;\r\n\r\n            result.ShouldBeFalse();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Sessions/CookieBasedSessionsFixture.cs",
    "content": "namespace Nancy.Tests.Unit.Sessions\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n    using System.Text;\r\n    using System.Threading;\r\n    using FakeItEasy;\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Cryptography;\r\n    using Nancy.Helpers;\r\n    using Nancy.IO;\r\n    using Nancy.Session;\r\n    using Nancy.Tests.Fakes;\r\n    using Xunit;\r\n\r\n    public class CookieBasedSessionsFixture\r\n    {\r\n        private const string ValidData = \"PzQmxxriR9Ht9a1rJMC1yAr5Ty+CIIE1/fXX/B2e32wtf8+KzGaBMOW6Ks9xb503haQnFTm9Z9QsJgoUPClwU6Ke25HRjXdKY7RQIG4XXT7APU/NV3KAJZuwbJObv22PR/yKbkTOEYAvn/m7FLM6jxvn5lCCw75Kw0vNvKiTbyE5ijh5EY4XfQHGt+5s6vrehh26reJBuXiY4hPwopGbOsvHNNw3HpbQPmut1qHiqX/w8naD2vuFmX0Dckv1Kkf+K3zG2BVHtXi+C3kufmUR+l/1C7p4Y7r+6n9+7o7Bf8aWkMNWdAA704+xrT+Zyy5NkKkFGMtNmju6bv+6PH1H6hwXs5QUSWcj3Ke9XQvWaYBHCkBdIvY4FvMZUeQfw5oaECST+Zz+nMxAQ5TgOrvVo6Zr0B+CF+COvXeyhX7YbbM=\";\r\n        private const string ValidHmac = \"QWc9gRZbQ6pK5ECs2Zp4E5WenpQ/XXgYUDPY46WihPY=\";\r\n\r\n        private readonly IEncryptionProvider fakeEncryptionProvider;\r\n        private readonly CookieBasedSessions cookieStore;\r\n        private readonly IHmacProvider fakeHmacProvider;\r\n        private readonly IObjectSerializer fakeObjectSerializer;\r\n        private readonly AesEncryptionProvider aesEncryptionProvider;\r\n        private readonly DefaultHmacProvider defaultHmacProvider;\r\n        private readonly IObjectSerializer defaultObjectSerializer;\r\n\r\n        public CookieBasedSessionsFixture()\r\n        {\r\n            this.fakeEncryptionProvider = A.Fake<IEncryptionProvider>();\r\n            this.fakeHmacProvider = A.Fake<IHmacProvider>();\r\n            this.fakeObjectSerializer = new FakeObjectSerializer();\r\n            this.cookieStore = new CookieBasedSessions(this.fakeEncryptionProvider, this.fakeHmacProvider, this.fakeObjectSerializer);\r\n\r\n            this.aesEncryptionProvider = new AesEncryptionProvider(new PassphraseKeyGenerator(\"password\", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000));\r\n            this.defaultHmacProvider = new DefaultHmacProvider(new PassphraseKeyGenerator(\"anotherpassword\", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000));\r\n            this.defaultObjectSerializer = new DefaultObjectSerializer();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_save_nothing_if_the_session_is_null()\r\n        {\r\n            var response = new Response();\r\n\r\n            cookieStore.Save(null, response);\r\n\r\n            response.Cookies.Count.ShouldEqual(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_save_nothing_if_the_session_has_not_changed()\r\n        {\r\n            var response = new Response();\r\n\r\n            cookieStore.Save(new Session(new Dictionary<string, object> { { \"key\", \"value\" } }), response);\r\n\r\n            response.Cookies.Count.ShouldEqual(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_save_the_session_cookie()\r\n        {\r\n            var response = new Response();\r\n            var session = new Session(new Dictionary<string, object>\r\n                                      {\r\n                                          {\"key1\", \"val1\"},\r\n                                      });\r\n            session[\"key2\"] = \"val2\";\r\n            A.CallTo(() => this.fakeEncryptionProvider.Encrypt(\"key1=val1;key2=val2;\")).Returns(\"encrypted=key1=val1;key2=val2;\");\r\n\r\n            cookieStore.Save(session, response);\r\n\r\n            response.Cookies.Count.ShouldEqual(1);\r\n            var cookie = response.Cookies.First();\r\n            cookie.Name.ShouldEqual(this.cookieStore.CookieName);\r\n            cookie.Value.ShouldEqual(\"encrypted%3dkey1%3dval1%3bkey2%3dval2%3b\");\r\n            cookie.Expires.ShouldBeNull();\r\n            cookie.Path.ShouldBeNull();\r\n            cookie.Domain.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_save_cookie_as_http_only()\r\n        {\r\n            var response = new Response();\r\n            var session = new Session();\r\n            session[\"key 1\"] = \"val=1\";\r\n            A.CallTo(() => this.fakeEncryptionProvider.Encrypt(\"key+1=val%3d1;\")).Returns(\"encryptedkey+1=val%3d1;\");\r\n\r\n            cookieStore.Save(session, response);\r\n\r\n            response.Cookies.First().HttpOnly.ShouldEqual(true);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_saves_url_safe_keys_and_values()\r\n        {\r\n            var response = new Response();\r\n            var session = new Session();\r\n            session[\"key 1\"] = \"val=1\";\r\n            A.CallTo(() => this.fakeEncryptionProvider.Encrypt(\"key+1=val%3d1;\")).Returns(\"encryptedkey+1=val%3d1;\");\r\n\r\n            cookieStore.Save(session, response);\r\n\r\n            response.Cookies.First().Value.ShouldEqual(\"encryptedkey%2b1%3dval%253d1%3b\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_load_an_empty_session_if_no_session_cookie_exists()\r\n        {\r\n            var request = CreateRequest(null);\r\n\r\n            var result = cookieStore.Load(request);\r\n\r\n            result.Count.ShouldEqual(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_load_an_empty_session_if_session_cookie_is_invalid()\r\n        {\r\n            //given\r\n            var inputValue = ValidHmac.Substring(0, 5); //invalid Hmac\r\n            inputValue = HttpUtility.UrlEncode(inputValue);\r\n            var store = new CookieBasedSessions(this.aesEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer);\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n            request.Cookies.Add(store.CookieName, inputValue);\r\n\r\n            //when\r\n            var result = store.Load(request);\r\n\r\n            //then\r\n            result.Count.ShouldEqual(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_load_a_single_valued_session()\r\n        {\r\n            var request = CreateRequest(\"encryptedkey1=value1\");\r\n            A.CallTo(() => this.fakeEncryptionProvider.Decrypt(\"encryptedkey1=value1\")).Returns(\"key1=value1;\");\r\n\r\n            var session = cookieStore.Load(request);\r\n\r\n            session.Count.ShouldEqual(1);\r\n            session[\"key1\"].ShouldEqual(\"value1\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_load_a_multi_valued_session()\r\n        {\r\n            var request = CreateRequest(\"encryptedkey1=value1;key2=value2\");\r\n            A.CallTo(() => this.fakeEncryptionProvider.Decrypt(\"encryptedkey1=value1;key2=value2\")).Returns(\"key1=value1;key2=value2\");\r\n\r\n            var session = cookieStore.Load(request);\r\n\r\n            session.Count.ShouldEqual(2);\r\n            session[\"key1\"].ShouldEqual(\"value1\");\r\n            session[\"key2\"].ShouldEqual(\"value2\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_load_properly_decode_the_url_safe_session()\r\n        {\r\n            var request = CreateRequest(HttpUtility.UrlEncode(\"encryptedkey+1=val%3D1;\"));\r\n            A.CallTo(() => this.fakeEncryptionProvider.Decrypt(\"encryptedkey+1=val%3D1;\")).Returns(\"key+1=val%3D1;\");\r\n\r\n            var session = cookieStore.Load(request);\r\n\r\n            session.Count.ShouldEqual(1);\r\n            session[\"key 1\"].ShouldEqual(\"val=1\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_pre_and_post_hooks_when_enabled()\r\n        {\r\n            var beforePipeline = new BeforePipeline();\r\n            var afterPipeline = new AfterPipeline();\r\n            var hooks = A.Fake<IPipelines>();\r\n            A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline);\r\n            A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline);\r\n\r\n            CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider));\r\n\r\n            beforePipeline.PipelineDelegates.Count().ShouldEqual(1);\r\n            afterPipeline.PipelineItems.Count().ShouldEqual(1);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_only_not_add_response_cookie_if_it_has_not_changed()\r\n        {\r\n            var beforePipeline = new BeforePipeline();\r\n            var afterPipeline = new AfterPipeline();\r\n            var hooks = A.Fake<IPipelines>();\r\n            A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline);\r\n            A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline);\r\n            CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider)).WithSerializer(this.fakeObjectSerializer);\r\n            var request = CreateRequest(\"encryptedkey1=value1\");\r\n            A.CallTo(() => this.fakeEncryptionProvider.Decrypt(\"encryptedkey1=value1\")).Returns(\"key1=value1;\");\r\n            var response = A.Fake<Response>();\r\n            var nancyContext = new NancyContext() { Request = request, Response = response };\r\n            beforePipeline.Invoke(nancyContext, new CancellationToken());\r\n\r\n            afterPipeline.Invoke(nancyContext, new CancellationToken());\r\n\r\n            response.Cookies.Count.ShouldEqual(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_response_cookie_if_it_has_changed()\r\n        {\r\n            var beforePipeline = new BeforePipeline();\r\n            var afterPipeline = new AfterPipeline();\r\n            var hooks = A.Fake<IPipelines>();\r\n            A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline);\r\n            A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline);\r\n            CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider)).WithSerializer(this.fakeObjectSerializer);\r\n            var request = CreateRequest(\"encryptedkey1=value1\");\r\n            A.CallTo(() => this.fakeEncryptionProvider.Decrypt(\"encryptedkey1=value1\")).Returns(\"key1=value1;\");\r\n            var response = A.Fake<Response>();\r\n            var nancyContext = new NancyContext() { Request = request, Response = response };\r\n            beforePipeline.Invoke(nancyContext, new CancellationToken());\r\n            request.Session[\"Testing\"] = \"Test\";\r\n\r\n            afterPipeline.Invoke(nancyContext, new CancellationToken());\r\n\r\n            response.Cookies.Count.ShouldEqual(1);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_call_formatter_on_load()\r\n        {\r\n            var fakeFormatter = A.Fake<IObjectSerializer>();\r\n            A.CallTo(() => this.fakeEncryptionProvider.Decrypt(\"encryptedkey1=value1\")).Returns(\"key1=value1;\");\r\n            var store = new CookieBasedSessions(this.fakeEncryptionProvider, this.fakeHmacProvider, fakeFormatter);\r\n            var request = CreateRequest(\"encryptedkey1=value1\", false);\r\n\r\n            store.Load(request);\r\n\r\n            A.CallTo(() => fakeFormatter.Deserialize(\"value1\")).MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_call_the_formatter_on_save()\r\n        {\r\n            var response = new Response();\r\n            var session = new Session(new Dictionary<string, object>());\r\n            session[\"key1\"] = \"value1\";\r\n            var fakeFormatter = A.Fake<IObjectSerializer>();\r\n            var store = new CookieBasedSessions(this.fakeEncryptionProvider, this.fakeHmacProvider, fakeFormatter);\r\n\r\n            store.Save(session, response);\r\n\r\n            A.CallTo(() => fakeFormatter.Serialize(\"value1\")).MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_formatter_when_using_formatter_selector()\r\n        {\r\n            var beforePipeline = new BeforePipeline();\r\n            var afterPipeline = new AfterPipeline();\r\n            var hooks = A.Fake<IPipelines>();\r\n            A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline);\r\n            A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline);\r\n            var fakeFormatter = A.Fake<IObjectSerializer>();\r\n            A.CallTo(() => this.fakeEncryptionProvider.Decrypt(\"encryptedkey1=value1\")).Returns(\"key1=value1;\");\r\n            CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider)).WithSerializer(fakeFormatter);\r\n            var request = CreateRequest(\"encryptedkey1=value1\");\r\n            var nancyContext = new NancyContext() { Request = request };\r\n\r\n            beforePipeline.Invoke(nancyContext, new CancellationToken());\r\n\r\n            A.CallTo(() => fakeFormatter.Deserialize(A<string>.Ignored)).MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_save_a_complex_object_to_session()\r\n        {\r\n            var response = new Response();\r\n            var session = new Session(new Dictionary<string, object>());\r\n            var payload = new DefaultSessionObjectFormatterFixture.Payload(27, true, \"Test string\");\r\n            var store = new CookieBasedSessions(this.aesEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer);\r\n            session[\"testObject\"] = payload;\r\n\r\n            store.Save(session, response);\r\n\r\n            response.Cookies.Count.ShouldEqual(1);\r\n            var cookie = response.Cookies.First();\r\n            cookie.Name.ShouldEqual(store.CookieName);\r\n            cookie.Value.ShouldNotBeNull();\r\n            cookie.Value.ShouldNotBeEmpty();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_load_an_object_previously_saved_to_session()\r\n        {\r\n            var response = new Response();\r\n            var session = new Session(new Dictionary<string, object>());\r\n            var payload = new DefaultSessionObjectFormatterFixture.Payload(27, true, \"Test string\");\r\n            var store = new CookieBasedSessions(this.aesEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer);\r\n            session[\"testObject\"] = payload;\r\n            store.Save(session, response);\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n            request.Cookies.Add(response.Cookies.First().Name, response.Cookies.First().Value);\r\n\r\n            var result = store.Load(request);\r\n\r\n            result[\"testObject\"].ShouldEqual(payload);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_encrypt_data()\r\n        {\r\n            var response = new Response();\r\n            var session = new Session(new Dictionary<string, object>\r\n                                      {\r\n                                          {\"key1\", \"val1\"},\r\n                                      });\r\n            session[\"key2\"] = \"val2\";\r\n\r\n            cookieStore.Save(session, response);\r\n\r\n            A.CallTo(() => this.fakeEncryptionProvider.Encrypt(A<string>.Ignored))\r\n                .MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_generate_hmac()\r\n        {\r\n            var response = new Response();\r\n            var session = new Session(new Dictionary<string, object>\r\n                                      {\r\n                                          {\"key1\", \"val1\"},\r\n                                      });\r\n            session[\"key2\"] = \"val2\";\r\n\r\n            cookieStore.Save(session, response);\r\n\r\n            A.CallTo(() => this.fakeHmacProvider.GenerateHmac(A<string>.Ignored))\r\n                .MustHaveHappenedOnceExactly();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_load_valid_test_data()\r\n        {\r\n            // Given\r\n            var payload = new DefaultSessionObjectFormatterFixture.Payload\r\n            {\r\n                BoolValue = true\r\n            };\r\n\r\n            var cookieData = GenerateCookieData(new Dictionary<string, object>\r\n            {\r\n                { \"key1\", payload }\r\n            });\r\n\r\n            var store =\r\n                new CookieBasedSessions(this.aesEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer);\r\n\r\n            var request =\r\n                new Request(\"GET\", \"/\", \"http\");\r\n\r\n            request.Cookies.Add(store.CookieName, cookieData.ToString());\r\n\r\n            // When\r\n            var result = store.Load(request);\r\n\r\n            // Then\r\n            result.Count.ShouldEqual(1);\r\n            result.First().Value.ShouldBeOfType(typeof(DefaultSessionObjectFormatterFixture.Payload));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_blank_session_if_hmac_changed()\r\n        {\r\n            var inputValue = \"b\" + ValidHmac.Substring(1) + ValidData;\r\n            inputValue = HttpUtility.UrlEncode(inputValue);\r\n            var store = new CookieBasedSessions(this.aesEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer);\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n            request.Cookies.Add(store.CookieName, inputValue);\r\n\r\n            var result = store.Load(request);\r\n\r\n            result.Count.ShouldEqual(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_blank_session_if_hmac_missing()\r\n        {\r\n            var inputValue = ValidData;\r\n            inputValue = HttpUtility.UrlEncode(inputValue);\r\n            var store = new CookieBasedSessions(this.aesEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer);\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n            request.Cookies.Add(store.CookieName, inputValue);\r\n\r\n            var result = store.Load(request);\r\n\r\n            result.Count.ShouldEqual(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_blank_session_if_encrypted_data_modified()\r\n        {\r\n            var inputValue = ValidHmac + ValidData.Substring(0, ValidData.Length - 1) + \"Z\";\r\n            inputValue = HttpUtility.UrlEncode(inputValue);\r\n            var store = new CookieBasedSessions(this.aesEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer);\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n            request.Cookies.Add(store.CookieName, inputValue);\r\n\r\n            var result = store.Load(request);\r\n\r\n            result.Count.ShouldEqual(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_blank_session_if_encrypted_data_are_invalid_but_contain_semicolon_when_decrypted()\r\n        {\r\n            var bogusEncrypted = this.aesEncryptionProvider.Encrypt(\"foo;bar\");\r\n            var inputValue = ValidHmac + bogusEncrypted;\r\n            inputValue = HttpUtility.UrlEncode(inputValue);\r\n            var store = new CookieBasedSessions(this.aesEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer);\r\n            var request = new Request(\"GET\", \"/\", \"http\");\r\n            request.Cookies.Add(store.CookieName, inputValue);\r\n\r\n            var result = store.Load(request);\r\n\r\n            result.Count.ShouldEqual(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_CookieName_when_config_provides_cookiename_value()\r\n        {\r\n            //Given\r\n            var cryptoConfig = new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider);\r\n            var storeConfig = new CookieBasedSessionsConfiguration(cryptoConfig)\r\n            {\r\n                CookieName = \"NamedCookie\",\r\n                Serializer = this.fakeObjectSerializer\r\n            };\r\n            var store = new CookieBasedSessions(storeConfig);\r\n\r\n            //When\r\n            var response = new Response();\r\n            var session = new Session(new Dictionary<string, object>\r\n                                        {\r\n                                            {\"key1\", \"val1\"},\r\n                                        });\r\n            session[\"key2\"] = \"val2\";\r\n            store.Save(session, response);\r\n\r\n            //Then\r\n            response.Cookies.ShouldHave(c => c.Name == storeConfig.CookieName);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_Domain_when_config_provides_domain_value()\r\n        {\r\n            //Given\r\n            var cryptoConfig = new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider);\r\n            var storeConfig = new CookieBasedSessionsConfiguration(cryptoConfig)\r\n            {\r\n                Domain = \".nancyfx.org\",\r\n                Serializer = this.fakeObjectSerializer\r\n            };\r\n            var store = new CookieBasedSessions(storeConfig);\r\n\r\n            //When\r\n            var response = new Response();\r\n            var session = new Session(new Dictionary<string, object>\r\n                                        {\r\n                                            {\"key1\", \"val1\"},\r\n                                        });\r\n            session[\"key2\"] = \"val2\";\r\n            store.Save(session, response);\r\n\r\n            //Then\r\n            var cookie = response.Cookies.First(c => c.Name == storeConfig.CookieName);\r\n            cookie.Domain.ShouldEqual(storeConfig.Domain);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_Path_when_config_provides_path_value()\r\n        {\r\n            //Given\r\n            var cryptoConfig = new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider);\r\n            var storeConfig = new CookieBasedSessionsConfiguration(cryptoConfig)\r\n            {\r\n                Path = \"/\",\r\n                Serializer = this.fakeObjectSerializer\r\n            };\r\n            var store = new CookieBasedSessions(storeConfig);\r\n\r\n            //When\r\n            var response = new Response();\r\n            var session = new Session(new Dictionary<string, object>\r\n                                          {\r\n                                              {\"key1\", \"val1\"},\r\n                                          });\r\n            session[\"key2\"] = \"val2\";\r\n            store.Save(session, response);\r\n\r\n            //Then\r\n            var cookie = response.Cookies.First(c => c.Name == storeConfig.CookieName);\r\n            cookie.Path.ShouldEqual(storeConfig.Path);\r\n        }\r\n\r\n        private class CookieData\r\n        {\r\n            public string Data { get; set; }\r\n\r\n            public string Hmac { get; set; }\r\n\r\n            public override string ToString()\r\n            {\r\n                return HttpUtility.UrlEncode(string.Concat(this.Hmac, this.Data));\r\n            }\r\n        }\r\n\r\n        private CookieData GenerateCookieData(string key, object data)\r\n        {\r\n            return this.GenerateCookieData(new Dictionary<string, object>\r\n            {\r\n                { key, data }\r\n            });\r\n        }\r\n\r\n        private CookieData GenerateCookieData(IDictionary<string, object> data)\r\n        {\r\n            var sb = new StringBuilder();\r\n\r\n            foreach (var key in data.Keys)\r\n            {\r\n                sb.Append(HttpUtility.UrlEncode(key));\r\n                sb.Append(\"=\");\r\n\r\n                var objectString = this.defaultObjectSerializer.Serialize(data[key]);\r\n\r\n                sb.Append(HttpUtility.UrlEncode(objectString));\r\n                sb.Append(\";\");\r\n            }\r\n\r\n            var encryptedData =\r\n                this.aesEncryptionProvider.Encrypt(sb.ToString());\r\n\r\n            var hmacBytes =\r\n                this.defaultHmacProvider.GenerateHmac(encryptedData);\r\n\r\n            return new CookieData\r\n            {\r\n                Data = encryptedData,\r\n                Hmac = Convert.ToBase64String(hmacBytes)\r\n            };\r\n        }\r\n\r\n        private Request CreateRequest(string sessionValue, bool load = true)\r\n        {\r\n            var headers = new Dictionary<string, IEnumerable<string>>(1);\r\n\r\n            if (!string.IsNullOrEmpty(sessionValue))\r\n            {\r\n                headers.Add(\"cookie\", new[] { this.cookieStore.CookieName + \"=\" + HttpUtility.UrlEncode(sessionValue) });\r\n            }\r\n\r\n            var request = new Request(\"GET\", new Url { Path = \"/\", Scheme = \"http\", Port = 9001, BasePath = \"goku.power\" }, CreateRequestStream(), headers);\r\n\r\n            if (load)\r\n            {\r\n                cookieStore.Load(request);\r\n            }\r\n\r\n            return request;\r\n        }\r\n\r\n        private static RequestStream CreateRequestStream()\r\n        {\r\n            return CreateRequestStream(new MemoryStream());\r\n        }\r\n\r\n        private static RequestStream CreateRequestStream(Stream stream)\r\n        {\r\n            return RequestStream.FromStream(stream, 0, 1, true);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/Sessions/DefaultSessionObjectFormatterFixture.cs",
    "content": "namespace Nancy.Tests.Unit.Sessions\r\n{\r\n    using System;\r\n    using Xunit;\r\n\r\n    public class DefaultSessionObjectFormatterFixture\r\n    {\r\n        private readonly DefaultObjectSerializer serializer;\r\n\r\n        public DefaultSessionObjectFormatterFixture()\r\n        {\r\n            this.serializer = new DefaultObjectSerializer();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_serialize_and_deserialize_simple_string()\r\n        {\r\n            var input = @\"This is a sample string\";\r\n            var serialised = this.serializer.Serialize(input);\r\n\r\n            var output = (string)this.serializer.Deserialize(serialised);\r\n\r\n            output.ShouldEqual(input);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_serialize_and_deserialize_serializable_object()\r\n        {\r\n            var input = new Payload(27, true, \"This is some text\");\r\n            var serialised = this.serializer.Serialize(input);\r\n\r\n            var output = (Payload)this.serializer.Deserialize(serialised);\r\n\r\n            output.ShouldEqual(input);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_string_when_serializing_null()\r\n        {\r\n            object input = null;\r\n\r\n            var output = this.serializer.Serialize(input);\r\n\r\n            output.ShouldEqual(string.Empty);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_when_deserializing_null()\r\n        {\r\n            string input = null;\r\n\r\n            var output = this.serializer.Deserialize(input);\r\n\r\n            output.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_when_deserializing_empty_string()\r\n        {\r\n            var input = String.Empty;\r\n\r\n            var output = this.serializer.Deserialize(input);\r\n\r\n            output.ShouldBeNull();\r\n        }\r\n\r\n#if !CORE\r\n        [Serializable]\r\n#endif\r\n        public class Payload : IEquatable<Payload>\r\n        {\r\n            public int IntValue { get;  set; }\r\n\r\n            public bool BoolValue { get;  set; }\r\n\r\n            public string StringValue { get;  set; }\r\n\r\n            public Payload()\r\n            {\r\n\r\n            }\r\n\r\n            /// <summary>\r\n            /// Initializes a new instance of the <see cref=\"T:System.Object\"/> class.\r\n            /// </summary>\r\n            public Payload(int intValue, bool boolValue, string stringValue)\r\n            {\r\n                this.IntValue = intValue;\r\n                this.BoolValue = boolValue;\r\n                this.StringValue = stringValue;\r\n            }\r\n\r\n            public bool Equals(Payload other)\r\n            {\r\n                if (ReferenceEquals(null, other))\r\n                {\r\n                    return false;\r\n                }\r\n\r\n                if (ReferenceEquals(this, other))\r\n                {\r\n                    return true;\r\n                }\r\n\r\n                return other.IntValue == this.IntValue && other.BoolValue.Equals(this.BoolValue) && Equals(other.StringValue, this.StringValue);\r\n            }\r\n\r\n            public override bool Equals(object obj)\r\n            {\r\n                if (ReferenceEquals(null, obj))\r\n                {\r\n                    return false;\r\n                }\r\n\r\n                if (ReferenceEquals(this, obj))\r\n                {\r\n                    return true;\r\n                }\r\n\r\n                if (obj.GetType() != typeof(Payload))\r\n                {\r\n                    return false;\r\n                }\r\n\r\n                return Equals((Payload)obj);\r\n            }\r\n\r\n            public override int GetHashCode()\r\n            {\r\n                unchecked\r\n                {\r\n                    int result = this.IntValue;\r\n                    result = (result * 397) ^ this.BoolValue.GetHashCode();\r\n                    result = (result * 397) ^ (this.StringValue != null ? this.StringValue.GetHashCode() : 0);\r\n                    return result;\r\n                }\r\n            }\r\n\r\n            public static bool operator ==(Payload left, Payload right)\r\n            {\r\n                return Equals(left, right);\r\n            }\r\n\r\n            public static bool operator !=(Payload left, Payload right)\r\n            {\r\n                return !Equals(left, right);\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Sessions/NullSessionProviderFixture.cs",
    "content": "namespace Nancy.Tests.Unit.Sessions\r\n{\r\n    using System;\r\n\r\n    using Nancy.Session;\r\n\r\n    using Xunit;\r\n\r\n    public class NullSessionProviderFixture\r\n    {\r\n        private NullSessionProvider provider;\r\n\r\n        public NullSessionProviderFixture()\r\n        {\r\n            this.provider = new NullSessionProvider();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_when_get_enumerator_called()\r\n        {\r\n            var exception = Record.Exception(() => provider.GetEnumerator());\r\n\r\n            exception.ShouldBeOfType(typeof(InvalidOperationException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_when_get_count_getter_called()\r\n        {\r\n            var exception = Record.Exception(() => provider.Count);\r\n\r\n            exception.ShouldBeOfType(typeof(InvalidOperationException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_when_deleteall_called()\r\n        {\r\n            var exception = Record.Exception(() => provider.DeleteAll());\r\n\r\n            exception.ShouldBeOfType(typeof(InvalidOperationException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_when_delete_called()\r\n        {\r\n            var exception = Record.Exception(() => provider.Delete(\"test\"));\r\n\r\n            exception.ShouldBeOfType(typeof(InvalidOperationException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_when_indexer_accessed()\r\n        {\r\n            var exception = Record.Exception(() => provider[\"test\"]);\r\n\r\n            exception.ShouldBeOfType(typeof(InvalidOperationException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_for_haschanged()\r\n        {\r\n            var result = provider.HasChanged;\r\n\r\n            result.ShouldBeFalse();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Sessions/SessionFixture.cs",
    "content": "namespace Nancy.Tests\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using Nancy.Session;\r\n\r\n    using Xunit;\r\n\r\n    public class SessionFixture\r\n    {\r\n        [Fact]\r\n        public void Clearing_the_session_should_not_mark_it_as_changed_if_it_as_empty()\r\n        {\r\n            // Given\r\n            var session = new Session();\r\n\r\n            // When\r\n            session.DeleteAll();\r\n\r\n            // Then\r\n            session.HasChanged.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Clearing_the_session_should_mark_it_as_changed_if_it_was_not_empty()\r\n        {\r\n            // Given\r\n            var session = new Session(new Dictionary<string, object> { { \"key\", 1 } });\r\n\r\n            // When\r\n            session.DeleteAll();\r\n\r\n            // Then\r\n            session.HasChanged.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Deleting_an_invalid_key_should_not_mark_it_as_changed()\r\n        {\r\n            // Given\r\n            var session = new Session(new Dictionary<string, object> { { \"key\", 1 } });\r\n\r\n            // When\r\n            session.Delete(\"something\");\r\n\r\n            // Then\r\n            session.HasChanged.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Deleting_a_key_should_mark_it_as_changed()\r\n        {\r\n            // Given\r\n            var session = new Session(new Dictionary<string, object> { { \"key\", 1 } });\r\n\r\n            // When\r\n            session.Delete(\"key\");\r\n\r\n            // Then\r\n            session.HasChanged.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Setting_a_session_should_mark_it_as_changed()\r\n        {\r\n            // Given\r\n            var session = new Session();\r\n\r\n            // When\r\n            session[\"key\"] = \"SomeValue\";\r\n\r\n            // Then\r\n            session.HasChanged.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Setting_a_key_with_the_same_value_should_not_mark_it_as_changed()\r\n        {\r\n          // Given\r\n          var session = new Session(new Dictionary<string, object> { { \"key\", \"SomeValue\" } } );\r\n\r\n          // When\r\n          session[\"key\"] = \"SomeValue\";\r\n\r\n          // Then\r\n          session.HasChanged.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Setting_a_key_with_a_different_value_should_mark_it_as_changed()\r\n        {\r\n          // Given\r\n          var session = new Session(new Dictionary<string, object> { { \"key\", \"SomeValue\" } });\r\n\r\n          // When\r\n          session[\"key\"] = \"SomeValue2\";\r\n\r\n          // Then\r\n          session.HasChanged.ShouldBeTrue();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/StaticContentConventionBuilderFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Globalization;\r\n    using System.IO;\r\n    using System.Text;\r\n\r\n    using Nancy.Configuration;\r\n    using Nancy.Conventions;\r\n    using Nancy.Diagnostics;\r\n    using Nancy.Extensions;\r\n    using Nancy.Responses;\r\n\r\n    using Xunit;\r\n\r\n    public class StaticContentConventionBuilderFixture\r\n    {\r\n        private const string StylesheetContents = @\"body {\r\n\tbackground-color: white;\r\n}\";\r\n\r\n        private readonly string directory;\r\n        private readonly INancyEnvironment environment;\r\n\r\n        public StaticContentConventionBuilderFixture()\r\n        {\r\n            var assembly = typeof(StaticContentConventionBuilderFixture).GetAssembly();\r\n            var localPath = new Uri(assembly.CodeBase).LocalPath;\r\n            this.directory = new DirectoryInfo(localPath).Parent.FullName;\r\n\r\n            this.environment = new DefaultNancyEnvironment();\r\n            this.environment.StaticContent(safepaths:this.directory);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_retrieve_static_content_when_file_name_contains_url_encoded_spaces()\r\n        {\r\n            // Given\r\n            // When\r\n            var result = GetStaticContent(\"css\", \"space%20in%20name.css\");\r\n\r\n            // Then\r\n            result.ShouldEqual(StylesheetContents);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_retrieve_static_content_when_path_has_same_name_as_extension()\r\n        {\r\n            // Given\r\n            // When\r\n            var result = GetStaticContent(\"css\", \"styles.css\");\r\n\r\n            // Then\r\n            result.ShouldEqual(StylesheetContents);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_retrieve_static_content_when_virtual_directory_name_exists_in_static_route()\r\n        {\r\n            // Given\r\n            // When\r\n            var result = GetStaticContent(\"css\", \"strange-css-filename.css\");\r\n\r\n            // Then\r\n            result.ShouldEqual(StylesheetContents);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_retrieve_static_content_when_path_is_nested()\r\n        {\r\n            // Given\r\n            // When\r\n            var result = GetStaticContent(\"css/sub\", \"styles.css\");\r\n\r\n            // Then\r\n            result.ShouldEqual(StylesheetContents);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_retrieve_static_content_when_path_contains_nested_folders_with_duplicate_name()\r\n        {\r\n            // Given\r\n            // When\r\n            var result = GetStaticContent(\"css/css\", \"styles.css\");\r\n\r\n            // Then\r\n            result.ShouldEqual(StylesheetContents);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_retrieve_static_content_when_filename_contains_dot()\r\n        {\r\n            // Given\r\n            // When\r\n            var result = GetStaticContent(\"css\", \"dotted.filename.css\");\r\n\r\n            // Then\r\n            result.ShouldEqual(StylesheetContents);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_retrieve_static_content_when_path_contains_dot()\r\n        {\r\n            // Given\r\n            // When\r\n            var result = GetStaticContent(\"css/Sub.folder\", \"styles.css\");\r\n\r\n            // Then\r\n            result.ShouldEqual(StylesheetContents);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_skip_the_request_if_resource_is_outside_the_content_folder()\r\n        {\r\n            // Given\r\n            // When\r\n            var result = GetStaticContent(\"css\", \"../../outside/styles.css\");\r\n\r\n            // Then\r\n            result.ShouldEqual(\"Static content returned an invalid response of (null)\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_retrieve_static_content_when_root_is_relative_path()\r\n        {\r\n            // Given\r\n            var resources = Path.Combine(directory, \"Resources\");\r\n            var relativeRootFolder = Path.Combine(resources, @\"../\");\r\n\r\n            // When\r\n            var result = GetStaticContent(\"css\", \"styles.css\", relativeRootFolder);\r\n\r\n            // Then\r\n            result.ShouldEqual(StylesheetContents);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_security_exception_when_content_path_points_to_root()\r\n        {\r\n            // Given\r\n            var convention = StaticContentConventionBuilder.AddDirectory(\"/\", \"/\");\r\n            var request = new Request(\"GET\", \"/face.png\", \"http\");\r\n            var context = new NancyContext\r\n            {\r\n                Request = request\r\n            };\r\n\r\n            // When\r\n            var exception = Record.Exception(() => convention.Invoke(context, directory));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ArgumentException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_security_exception_when_content_path_is_null_and_requested_path_points_to_root()\r\n        {\r\n            // Given\r\n            var convention = StaticContentConventionBuilder.AddDirectory(\"/\");\r\n            var request = new Request(\"GET\", \"/face.png\", \"http\");\r\n            var context = new NancyContext\r\n            {\r\n                Request = request\r\n            };\r\n\r\n            // When\r\n            var exception = Record.Exception(() => convention.Invoke(context, directory));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ArgumentException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_not_modified_if_not_changed_and_conditional_request_on_etag_sent()\r\n        {\r\n            var initialResult = this.GetStaticContentResponse(\"css/css\", \"styles.css\");\r\n            var etag = initialResult.Headers[\"ETag\"];\r\n            var headers = new Dictionary<string, IEnumerable<string>> { { \"If-None-Match\", new[] { etag } } };\r\n\r\n            var result = this.GetStaticContentResponse(\"css/css\", \"styles.css\", headers: headers);\r\n\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.NotModified);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_not_modified_if_not_changed_and_conditional_request_on_modified_sent()\r\n        {\r\n            var initialResult = this.GetStaticContentResponse(\"css/css\", \"styles.css\");\r\n            var moddedTime = initialResult.Headers[\"Last-Modified\"];\r\n            var headers = new Dictionary<string, IEnumerable<string>> { { \"If-Modified-Since\", new[] { moddedTime } } };\r\n\r\n            var result = this.GetStaticContentResponse(\"css/css\", \"styles.css\", headers: headers);\r\n\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.NotModified);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_full_response_if_changed_and_conditional_request_on_etag_sent()\r\n        {\r\n            var initialResult = this.GetStaticContentResponse(\"css/css\", \"styles.css\");\r\n            var etag = initialResult.Headers[\"ETag\"];\r\n            var headers = new Dictionary<string, IEnumerable<string>> { { \"If-None-Match\", new[] { etag.Substring(1) } } };\r\n\r\n            var result = this.GetStaticContentResponse(\"css/css\", \"styles.css\", headers: headers);\r\n\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.OK);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_full_response_if_changed_and_conditional_request_on_modified_sent()\r\n        {\r\n            var initialResult = this.GetStaticContentResponse(\"css/css\", \"styles.css\");\r\n            var moddedTimeString = initialResult.Headers[\"Last-Modified\"];\r\n            var moddedTime = DateTime.ParseExact(moddedTimeString, \"R\", CultureInfo.InvariantCulture, DateTimeStyles.None)\r\n                                     .AddHours(-1);\r\n            moddedTimeString = moddedTime.ToString(\"R\", CultureInfo.InvariantCulture);\r\n            var headers = new Dictionary<string, IEnumerable<string>> { { \"If-Modified-Since\", new[] { moddedTimeString } } };\r\n\r\n            var result = this.GetStaticContentResponse(\"css/css\", \"styles.css\", headers: headers);\r\n\r\n            result.StatusCode.ShouldEqual(HttpStatusCode.OK);\r\n        }\r\n\r\n        [Fact]\r\n        public void Not_modified_response_should_have_no_body()\r\n        {\r\n            var initialResult = this.GetStaticContentResponse(\"css/css\", \"styles.css\");\r\n            var etag = initialResult.Headers[\"ETag\"];\r\n            var headers = new Dictionary<string, IEnumerable<string>> { { \"If-None-Match\", new[] { etag } } };\r\n\r\n            var result = this.GetStaticContent(\"css/css\", \"styles.css\", headers: headers);\r\n\r\n            result.ShouldEqual(string.Empty);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData('\"')]\r\n        [InlineData('<')]\r\n        [InlineData('>')]\r\n        [InlineData('|')]\r\n        public void Should_not_throw_exception_when_path_contains_invalid_filename_character(char invalidCharacter)\r\n        {\r\n            // Given\r\n            var fileName = string.Format(\"name{0}.ext\", invalidCharacter);\r\n\r\n            // When\r\n            var exception = Record.Exception(() =>\r\n                {\r\n                    this.GetStaticContent(\"css/css\", fileName);\r\n                });\r\n\r\n            // Then\r\n            exception.ShouldBeNull();\r\n        }\r\n\r\n        private string GetStaticContent(string virtualDirectory, string requestedFilename, string root = null, IDictionary<string, IEnumerable<string>> headers = null)\r\n        {\r\n            var response = this.GetStaticContentResponse(virtualDirectory, requestedFilename, root, headers);\r\n\r\n            var fileResponse = response as GenericFileResponse;\r\n\r\n            if (fileResponse != null)\r\n            {\r\n                using (var stream = new MemoryStream())\r\n                {\r\n                    fileResponse.Contents(stream);\r\n                    return Encoding.UTF8.GetString(stream.ToArray());\r\n                }\r\n            }\r\n\r\n            return string.Format(\"Static content returned an invalid response of {0}\", response == null ? \"(null)\" : response.GetType().ToString());\r\n        }\r\n\r\n        private Response GetStaticContentResponse(string virtualDirectory, string requestedFilename, string root = null, IDictionary<string, IEnumerable<string>> headers = null)\r\n        {\r\n            var context = GetContext(virtualDirectory, requestedFilename, headers);\r\n\r\n            var resolver = GetResolver(virtualDirectory);\r\n\r\n            var rootFolder = root ?? this.directory;\r\n\r\n            context.Environment = new DefaultNancyEnvironment();\r\n            context.Environment.StaticContent(safepaths:rootFolder);\r\n\r\n            var response = resolver.Invoke(context, rootFolder);\r\n            return response;\r\n        }\r\n\r\n        private NancyContext GetContext(string virtualDirectory, string requestedFilename, IDictionary<string, IEnumerable<string>> headers = null)\r\n        {\r\n            var resource = string.Format(\"/{0}/{1}\", virtualDirectory, requestedFilename);\r\n\r\n            var request = new Request(\r\n                              \"GET\",\r\n                              new Url { Path = resource, Scheme = \"http\" },\r\n                              headers: headers ?? new Dictionary<string, IEnumerable<string>>());\r\n\r\n            var context = new NancyContext\r\n            {\r\n                Request = request,\r\n                Trace = new DefaultRequestTrace\r\n                {\r\n                    TraceLog = new DefaultTraceLog(),\r\n                },\r\n                Environment = this.environment\r\n            };\r\n\r\n            return context;\r\n        }\r\n\r\n        private static Func<NancyContext, string, Response> GetResolver(string virtualDirectory)\r\n        {\r\n            return StaticContentConventionBuilder.AddDirectory(virtualDirectory, \"Resources/Assets/Styles\");\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/TextFormatterFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit\r\n{\r\n    using System.IO;\r\n    using System.Text;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Xunit;\r\n\r\n    public class TextFormatterFixture\r\n    {\r\n        private readonly IResponseFormatter formatter;\r\n        private readonly Response response;\r\n\r\n        public TextFormatterFixture()\r\n        {\r\n            this.formatter = A.Fake<IResponseFormatter>();\r\n            this.response = this.formatter.AsText(\"sample text\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_a_response_with_content_type_text_plain()\r\n        {\r\n            response.ContentType.ShouldEqual(\"text/plain; charset=utf-8\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_a_response_with_status_code_200_ok()\r\n        {\r\n            response.StatusCode.ShouldEqual(HttpStatusCode.OK);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_return_valid_response_string()\r\n        {\r\n            using (var stream = new MemoryStream())\r\n            {\r\n                response.Contents(stream);\r\n\r\n                Encoding.UTF8.GetString(stream.ToArray()).ShouldEqual(\"sample text\");\r\n            }\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_override_the_content_type()\r\n        {\r\n            var response = formatter.AsText(\"sample text\", \"text/cache-manifest\");\r\n            using (var stream = new MemoryStream())\r\n            {\r\n                response.Contents(stream);\r\n                response.ContentType.ShouldEqual(\"text/cache-manifest; charset=utf-8\");\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/UrlFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit\r\n{\r\n    using System;\r\n\r\n    using Xunit;\r\n    using Xunit.Extensions;\r\n\r\n    public class UrlFixture\r\n    {\r\n        private readonly Url url;\r\n\r\n        public UrlFixture()\r\n        {\r\n            this.url = new Url();\r\n        }\r\n        \r\n        [Fact]\r\n        public void Should_contain_schema_when_converted_to_string()\r\n        {\r\n            // Given\r\n            this.url.Scheme = \"https\";\r\n\r\n            // When\r\n            var result = this.url.ToString();\r\n\r\n            // Then\r\n            result.ShouldEndWith(\"https://\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_append_hostname_when_converted_to_string()\r\n        {\r\n            // Given\r\n            this.url.Scheme = \"https\";\r\n            this.url.HostName = \"www.nancyfx.org\";\r\n\r\n            // When\r\n            var result = this.url.ToString();\r\n\r\n            // Then\r\n            result.ShouldEndWith(\"https://www.nancyfx.org\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_enclose_ipv6_hostname_in_square_brackets_when_converted_to_string()\r\n        {\r\n            // Given\r\n            this.url.Scheme = \"https\";\r\n            this.url.HostName = \"::1\";\r\n\r\n            // When\r\n            var result = this.url.ToString();\r\n\r\n            // Then\r\n            result.ShouldStartWith(\"https://[\");\r\n            result.ShouldEndWith(\"]\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_leave_ipv4_hostname_untouched_when_converted_to_string()\r\n        {\r\n            // Given\r\n            this.url.Scheme = \"https\";\r\n            this.url.HostName = \"127.0.0.1\";\r\n\r\n            // When\r\n            var result = this.url.ToString();\r\n\r\n            // Then\r\n            result.ShouldEndWith(\"https://127.0.0.1\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_append_port_if_available_when_converted_to_string()\r\n        {\r\n            // Given\r\n            this.url.Scheme = \"https\";\r\n            this.url.HostName = \"www.nancyfx.org\";\r\n            this.url.Port = 1234;\r\n\r\n            // When\r\n            var result = this.url.ToString();\r\n\r\n            // Then\r\n            result.ShouldEndWith(\"https://www.nancyfx.org:1234\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_append_basepath_when_converted_to_string()\r\n        {\r\n            // Given\r\n            this.url.Scheme = \"https\";\r\n            this.url.HostName = \"www.nancyfx.org\";\r\n            this.url.Port = 1234;\r\n            this.url.BasePath = \"/base\";\r\n\r\n            // When\r\n            var result = this.url.ToString();\r\n\r\n            // Then\r\n            result.ShouldEndWith(\"https://www.nancyfx.org:1234/base\");\r\n        }\r\n        \r\n        [Fact]\r\n        public void Should_append_path_when_converted_to_string()\r\n        {\r\n            // Given\r\n            this.url.Scheme = \"https\";\r\n            this.url.HostName = \"www.nancyfx.org\";\r\n            this.url.Port = 1234;\r\n            this.url.BasePath = \"/base\";\r\n            this.url.Path = \"/path\";\r\n\r\n            // When\r\n            var result = this.url.ToString();\r\n\r\n            // Then\r\n            result.ShouldEndWith(\"https://www.nancyfx.org:1234/base/path\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_append_path_when_rooted_when_converted_to_string()\r\n        {\r\n            // Given\r\n            this.url.Scheme = \"https\";\r\n            this.url.HostName = \"www.nancyfx.org\";\r\n            this.url.Port = 1234;\r\n            this.url.BasePath = \"/base\";\r\n            this.url.Path = \"/\";\r\n\r\n            // When\r\n            var result = this.url.ToString();\r\n\r\n            // Then\r\n            result.ShouldEndWith(\"https://www.nancyfx.org:1234/base\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_append_query_when_converting_to_string()\r\n        {\r\n            // Given\r\n            this.url.Scheme = \"https\";\r\n            this.url.HostName = \"www.nancyfx.org\";\r\n            this.url.Port = 1234;\r\n            this.url.BasePath = \"/base\";\r\n            this.url.Path = \"/\";\r\n            this.url.Query = \"?foo=some%20text\";\r\n\r\n            // When\r\n            var result = this.url.ToString();\r\n\r\n            // Then\r\n            result.ShouldEndWith(\"https://www.nancyfx.org:1234/base?foo=some%20text\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_append_question_mark_to_querystring_when_missing()\r\n        {\r\n            // Given\r\n            this.url.Scheme = \"https\";\r\n            this.url.HostName = \"www.nancyfx.org\";\r\n            this.url.Port = 1234;\r\n            this.url.BasePath = \"/base\";\r\n            this.url.Path = \"/\";\r\n            this.url.Query = \"foo=some%20text\";\r\n\r\n            // When\r\n            var result = this.url.ToString();\r\n\r\n            // Then\r\n            result.ShouldEndWith(\"https://www.nancyfx.org:1234/base?foo=some%20text\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_from_string()\r\n        {\r\n            // Given\r\n            string urlAsString = \"https://www.nancyfx.org:1234/base?foo=some%20text#anchor\";\r\n\r\n            // When\r\n            Url result = urlAsString;\r\n\r\n            // Then\r\n            result.Scheme.ShouldEqual(\"https\");\r\n            result.HostName.ShouldEqual(\"www.nancyfx.org\");\r\n            result.Port.ShouldEqual(1234);\r\n            result.BasePath.ShouldEqual(string.Empty);\r\n            result.Path.ShouldEqual(\"/base\");\r\n            result.Query.ShouldEqual(\"?foo=some%20text\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_string()\r\n        {\r\n            // Given\r\n            this.url.Scheme = \"https\";\r\n            this.url.HostName = \"www.nancyfx.org\";\r\n            this.url.Port = 1234;\r\n            this.url.BasePath = \"/base\";\r\n            this.url.Path = \"/\";\r\n            this.url.Query = \"?foo=some%20text\";\r\n\r\n            // When\r\n            string result = this.url;\r\n\r\n            // Then\r\n            result.ShouldEqual(\"https://www.nancyfx.org:1234/base?foo=some%20text\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_from_uri()\r\n        {\r\n            // Given\r\n            Uri uri = new Uri(\"https://www.nancyfx.org:1234/base?foo=some%20text#anchor\");\r\n\r\n            // When\r\n            Url result = uri;\r\n\r\n            // Then\r\n            result.Scheme.ShouldEqual(\"https\");\r\n            result.HostName.ShouldEqual(\"www.nancyfx.org\");\r\n            result.Port.ShouldEqual(1234);\r\n            result.BasePath.ShouldEqual(string.Empty);\r\n            result.Path.ShouldEqual(\"/base\");\r\n            result.Query.ShouldEqual(\"?foo=some%20text\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_from_relative_uri()\r\n        {\r\n            // Given\r\n            var uri = new Uri(\"/hello\", UriKind.Relative);\r\n\r\n            // When\r\n            Url result = uri;\r\n\r\n            // Then\r\n            result.Scheme.ShouldEqual(\"http\");\r\n            result.HostName.ShouldEqual(string.Empty);\r\n            result.Port.ShouldEqual(null);\r\n            result.BasePath.ShouldEqual(string.Empty);\r\n            result.Path.ShouldEqual(\"/hello\");\r\n            result.Query.ShouldEqual(string.Empty);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_uri()\r\n        {\r\n            // Given\r\n            this.url.Scheme = \"https\";\r\n            this.url.HostName = \"www.nancyfx.org\";\r\n            this.url.Port = 1234;\r\n            this.url.BasePath = \"/base\";\r\n            this.url.Path = \"/\";\r\n            this.url.Query = \"?foo=some%20text\";\r\n\r\n            // When\r\n            Uri result = this.url;\r\n\r\n            // Then\r\n            result.Scheme.ShouldEqual(\"https\");\r\n            result.Host.ShouldEqual(\"www.nancyfx.org\");\r\n            result.Port.ShouldEqual(1234);\r\n            result.AbsolutePath.ShouldEqual(\"/base\");\r\n            result.Query.ShouldEqual(\"?foo=some%20text\");\r\n            result.Fragment.ShouldBeEmpty();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_implicitly_cast_to_absolute_uri()\r\n        {\r\n            // Given\r\n            this.url.Scheme = \"https\";\r\n            this.url.HostName = \"www.nancyfx.org\";\r\n            this.url.Port = 1234;\r\n            this.url.BasePath = \"/base\";\r\n            this.url.Path = \"/\";\r\n            this.url.Query = \"?foo=some%20text\";\r\n\r\n            // When\r\n            Uri result = this.url;\r\n\r\n            // Then\r\n            result.IsAbsoluteUri.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_take_a_string_in_the_constructor()\r\n        {\r\n            //Given, When\r\n            var url = new Url(\"https://www.nancyfx.org:1234/base?foo=some text\");\r\n\r\n            //Then\r\n            url.Scheme.ShouldEqual(\"https\");\r\n            url.HostName.ShouldEqual(\"www.nancyfx.org\");\r\n            url.Port.ShouldEqual(1234);\r\n            url.Path.ShouldEqual(\"/base\");\r\n            url.Query.ShouldEqual(\"?foo=some%20text\");\r\n        }\r\n        \r\n        [Theory]\r\n        [InlineData(\"https://www.nancyfx.org:1234/base?foo=some%20text\", \"https\", \"www.nancyfx.org\", 1234, \"/base\", \"?foo=some%20text\")]\r\n        [InlineData(\"http://nancyfx.org\", \"http\", \"nancyfx.org\", 80, \"/\", \"\")]\r\n        [InlineData(\"http://nancyfx.org?foo=some%20text\", \"http\", \"nancyfx.org\", 80, \"/\", \"?foo=some%20text\")]\r\n        [InlineData(\"https://nancyfx.org/base/admin/area?foo=some%20text\", \"https\", \"nancyfx.org\", 443, \"/base/admin/area\", \"?foo=some%20text\")]\r\n        [InlineData(\"http://nancyfx.org/base/admin/area\", \"http\", \"nancyfx.org\", 80, \"/base/admin/area\", \"\")]\r\n        public void Should_implicitly_cast_uri_to_url(string fullurl, string scheme, string host, int port, string path, string query)\r\n        {\r\n            //Given\r\n            var uri = new Uri(fullurl);\r\n\r\n            //When\r\n            Url result = uri;\r\n\r\n            //Then\r\n            Assert.Equal(scheme, result.Scheme);\r\n            Assert.Equal(host,result.HostName);\r\n            Assert.Equal(port, result.Port);\r\n            Assert.Equal(path, result.Path);\r\n            Assert.Equal(query, result.Query);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"https\")]\r\n        [InlineData(\"Https\")]\r\n        [InlineData(\"httPs\")]\r\n        [InlineData(\"HTTPS\")]\r\n        public void IsSecure_should_return_true_if_https(string scheme)\r\n        {\r\n            // Given\r\n            this.url.Scheme = scheme;\r\n\r\n            // When\r\n            var result = this.url.IsSecure;\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"http\")]\r\n        [InlineData(\"Http\")]\r\n        [InlineData(\"blah\")]\r\n        [InlineData(\"blahs\")]\r\n        public void IsSecure_should_return_false_if_scheme_is_not_https(string scheme)\r\n        {\r\n            // Given\r\n            this.url.Scheme = scheme;\r\n\r\n            // When\r\n            var result = this.url.IsSecure;\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(null)]\r\n        [InlineData(\"\")]\r\n        public void IsSecure_should_return_false_when_scheme_is_null_or_empty(string scheme)\r\n        {\r\n            // Given\r\n            this.url.Scheme = scheme;\r\n\r\n            // When\r\n            var result = this.url.IsSecure;\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Validation/CompositeValidatorFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Validation\r\n{\r\n    using System.Linq;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Validation;\r\n\r\n    using Xunit;\r\n\r\n    public class CompositeValidatorFixture\r\n    {\r\n        [Fact]\r\n        public void Should_yield_composite_description()\r\n        {\r\n            // Given\r\n            var fakeValidators = A.CollectionOfFake<IModelValidator>(2);\r\n            A.CallTo(() => fakeValidators[0].Description).Returns(new ModelValidationDescriptor(new[] { new ModelValidationRule(\"Test1\", s => s, new[] { \"Member1\" }) }, typeof(object)));\r\n            A.CallTo(() => fakeValidators[1].Description).Returns(new ModelValidationDescriptor(new[] { new ModelValidationRule(\"Test2\", s => s, new[] { \"Member2\" }) }, typeof(object)));\r\n            var subject = new CompositeValidator(fakeValidators, typeof(object));\r\n\r\n            // When\r\n            var result = subject.Description;\r\n\r\n            // Then\r\n            result.Rules.ShouldHaveCount(2);\r\n            result.Rules.First().Value.ShouldHave(r => r.RuleType == \"Test1\" && r.MemberNames.Contains(\"Member1\"));\r\n            result.Rules.Last().Value.ShouldHave(r => r.RuleType == \"Test2\" && r.MemberNames.Contains(\"Member2\"));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_each_validator()\r\n        {\r\n            // Given\r\n            var fakeValidators = A.CollectionOfFake<IModelValidator>(2);\r\n            var subject = new CompositeValidator(fakeValidators, typeof(object));\r\n\r\n            // When\r\n            subject.Validate(\"blah\", new NancyContext());\r\n\r\n            // Then\r\n            A.CallTo(() => fakeValidators[0].Validate(A<object>._, A<NancyContext>._)).MustHaveHappened();\r\n            A.CallTo(() => fakeValidators[1].Validate(A<object>._, A<NancyContext>._)).MustHaveHappened();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Validation/DefaultValidatorLocatorFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Validation\r\n{\r\n    using System;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Validation;\r\n\r\n    using Xunit;\r\n\r\n    public class DefaultValidatorLocatorFixture\r\n    {\r\n        [Fact]\r\n        public void Should_not_throw_if_null_validator_locators_collection_is_passed()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => new DefaultValidatorLocator(null));\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_if_no_validator_can_validate_the_given_type()\r\n        {\r\n            // Given\r\n            var fakeFactories = A.CollectionOfFake<IModelValidatorFactory>(3);\r\n            A.CallTo(() => fakeFactories[0].Create(A<Type>.Ignored)).Returns(null);\r\n            A.CallTo(() => fakeFactories[1].Create(A<Type>.Ignored)).Returns(null);\r\n            A.CallTo(() => fakeFactories[2].Create(A<Type>.Ignored)).Returns(null);\r\n            var subject = new DefaultValidatorLocator(fakeFactories);\r\n\r\n            // When\r\n            var result = subject.GetValidatorForType(typeof(string));\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_the_original_validator_when_only_one_factory_can_provide_a_validator_for_the_given_type()\r\n        {\r\n            // Given\r\n            var fakeFactories = A.CollectionOfFake<IModelValidatorFactory>(3);\r\n            var fakeValidator = A.Fake<IModelValidator>();\r\n            A.CallTo(() => fakeFactories[0].Create(A<Type>.Ignored)).Returns(null);\r\n            A.CallTo(() => fakeFactories[1].Create(A<Type>.Ignored)).Returns(fakeValidator);\r\n            A.CallTo(() => fakeFactories[2].Create(A<Type>.Ignored)).Returns(null);\r\n\r\n            var subject = new DefaultValidatorLocator(fakeFactories);\r\n\r\n            // When\r\n            var result = subject.GetValidatorForType(typeof(string));\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(fakeValidator);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_a_composite_validator_when_more_than_one_factory_can_provide_a_validator_for_the_given_type()\r\n        {\r\n            // Given\r\n            var fakeFactories = A.CollectionOfFake<IModelValidatorFactory>(3);\r\n            var fakeValidator1 = A.Fake<IModelValidator>();\r\n            var fakeValidator2 = A.Fake<IModelValidator>();\r\n            A.CallTo(() => fakeFactories[1].Create(A<Type>.Ignored)).Returns(fakeValidator1);\r\n            A.CallTo(() => fakeFactories[2].Create(A<Type>.Ignored)).Returns(fakeValidator2);\r\n\r\n            var subject = new DefaultValidatorLocator(fakeFactories);\r\n\r\n            // When\r\n            var result = subject.GetValidatorForType(typeof(string));\r\n\r\n            // Then\r\n            result.ShouldBeOfType<CompositeValidator>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_modelvalidationexception_when_retrieving_validator_but_no_factories_have_been_registered()\r\n        {\r\n            // Given\r\n            var subject = new DefaultValidatorLocator(null);\r\n\r\n            // When\r\n            var exception = Record.Exception(() => subject.GetValidatorForType(typeof(string)));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ModelValidationException>();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Validation/ModuleExtensionsFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Validation\r\n{\r\n    using System;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Tests.Fakes;\r\n    using Nancy.Validation;\r\n\r\n    using Xunit;\r\n\r\n    public class ModuleExtensionsFixture\r\n    {\r\n        private readonly NancyContext context;\r\n        private readonly IModelValidatorLocator validatorLocator;\r\n        private readonly FakeNancyModule subject;\r\n\r\n        public ModuleExtensionsFixture()\r\n        {\r\n            this.context = new NancyContext();\r\n            this.validatorLocator = A.Fake<IModelValidatorLocator>();\r\n            this.subject = new FakeNancyModule\r\n            {\r\n                Context = this.context,\r\n                ValidatorLocator = this.validatorLocator\r\n            };\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_valid_when_no_validator_exists_for_type()\r\n        {\r\n            // Given, When\r\n            var result = subject.Validate<FakeModel>(new FakeModel());\r\n\r\n            // Then\r\n            result.IsValid.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_valid_when_a_validator_exists_and_the_instance_is_valid()\r\n        {\r\n            // Given\r\n            var validator = A.Fake<IModelValidator>();\r\n            A.CallTo(() => validator.Validate(A<object>.Ignored, A<NancyContext>._)).Returns(new ModelValidationResult());\r\n            A.CallTo(() => validatorLocator.GetValidatorForType(A<Type>.Ignored)).Returns(validator);\r\n\r\n            // When\r\n            var result = subject.Validate(new FakeModel());\r\n\r\n            // Then\r\n            result.IsValid.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_invalid_when_a_validator_exists_and_the_instance_is_valid()\r\n        {\r\n            // Given\r\n            var validator = A.Fake<IModelValidator>();\r\n            A.CallTo(() => validator.Validate(A<object>.Ignored, A<NancyContext>._)).Returns(new ModelValidationResult(new[] { new ModelValidationError(\"blah\", \"blah\") }));\r\n            A.CallTo(() => validatorLocator.GetValidatorForType(A<Type>.Ignored)).Returns(validator);\r\n\r\n            // When\r\n            var result = subject.Validate(new FakeModel());\r\n\r\n            // Then\r\n            result.IsValid.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_pass_context_to_validator()\r\n        {\r\n            // Given\r\n            var validator = A.Fake<IModelValidator>();\r\n            A.CallTo(() => validatorLocator.GetValidatorForType(A<Type>.Ignored)).Returns(validator);\r\n\r\n            // When\r\n            subject.Validate(new FakeModel());\r\n\r\n            // Then\r\n            A.CallTo(() => validator.Validate(A<object>._, this.context)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_pass_model_instance_to_validator()\r\n        {\r\n            // Given\r\n            var model = new FakeModel();\r\n            var validator = A.Fake<IModelValidator>();\r\n            A.CallTo(() => validatorLocator.GetValidatorForType(A<Type>.Ignored)).Returns(validator);\r\n\r\n            // When\r\n            subject.Validate(model);\r\n\r\n            // Then\r\n            A.CallTo(() => validator.Validate(model, A<NancyContext>._)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_add_errors_to_existing_module_errors()\r\n        {\r\n            //Given\r\n            subject.ModelValidationResult =\r\n                new ModelValidationResult(new[] { new ModelValidationError(\"FirstName\", \"Please enter a name\") });\r\n            \r\n            var model = new FakeModel();\r\n            \r\n            var validator = A.Fake<IModelValidator>();\r\n            \r\n            A.CallTo(() => validatorLocator.GetValidatorForType(A<Type>.Ignored)).Returns(validator);\r\n            \r\n            A.CallTo(() => validator.Validate(model, A<NancyContext>._))\r\n             .Returns(\r\n                 new ModelValidationResult(new[] { new ModelValidationError(\"LastName\", \"Please enter a last name\") }));\r\n\r\n            // When\r\n            subject.Validate(model);\r\n\r\n            // Then\r\n            subject.ModelValidationResult.Errors.ShouldHaveCount(2);\r\n        }\r\n\r\n        private class FakeModel\r\n        {\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/Validation/ValidationResultFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.Validation\r\n{\r\n    using System.Collections.Generic;\r\n\r\n    using Nancy.Validation;\r\n\r\n    using Xunit;\r\n\r\n    public class ModelValidationResultFixture\r\n    {\r\n        [Fact]\r\n        public void Should_not_throw_if_null_errors_collection_is_passed()\r\n        {\r\n            // Given, When\r\n            var result = Record.Exception(() => new ModelValidationResult((IEnumerable<ModelValidationError>)null));\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_valid_when_no_errors_exist()\r\n        {\r\n            // Given\r\n            var subject = new ModelValidationResult((IEnumerable<ModelValidationError>)null);\r\n\r\n            // When\r\n            var result = subject.IsValid;\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_invalid_if_any_errors_exist()\r\n        {\r\n            // Given\r\n            var subject = new ModelValidationResult(new[] { new ModelValidationError(\"blah\", \"blah\") });\r\n\r\n            // When\r\n            var result = subject.IsValid;\r\n\r\n            // Then\r\n            result.ShouldBeFalse();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/ViewEngines/DefaultRenderContextFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.ViewEngines\r\n{\r\n    using System;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Security;\r\n    using Nancy.ViewEngines;\r\n\r\n    using Xunit;\r\n\r\n    public class DefaultRenderContextFixture\r\n    {\r\n        [Fact]\r\n        public void Should_html_encode_string()\r\n        {\r\n            // Given\r\n            var context = new DefaultRenderContext(null, null, null, this.GetContext());\r\n\r\n            // When\r\n            var result = context.HtmlEncode(\"This is a string value & should be HTML-encoded\");\r\n\r\n            // Then\r\n            result.ShouldEqual(\"This is a string value &amp; should be HTML-encoded\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_expose_view_cache_instance_that_is_passed_in()\r\n        {\r\n            // Given\r\n            var cache = A.Fake<IViewCache>();\r\n\r\n            // When\r\n            var context = new DefaultRenderContext(null, cache, null, this.GetContext());\r\n\r\n            // Then\r\n            context.ViewCache.ShouldBeSameAs(cache);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_call_view_resolver_with_view_name_when_locating_view()\r\n        {\r\n            // Given\r\n            const string viewName = \"view.html\";\r\n            var resolver = A.Fake<IViewResolver>();\r\n            var context = new DefaultRenderContext(resolver, null, null, this.GetContext());\r\n\r\n            // When\r\n            context.LocateView(viewName, null);\r\n\r\n            // Then\r\n            A.CallTo(() => resolver.GetViewLocation(viewName, A<object>.Ignored, A<ViewLocationContext>.Ignored)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_call_view_resolver_with_model_when_locating_view()\r\n        {\r\n            // Given\r\n            var model = new object();\r\n            var resolver = A.Fake<IViewResolver>();\r\n            var context = new DefaultRenderContext(resolver, null, null, this.GetContext());\r\n\r\n            // When\r\n            context.LocateView(null, model);\r\n\r\n            // Then\r\n            A.CallTo(() => resolver.GetViewLocation(A<string>.Ignored, model, A<ViewLocationContext>.Ignored)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_call_view_resolver_with_view_location_context_when_locating_view()\r\n        {\r\n            // Given\r\n            var locationContext = new ViewLocationContext();\r\n            var resolver = A.Fake<IViewResolver>();\r\n            var context = new DefaultRenderContext(resolver, null, null, locationContext);\r\n\r\n            // When\r\n            context.LocateView(null, null);\r\n\r\n            // Then)\r\n            A.CallTo(() => resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, locationContext)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_result_from_view_resolver_when_locating_view()\r\n        {\r\n            // Given\r\n            var viewResult = new ViewLocationResult(null, null, null, null);\r\n            var resolver = A.Fake<IViewResolver>();\r\n            A.CallTo(() => resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(viewResult);\r\n            var context = new DefaultRenderContext(resolver, null, null, this.GetContext());\r\n\r\n            // When\r\n            var result = context.LocateView(null, null);\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(viewResult);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_same_path_when_parsing_path_if_path_doesnt_contain_tilde()\r\n        {\r\n            const string input = \"/scripts/test.js\";\r\n            var url = new Url\r\n                {\r\n                    BasePath = \"/base/path\",\r\n                    Path = \"/\"\r\n                };\r\n            var request = new Request(\"GET\", url);\r\n            var nancyContext = new NancyContext { Request = request };\r\n            var viewLocationContext = new ViewLocationContext { Context = nancyContext };\r\n            var context = new DefaultRenderContext(null, null, null, viewLocationContext);\r\n\r\n            var result = context.ParsePath(input);\r\n\r\n            result.ShouldEqual(input);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_replace_tilde_with_base_path_when_parsing_path_if_one_present()\r\n        {\r\n            const string input = \"~/scripts/test.js\";\r\n            var url = new Url\r\n                {\r\n                    BasePath = \"/base/path/\",\r\n                    Path = \"/\"\r\n                };\r\n            var request = new Request(\"GET\", url);\r\n            var nancyContext = new NancyContext { Request = request };\r\n            var viewLocationContext = new ViewLocationContext { Context = nancyContext };\r\n            var context = new DefaultRenderContext(null, null, null, viewLocationContext);\r\n\r\n            var result = context.ParsePath(input);\r\n\r\n            result.ShouldEqual(\"/base/path/scripts/test.js\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_replace_tilde_with_nothing_when_parsing_path_if_one_present_and_base_path_is_null()\r\n        {\r\n            const string input = \"~/scripts/test.js\";\r\n            var url = new Url\r\n                {\r\n                    BasePath = null,\r\n                    Path = \"/\"\r\n                };\r\n            var request = new Request(\"GET\", url);\r\n            var nancyContext = new NancyContext { Request = request };\r\n            var viewLocationContext = new ViewLocationContext { Context = nancyContext };\r\n            var context = new DefaultRenderContext(null, null, null, viewLocationContext);\r\n\r\n            var result = context.ParsePath(input);\r\n\r\n            result.ShouldEqual(\"/scripts/test.js\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_csrf_token_from_context_if_it_exists()\r\n        {\r\n            var nancyContext = new NancyContext();\r\n            nancyContext.Items[CsrfToken.DEFAULT_CSRF_KEY] = \"testing\";\r\n            var viewLocationContext = new ViewLocationContext { Context = nancyContext };\r\n            var context = new DefaultRenderContext(null, null, null, viewLocationContext);\r\n\r\n            var result = context.GetCsrfToken();\r\n\r\n            result.ShouldNotBeNull();\r\n            result.Key.ShouldEqual(CsrfToken.DEFAULT_CSRF_KEY);\r\n            result.Value.ShouldEqual(\"testing\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_if_context_does_not_contain_csrf_token_and_its_requested()\r\n        {\r\n            var nancyContext = new NancyContext();\r\n            nancyContext.Items[CsrfToken.DEFAULT_CSRF_KEY] = new object();\r\n            var viewLocationContext = new ViewLocationContext { Context = nancyContext };\r\n            var context = new DefaultRenderContext(null, null, null, viewLocationContext);\r\n\r\n            var result = Record.Exception(() => context.GetCsrfToken());\r\n\r\n            result.ShouldBeOfType(typeof(InvalidOperationException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_if_context_does_not_contain_valid_csrf_token_and_its_requested()\r\n        {\r\n            var nancyContext = new NancyContext();\r\n            var viewLocationContext = new ViewLocationContext { Context = nancyContext };\r\n            var context = new DefaultRenderContext(null, null, null, viewLocationContext);\r\n\r\n            var result = Record.Exception(() => context.GetCsrfToken());\r\n\r\n            result.ShouldBeOfType(typeof(InvalidOperationException));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_expose_context_from_viewlocationcontext()\r\n        {\r\n            // Given\r\n            var nancyContext = new NancyContext();\r\n            var viewLocationContext = new ViewLocationContext { Context = nancyContext };\r\n\r\n            // When\r\n            var context = new DefaultRenderContext(null, null, null, viewLocationContext);\r\n\r\n            // Then\r\n            context.Context.ShouldBeSameAs(nancyContext);\r\n        }\r\n\r\n        private ViewLocationContext GetContext()\r\n        {\r\n            var context = new ViewLocationContext();\r\n\r\n            context.Context = new NancyContext();\r\n\r\n            return context;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/ViewEngines/DefaultViewFactoryFixture.cs",
    "content": "namespace Nancy.Tests.Unit.ViewEngines\r\n{\r\n    using System;\r\n    using System.Dynamic;\r\n    using System.IO;\r\n    using System.Linq;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Conventions;\r\n    using Nancy.Diagnostics;\r\n    using Nancy.Tests.Fakes;\r\n    using Nancy.ViewEngines;\r\n\r\n    using Xunit;\r\n\r\n    public class DefaultViewFactoryFixture\r\n    {\r\n        private readonly IViewResolver resolver;\r\n        private readonly IRenderContextFactory renderContextFactory;\r\n        private readonly ViewLocationContext viewLocationContext;\r\n        private readonly ViewLocationConventions conventions;\r\n        private readonly IRootPathProvider rootPathProvider;\r\n\r\n        public DefaultViewFactoryFixture()\r\n        {\r\n            this.rootPathProvider = A.Fake<IRootPathProvider>();\r\n            A.CallTo(() => this.rootPathProvider.GetRootPath()).Returns(\"The root path\");\r\n\r\n            this.resolver = A.Fake<IViewResolver>();\r\n            this.renderContextFactory = A.Fake<IRenderContextFactory>();\r\n            this.conventions = new ViewLocationConventions(Enumerable.Empty<Func<string, object, ViewLocationContext, string>>());\r\n\r\n            this.viewLocationContext =\r\n                new ViewLocationContext\r\n                {\r\n                    Context = new NancyContext\r\n                    {\r\n                        Trace = new DefaultRequestTrace\r\n                        {\r\n                            TraceLog = new DefaultTraceLog()\r\n                        }\r\n                    }\r\n                };\r\n        }\r\n\r\n        private DefaultViewFactory CreateFactory(params IViewEngine[] viewEngines)\r\n        {\r\n            if (viewEngines == null)\r\n            {\r\n                viewEngines = ArrayCache.Empty<IViewEngine>();\r\n            }\r\n\r\n            return new DefaultViewFactory(this.resolver, viewEngines, this.renderContextFactory, this.conventions, this.rootPathProvider);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_get_render_context_from_factory_when_rendering_view()\r\n        {\r\n            // Given\r\n            var viewEngines = new[] {\r\n              A.Fake<IViewEngine>(),\r\n            };\r\n\r\n            A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { \"html\" });\r\n\r\n            var location = new ViewLocationResult(\"location\", \"name\", \"html\", GetEmptyContentReader());\r\n            A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location);\r\n\r\n            var factory = this.CreateFactory(viewEngines);\r\n\r\n            // When\r\n            factory.RenderView(\"view.html\", new object(), this.viewLocationContext);\r\n\r\n            // Then\r\n            A.CallTo(() => this.renderContextFactory.GetRenderContext(A<ViewLocationContext>.Ignored)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_render_view_with_context_created_by_factory()\r\n        {\r\n            // Given\r\n            var viewEngines = new[] {\r\n              A.Fake<IViewEngine>(),\r\n            };\r\n\r\n            A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { \"html\" });\r\n\r\n            var location = new ViewLocationResult(\"location\", \"name\", \"html\", GetEmptyContentReader());\r\n            A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location);\r\n\r\n            var context = A.Fake<IRenderContext>();\r\n            A.CallTo(() => this.renderContextFactory.GetRenderContext(A<ViewLocationContext>.Ignored)).Returns(context);\r\n\r\n            var factory = this.CreateFactory(viewEngines);\r\n\r\n            // When\r\n            factory.RenderView(\"view.html\", new object(), this.viewLocationContext);\r\n\r\n            // Then\r\n            A.CallTo(() => viewEngines[0].RenderView(A<ViewLocationResult>.Ignored, A<object>.Ignored, context)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_build_render_context_more_than_once()\r\n        {\r\n            // Given\r\n            var viewEngines = new[] {\r\n              A.Fake<IViewEngine>(),\r\n            };\r\n\r\n            A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { \"html\" });\r\n\r\n            var location = new ViewLocationResult(\"location\", \"name\", \"html\", GetEmptyContentReader());\r\n            A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location);\r\n\r\n            var factory = this.CreateFactory(viewEngines);\r\n\r\n            // When\r\n            factory.RenderView(\"view.html\", new object(), this.viewLocationContext);\r\n\r\n            // Then\r\n            A.CallTo(() => this.renderContextFactory.GetRenderContext(A<ViewLocationContext>.Ignored)).MustHaveHappenedOnceOrLess();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_argumentnullexception_when_rendering_view_and_viewlocationcontext_is_null()\r\n        {\r\n            // Given\r\n            var factory = this.CreateFactory(null);\r\n\r\n            // When\r\n            var exception = Record.Exception(() => factory.RenderView(\"viewName\", new object(), null));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ArgumentNullException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_argumentexception_when_rendering_view_and_view_name_is_empty_and_model_is_null()\r\n        {\r\n            // Given\r\n            var factory = this.CreateFactory(null);\r\n\r\n            // When\r\n            var exception = Record.Exception(() => factory.RenderView(string.Empty, null, this.viewLocationContext));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ArgumentException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_argumentexception_when_rendering_view_and_both_viewname_and_model_is_null()\r\n        {\r\n            // Given\r\n            var factory = this.CreateFactory(null);\r\n\r\n            // When\r\n            var exception = Record.Exception(() => factory.RenderView(null, null, this.viewLocationContext));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<ArgumentException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_retrieve_view_from_view_locator_using_provided_view_name()\r\n        {\r\n            // Given\r\n            var factory = this.CreateFactory();\r\n\r\n            // When\r\n            Record.Exception(() => factory.RenderView(\"viewname.html\", null, this.viewLocationContext));\r\n\r\n            // Then\r\n            A.CallTo(() => this.resolver.GetViewLocation(\"viewname.html\", A<object>.Ignored, A<ViewLocationContext>.Ignored)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_retrieve_view_from_view_locator_using_provided_model()\r\n        {\r\n            // Given\r\n            var factory = this.CreateFactory();\r\n            var model = new object();\r\n\r\n            // When\r\n            Record.Exception(() => factory.RenderView(null, model, this.viewLocationContext));\r\n\r\n            // Then\r\n            A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, model, A<ViewLocationContext>.Ignored)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_retrieve_view_from_view_locator_using_provided_module_path()\r\n        {\r\n            // Given\r\n            var factory = this.CreateFactory();\r\n            var model = new object();\r\n\r\n            var viewContext = \r\n                new ViewLocationContext\r\n                {\r\n                    Context = new NancyContext\r\n                    {\r\n                        Trace = new DefaultRequestTrace\r\n                        {\r\n                            TraceLog = new DefaultTraceLog()\r\n                        }\r\n                    },\r\n                    ModulePath = \"/bar\"\r\n                };\r\n\r\n            // When\r\n            Record.Exception(() => factory.RenderView(null, model, viewContext));\r\n\r\n            // Then\r\n            A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.That.Matches(x => x.ModulePath.Equals(\"/bar\")))).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_call_first_view_engine_that_supports_extension_with_view_location_results()\r\n        {\r\n            // Given\r\n            var viewEngines = new[] {\r\n              A.Fake<IViewEngine>(),\r\n              A.Fake<IViewEngine>(),\r\n            };\r\n\r\n            A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { \"html\" });\r\n            A.CallTo(() => viewEngines[1].Extensions).Returns(new[] { \"html\" });\r\n\r\n            var location = new ViewLocationResult(\"location\", \"name\", \"html\", GetEmptyContentReader());\r\n            A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location);\r\n\r\n            var factory = this.CreateFactory(viewEngines);\r\n\r\n            // When\r\n            factory.RenderView(\"foo\", null, this.viewLocationContext);\r\n\r\n            // Then\r\n            A.CallTo(() => viewEngines[0].RenderView(location, null, A<IRenderContext>.Ignored)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_ignore_case_when_locating_view_engine_for_view_name_extension()\r\n        {\r\n            // Given\r\n            var viewEngines = new[] {\r\n              A.Fake<IViewEngine>(),\r\n            };\r\n\r\n            A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { \"HTML\" });\r\n\r\n            var location = new ViewLocationResult(\"location\", \"name\", \"html\", GetEmptyContentReader());\r\n            A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location);\r\n\r\n            var factory = this.CreateFactory(viewEngines);\r\n\r\n            // When\r\n            factory.RenderView(\"foo\", null, this.viewLocationContext);\r\n\r\n            // Then\r\n            A.CallTo(() => viewEngines[0].RenderView(location, null, A<IRenderContext>.Ignored)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_response_from_invoked_engine()\r\n        {\r\n            // Given\r\n            var viewEngines = new[] {\r\n              A.Fake<IViewEngine>(),\r\n            };\r\n\r\n            Action<Stream> actionReturnedFromEngine = x => { };\r\n\r\n            A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { \"html\" });\r\n            A.CallTo(() => viewEngines[0].RenderView(A<ViewLocationResult>.Ignored, null, A<IRenderContext>.Ignored)).Returns(actionReturnedFromEngine);\r\n\r\n            var location = new ViewLocationResult(\"location\", \"name\", \"html\", GetEmptyContentReader());\r\n            A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location);\r\n\r\n            var factory = this.CreateFactory(viewEngines);\r\n\r\n            // When\r\n            var response = factory.RenderView(\"foo\", null, this.viewLocationContext);\r\n\r\n            // Then\r\n            response.Contents.ShouldBeSameAs(actionReturnedFromEngine);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_action_when_view_engine_throws_exception()\r\n        {\r\n            var viewEngines = new[] {\r\n              A.Fake<IViewEngine>(),\r\n            };\r\n\r\n            A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { \"html\" });\r\n            A.CallTo(() => viewEngines[0].RenderView(A<ViewLocationResult>.Ignored, null, A<IRenderContext>.Ignored)).Throws(new Exception());\r\n\r\n            var location = new ViewLocationResult(\"location\", \"name\", \"html\", GetEmptyContentReader());\r\n            A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location);\r\n\r\n            var stream = new MemoryStream();\r\n            var factory = this.CreateFactory(viewEngines);\r\n\r\n            // When\r\n            var response = factory.RenderView(\"foo\", null, this.viewLocationContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            stream.Length.ShouldEqual(0L);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_view_engine_with_model()\r\n        {\r\n            // Given\r\n            var viewEngines = new[] {\r\n              A.Fake<IViewEngine>(),\r\n            };\r\n\r\n            A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { \"html\" });\r\n            A.CallTo(() => viewEngines[0].RenderView(A<ViewLocationResult>.Ignored, null, null)).Throws(new Exception());\r\n\r\n            var location = new ViewLocationResult(\"location\", \"name\", \"html\", GetEmptyContentReader());\r\n            A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location);\r\n\r\n            var model = new object();\r\n            var factory = this.CreateFactory(viewEngines);\r\n\r\n            // When\r\n            factory.RenderView(\"foo\", model, this.viewLocationContext);\r\n\r\n            // Then\r\n            A.CallTo(() => viewEngines[0].RenderView(A<ViewLocationResult>.Ignored, model, A<IRenderContext>.Ignored)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_covert_anonymoustype_model_to_expandoobject_before_invoking_view_engine()\r\n        {\r\n            // Given\r\n            var viewEngines = new[] {\r\n              A.Fake<IViewEngine>(),\r\n            };\r\n\r\n            A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { \"html\" });\r\n\r\n            var location = new ViewLocationResult(\"location\", \"name\", \"html\", GetEmptyContentReader());\r\n            A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location);\r\n\r\n            var model = new { Name = \"\" };\r\n            var factory = this.CreateFactory(viewEngines);\r\n\r\n            // When\r\n            factory.RenderView(\"foo\", model, this.viewLocationContext);\r\n\r\n            // Then\r\n            A.CallTo(() => viewEngines[0].RenderView(A<ViewLocationResult>.Ignored, A<object>.That.Matches(x => x.GetType().Equals(typeof(ExpandoObject))), A<IRenderContext>.Ignored)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_transfer_anonymoustype_model_members_to_expandoobject_members_before_invoking_view_engines()\r\n        {\r\n            // Given\r\n            var viewEngines = new[] {\r\n              new FakeViewEngine { Extensions = new[] { \"html\"}}\r\n            };\r\n\r\n            var location = new ViewLocationResult(\"location\", \"name\", \"html\", GetEmptyContentReader());\r\n            A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location);\r\n\r\n            var model = new { Name = \"Nancy\" };\r\n            var factory = this.CreateFactory(viewEngines);\r\n\r\n            // When\r\n            factory.RenderView(\"foo\", model, this.viewLocationContext);\r\n\r\n            // Then\r\n            ((string)viewEngines[0].Model.Name).ShouldEqual(\"Nancy\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_the_name_of_the_model_type_as_view_name_when_only_model_is_specified()\r\n        {\r\n            // Given\r\n            var factory = this.CreateFactory();\r\n\r\n            // When\r\n            Record.Exception(() => factory.RenderView(null, new object(), this.viewLocationContext));\r\n\r\n            // Then\r\n            A.CallTo(() => this.resolver.GetViewLocation(\"Object\", A<object>.Ignored, A<ViewLocationContext>.Ignored)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_the_name_of_the_model_type_without_model_suffix_as_view_name_when_only_model_is_specified()\r\n        {\r\n            // Given\r\n            var factory = this.CreateFactory();\r\n\r\n            // When\r\n            Record.Exception(() => factory.RenderView(null, new ViewModel(), this.viewLocationContext));\r\n\r\n            // Then\r\n            A.CallTo(() => this.resolver.GetViewLocation(\"View\", A<object>.Ignored, A<ViewLocationContext>.Ignored)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_when_view_could_not_be_located()\r\n        {\r\n            var factory = this.CreateFactory();\r\n\r\n            A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(null);\r\n\r\n            var result = Record.Exception(() => factory.RenderView(\"foo\", null, this.viewLocationContext));\r\n\r\n            result.ShouldBeOfType<ViewNotFoundException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_provide_view_name_and_available_extensions_in_not_found_exception()\r\n        {\r\n            var viewEngines = new[] {\r\n              A.Fake<IViewEngine>(),\r\n              A.Fake<IViewEngine>(),\r\n            };\r\n            A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { \"html\" });\r\n            A.CallTo(() => viewEngines[1].Extensions).Returns(new[] { \"sshtml\" });\r\n            var factory = this.CreateFactory(viewEngines);\r\n            A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(null);\r\n\r\n            var result = Record.Exception(() => factory.RenderView(\"foo\", null, this.viewLocationContext)) as ViewNotFoundException;\r\n\r\n            result.AvailableViewEngineExtensions.ShouldEqualSequence(new[] { \"html\", \"sshtml\" });\r\n            result.ViewName.ShouldEqual(\"foo\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_provide_list_of_inspected_view_locations_in_not_found_exception()\r\n        {\r\n            var viewEngines = new[] {\r\n              A.Fake<IViewEngine>(),\r\n              A.Fake<IViewEngine>(),\r\n            };\r\n            A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { \"html\" });\r\n            A.CallTo(() => viewEngines[1].Extensions).Returns(new[] { \"sshtml\" });            \r\n             \r\n            var conventions = new Func<string, dynamic, ViewLocationContext, string>[] {(a,b,c) => \"baz\"};\r\n            var factory = new DefaultViewFactory(this.resolver, viewEngines, this.renderContextFactory, new ViewLocationConventions(conventions), this.rootPathProvider);\r\n            \r\n            A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(null);\r\n\r\n            var result = (Record.Exception(() => factory.RenderView(\"foo\", null, this.viewLocationContext))) as ViewNotFoundException;\r\n\r\n            result.AvailableViewEngineExtensions.ShouldEqualSequence(new[] { \"html\", \"sshtml\" });\r\n            result.ViewName.ShouldEqual(\"foo\");\r\n            result.InspectedLocations.ShouldEqualSequence(new [] {\"baz\"});\r\n        }\r\n\r\n\r\n        private static Func<TextReader> GetEmptyContentReader()\r\n        {\r\n            return () => new StreamReader(new MemoryStream());\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/ViewEngines/DefaultViewLocatorFixture.cs",
    "content": "namespace Nancy.Tests.Unit.ViewEngines\r\n{\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using FakeItEasy;\r\n    using Nancy.Configuration;\r\n    using Nancy.ViewEngines;\r\n    using Xunit;\r\n    using Xunit.Extensions;\r\n\r\n    public class DefaultViewLocatorFixture\r\n    {\r\n        private readonly DefaultViewLocator viewLocator;\r\n        private readonly INancyEnvironment environment;\r\n\r\n        public DefaultViewLocatorFixture()\r\n        {\r\n            this.environment = new DefaultNancyEnvironment();\r\n            this.environment.AddValue(ViewConfiguration.Default);\r\n            this.viewLocator = this.CreateViewLocator();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_if_locate_view_is_invoked_with_null_view_name()\r\n        {\r\n            // Given\r\n            string viewName = null;\r\n\r\n            // When\r\n            var result = this.viewLocator.LocateView(viewName, null);\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_if_locate_view_is_invoked_with_empty_view_name()\r\n        {\r\n            // Given\r\n            var viewName = string.Empty;\r\n\r\n            // When\r\n            var result = this.viewLocator.LocateView(viewName, null);\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_locate_view_when_only_name_is_provided()\r\n        {\r\n            // Given\r\n            var expectedView = new ViewLocationResult(string.Empty, \"index\", string.Empty, () => null);\r\n\r\n            var locator = this.CreateViewLocator(expectedView);\r\n\r\n            // When\r\n            var result = locator.LocateView(\"index\", null);\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(expectedView);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"INDEX\")]\r\n        [InlineData(\"InDEx\")]\r\n        public void Should_ignore_case_when_locating_view_based_on_name(string viewName)\r\n        {\r\n            // Given\r\n            var expectedView = new ViewLocationResult(string.Empty, \"index\", string.Empty, () => null);\r\n            var locator = this.CreateViewLocator(expectedView);\r\n\r\n            // When\r\n            var result = locator.LocateView(viewName, null);\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(expectedView);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_ambiguousviewsexception_when_locating_view_by_name_returns_multiple_results()\r\n        {\r\n            // Given\r\n            var expectedView1 = new ViewLocationResult(string.Empty, \"index\", string.Empty, () => null);\r\n            var expectedView2 = new ViewLocationResult(string.Empty, \"index\", string.Empty, () => null);\r\n            var locator = this.CreateViewLocator(expectedView1, expectedView2);\r\n\r\n            // When\r\n            var exception = Record.Exception(() => locator.LocateView(\"index\", null));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<AmbiguousViewsException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_ambiguousviewsexception_when_locating_view_by_name_and_multiple_views_share_the_same_name_and_location_but_different_extensions()\r\n        {\r\n            // Given\r\n            var expectedView1 = new ViewLocationResult(string.Empty, \"index\", \"spark\", () => null);\r\n            var expectedView2 = new ViewLocationResult(string.Empty, \"index\", \"html\", () => null);\r\n            var locator = this.CreateViewLocator(expectedView1, expectedView2);\r\n\r\n            // When\r\n            var exception = Record.Exception(() => locator.LocateView(\"index\", null));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<AmbiguousViewsException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_message_on_ambiguousviewexception()\r\n        {\r\n            // Given\r\n            var expectedView1 = new ViewLocationResult(string.Empty, \"index\", \"spark\", () => null);\r\n            var expectedView2 = new ViewLocationResult(string.Empty, \"index\", \"html\", () => null);\r\n            var locator = this.CreateViewLocator(expectedView1, expectedView2);\r\n\r\n            const string expectedMessage = \"This exception was thrown because multiple views were found. 2 view(s):\\r\\n\\t/index.spark\\r\\n\\t/index.html\";\r\n\r\n            // When\r\n            var exception = Record.Exception(() => locator.LocateView(\"index\", null));\r\n\r\n            // Then\r\n            exception.Message.ShouldEqual(expectedMessage);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_when_view_cannot_be_located_using_name()\r\n        {\r\n            // Given\r\n            var expectedView = new ViewLocationResult(string.Empty, \"index\", string.Empty, () => null);\r\n\r\n            var locator = this.CreateViewLocator(expectedView);\r\n\r\n            // When\r\n            var result = locator.LocateView(\"main\", null);\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_locate_view_when_name_and_extension_are_provided()\r\n        {\r\n            // Given\r\n            var expectedView = new ViewLocationResult(string.Empty, \"index\", \"cshtml\", () => null);\r\n\r\n            var locator = this.CreateViewLocator(expectedView);\r\n\r\n            // When\r\n            var result = locator.LocateView(\"index.cshtml\", null);\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(expectedView);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"INDEX.CSHTML\")]\r\n        [InlineData(\"InDEx.csHTml\")]\r\n        public void Should_ignore_case_when_locating_view_based_on_name_and_extension(string viewName)\r\n        {\r\n            // Given\r\n            var expectedView = new ViewLocationResult(string.Empty, \"index\", \"cshtml\", () => null);\r\n            var locator = this.CreateViewLocator(expectedView);\r\n\r\n            // When\r\n            var result = locator.LocateView(viewName, null);\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(expectedView);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_when_view_cannot_be_located_using_name_and_extension()\r\n        {\r\n            // Given\r\n            var expectedView = new ViewLocationResult(string.Empty, \"index\", \"spark\", () => null);\r\n\r\n            var locator = this.CreateViewLocator(expectedView);\r\n\r\n            // When\r\n            var result = locator.LocateView(\"index.cshtml\", null);\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_locate_view_when_name_extension_and_location_are_provided()\r\n        {\r\n            // Given\r\n            var expectedView = new ViewLocationResult(\"views/sub\", \"index\", \"cshtml\", () => null);\r\n\r\n            var locator = this.CreateViewLocator(expectedView);\r\n\r\n            // When\r\n            var result = locator.LocateView(\"views/sub/index.cshtml\", null);\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(expectedView);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"VIEWS/SUB/INDEX.CSHTML\")]\r\n        [InlineData(\"viEWS/sUb/InDEx.csHTml\")]\r\n        public void Should_ignore_case_when_locating_view_based_on_name_extension_and_location(string viewName)\r\n        {\r\n            // Given\r\n            var expectedView = new ViewLocationResult(\"views/sub\", \"index\", \"cshtml\", () => null);\r\n            var locator = this.CreateViewLocator(expectedView);\r\n\r\n            // When\r\n            var result = locator.LocateView(viewName, null);\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(expectedView);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_when_view_cannot_be_located_using_name_extension_and_location()\r\n        {\r\n            // Given\r\n            var expectedView = new ViewLocationResult(\"views/sub\", \"index\", \"spark\", () => null);\r\n\r\n            var locator = this.CreateViewLocator(expectedView);\r\n\r\n            // When\r\n            var result = locator.LocateView(\"views/feature/index.cshtml\", null);\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_locate_view_by_name_when_two_views_with_same_name_exists_at_different_locations()\r\n        {\r\n            // Given\r\n            var expectedView = new ViewLocationResult(\"views/sub\", \"index\", string.Empty, () => null);\r\n            var additionalView = new ViewLocationResult(\"views\", \"index\", string.Empty, () => null);\r\n            var locator = this.CreateViewLocator(expectedView, additionalView);\r\n\r\n            // When\r\n            var result = locator.LocateView(\"views/sub/index\", null);\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(expectedView);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_locate_view_by_name_and_extension_when_two_view_with_same_name_but_different_extensions_exists_in_the_same_location()\r\n        {\r\n            // Given\r\n            var expectedView = new ViewLocationResult(\"views\", \"index\", \"cshtml\", () => null);\r\n            var additionalView = new ViewLocationResult(\"views\", \"index\", \"spark\", () => null);\r\n            var locator = this.CreateViewLocator(expectedView, additionalView);\r\n\r\n            // When\r\n            var result = locator.LocateView(\"views/index.cshtml\", null);\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(expectedView);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_locate_view_by_name_when_two_views_with_same_name_and_extension_exists_at_different_locations()\r\n        {\r\n            // Given\r\n            var expectedView = new ViewLocationResult(\"views/sub\", \"index\", \"cshtml\", () => null);\r\n            var additionalView = new ViewLocationResult(\"views\", \"index\", \"spark\", () => null);\r\n            var locator = this.CreateViewLocator(expectedView, additionalView);\r\n\r\n            // When\r\n            var result = locator.LocateView(\"views/sub/index.cshtml\", null);\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(expectedView);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_locate_view_by_name_when_the_viewname_occures_in_the_location()\r\n        {\r\n           // Given\r\n           var expectedView = new ViewLocationResult( \"views/hello\", \"hello\", \"cshtml\", () => null );\r\n           //var additionalView = new ViewLocationResult( \"views\", \"index\", \"spark\", () => null );\r\n           var locator = this.CreateViewLocator(expectedView);\r\n\r\n           // When\r\n           var result = locator.LocateView( \"views/hello/hello\", null );\r\n\r\n           // Then\r\n           result.ShouldBeSameAs( expectedView );\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_get_located_views_from_view_location_providers_with_available_extensions_when_created()\r\n        {\r\n            // Given\r\n            var viewEngine1 = A.Fake<IViewEngine>();\r\n            A.CallTo(() => viewEngine1.Extensions).Returns(new[] { \"html\" });\r\n\r\n            var viewEngine2 = A.Fake<IViewEngine>();\r\n            A.CallTo(() => viewEngine2.Extensions).Returns(new[] { \"spark\" });\r\n\r\n            var viewLocationProvider = A.Fake<IViewLocationProvider>();\r\n            var expectedViewEngineExtensions = new[] { \"html\", \"spark\" };\r\n            var viewEngine = A.Fake<IViewEngine>();\r\n            A.CallTo(() => viewEngine.Extensions).Returns(expectedViewEngineExtensions);\r\n\r\n            // When\r\n            new DefaultViewLocator(viewLocationProvider, new[] { viewEngine }, this.environment);\r\n\r\n            // Then\r\n            A.CallTo(() => viewLocationProvider.GetLocatedViews(A<IEnumerable<string>>.That.Matches(\r\n                    x => x.All(expectedViewEngineExtensions.Contains)))).MustHaveHappened();\r\n        }\r\n\r\n\r\n        private DefaultViewLocator CreateViewLocator(params ViewLocationResult[] results)\r\n        {\r\n            var viewLocationProvider = A.Fake<IViewLocationProvider>();\r\n            A.CallTo(() => viewLocationProvider.GetLocatedViews(A<IEnumerable<string>>._))\r\n                                               .Returns(results);\r\n\r\n            var viewEngine = A.Fake<IViewEngine>();\r\n            A.CallTo(() => viewEngine.Extensions).Returns(new[] { \"liquid\" });\r\n\r\n            var viewLocator = new DefaultViewLocator(viewLocationProvider, new[] { viewEngine }, this.environment);\r\n\r\n            return viewLocator;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/ViewEngines/DefaultViewResolverFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.ViewEngines\r\n{\r\n    using System;\r\n    using System.IO;\r\n    using System.Linq;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Conventions;\r\n    using Nancy.Diagnostics;\r\n    using Nancy.ViewEngines;\r\n\r\n    using Xunit;\r\n\r\n    public class DefaultViewResolverFixture\r\n    {\r\n        private readonly IViewLocator viewLocator;\r\n        private readonly DefaultViewResolver viewResolver;\r\n        private readonly ViewLocationContext viewLocationContext;\r\n\r\n        public DefaultViewResolverFixture()\r\n        {\r\n            this.viewLocator = A.Fake<IViewLocator>();\r\n            this.viewResolver = new DefaultViewResolver(this.viewLocator, new ViewLocationConventions(Enumerable.Empty<Func<string, object, ViewLocationContext, string>>()));\r\n\r\n            this.viewLocationContext =\r\n                new ViewLocationContext\r\n                {\r\n                    Context = new NancyContext\r\n                    {\r\n                        Trace = new DefaultRequestTrace\r\n                        {\r\n                            TraceLog = new DefaultTraceLog()\r\n                        }\r\n                    }\r\n                };\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_invalidoperationexception_when_created_with_null_view_locator()\r\n        {\r\n            // Given, When\r\n            var exception = Record.Exception(() => new DefaultViewResolver(null, new ViewLocationConventions(Enumerable.Empty<Func<string, object, ViewLocationContext, string>>())));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<InvalidOperationException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_invalidoperationexception_when_created_with_null_conventions()\r\n        {\r\n            // Given, When\r\n            var exception = Record.Exception(() => new DefaultViewResolver(A.Fake<IViewLocator>(), null));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<InvalidOperationException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_when_the_viewlocationcontext_is_null()\r\n        {\r\n            // Given\r\n            ViewLocationContext context = null;\r\n\r\n            // When\r\n            var result = this.viewResolver.GetViewLocation(\"viewName\", new object(), context);\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_when_viewname_is_null()\r\n        {\r\n            // Given\r\n            string viewName = null;\r\n\r\n            // When\r\n            var result = this.viewResolver.GetViewLocation(viewName, new object(), null);\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_when_viewname_is_empty()\r\n        {\r\n            // Given\r\n            var viewName = string.Empty;\r\n\r\n            // When\r\n            var result = this.viewResolver.GetViewLocation(viewName, new object(), null);\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_call_conventions_with_viewname()\r\n        {\r\n            // Given\r\n            const string viewName = \"foo.html\";\r\n            string viewNamePassedToFirstConvention = null;\r\n            string viewNamePassedToSecondConvention = null;\r\n\r\n            var resolver = new DefaultViewResolver(\r\n                this.viewLocator,\r\n                new ViewLocationConventions(new Func<string, dynamic, ViewLocationContext, string>[] {\r\n                    (name, model, path) => {\r\n                        viewNamePassedToFirstConvention = viewName;\r\n                        return string.Empty;\r\n                    },\r\n                    (name, model, path) => {\r\n                        viewNamePassedToSecondConvention = viewName;\r\n                        return string.Empty;\r\n                    }\r\n                }));\r\n\r\n            // When\r\n            resolver.GetViewLocation(viewName, null, this.viewLocationContext);\r\n\r\n            // Then\r\n            viewNamePassedToFirstConvention.ShouldEqual(viewName);\r\n            viewNamePassedToSecondConvention.ShouldEqual(viewName);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_call_conventions_with_model()\r\n        {\r\n            // Given\r\n            const string viewName = \"foo.html\";\r\n            var viewModel = new object();\r\n\r\n            object modelPassedToFirstConvention = null;\r\n            object modelPassedToSecondConvention = null;\r\n\r\n            var resolver = new DefaultViewResolver(\r\n                this.viewLocator,\r\n                new ViewLocationConventions(new Func<string, dynamic, ViewLocationContext, string>[] {\r\n                    (name, model, path) => {\r\n                        modelPassedToFirstConvention = model;\r\n                        return string.Empty;\r\n                    },\r\n                    (name, model, path) => {\r\n                        modelPassedToSecondConvention = model;\r\n                        return string.Empty;\r\n                    }\r\n                }));\r\n\r\n            // When\r\n            resolver.GetViewLocation(viewName, viewModel, this.viewLocationContext);\r\n\r\n            // Then\r\n            modelPassedToFirstConvention.ShouldBeSameAs(viewModel);\r\n            modelPassedToSecondConvention.ShouldBeSameAs(viewModel);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_call_conventions_with_viewlocationcontext()\r\n        {\r\n            // Given\r\n            const string viewName = \"foo.html\";\r\n            var context = this.viewLocationContext;\r\n\r\n            ViewLocationContext modulePathPassedToFirstConvention = null;\r\n            ViewLocationContext modulePathPassedToSecondConvention = null;\r\n\r\n            var resolver = new DefaultViewResolver(\r\n                this.viewLocator,\r\n                new ViewLocationConventions(new Func<string, dynamic, ViewLocationContext, string>[] {\r\n                    (name, model, viewLocationContext) => {\r\n                        modulePathPassedToFirstConvention = viewLocationContext;\r\n                        return string.Empty;\r\n                    },\r\n                    (name, model, viewLocationContext) => {\r\n                        modulePathPassedToSecondConvention = viewLocationContext;\r\n                        return string.Empty;\r\n                    }\r\n                }));\r\n\r\n            // When\r\n            resolver.GetViewLocation(viewName, null, context);\r\n\r\n            // Then\r\n            modulePathPassedToFirstConvention.ShouldBeSameAs(context);\r\n            modulePathPassedToSecondConvention.ShouldBeSameAs(context);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_viewlocator_with_viewname_from_conventions()\r\n        {\r\n            // Given\r\n            const string viewName = \"foo.html\";\r\n\r\n            var resolver = new DefaultViewResolver(\r\n                this.viewLocator,\r\n                new ViewLocationConventions(new Func<string, dynamic, ViewLocationContext, string>[] {\r\n                    (name, model, path) =>  \"bar.html\" \r\n                }));\r\n\r\n            // When\r\n            resolver.GetViewLocation(viewName, null, this.viewLocationContext);\r\n\r\n            // Then\r\n            A.CallTo(() => this.viewLocator.LocateView(\"bar.html\", A<NancyContext>.Ignored)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_view_locator_with_context()\r\n        {\r\n            // Given\r\n            var resolver = new DefaultViewResolver(\r\n                this.viewLocator,\r\n                new ViewLocationConventions(new Func<string, dynamic, ViewLocationContext, string>[] {\r\n                    (name, model, path) =>  \"bar.html\" \r\n                }));\r\n\r\n            // When\r\n            resolver.GetViewLocation(\"foo.html\", null, this.viewLocationContext);\r\n\r\n            // Then\r\n            A.CallTo(() => this.viewLocator.LocateView(A<string>.Ignored, this.viewLocationContext.Context)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_invoke_viewlocator_when_conventions_returns_null_view_name()\r\n        {\r\n            // Given\r\n            const string viewName = \"foo.html\";\r\n\r\n            var resolver = new DefaultViewResolver(\r\n                this.viewLocator,\r\n                new ViewLocationConventions(new Func<string, dynamic, ViewLocationContext, string>[] {\r\n                    (name, model, path) =>  null \r\n                }));\r\n\r\n            // When\r\n            resolver.GetViewLocation(viewName, null, this.viewLocationContext);\r\n\r\n            // Then\r\n            A.CallTo(() => this.viewLocator.LocateView(A<string>.Ignored, A<NancyContext>.Ignored)).MustNotHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_invoke_viewlocator_when_conventions_returns_empty_view_name()\r\n        {\r\n            // Given\r\n            const string viewName = \"foo.html\";\r\n\r\n            var resolver = new DefaultViewResolver(\r\n                this.viewLocator,\r\n                new ViewLocationConventions(new Func<string, dynamic, ViewLocationContext, string>[] {\r\n                    (name, model, path) => string.Empty \r\n                }));\r\n\r\n            // When\r\n            resolver.GetViewLocation(viewName, null, this.viewLocationContext);\r\n\r\n            // Then\r\n            A.CallTo(() => this.viewLocator.LocateView(A<string>.Ignored, A<NancyContext>.Ignored)).MustNotHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_catch_exceptions_that_are_thrown_by_conventions()\r\n        {\r\n            // Given\r\n            const string viewName = \"foo.html\";\r\n\r\n            var resolver = new DefaultViewResolver(\r\n                this.viewLocator,\r\n                new ViewLocationConventions(new Func<string, dynamic, ViewLocationContext, string>[] {\r\n                    (name, model, path) => { throw new Exception(); }\r\n                }));\r\n\r\n            // When\r\n            var exception = Record.Exception(() => resolver.GetViewLocation(viewName, null, this.viewLocationContext));\r\n\r\n            // Then\r\n            exception.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_when_no_view_could_be_located()\r\n        {\r\n            // Given\r\n            const string viewName = \"foo.html\";\r\n\r\n            var resolver = new DefaultViewResolver(\r\n                this.viewLocator,\r\n                new ViewLocationConventions(new Func<string, dynamic, ViewLocationContext, string>[] {\r\n                    (name, model, path) => \"bar.html\"\r\n                }));\r\n\r\n            A.CallTo(() => this.viewLocator.LocateView(A<string>.Ignored, A<NancyContext>.Ignored)).Returns(null);\r\n\r\n            // When\r\n            var result = resolver.GetViewLocation(viewName, null, this.viewLocationContext);\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void return_viewlocationresult_when_view_could_be_located()\r\n        {\r\n            // Given\r\n            const string viewName = \"foo.html\";\r\n\r\n            var resolver = new DefaultViewResolver(\r\n                this.viewLocator,\r\n                new ViewLocationConventions(new Func<string, dynamic, ViewLocationContext, string>[] {\r\n                    (name, model, path) => \"bar.html\"\r\n                }));\r\n\r\n            var locatedView =\r\n                new ViewLocationResult(\"name\", \"location\", \"extension\", GetEmptyContentReader());\r\n\r\n            A.CallTo(() => this.viewLocator.LocateView(A<string>.Ignored, A<NancyContext>.Ignored)).Returns(locatedView);\r\n\r\n            // When\r\n            var result = resolver.GetViewLocation(viewName, null, this.viewLocationContext);\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(locatedView);\r\n        }\r\n\r\n        private static Func<TextReader> GetEmptyContentReader()\r\n        {\r\n            return () => new StreamReader(new MemoryStream());\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/ViewEngines/FileSystemViewLocationProviderFixture.cs",
    "content": "namespace Nancy.Tests.Unit.ViewEngines\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Nancy.ViewEngines;\r\n\r\n    using Xunit;\r\n\r\n    public class FileSystemViewLocationProviderFixture\r\n    {\r\n        private FileSystemViewLocationProvider provider;\r\n        private readonly IRootPathProvider rootPathProvider;\r\n        private readonly IFileSystemReader reader;\r\n        private readonly Tuple<string, Func<StreamReader>> locationResult;\r\n\r\n        public FileSystemViewLocationProviderFixture()\r\n        {\r\n            this.reader = A.Fake<IFileSystemReader>();\r\n            this.rootPathProvider = A.Fake<IRootPathProvider>();\r\n\r\n            A.CallTo(() => this.rootPathProvider.GetRootPath()).Returns(\"rootPath\");\r\n            \r\n            this.provider = new FileSystemViewLocationProvider(this.rootPathProvider, this.reader);\r\n\r\n            this.locationResult = new Tuple<string, Func<StreamReader>>(\r\n                Path.Combine(\"this\", \"is\", \"a\", \"fake\", \"view.html\"),\r\n                () => null);\r\n\r\n            A.CallTo(() => this.reader.GetViewsWithSupportedExtensions(A<string>._, A<IEnumerable<string>>._)).Returns(new[] { this.locationResult });\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_file_system_reader_with_supported_extension()\r\n        {\r\n            // Given\r\n            var extensions = new[] { \"html\", \"spark\", \"razor\" };\r\n\r\n            // When\r\n            this.provider.GetLocatedViews(extensions);\r\n\r\n            // Then\r\n            A.CallTo(() => this.reader.GetViewsWithSupportedExtensions(A<string>._, extensions)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_file_system_reader_with_root_path()\r\n        {\r\n            // Given\r\n            var extensions = new[] { \"html\" };\r\n            var rootPath = this.rootPathProvider.GetRootPath();\r\n\r\n            // When\r\n            this.provider.GetLocatedViews(extensions);\r\n\r\n            // Then\r\n            A.CallTo(() => this.reader.GetViewsWithSupportedExtensions(rootPath, A<IEnumerable<string>>._)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_result_when_root_path_is_null()\r\n        {\r\n            // Given\r\n            var extensions = new[] { \"html\" };\r\n            A.CallTo(() => this.rootPathProvider.GetRootPath()).Returns(null);\r\n            this.provider = new FileSystemViewLocationProvider(this.rootPathProvider, this.reader);\r\n\r\n            // When\r\n            var result = this.provider.GetLocatedViews(extensions);\r\n\r\n            // Then\r\n            result.ShouldHaveCount(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_result_when_root_path_is_empty()\r\n        {\r\n            // Given\r\n            var extensions = new[] { \"html\" };\r\n            A.CallTo(() => this.rootPathProvider.GetRootPath()).Returns(string.Empty);\r\n            this.provider = new FileSystemViewLocationProvider(this.rootPathProvider, this.reader);\r\n\r\n            // When\r\n            var result = this.provider.GetLocatedViews(extensions);\r\n\r\n            // Then\r\n            result.ShouldHaveCount(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_view_location_result_with_file_extension_set()\r\n        {\r\n            // Given\r\n            var extensions = new[] { \"html\" };\r\n\r\n            // When\r\n            var result = this.provider.GetLocatedViews(extensions).First();\r\n\r\n            // Then\r\n            result.Extension.ShouldEqual(\"html\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_view_location_result_with_file_name_set()\r\n        {\r\n            // Given\r\n            var extensions = new[] { \"html\" };\r\n\r\n            // When\r\n            var result = this.provider.GetLocatedViews(extensions).First();\r\n\r\n            // Then\r\n            result.Name.ShouldEqual(\"view\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_view_location_result_where_location_is_set_in_platform_neutral_format()\r\n        {\r\n            // Given\r\n            var extensions = new[] { \"html\" };\r\n\r\n            // When\r\n            var result = this.provider.GetLocatedViews(extensions).First();\r\n\r\n            // Then\r\n            result.Location.ShouldEqual(\"this/is/a/fake\");\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/ViewEngines/FileSystemViewLocationResultFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.ViewEngines\r\n{\r\n    using System;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Nancy.ViewEngines;\r\n\r\n    using Xunit;\r\n\r\n    public class FileSystemViewLocationResultFixture\r\n    {\r\n        private readonly IFileSystemReader reader;\r\n\r\n        public FileSystemViewLocationResultFixture()\r\n        {\r\n            this.reader = A.Fake<IFileSystemReader>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_stale_if_never_read_before()\r\n        {\r\n            A.CallTo(() => this.reader.GetLastModified(A<string>._)).Returns(DateTime.UtcNow);\r\n            var vlr = new FileSystemViewLocationResult(\"here\", \"there\", \"everywhere\", () => null, \"full\", this.reader);\r\n\r\n            var result = vlr.IsStale();\r\n\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_stale_if_last_modified_changed()\r\n        {\r\n            A.CallTo(() => this.reader.GetLastModified(A<string>._)).Returns(DateTime.UtcNow);\r\n            var vlr = new FileSystemViewLocationResult(\"here\", \"there\", \"everywhere\", () => null, \"full\", this.reader);\r\n            A.CallTo(() => this.reader.GetLastModified(A<string>._)).Returns(DateTime.UtcNow);\r\n\r\n            var result = vlr.IsStale();\r\n\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_not_stale_if_modified_changed_not_changed_since_last_read()\r\n        {\r\n            A.CallTo(() => this.reader.GetLastModified(A<string>._)).Returns(DateTime.UtcNow);\r\n            var vlr = new FileSystemViewLocationResult(\"here\", \"there\", \"everywhere\", () => null, \"full\", this.reader);\r\n            A.CallTo(() => this.reader.GetLastModified(A<string>._)).Returns(DateTime.UtcNow);\r\n\r\n            vlr.Contents();\r\n            var result = vlr.IsStale();\r\n\r\n            result.ShouldBeFalse();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_stale_if_modified_changed_since_last_read()\r\n        {\r\n            var vlr = new FileSystemViewLocationResult(\"here\", \"there\", \"everywhere\", () => null, \"full\", this.reader);\r\n            A.CallTo(() => this.reader.GetLastModified(A<string>._)).Returns(DateTime.UtcNow.AddMinutes(-1));\r\n            vlr.Contents();\r\n            A.CallTo(() => this.reader.GetLastModified(A<string>._)).Returns(DateTime.UtcNow);\r\n\r\n            var result = vlr.IsStale();\r\n\r\n            result.ShouldBeTrue();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/ViewEngines/ResourceViewLocationProviderFixture.cs",
    "content": "namespace Nancy.Tests.Unit.ViewEngines\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Reflection;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Extensions;\r\n    using Nancy.ViewEngines;\r\n\r\n    using Xunit;\r\n\r\n    public class ResourceViewLocationProviderFixture\r\n    {\r\n        private readonly IResourceReader reader;\r\n        private readonly IResourceAssemblyProvider resourceAssemblyProvider;\r\n        private readonly ResourceViewLocationProvider viewProvider;\r\n\r\n        public ResourceViewLocationProviderFixture()\r\n        {\r\n            ResourceViewLocationProvider.Ignore.Clear(); \r\n            this.reader = A.Fake<IResourceReader>();\r\n            this.resourceAssemblyProvider = A.Fake<IResourceAssemblyProvider>();\r\n            this.viewProvider = new ResourceViewLocationProvider(this.reader, this.resourceAssemblyProvider);\r\n\r\n            if (!ResourceViewLocationProvider.RootNamespaces.ContainsKey(this.GetType().GetAssembly()))\r\n            {\r\n                ResourceViewLocationProvider.RootNamespaces.Add(this.GetType().GetAssembly(), \"Some.Resource\");\r\n            }\r\n\r\n            A.CallTo(() => this.resourceAssemblyProvider.GetAssembliesToScan()).Returns(new[] { this.GetType().GetAssembly() });\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_result_when_supported_view_extensions_is_null()\r\n        {\r\n            // Given\r\n            IEnumerable<string> extensions = null;\r\n\r\n            // When\r\n            var result = this.viewProvider.GetLocatedViews(extensions);\r\n\r\n            // Then\r\n            result.ShouldHaveCount(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_result_when_supported_view_extensions_is_empty()\r\n        {\r\n            // Given\r\n            var extensions = Enumerable.Empty<string>();\r\n\r\n            // When\r\n            var result = this.viewProvider.GetLocatedViews(extensions);\r\n\r\n            // Then\r\n            result.ShouldHaveCount(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_empty_result_when_view_resources_could_be_found()\r\n        {\r\n            // Given\r\n            var extensions = new[] { \"html\" };\r\n            \r\n\r\n            // When\r\n            var result = this.viewProvider.GetLocatedViews(extensions);\r\n\r\n            // Then\r\n            result.ShouldHaveCount(0);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_view_location_result_with_file_name_set()\r\n        {\r\n            // Given\r\n            var extensions = new[] { \"html\" };\r\n\r\n            var match = new Tuple<string, Func<StreamReader>>(\r\n                \"Some.Resource.View.html\",\r\n                () => null);\r\n\r\n            A.CallTo(() => this.reader.GetResourceStreamMatches(A<Assembly>._, A<IEnumerable<string>>._)).Returns(new[] {match});\r\n\r\n            // When\r\n            var result = this.viewProvider.GetLocatedViews(extensions);\r\n\r\n            // Then\r\n            result.First().Name.ShouldEqual(\"View\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_view_location_result_with_content_set()\r\n        {\r\n            // Given\r\n            var extensions = new[] { \"html\" };\r\n\r\n            var match = new Tuple<string, Func<StreamReader>>(\r\n                \"Some.Resource.View.html\",\r\n                () => null);\r\n\r\n            A.CallTo(() => this.reader.GetResourceStreamMatches(A<Assembly>._, A<IEnumerable<string>>._)).Returns(new[] { match });\r\n\r\n            // When\r\n            var result = this.viewProvider.GetLocatedViews(extensions);\r\n\r\n            // Then\r\n            result.First().Contents.ShouldNotBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_invalid_operation_exception_if_only_one_view_was_found_and_no_root_namespace_has_been_defined()\r\n        {\r\n            // Given\r\n            var extensions = new[] { \"html\" };\r\n\r\n            ResourceViewLocationProvider.RootNamespaces.Remove(this.GetType().GetAssembly());\r\n\r\n            var match = new Tuple<string, Func<StreamReader>>(\r\n                \"Some.Resource.View.html\",\r\n                () => null);\r\n\r\n            A.CallTo(() => this.reader.GetResourceStreamMatches(A<Assembly>._, A<IEnumerable<string>>._)).Returns(new[] { match });\r\n\r\n            // When\r\n            var exception = Record.Exception(() => this.viewProvider.GetLocatedViews(extensions).ToList());\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<InvalidOperationException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_set_error_message_when_throwing_invalid_operation_exception_due_to_not_being_able_to_figure_out_common_namespace()\r\n        {\r\n            // Given\r\n            var extensions = new[] { \"html\" };\r\n\r\n            ResourceViewLocationProvider.RootNamespaces.Remove(this.GetType().GetAssembly());\r\n\r\n            var match = new Tuple<string, Func<StreamReader>>(\r\n                \"Some.Resource.View.html\",\r\n                () => null);\r\n\r\n            A.CallTo(() => this.reader.GetResourceStreamMatches(A<Assembly>._, A<IEnumerable<string>>._)).Returns(new[] { match });\r\n\r\n            var expectedErrorMessage =\r\n                string.Format(\"Only one view was found in assembly {0}, but no rootnamespace had been registered.\", this.GetType().GetAssembly().FullName);\r\n\r\n            // When\r\n            var exception = Record.Exception(() => this.viewProvider.GetLocatedViews(extensions).ToList());\r\n\r\n            // Then\r\n            exception.Message.ShouldEqual(expectedErrorMessage);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_view_location_result_where_location_is_set_in_platform_neutral_format()\r\n        {\r\n            // Given\r\n            var extensions = new[] { \"html\" };\r\n\r\n            var match = new Tuple<string, Func<StreamReader>>(\r\n                \"Some.Resource.Path.With.Sub.Folder.View.html\",\r\n                () => null);\r\n\r\n            A.CallTo(() => this.reader.GetResourceStreamMatches(A<Assembly>._, A<IEnumerable<string>>._)).Returns(new[] { match });\r\n\r\n            // When\r\n            var result = this.viewProvider.GetLocatedViews(extensions);\r\n\r\n            // Then\r\n            result.First().Location.ShouldEqual(\"Path/With/Sub/Folder\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_scan_assemblies_returned_by_assembly_provider()\r\n        {\r\n            // Given\r\n            A.CallTo(() => this.resourceAssemblyProvider.GetAssembliesToScan()).Returns(new[]\r\n            {\r\n                typeof(NancyEngine).GetAssembly(),\r\n                this.GetType().GetAssembly()\r\n            });\r\n\r\n            var extensions = new[] { \"html\" };\r\n\r\n            // When\r\n            this.viewProvider.GetLocatedViews(extensions).ToList();\r\n\r\n            // Then\r\n            A.CallTo(() => this.reader.GetResourceStreamMatches(this.GetType().GetAssembly(), A<IEnumerable<string>>._)).MustHaveHappened();\r\n            A.CallTo(() => this.reader.GetResourceStreamMatches(typeof(NancyEngine).GetAssembly(), A<IEnumerable<string>>._)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_scan_ignored_assemblies()\r\n        {\r\n            // Given\r\n            A.CallTo(() => this.resourceAssemblyProvider.GetAssembliesToScan()).Returns(new[]\r\n            {\r\n                typeof(NancyEngine).GetAssembly(),\r\n                this.GetType().GetAssembly()\r\n            });\r\n\r\n            ResourceViewLocationProvider.Ignore.Add(this.GetType().GetAssembly());\r\n\r\n            var extensions = new[] { \"html\" };\r\n\r\n            // When\r\n            this.viewProvider.GetLocatedViews(extensions).ToList();\r\n\r\n            // Then\r\n            A.CallTo(() => this.reader.GetResourceStreamMatches(this.GetType().GetAssembly(), A<IEnumerable<string>>._)).MustNotHaveHappened();\r\n            A.CallTo(() => this.reader.GetResourceStreamMatches(typeof(NancyEngine).GetAssembly(), A<IEnumerable<string>>._)).MustHaveHappened();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/ViewEngines/SuperSimpleViewEngineTests.cs",
    "content": "﻿namespace Nancy.Tests.Unit.ViewEngines\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Dynamic;\r\n    using System.Linq;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Tests.Fakes;\r\n    using Nancy.ViewEngines.SuperSimpleViewEngine;\r\n\r\n    using Xunit;\r\n\r\n    public class SuperSimpleViewEngineTests\r\n    {\r\n        private readonly SuperSimpleViewEngine viewEngine;\r\n\r\n        private readonly IViewEngineHost fakeHost;\r\n\r\n        public SuperSimpleViewEngineTests()\r\n        {\r\n            this.fakeHost = new FakeViewEngineHost();\r\n            this.viewEngine = new SuperSimpleViewEngine(Enumerable.Empty<ISuperSimpleViewEngineMatcher>());\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_expand_partial_inside_each_section()\r\n        {\r\n            const string input = @\"<html><head></head><body>@Each;@Partial['testing'];@EndEach</body></html>\";\r\n            var fakeViewEngineHost = new FakeViewEngineHost();\r\n            fakeViewEngineHost.GetTemplateCallback = (s, m) => \"Hi\";\r\n            var model = new List<string>() { \"foo\", \"bar\" };\r\n\r\n            var result = viewEngine.Render(input, model, fakeViewEngineHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>HiHi</body></html>\", result);\r\n        }\r\n        \r\n        [Fact]\r\n        public void Should_expand_dynamic_partial_inside_each_section()\r\n        {\r\n            const string input = @\"<html><head></head><body>@Each;@Partial['@Current'];@EndEach</body></html>\";\r\n            var fakeViewEngineHost = new FakeViewEngineHost();\r\n            fakeViewEngineHost.GetTemplateCallback = (s, m) =>\r\n            {\r\n                switch (s)\r\n                {\r\n                    case \"model1\":\r\n                        return \"FirstPartial\";\r\n                    case \"model2\":\r\n                        return \"SecondPartial\";\r\n                     default:\r\n                         return s;\r\n                }\r\n            };\r\n            var model = new List<string>() { \"model1\", \"model2\" };\r\n            var result = viewEngine.Render(input, model, fakeViewEngineHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>FirstPartialSecondPartial</body></html>\", result);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_expand_multiple_partials_inside_each_section()\r\n        {\r\n            const string input = @\"<html><head></head><body>@Each;@Partial['greeting'], @Partial['name'];@EndEach</body></html>\";\r\n            var fakeViewEngineHost = new FakeViewEngineHost();\r\n            fakeViewEngineHost.GetTemplateCallback = (s, m) =>\r\n            {\r\n                return (s.Equals(\"greeting\")) ? \"Hi\" : \"Nancy\";\r\n            };\r\n            var model = new List<string>() { \"foo\", \"bar\" };\r\n\r\n            var result = viewEngine.Render(input, model, fakeViewEngineHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Hi, NancyHi, Nancy</body></html>\", result);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_expand_partial_inside_each_section_with_current_as_model()\r\n        {\r\n            const string input = @\"<html><head></head><body>@Each;@Partial['testing', @Current];@EndEach</body></html>\";\r\n            var fakeViewEngineHost = new FakeViewEngineHost();\r\n            fakeViewEngineHost.GetTemplateCallback = (s, m) => \"Hi @Model \";\r\n            var model = new List<string>() { \"foo\", \"bar\" };\r\n\r\n            var result = viewEngine.Render(input, model, fakeViewEngineHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Hi foo Hi bar </body></html>\", result);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_expand_partial_inside_each_section_with_parameter_of_current_as_model()\r\n        {\r\n            const string input = @\"<html><head></head><body>@Each;@Partial['testing', @Current.Name];@EndEach</body></html>\";\r\n            var fakeViewEngineHost = new FakeViewEngineHost();\r\n            fakeViewEngineHost.GetTemplateCallback = (s, m) => \"Hi @Model \";\r\n\r\n            dynamic foo = new ExpandoObject();\r\n            foo.Name = \"foo\";\r\n\r\n            dynamic bar = new ExpandoObject();\r\n            bar.Name = \"bar\";\r\n\r\n            var model = new List<ExpandoObject>() { foo, bar };\r\n\r\n            var result = viewEngine.Render(input, model, fakeViewEngineHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Hi foo Hi bar </body></html>\", result);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_expand_partial_inside_each_section_with_property_parameter_of_current_as_model()\r\n        {\r\n            const string input = @\"<html><head></head><body>@Each;@Partial['testing', @Current.FirstName];@EndEach</body></html>\";\r\n            var fakeViewEngineHost = new FakeViewEngineHost();\r\n            fakeViewEngineHost.GetTemplateCallback = (s, m) => \"Hi @Model \";\r\n\r\n            var clark  = new PersonWithAgeField()\r\n            {\r\n                FirstName = \"Clark\",\r\n            };\r\n\r\n            var lois = new PersonWithAgeField()\r\n            {\r\n                FirstName = \"Lois\",\r\n            };\r\n\r\n            var model = new List<PersonWithAgeField>() { clark, lois };\r\n\r\n            var result = viewEngine.Render(input, model, fakeViewEngineHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Hi Clark Hi Lois </body></html>\", result);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_expand_partial_inside_each_section_with_field_parameter_of_current_as_model()\r\n        {\r\n            const string input = @\"<html><head></head><body>@Each;@Partial['testing', @Current.Age];@EndEach</body></html>\";\r\n            var fakeViewEngineHost = new FakeViewEngineHost();\r\n            fakeViewEngineHost.GetTemplateCallback = (s, m) => \"Hi @Model \";\r\n\r\n            var clark  = new PersonWithAgeField()\r\n            {\r\n                Age = 28,\r\n            };\r\n\r\n            var lois = new PersonWithAgeField()\r\n            {\r\n                Age = 37,\r\n            };\r\n\r\n            var model = new List<Person>() { clark, lois };\r\n\r\n            var result = viewEngine.Render(input, model, fakeViewEngineHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Hi 28 Hi 37 </body></html>\", result);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_expand_multiple_partial_inside_each_section_with_parameter_of_current_as_model()\r\n        {\r\n            const string input = @\"<html><head></head><body>@Each;@Partial['first', @Current.Name];-@Partial['second', @Current.Name];@EndEach</body></html>\";\r\n            \r\n            var fakeViewEngineHost = new FakeViewEngineHost\r\n            {\r\n                GetTemplateCallback = (s, m) =>\r\n                {\r\n                    return (s.Equals(\"first\")) ?\r\n                        \"Hi @Model\" :\r\n                        \"Hello @Model\";\r\n                }\r\n            };\r\n\r\n            dynamic foo = new ExpandoObject();\r\n            foo.Name = \"foo\";\r\n\r\n            dynamic bar = new ExpandoObject();\r\n            bar.Name = \"bar\";\r\n\r\n            var model = new List<ExpandoObject>() { foo, bar };\r\n\r\n            var result = viewEngine.Render(input, model, fakeViewEngineHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Hi foo-Hello fooHi bar-Hello bar</body></html>\", result);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_expand_multiple_partial_inside_each_section_with_different_parameter_of_current_as_model()\r\n        {\r\n            const string input = @\"<html><head></head><body>@Each;@Partial['first', @Current.First];-@Partial['second', @Current.Last];@EndEach</body></html>\";\r\n\r\n            var fakeViewEngineHost = new FakeViewEngineHost\r\n            {\r\n                GetTemplateCallback = (s, m) =>\r\n                {\r\n                    return (s.Equals(\"first\")) ?\r\n                        \"Hi @Model\" :\r\n                        \"Hello @Model\";\r\n                }\r\n            };\r\n\r\n            dynamic foo = new ExpandoObject();\r\n            foo.First = \"foo\";\r\n            foo.Last = \"bar\";\r\n\r\n            dynamic bar = new ExpandoObject();\r\n            bar.First = \"baz\";\r\n            bar.Last = \"bin\";\r\n\r\n            var model = new List<ExpandoObject>() { foo, bar };\r\n\r\n            var result = viewEngine.Render(input, model, fakeViewEngineHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Hi foo-Hello barHi baz-Hello bin</body></html>\", result);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_evaluate_nested_conditionals()\r\n        {\r\n            // Given\r\n            const string input =\r\n                @\"<html><head></head><body>@If.SayHello;Hey @If.ShowName;@Model.Name@If.Zalgo;HE COMES@EndIf;!@EndIf; Bye!@EndIf</body></html>\";\r\n            var model = new\r\n            {\r\n                Name = \"Bob\",\r\n                SayHello = true,\r\n                ShowName = true,\r\n                Zalgo = false\r\n            };\r\n\r\n            // When\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            // Then\r\n            Assert.Equal(@\"<html><head></head><body>Hey Bob! Bye!</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_evaluate_multiple_nested_conditionals()\r\n        {\r\n            // Given\r\n            const string input =\r\n                @\"<html><head></head><body>@If.SayHello;Hey @If.ShowName;@Model.Name@If.Zalgo; HE COMES@EndIf;!@EndIf; Bye!@EndIf</body></html>\";\r\n            var model = new\r\n            {\r\n                Name = \"Bob\",\r\n                SayHello = true,\r\n                ShowName = true,\r\n                Zalgo = true\r\n            };\r\n\r\n            // When\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            // Then\r\n            Assert.Equal(@\"<html><head></head><body>Hey Bob HE COMES! Bye!</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_evaluate_current_conditional_inside_each()\r\n        {\r\n            // Given\r\n            const string input = @\"<html><head></head><body><ul>@Each.Users;<li>@Current.Name says:@If.IsGreekCitizen;<b>Yay Greece!</b>@EndIf;@IfNot.IsGreekCitizen;<b>Boo Greece!</b>@EndIf;</li>@EndEach;</ul></body></html>\";\r\n            dynamic model = new ExpandoObject();\r\n            model.Users = new List<object>() { new { Name = \"Bob\", IsGreekCitizen = true }, new { Name = \"Malin\", IsGreekCitizen = false } };\r\n\r\n            // When\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            // Then\r\n            Assert.Equal(@\"<html><head></head><body><ul><li>Bob says:<b>Yay Greece!</b></li><li>Malin says:<b>Boo Greece!</b></li></ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_evaluate_current_conditional_from_outside_each()\r\n        {\r\n            // Given\r\n            const string input = @\"<html><head></head><body>@If.HasUsers;Yay Users!@EndIf<ul>@Each.Users;<li>@Current.Name:@If.IsGreekCitizen;<b>Yay Greece!</b>@EndIf;</li>@EndEach;</ul>@IfNot.HasUsers;Yay Users!@EndIf</body></html>\";\r\n            dynamic model = new ExpandoObject();\r\n            model.Users = new List<object>() { new { Name = \"Bob\", IsGreekCitizen = true }, new { Name = \"Malin\", IsGreekCitizen = false } };\r\n\r\n            // When\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            // Then\r\n            Assert.Equal(@\"<html><head></head><body>Yay Users!<ul><li>Bob:<b>Yay Greece!</b></li><li>Malin:</li></ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_evaluate_viewbag_as_dynamic_dictionary_conditional()\r\n        {\r\n            const string input = @\"@Context.ViewBag.HaveMessage;! @If.Context.ViewBag.HaveMessage;Yay message!@EndIf;\";\r\n            var context = new { ViewBag = (dynamic)new DynamicDictionary() };\r\n            context.ViewBag.HaveMessage = true;\r\n\r\n            ((FakeViewEngineHost)this.fakeHost).Context = context;\r\n\r\n            var output = viewEngine.Render(input, null, this.fakeHost);\r\n\r\n            Assert.Equal(@\"True! Yay message!\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_throw_when_viewbag_property_is_null()\r\n        {\r\n            const string input = @\"<html><head></head><body>Hey@If.Context.ViewBag.HaveMessage;Yay message!@EndIf;</body></html>\";\r\n            var context = new { ViewBag = (dynamic)new DynamicDictionary() };\r\n\r\n            ((FakeViewEngineHost)this.fakeHost).Context = context;\r\n\r\n            var output = viewEngine.Render(input, null, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Hey</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_replace_primitive_model_with_value()\r\n        {\r\n            // Given\r\n            const string input = @\"<html><head></head><body>Hello there @Model</body></html>\";\r\n            const string model = \"Bob\";\r\n\r\n            // When\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            // Then\r\n            Assert.Equal(@\"<html><head></head><body>Hello there Bob</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_replace_primitive_model_with_value_when_followed_by_closing_tag()\r\n        {\r\n            // Given\r\n            const string input = @\"<html><head></head><body>Hello there @Model;</body></html>\";\r\n            const string model = \"Bob\";\r\n\r\n            // When\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            // Then\r\n            Assert.Equal(@\"<html><head></head><body>Hello there Bob</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_replaces_valid_property_when_followed_by_closing_tag()\r\n        {\r\n            const string input = @\"<html><head></head><body>Hello there @Model.Name;</body></html>\";\r\n            dynamic model = new ExpandoObject();\r\n            model.Name = \"Bob\";\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Hello there Bob</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_replace_multiple_properties_with_the_same_name()\r\n        {\r\n            const string input = @\"<html><head></head><body>Hello there @Model.Name;, nice to see you @Model.Name;</body></html>\";\r\n            dynamic model = new ExpandoObject();\r\n            model.Name = \"Bob\";\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Hello there Bob, nice to see you Bob</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_replace_invalid_properties_with_error_string()\r\n        {\r\n            const string input = @\"<html><head></head><body>Hello there @Model.Wrong;</body></html>\";\r\n            dynamic model = new ExpandoObject();\r\n            model.Name = \"Bob\";\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Hello there [ERR!]</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_replace_properties_if_case_is_incorrect()\r\n        {\r\n            const string input = @\"<html><head></head><body>Hello there @Model.name;</body></html>\";\r\n            dynamic model = new ExpandoObject();\r\n            model.Name = \"Bob\";\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Hello there [ERR!]</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_replace_multiple_properties_from_dictionary()\r\n        {\r\n            const string input = @\"<html><head></head><body>Hello there @Model.Name; - welcome to @Model.SiteName;</body></html>\";\r\n            dynamic model = new ExpandoObject();\r\n            model.Name = \"Bob\";\r\n            model.SiteName = \"Cool Site!\";\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Hello there Bob - welcome to Cool Site!</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_create_multiple_entries_for_each_statements()\r\n        {\r\n            const string input = @\"<html><head></head><body><ul>@Each.Users;<li>@Current;</li>@EndEach;</ul></body></html>\";\r\n            dynamic model = new ExpandoObject();\r\n            model.Users = new List<string>() { \"Bob\", \"Jim\", \"Bill\" };\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><ul><li>Bob</li><li>Jim</li><li>Bill</li></ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_multiple_current_statements_inside_each()\r\n        {\r\n            const string input = @\"<html><head></head><body><ul>@Each.Users;<li id=\"\"@Current;\"\">@Current;</li>@EndEach;</ul></body></html>\";\r\n            dynamic model = new ExpandoObject();\r\n            model.Users = new List<string>() { \"Bob\", \"Jim\", \"Bill\" };\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><ul><li id=\"\"Bob\"\">Bob</li><li id=\"\"Jim\"\">Jim</li><li id=\"\"Bill\"\">Bill</li></ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_try_to_use_non_enumerable_in_each_shows_error()\r\n        {\r\n            const string input = @\"<html><head></head><body><ul>@Each.Users;<li id=\"\"@Current;\"\">@Current;</li>@EndEach;</ul></body></html>\";\r\n            dynamic model = new ExpandoObject();\r\n            model.Users = new object();\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><ul>[ERR!]</ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_combine_single_substitutions_and_each_substitutions()\r\n        {\r\n            const string input = @\"<html><head></head><body><ul>@Each.Users;<li>Hello @Current;, @Model.Name; says hello!</li>@EndEach;</ul></body></html>\";\r\n            dynamic model = new ExpandoObject();\r\n            model.Name = \"Nancy\";\r\n            model.Users = new List<string>() { \"Bob\", \"Jim\", \"Bill\" };\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><ul><li>Hello Bob, Nancy says hello!</li><li>Hello Jim, Nancy says hello!</li><li>Hello Bill, Nancy says hello!</li></ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_model_statement_to_be_followed_by_a_newline()\r\n        {\r\n            const string input = \"<html><head></head><body>Hello there @Model.Name;\\n</body></html>\";\r\n            dynamic model = new ExpandoObject();\r\n            model.Name = \"Bob\";\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(\"<html><head></head><body>Hello there Bob\\n</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_each_statements_to_work_over_multiple_lines()\r\n        {\r\n            const string input = \"<html>\\n\\t<head>\\n\\t</head>\\n\\t<body>\\n\\t\\t<ul>@Each.Users;\\n\\t\\t\\t<li>@Current;</li>@EndEach;\\n\\t\\t</ul>\\n\\t</body>\\n</html>\";\r\n            dynamic model = new ExpandoObject();\r\n            model.Users = new List<string>() { \"Bob\", \"Jim\", \"Bill\" };\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(\"<html>\\n\\t<head>\\n\\t</head>\\n\\t<body>\\n\\t\\t<ul>\\n\\t\\t\\t<li>Bob</li>\\n\\t\\t\\t<li>Jim</li>\\n\\t\\t\\t<li>Bill</li>\\n\\t\\t</ul>\\n\\t</body>\\n</html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Single_substitutions_work_with_standard_anonymous_type_objects()\r\n        {\r\n            const string input = @\"<html><head></head><body>Hello there @Model.Name; - welcome to @Model.SiteName;</body></html>\";\r\n            var model = new { Name = \"Bob\", SiteName = \"Cool Site!\" };\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Hello there Bob - welcome to Cool Site!</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_each_substitutions_to_work_with_standard_anonymous_type_objects()\r\n        {\r\n            const string input = @\"<html><head></head><body><ul>@Each.Users;<li id=\"\"@Current;\"\">@Current;</li>@EndEach;</ul></body></html>\";\r\n            var model = new { Users = new List<string>() { \"Bob\", \"Jim\", \"Bill\" } };\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><ul><li id=\"\"Bob\"\">Bob</li><li id=\"\"Jim\"\">Jim</li><li id=\"\"Bill\"\">Bill</li></ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_substitutions_to_work_with_standard_objects()\r\n        {\r\n            const string input = @\"<html><head></head><body><ul>@Each.Users;<li>Hello @Current;, @Model.Name; says hello!</li>@EndEach;</ul></body></html>\";\r\n            var model = new FakeModel(\"Nancy\", new List<string>() { \"Bob\", \"Jim\", \"Bill\" });\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><ul><li>Hello Bob, Nancy says hello!</li><li>Hello Jim, Nancy says hello!</li><li>Hello Bill, Nancy says hello!</li></ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_render_block_when_if_statement_returns_true()\r\n        {\r\n            const string input = @\"<html><head></head><body>@If.HasUsers;<ul>@Each.Users;<li>Hello @Current;, @Model.Name; says hello!</li>@EndEach;</ul>@EndIf;</body></html>\";\r\n            var model = new FakeModel(\"Nancy\", new List<string>() { \"Bob\", \"Jim\", \"Bill\" });\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><ul><li>Hello Bob, Nancy says hello!</li><li>Hello Jim, Nancy says hello!</li><li>Hello Bill, Nancy says hello!</li></ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_render_block_when_if_statement_returns_false()\r\n        {\r\n            const string input = @\"<html><head></head><body>@If.HasUsers;<ul>@Each.Users;<li>Hello @Current;, @Model.Name; says hello!</li>@EndEach;</ul>@EndIf;</body></html>\";\r\n            var model = new FakeModel(\"Nancy\", new List<string>());\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_render_block_when_ifnot_statements_returns_true()\r\n        {\r\n            const string input = @\"<html><head></head><body>@IfNot.HasUsers;<p>No users found!</p>@EndIf;<ul>@Each.Users;<li>Hello @Current;, @Model.Name; says hello!</li>@EndEach;</ul></body></html>\";\r\n            var model = new FakeModel(\"Nancy\", new List<string>() { \"Bob\", \"Jim\", \"Bill\" });\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><ul><li>Hello Bob, Nancy says hello!</li><li>Hello Jim, Nancy says hello!</li><li>Hello Bill, Nancy says hello!</li></ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_render_block_when_ifnot_statement_returns_false()\r\n        {\r\n            const string input = @\"<html><head></head><body>@IfNot.HasUsers;<p>No users found!</p>@EndIf;<ul>@Each.Users;<li>Hello @Current;, @Model.Name; says hello!</li>@EndEach;</ul></body></html>\";\r\n            var model = new FakeModel(\"Nancy\", new List<string>());\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><p>No users found!</p><ul></ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_conflict_when_if_and_ifNot_statements_combined_but_not_nested()\r\n        {\r\n            const string input = @\"<html><head></head><body>@IfNot.HasUsers;<p>No users found!</p>@EndIf;@If.HasUsers;<ul>@Each.Users;<li>Hello @Current;, @Model.Name; says hello!</li>@EndEach;</ul>@EndIf;</body></html>\";\r\n            var model = new FakeModel(\"Nancy\", new List<string>());\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><p>No users found!</p></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_match_multiple_if_statements_correctly()\r\n        {\r\n            const string input = \"@If.One;<p>One</p>@EndIf; @If.Two;<p>Two</p>@EndIf;\";\r\n            var model = new { One = true, Two = true };\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<p>One</p> <p>Two</p>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_match_correctly_when_multiple_each_statements()\r\n        {\r\n            const string input = \"@Each.Users;<li>@Current;</li>@EndEach; @Each.Admins;<li>@Current;</li>@EndEach;\";\r\n            var model = new { Users = new List<string> { \"1\", \"2\" }, Admins = new List<string> { \"3\", \"4\" } };\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<li>1</li><li>2</li> <li>3</li><li>4</li>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_for_ifhascollection_when_if_model_has_a_collection_with_items_but_no_bool()\r\n        {\r\n            const string input = @\"<html><head></head><body>@If.HasUsers;<ul>@Each.Users;<li>Hello @Current;, @Model.Name; says hello!</li>@EndEach;</ul>@EndIf;</body></html>\";\r\n            var model = new { Users = new List<string>() { \"Bob\", \"Jim\", \"Bill\" }, Name = \"Nancy\" };\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><ul><li>Hello Bob, Nancy says hello!</li><li>Hello Jim, Nancy says hello!</li><li>Hello Bill, Nancy says hello!</li></ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_false_for_ifnot_hascollection_when_model_has_a_collection_with_items_but_no_bool()\r\n        {\r\n            const string input = @\"<html><head></head><body>@IfNot.HasUsers;<p>No Users!</p>@EndIf;</body></html>\";\r\n            var model = new { Users = new List<string>() { \"Bob\", \"Jim\", \"Bill\" } };\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_ignore_item_for_implicit_has_support_when_item_isnt_a_collection()\r\n        {\r\n            const string input = @\"<html><head></head><body>@If.HasUsers;<p>Users!</p>@EndIf;</body></html>\";\r\n            var model = new { Users = new object() };\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_give_precedence_to_hasitem_bool_when_model_has_bool_and_collection()\r\n        {\r\n            const string input = @\"<html><head></head><body>@If.HasUsers;<ul>@Each.Users;<li>Hello @Current;, @Model.Name; says hello!</li>@EndEach;</ul>@EndIf;</body></html>\";\r\n            var model = new { HasUsers = false, Users = new List<string>() { \"Bob\", \"Jim\", \"Bill\" }, Name = \"Nancy\" };\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_property_name_in_current_inside_each_loop_for_dynamic_model_and_dynamic_collection()\r\n        {\r\n            const string input = @\"<html><head></head><body><ul>@Each.Users;<li>@Current.Name;</li>@EndEach;</ul></body></html>\";\r\n            dynamic model = new ExpandoObject();\r\n            dynamic user1 = new ExpandoObject();\r\n            user1.Name = \"Bob\";\r\n            dynamic user2 = new ExpandoObject();\r\n            user2.Name = \"Jim\";\r\n            dynamic user3 = new ExpandoObject();\r\n            user3.Name = \"Bill\";\r\n            model.Users = new List<object>() { user1, user2, user3 };\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><ul><li>Bob</li><li>Jim</li><li>Bill</li></ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_property_name_in_current_inside_each_loop_for_dynamic_model_and_normal_collection()\r\n        {\r\n            const string input = @\"<html><head></head><body><ul>@Each.Users;<li>@Current.Name;</li>@EndEach;</ul></body></html>\";\r\n            dynamic model = new ExpandoObject();\r\n            model.Users = new List<User>() { new User(\"Bob\"), new User(\"Jim\"), new User(\"Bill\") };\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><ul><li>Bob</li><li>Jim</li><li>Bill</li></ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_property_name_in_current_inside_each_loop_for_normal_model_and_dynamic_collection()\r\n        {\r\n            const string input = @\"<html><head></head><body><ul>@Each.Users;<li>@Current.Name;</li>@EndEach;</ul></body></html>\";\r\n            dynamic user1 = new ExpandoObject();\r\n            user1.Name = \"Bob\";\r\n            dynamic user2 = new ExpandoObject();\r\n            user2.Name = \"Jim\";\r\n            dynamic user3 = new ExpandoObject();\r\n            user3.Name = \"Bill\";\r\n            var model = new { Users = new List<object> { user1, user2, user3 } };\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><ul><li>Bob</li><li>Jim</li><li>Bill</li></ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_sub_properties_using_model_statement()\r\n        {\r\n            const string input = @\"<h1>Hello @Model.User.Name;</h1>\";\r\n            var model = new { User = new User(\"Bob\") };\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<h1>Hello Bob</h1>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_sub_properties_using_if_statement()\r\n        {\r\n            const string input = @\"<h1>Hello @If.User.IsFriend;Friend!@EndIf;</h1>\";\r\n            var model = new { User = new User(\"Bob\", true) };\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<h1>Hello Friend!</h1>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_sub_properties_using_ifnot_statement()\r\n        {\r\n            const string input = @\"<h1>Hello @IfNot.User.IsFriend;Friend!@EndIf;</h1>\";\r\n            var model = new { User = new User(\"Bob\", true) };\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<h1>Hello </h1>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_sub_properties_for_each_statement()\r\n        {\r\n            const string input = @\"<html><head></head><body><ul>@Each.Sub.Users;<li>@Current;</li>@EndEach;</ul></body></html>\";\r\n            var model = new { Sub = new { Users = new List<string>() { \"Bob\", \"Jim\", \"Bill\" } } };\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><ul><li>Bob</li><li>Jim</li><li>Bill</li></ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_sub_properties_for_current_statement_inside_each()\r\n        {\r\n            const string input = @\"<html><head></head><body><ul>@Each.Users;<li>@Current.Item2.Name;</li>@EndEach;</ul></body></html>\";\r\n            var model = new { Users = new List<Tuple<int, User>>() { new Tuple<int, User>(1, new User(\"Bob\")), new Tuple<int, User>(1, new User(\"Jim\")), new Tuple<int, User>(1, new User(\"Bill\")) } };\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><ul><li>Bob</li><li>Jim</li><li>Bill</li></ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_Model_substitutions_wihout_semi_colon()\r\n        {\r\n            const string input = @\"<html><head></head><body>Hello there @Model.Name</body></html>\";\r\n            dynamic model = new ExpandoObject();\r\n            model.Name = \"Bob\";\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Hello there Bob</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_each_without_semi_colon()\r\n        {\r\n            const string input = @\"<html><head></head><body><ul>@Each.Users<li>@Current;</li>@EndEach;</ul></body></html>\";\r\n            dynamic model = new ExpandoObject();\r\n            model.Users = new List<string>() { \"Bob\", \"Jim\", \"Bill\" };\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><ul><li>Bob</li><li>Jim</li><li>Bill</li></ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_each_and_end_each_without_semi_colon()\r\n        {\r\n            const string input = @\"<html><head></head><body><ul>@Each.Users<li>@Current;</li>@EndEach</ul></body></html>\";\r\n            dynamic model = new ExpandoObject();\r\n            model.Users = new List<string>() { \"Bob\", \"Jim\", \"Bill\" };\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><ul><li>Bob</li><li>Jim</li><li>Bill</li></ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_current_within_each_without_semi_colon()\r\n        {\r\n            const string input = @\"<html><head></head><body><ul>@Each.Users;<li>@Current</li>@EndEach;</ul></body></html>\";\r\n            dynamic model = new ExpandoObject();\r\n            model.Users = new List<string>() { \"Bob\", \"Jim\", \"Bill\" };\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><ul><li>Bob</li><li>Jim</li><li>Bill</li></ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_if_and_endif_without_semi_colon()\r\n        {\r\n            const string input = @\"<html><head></head><body>@If.HasUsers<ul>@Each.Users;<li>Hello @Current;, @Model.Name; says hello!</li>@EndEach;</ul>@EndIf</body></html>\";\r\n            var model = new FakeModel(\"Nancy\", new List<string>() { \"Bob\", \"Jim\", \"Bill\" });\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><ul><li>Hello Bob, Nancy says hello!</li><li>Hello Jim, Nancy says hello!</li><li>Hello Bill, Nancy says hello!</li></ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_ifnot_and_endif_without_semi_colon()\r\n        {\r\n            const string input = @\"<html><head></head><body>@IfNot.HasUsers<p>No users found!</p>@EndIf<ul>@Each.Users;<li>Hello @Current;, @Model.Name; says hello!</li>@EndEach;</ul></body></html>\";\r\n            var model = new FakeModel(\"Nancy\", new List<string>() { \"Bob\", \"Jim\", \"Bill\" });\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><ul><li>Hello Bob, Nancy says hello!</li><li>Hello Jim, Nancy says hello!</li><li>Hello Bill, Nancy says hello!</li></ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_each_without_a_variable_and_iterate_over_the_model_if_it_is_enumerable()\r\n        {\r\n            const string input = @\"<html><head></head><body><ul>@Each<li>Hello @Current</li>@EndEach</ul></body></html>\";\r\n            var model = new List<string>() { \"Bob\", \"Jim\", \"Bill\" };\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><ul><li>Hello Bob</li><li>Hello Jim</li><li>Hello Bill</li></ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_variableless_each_with_semicolon()\r\n        {\r\n            const string input = @\"<html><head></head><body><ul>@Each;<li>Hello @Current</li>@EndEach</ul></body></html>\";\r\n            var model = new List<string>() { \"Bob\", \"Jim\", \"Bill\" };\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><ul><li>Hello Bob</li><li>Hello Jim</li><li>Hello Bill</li></ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Model_with_exclaimation_should_html_encode()\r\n        {\r\n            const string input = @\"<html><head></head><body>Hello there @!Model.Name;</body></html>\";\r\n            dynamic model = new ExpandoObject();\r\n            model.Name = \"<b>Bob</b>\";\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Hello there &lt;b&gt;Bob&lt;/b&gt;</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Current_with_exclaimation_and_no_parameters_should_html_encode()\r\n        {\r\n            const string input = @\"<html><head></head><body><ul>@Each;<li>Hello @!Current</li>@EndEach</ul></body></html>\";\r\n            var model = new List<string>() { \"Bob<br/>\", \"Jim<br/>\", \"Bill<br/>\" };\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><ul><li>Hello Bob&lt;br/&gt;</li><li>Hello Jim&lt;br/&gt;</li><li>Hello Bill&lt;br/&gt;</li></ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Current_with_explaimation_and_parameters_should_html_encode()\r\n        {\r\n            const string input = @\"<html><head></head><body><ul>@Each.Users;<li>@!Current.Name;</li>@EndEach;</ul></body></html>\";\r\n            dynamic model = new ExpandoObject();\r\n            dynamic user1 = new ExpandoObject();\r\n            user1.Name = \"Bob<br/>\";\r\n            dynamic user2 = new ExpandoObject();\r\n            user2.Name = \"Jim<br/>\";\r\n            dynamic user3 = new ExpandoObject();\r\n            user3.Name = \"Bill<br/>\";\r\n            model.Users = new List<object>() { user1, user2, user3 };\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><ul><li>Bob&lt;br/&gt;</li><li>Jim&lt;br/&gt;</li><li>Bill&lt;br/&gt;</li></ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_expand_basic_partials()\r\n        {\r\n            const string input = @\"<html><head></head><body>@Partial['testing'];</body></html>\";\r\n            var fakeViewEngineHost = new FakeViewEngineHost();\r\n            fakeViewEngineHost.GetTemplateCallback = (s, m) => \"Test partial content\";\r\n\r\n            var result = viewEngine.Render(input, new object(), fakeViewEngineHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Test partial content</body></html>\", result);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_expand_partial_content_with_model_if_no_model_specified()\r\n        {\r\n            const string input = @\"<html><head></head><body>@Partial['testing'];</body></html>\";\r\n            var fakeViewEngineHost = new FakeViewEngineHost();\r\n            fakeViewEngineHost.GetTemplateCallback = (s, m) => \"Hello @Model.Name\";\r\n            dynamic model = new ExpandoObject();\r\n            model.Name = \"Bob\";\r\n\r\n            var result = viewEngine.Render(input, model, fakeViewEngineHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Hello Bob</body></html>\", result);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_expand_partial_content_with_specified_model_property_if_specified()\r\n        {\r\n            const string input = @\"<html><head></head><body>@Partial['testing', Model.User];</body></html>\";\r\n            var fakeViewEngineHost = new FakeViewEngineHost();\r\n            fakeViewEngineHost.GetTemplateCallback = (s, m) => \"Hello @Model.Name\";\r\n            dynamic model = new ExpandoObject();\r\n            dynamic subModel = new ExpandoObject();\r\n            model.Name = \"Jim\";\r\n            subModel.Name = \"Bob\";\r\n            model.User = subModel;\r\n\r\n            var result = viewEngine.Render(input, model, fakeViewEngineHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Hello Bob</body></html>\", result);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_expand_partial_content_even_with_no_model()\r\n        {\r\n            const string input = @\"<html><head></head><body>@Partial['testing'];</body></html>\";\r\n            var fakeViewEngineHost = new FakeViewEngineHost();\r\n            fakeViewEngineHost.GetTemplateCallback = (s, m) => \"Test partial content\";\r\n\r\n            var result = this.viewEngine.Render(input, null, fakeViewEngineHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Test partial content</body></html>\", result);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_try_to_locate_master_page_if_one_specified()\r\n        {\r\n            const string input = \"@Master['myMaster']\\r\\n@Section['Header'];\\r\\nHeader\\r\\n@EndSection\\r\\n@Section['Footer']\\r\\nFooter\\r\\n@EndSection\";\r\n            var called = false;\r\n            var fakeViewEngineHost = new FakeViewEngineHost();\r\n            fakeViewEngineHost.GetTemplateCallback = (s, m) =>\r\n            {\r\n                called = (s == \"myMaster\");\r\n                return \"\";\r\n            };\r\n\r\n            this.viewEngine.Render(input, null, fakeViewEngineHost);\r\n\r\n            Assert.True(called);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_replace_sections_in_master_page()\r\n        {\r\n            const string input = \"@Master['myMaster']\\r\\n@Section['Header'];\\r\\nHeader\\r\\n@EndSection\\r\\n@Section['Footer']\\r\\nFooter\\r\\n@EndSection\";\r\n            const string master = @\"<div id='header'>@Section['Header'];</div><div id='footer'>@Section['Footer'];</div>\";\r\n            var fakeViewEngineHost = new FakeViewEngineHost();\r\n            fakeViewEngineHost.GetTemplateCallback = (s, m) => master;\r\n\r\n            var result = this.viewEngine.Render(input, null, fakeViewEngineHost);\r\n\r\n            Assert.Equal(\"<div id='header'>\\r\\nHeader\\r\\n</div><div id='footer'>\\r\\nFooter\\r\\n</div>\", result);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_also_expand_master_page_with_same_model()\r\n        {\r\n            const string input = \"@Master['myMaster']\\r\\n@Section['Header'];\\r\\nHeader\\r\\n@EndSection\\r\\n@Section['Footer']\\r\\nFooter\\r\\n@EndSection\";\r\n            const string master = @\"Hello @Model.Name!<div id='header'>@Section['Header'];</div><div id='footer'>@Section['Footer'];</div>\";\r\n            var fakeViewEngineHost = new FakeViewEngineHost();\r\n            fakeViewEngineHost.GetTemplateCallback = (s, m) => master;\r\n\r\n            var result = viewEngine.Render(input, new { Name = \"Bob\" }, fakeViewEngineHost);\r\n\r\n            Assert.Equal(\"Hello Bob!<div id='header'>\\r\\nHeader\\r\\n</div><div id='footer'>\\r\\nFooter\\r\\n</div>\", result);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_handle_master_page_hierarchies()\r\n        {\r\n            const string input = \"@Master['middle']\\r\\n@Section['MiddleContent']Middle@EndSection\";\r\n            const string middle = \"@Master['top']\\r\\n@Section['TopContent']Top\\r\\n@Section['MiddleContent']@EndSection\";\r\n            const string top = \"Top! @Section['TopContent']\";\r\n\r\n            var fakeViewEngineHost = new FakeViewEngineHost();\r\n            fakeViewEngineHost.GetTemplateCallback = (s, m) => s == \"middle\" ? middle : top;\r\n\r\n            var result = viewEngine.Render(input, null, fakeViewEngineHost);\r\n\r\n            Assert.Equal(\"Top! Top\\r\\nMiddle\", result);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_call_to_expand_paths()\r\n        {\r\n            const string input = @\"<script src='@Path['~/scripts/test.js']'></script>\";\r\n            var fakeViewEngineHost = new FakeViewEngineHost();\r\n            fakeViewEngineHost.ExpandPathCallBack = s => s.Replace(\"~/\", \"/BasePath/\");\r\n\r\n            var result = viewEngine.Render(input, null, fakeViewEngineHost);\r\n\r\n            Assert.Equal(\"<script src='/BasePath/scripts/test.js'></script>\", result);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_expand_paths_in_attribute_values()\r\n        {\r\n            const string input = @\"<script src='~/scripts/test.js'></script> <link href=\"\"~/stylesheets/style.css\"\" />\";\r\n            var fakeViewEngineHost = new FakeViewEngineHost();\r\n            fakeViewEngineHost.ExpandPathCallBack = s => s.Replace(\"~/\", \"/BasePath/\");\r\n\r\n            var result = viewEngine.Render(input, null, fakeViewEngineHost);\r\n\r\n            Assert.Equal(@\"<script src='/BasePath/scripts/test.js'></script> <link href=\"\"/BasePath/stylesheets/style.css\"\" />\", result);\r\n        }\r\n\r\n\r\n        [Fact]\r\n        public void Should_expand_anti_forgery_tokens()\r\n        {\r\n            const string input = \"<html><body><form>@AntiForgeryToken</form><body></html>\";\r\n            var fakeViewEngineHost = new FakeViewEngineHost();\r\n\r\n            var result = viewEngine.Render(input, null, fakeViewEngineHost);\r\n\r\n            Assert.Equal(\"<html><body><form>CSRF</form><body></html>\", result);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_replace_primitive_context_with_value()\r\n        {\r\n            // Given\r\n            const string input = @\"<html><head></head><body>Hello there @Context</body></html>\";\r\n\r\n            ((FakeViewEngineHost)this.fakeHost).Context = \"Frank\";\r\n\r\n            // When\r\n            var output = viewEngine.Render(input, null, this.fakeHost);\r\n\r\n            // Then\r\n            Assert.Equal(@\"<html><head></head><body>Hello there Frank</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_replace_primitive_context_with_value_when_followed_by_closing_tag()\r\n        {\r\n            // Given\r\n            const string input = @\"<html><head></head><body>Hello there @Context;</body></html>\";\r\n            ((FakeViewEngineHost)this.fakeHost).Context = \"Frank\";\r\n\r\n            // When\r\n            var output = viewEngine.Render(input, null, this.fakeHost);\r\n\r\n            // Then\r\n            Assert.Equal(@\"<html><head></head><body>Hello there Frank</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_replaces_valid_context_property_when_followed_by_closing_tag()\r\n        {\r\n            const string input = @\"<html><head></head><body>Hello there @Context.Name;</body></html>\";\r\n            dynamic context = new ExpandoObject();\r\n            context.Name = \"Frank\";\r\n\r\n            ((FakeViewEngineHost)this.fakeHost).Context = context;\r\n\r\n            var output = viewEngine.Render(input, null, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Hello there Frank</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_replace_multiple_context_properties_with_the_same_name()\r\n        {\r\n            const string input = @\"<html><head></head><body>Hello there @Context.Name;, nice to see you @Context.Name;</body></html>\";\r\n            dynamic context = new ExpandoObject();\r\n            context.Name = \"Frank\";\r\n\r\n            ((FakeViewEngineHost)this.fakeHost).Context = context;\r\n\r\n            var output = viewEngine.Render(input, null, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Hello there Frank, nice to see you Frank</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_replace_invalid_context_properties_with_error_string()\r\n        {\r\n            const string input = @\"<html><head></head><body>Hello there @Context.Wrong;</body></html>\";\r\n            dynamic context = new ExpandoObject();\r\n            context.Name = \"Frank\";\r\n\r\n            ((FakeViewEngineHost)this.fakeHost).Context = context;\r\n\r\n            var output = viewEngine.Render(input, null, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Hello there [ERR!]</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_replace_context_properties_if_case_is_incorrect()\r\n        {\r\n            const string input = @\"<html><head></head><body>Hello there @Context.name;</body></html>\";\r\n            dynamic context = new ExpandoObject();\r\n            context.Name = \"Franke\";\r\n\r\n            ((FakeViewEngineHost)this.fakeHost).Context = context;\r\n\r\n            var output = viewEngine.Render(input, null, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Hello there [ERR!]</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_replace_multiple_context_properties_from_dictionary()\r\n        {\r\n            const string input = @\"<html><head></head><body>Hello there @Context.Name; - welcome to @Context.SiteName;</body></html>\";\r\n            dynamic context = new ExpandoObject();\r\n            context.Name = \"Frank\";\r\n            context.SiteName = \"Cool Site!\";\r\n\r\n            ((FakeViewEngineHost)this.fakeHost).Context = context;\r\n\r\n            var output = viewEngine.Render(input, null, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Hello there Frank - welcome to Cool Site!</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_context_statement_to_be_followed_by_a_newline()\r\n        {\r\n            const string input = \"<html><head></head><body>Hello there @Context.Name;\\n</body></html>\";\r\n\r\n            var output = viewEngine.Render(input, null, this.fakeHost);\r\n\r\n            Assert.Equal(\"<html><head></head><body>Hello there Frank\\n</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Context_substitutions_work_with_standard_anonymous_type_objects()\r\n        {\r\n            const string input = @\"<html><head></head><body>Hello there @Context.Name; - welcome to @Context.SiteName;</body></html>\";\r\n            var context = new { Name = \"Bob\", SiteName = \"Cool Site!\" };\r\n\r\n            ((FakeViewEngineHost)this.fakeHost).Context = context;\r\n\r\n            var output = viewEngine.Render(input, null, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Hello there Bob - welcome to Cool Site!</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_sub_properties_using_context_statement()\r\n        {\r\n            const string input = @\"<h1>Hello @Context.User.Username;</h1>\";\r\n\r\n            var output = viewEngine.Render(input, null, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<h1>Hello Frank123</h1>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_Context_substitutions_wihout_semi_colon()\r\n        {\r\n            const string input = @\"<html><head></head><body>Hello there @Context.Name</body></html>\";\r\n\r\n            var output = viewEngine.Render(input, null, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Hello there Frank</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_expand_partial_content_with_context()\r\n        {\r\n            const string input = @\"<html><head></head><body>@Partial['testing'];</body></html>\";\r\n            var fakeViewEngineHost = new FakeViewEngineHost();\r\n            fakeViewEngineHost.GetTemplateCallback = (s, m) => \"Hello @Context.Name\";\r\n\r\n            var result = viewEngine.Render(input, null, fakeViewEngineHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Hello Frank</body></html>\", result);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_also_expand_master_page_with_same_context()\r\n        {\r\n            const string input = \"@Master['myMaster']\\r\\n@Section['Header'];\\r\\nHeader\\r\\n@EndSection\\r\\n@Section['Footer']\\r\\nFooter\\r\\n@EndSection\";\r\n            const string master = @\"Hello @Context.Name!<div id='header'>@Section['Header'];</div><div id='footer'>@Section['Footer'];</div>\";\r\n            var fakeViewEngineHost = new FakeViewEngineHost();\r\n            fakeViewEngineHost.GetTemplateCallback = (s, m) => master;\r\n\r\n            var result = viewEngine.Render(input, null, fakeViewEngineHost);\r\n\r\n            Assert.Equal(\"Hello Frank!<div id='header'>\\r\\nHeader\\r\\n</div><div id='footer'>\\r\\nFooter\\r\\n</div>\", result);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_stuffrender_block_when_ifnot_statement_returns_false()\r\n        {\r\n            const string input = @\"<html><head></head><body>@IfNot.Context.HasUsers;<p>No users found!</p>@EndIf;</body></html>\";\r\n\r\n            var model = new FakeModel(\"Nancy\", new List<string>() { \"Nancy \" });\r\n\r\n            ((FakeViewEngineHost)this.fakeHost).Context = new FakeModel(\"NancyContext\", new List<string>());\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><p>No users found!</p></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_ifnot_and_endif_and_context_model_source()\r\n        {\r\n            const string input = @\"<html><head></head><body>@IfNot.Context.HasUsers;No users found!@EndIf</body></html>\";\r\n            var model = new FakeModel(\"Nancy\", new List<string>() { \"Bob\", \"Jim\", \"Bill\" });\r\n\r\n            ((FakeViewEngineHost)this.fakeHost).Context = new FakeModel(\"NancyContext\", new List<string>());\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>No users found!</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_ifnot_and_endif_and_model_model_source()\r\n        {\r\n            const string input = @\"<html><head></head><body>@IfNot.Model.HasUsers;No users found!@EndIf</body></html>\";\r\n            var model = new FakeModel(\"Nancy\", new List<string>());\r\n\r\n            ((FakeViewEngineHost)this.fakeHost).Context = new FakeModel(\"NancyContext\", new List<string>() { \"Bob\", \"Jim\", \"Bill\" });\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>No users found!</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_ifnot_and_endif_and_implicit_model_model_source()\r\n        {\r\n            const string input = @\"<html><head></head><body>@IfNot.HasUsers;No users found!@EndIf</body></html>\";\r\n            var model = new FakeModel(\"Nancy\", new List<string>());\r\n\r\n            ((FakeViewEngineHost)this.fakeHost).Context = new FakeModel(\"NancyContext\", new List<string>() { \"Bob\", \"Jim\", \"Bill\" });\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>No users found!</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_if_and_endif_and_context_model_source()\r\n        {\r\n            const string input = @\"<html><head></head><body>@If.Context.HasUsers;Users found!@EndIf</body></html>\";\r\n            var model = new FakeModel(\"Nancy\", new List<string>());\r\n\r\n            ((FakeViewEngineHost)this.fakeHost).Context = new FakeModel(\"NancyContext\", new List<string>() { \"Bob\", \"Jim\", \"Bill\" });\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Users found!</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_if_and_endif_and_model_model_source()\r\n        {\r\n            const string input = @\"<html><head></head><body>@If.Model.HasUsers;Users found!@EndIf</body></html>\";\r\n            var model = new FakeModel(\"Nancy\", new List<string>() { \"Bob\", \"Jim\", \"Bill\" });\r\n\r\n            ((FakeViewEngineHost)this.fakeHost).Context = new FakeModel(\"NancyContext\", new List<string>());\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Users found!</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_if_and_endif_and_implicit_model_model_source()\r\n        {\r\n            const string input = @\"<html><head></head><body>@If.HasUsers;Users found!@EndIf</body></html>\";\r\n            var model = new FakeModel(\"Nancy\", new List<string>() { \"Bob\", \"Jim\", \"Bill\" });\r\n\r\n            ((FakeViewEngineHost)this.fakeHost).Context = new FakeModel(\"NancyContext\", new List<string>());\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Users found!</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_support_each_block_with_model_as_model_source()\r\n        {\r\n            const string input = @\"<html><head></head><body><ul>@Each.Model.Users;<li>Hello @Current;, @Model.Name; says hello!</li>@EndEach;</ul></body></html>\";\r\n            var model = new FakeModel(\"Nancy\", new List<string>() { \"Bob\", \"Jim\", \"Bill\" });\r\n\r\n            ((FakeViewEngineHost)this.fakeHost).Context = new FakeModel(\"NancyContext\", new List<string>());\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><ul><li>Hello Bob, Nancy says hello!</li><li>Hello Jim, Nancy says hello!</li><li>Hello Bill, Nancy says hello!</li></ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_support_each_block_with_implicit_model_source()\r\n        {\r\n            const string input = @\"<html><head></head><body><ul>@Each.Users;<li>Hello @Current;, @Model.Name; says hello!</li>@EndEach;</ul></body></html>\";\r\n            var model = new FakeModel(\"Nancy\", new List<string>() { \"Bob\", \"Jim\", \"Bill\" });\r\n\r\n            ((FakeViewEngineHost)this.fakeHost).Context = new FakeModel(\"NancyContext\", new List<string>());\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body><ul><li>Hello Bob, Nancy says hello!</li><li>Hello Jim, Nancy says hello!</li><li>Hello Bill, Nancy says hello!</li></ul></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_include_block_with_ifnull_if_value_null()\r\n        {\r\n            const string input = @\"<html><head></head><body>@IfNull.Name;No users found@EndIf;</body></html>\";\r\n            var model = new User(null, true);\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>No users found</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_include_block_with_ifnull_if_value_non_null()\r\n        {\r\n            const string input = @\"<html><head></head><body>@IfNull.Name;No users found@EndIf;</body></html>\";\r\n            var model = new User(\"Bob\", true);\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_include_block_with_ifnotnull_if_value_non_null()\r\n        {\r\n            const string input = @\"<html><head></head><body>@IfNotNull.Name;Hello @Model.Name@EndIf;</body></html>\";\r\n            var model = new User(\"Bob\", true);\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body>Hello Bob</body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_include_block_with_ifnotnull_if_value_null()\r\n        {\r\n            const string input = @\"<html><head></head><body>@IfNotNull.Name;Hello @Model.Name@EndIf;</body></html>\";\r\n            var model = new User(null, true);\r\n\r\n            var output = viewEngine.Render(input, model, this.fakeHost);\r\n\r\n            Assert.Equal(@\"<html><head></head><body></body></html>\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_all_matchers()\r\n        {\r\n            // Given\r\n            var extension1 = A.Fake<ISuperSimpleViewEngineMatcher>();\r\n            A.CallTo(() => extension1.Invoke(A<string>._, A<object>._, A<IViewEngineHost>._)).Returns(\"Foo\");\r\n\r\n            var extension2 = A.Fake<ISuperSimpleViewEngineMatcher>();\r\n            A.CallTo(() => extension2.Invoke(A<string>._, A<object>._, A<IViewEngineHost>._)).ReturnsLazily(x => (string)x.Arguments[0] + \"Bar\");\r\n\r\n            const string input = @\"<html><head></head><body></body></html>\";\r\n\r\n            var engine = new SuperSimpleViewEngine(new[] { extension1, extension2 });\r\n\r\n            // When\r\n            var output = engine.Render(input, null, this.fakeHost);\r\n\r\n            // Then\r\n            Assert.Equal(\"FooBar\", output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_support_being_passed_null_matchers()\r\n        {\r\n            // Given\r\n            const string input = @\"<html><head></head><body></body></html>\";\r\n\r\n            var engine = new SuperSimpleViewEngine(null);\r\n\r\n            // When\r\n            var output = engine.Render(input, null, this.fakeHost);\r\n\r\n            // Then\r\n            Assert.Equal(input, output);\r\n        }\r\n\r\n        [Fact]\r\n        public void Shoud_pass_model_to_matchers()\r\n        {\r\n            // Given\r\n            const string input = @\"<html><head></head><body></body></html>\";\r\n\r\n            var extension = A.Fake<ISuperSimpleViewEngineMatcher>();\r\n            var engine = new SuperSimpleViewEngine(new[] { extension });\r\n            var model = new object();\r\n\r\n            // When\r\n            engine.Render(input, model, this.fakeHost);\r\n\r\n            // Then\r\n            A.CallTo(() => extension.Invoke(A<string>._, model, A<IViewEngineHost>._)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Shoud_pass_content_to_matchers()\r\n        {\r\n            // Given\r\n            const string input = @\"<html><head></head><body></body></html>\";\r\n\r\n            var extension = A.Fake<ISuperSimpleViewEngineMatcher>();\r\n            var engine = new SuperSimpleViewEngine(new[] { extension });\r\n\r\n            // When\r\n            engine.Render(input, null, this.fakeHost);\r\n\r\n            // Then\r\n            A.CallTo(() => extension.Invoke(input, A<object>._, A<IViewEngineHost>._)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Shoud_pass_view_engine_host_to_matchers()\r\n        {\r\n            // Given\r\n            const string input = @\"<html><head></head><body></body></html>\";\r\n\r\n            var extension = A.Fake<ISuperSimpleViewEngineMatcher>();\r\n            var engine = new SuperSimpleViewEngine(new[] { extension });\r\n\r\n            // When\r\n            engine.Render(input, null, this.fakeHost);\r\n\r\n            // Then\r\n            A.CallTo(() => extension.Invoke(A<string>._, A<object>._, this.fakeHost)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_pass_context_nested_dictionary_to_matchers()\r\n        {\r\n            // Given\r\n            const string keyConst = \"TestKey\";\r\n            const string valueConst = \"testvalue\";\r\n\r\n            var dict = new Dictionary<string, object> { { keyConst, valueConst } };\r\n            var context = this.fakeHost.Context as FakeViewEngineHost.FakeContext;\r\n            context.ViewBag.Nested = new\r\n            {\r\n                Dictionary = dict\r\n            };\r\n\r\n            var input = string.Format(@\"<html><head></head><body>@Context.ViewBag.Nested.Dictionary.{0}</body></html>\", keyConst);\r\n            var engine = new SuperSimpleViewEngine();\r\n\r\n            // When\r\n            var result = engine.Render(input, null, this.fakeHost);\r\n\r\n            // Then\r\n            Assert.Equal(string.Format(\"<html><head></head><body>{0}</body></html>\", valueConst), result);\r\n        }\r\n    }\r\n\r\n    public class User\r\n    {\r\n        public User(string name)\r\n            : this(name, false)\r\n        {\r\n        }\r\n\r\n        public User(string name, bool isFriend)\r\n        {\r\n            Name = name;\r\n            IsFriend = isFriend;\r\n        }\r\n\r\n        public string Name { get; private set; }\r\n        public bool IsFriend { get; private set; }\r\n    }\r\n\r\n    public class FakeModel\r\n    {\r\n        public FakeModel(string name, List<string> users)\r\n        {\r\n            this.Name = name;\r\n            this.Users = users;\r\n        }\r\n\r\n        public List<string> Users { get; private set; }\r\n\r\n        public string Name { get; private set; }\r\n\r\n        public bool HasUsers\r\n        {\r\n            get\r\n            {\r\n                return this.Users.Any();\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/ViewEngines/ViewEngineStartupFixture.cs",
    "content": "namespace Nancy.Tests.Unit.ViewEngines\r\n{\r\n    using System.Collections.Generic;\r\n    using FakeItEasy;\r\n    using Nancy.Configuration;\r\n    using Nancy.ViewEngines;\r\n    using Xunit;\r\n\r\n    public class ViewEngineStartupFixture\r\n    {\r\n        private IList<ViewLocationResult> views;\r\n        private readonly IViewCache viewCache;\r\n        private readonly IViewLocator viewLocator;\r\n        private readonly INancyEnvironment environment;\r\n\r\n        public ViewEngineStartupFixture()\r\n        {\r\n            this.views = new List<ViewLocationResult>\r\n            {\r\n                new ViewLocationResult(\"\", \"\", \"html\", null),\r\n                new ViewLocationResult(\"\", \"\", \"spark\", null),\r\n            };\r\n\r\n            var viewLocationProvider = A.Fake<IViewLocationProvider>();\r\n            A.CallTo(() => viewLocationProvider.GetLocatedViews(A<IEnumerable<string>>._))\r\n                                               .Returns(views);\r\n\r\n            var viewEngine = A.Fake<IViewEngine>();\r\n            A.CallTo(() => viewEngine.Extensions).Returns(new[] { \"liquid\" });\r\n\r\n            this.environment = new DefaultNancyEnvironment();\r\n            this.environment.AddValue(ViewConfiguration.Default);\r\n\r\n            this.viewLocator = new DefaultViewLocator(viewLocationProvider, new[] { viewEngine }, this.environment);\r\n            this.viewCache = A.Fake<IViewCache>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_initialize_on_each_view_engine()\r\n        {\r\n            // Given\r\n            var engines = new[] { A.Fake<IViewEngine>(), A.Fake<IViewEngine>() };\r\n            var startup = new ViewEngineApplicationStartup(engines, this.viewCache, this.viewLocator);\r\n\r\n            // When\r\n            startup.Initialize(null);\r\n\r\n            // Then\r\n            A.CallTo(() => engines[0].Initialize(A<ViewEngineStartupContext>.Ignored)).MustHaveHappened();\r\n            A.CallTo(() => engines[1].Initialize(A<ViewEngineStartupContext>.Ignored)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_intialize_on_engine_with_view_cache_set_on_context()\r\n        {\r\n            // Given\r\n            var engines = new[] { A.Fake<IViewEngine>() };\r\n            var startup = new ViewEngineApplicationStartup(engines, this.viewCache, this.viewLocator);\r\n\r\n            // When\r\n            startup.Initialize(null);\r\n\r\n            // Then\r\n            A.CallTo(() => engines[0].Initialize(A<ViewEngineStartupContext>.That.Matches(x => x.ViewCache.Equals(this.viewCache)))).MustHaveHappened();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/Unit/ViewEngines/ViewNotFoundExceptionFixture.cs",
    "content": "﻿namespace Nancy.Tests.Unit.ViewEngines\r\n{\r\n    using FakeItEasy;\r\n\r\n    using Nancy.ViewEngines;\r\n\r\n    using Xunit;\r\n\r\n    public class ViewNotFoundExceptionFixture\r\n    {\r\n        [Fact]\r\n        public void Should_include_both_name_and_extensions_in_message()\r\n        {\r\n            // Given\r\n            var rootPathProvider = A.Fake<IRootPathProvider>();\r\n            A.CallTo(() => rootPathProvider.GetRootPath()).Returns(\"The root path\");\r\n\r\n            // When\r\n            var result = new ViewNotFoundException(\"foo\", new[] { \"html\", \"sshtml\" }, new[] { \"baz\", \"bar\" }, rootPathProvider);\r\n\r\n            // Then\r\n            result.Message.ShouldContain(\"foo\");\r\n            result.Message.ShouldContain(\"html\");\r\n            result.Message.ShouldContain(\"sshtml\");\r\n            result.Message.ShouldContain(\"baz\");\r\n            result.Message.ShouldContain(\"bar\");\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/Unit/XmlFormatterExtensionsFixtures.cs",
    "content": "namespace Nancy.Tests.Unit\r\n{\r\n    using System.IO;\r\n    using System.Xml;\r\n    using FakeItEasy;\r\n    using Nancy.Configuration;\r\n    using Nancy.Responses;\r\n    using Nancy.Tests.Fakes;\r\n    using Nancy.Xml;\r\n    using Xunit;\r\n\r\n    public class XmlFormatterExtensionsFixtures\r\n    {\r\n        private readonly DefaultResponseFormatter responseFormatter;\r\n        private readonly Person model;\r\n        private readonly Response response;\r\n        private readonly IRootPathProvider rootPathProvider;\r\n\r\n        public XmlFormatterExtensionsFixtures()\r\n        {\r\n            this.rootPathProvider = A.Fake<IRootPathProvider>();\r\n            var environment = new DefaultNancyEnvironment();\r\n            environment.AddValue(XmlConfiguration.Default);\r\n            environment.Tracing(\r\n                enabled: true,\r\n                displayErrorTraces: true);\r\n\r\n            var serializerFactory =\r\n                new DefaultSerializerFactory(new ISerializer[] { new DefaultXmlSerializer(environment) });\r\n\r\n            this.responseFormatter =\r\n                new DefaultResponseFormatter(this.rootPathProvider, new NancyContext(), serializerFactory, environment);\r\n\r\n            this.model = new Person { FirstName = \"Andy\", LastName = \"Pike\" };\r\n            this.response = this.responseFormatter.AsXml(model);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_a_response_with_the_application_xml_content_type()\r\n        {\r\n            response.ContentType.ShouldEqual(\"application/xml\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_a_response_with_status_code_200_OK()\r\n        {\r\n            response.StatusCode.ShouldEqual(HttpStatusCode.OK);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_a_valid_model_in_xml_format()\r\n        {\r\n            using (var stream = new MemoryStream())\r\n            {\r\n                response.Contents(stream);\r\n\r\n                var root = GetXmlRoot(stream);\r\n\r\n                root.Name.ShouldEqual(\"Person\");\r\n                root.ChildNodes.Count.ShouldEqual(2);\r\n                root[\"FirstName\"].InnerText.ShouldEqual(\"Andy\");\r\n                root[\"LastName\"].InnerText.ShouldEqual(\"Pike\");\r\n            }\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_a_null_in_xml_format()\r\n        {\r\n            using (var stream = new MemoryStream())\r\n            {\r\n                responseFormatter.AsXml<Person>(null).Contents(stream);\r\n\r\n                var root = GetXmlRoot(stream);\r\n                root.GetAttribute(\"nil\", \"http://www.w3.org/2001/XMLSchema-instance\").ShouldEqual(\"true\");\r\n                root.ChildNodes.Count.ShouldEqual(0);\r\n            }\r\n        }\r\n\r\n        private static XmlElement GetXmlRoot(Stream stream)\r\n        {\r\n            stream.Position = 0;\r\n            var xml = new XmlDocument();\r\n            xml.Load(stream);\r\n\r\n            return xml.DocumentElement;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/xUnitExtensions/RecordAsync.cs",
    "content": "﻿namespace Nancy.Tests.xUnitExtensions\r\n{\r\n    using System;\r\n    using System.Threading.Tasks;\r\n    using Xunit;\r\n\r\n    public static class RecordAsync\r\n    {\r\n        public static async Task<Exception> Exception(Func<Task> method)\r\n        {\r\n            try\r\n            {\r\n                await method();\r\n                return null;\r\n            }\r\n            catch (Exception ex)\r\n            {\r\n                return ex;\r\n            }\r\n        }\r\n    }\r\n\r\n    public static class AssertAsync\r\n    {\r\n        public static async Task<T> Throws<T>(Func<Task> testCode) where T : Exception\r\n        {\r\n            try\r\n            {\r\n                await testCode();\r\n                Assert.Throws<T>(() => { }); // Use xUnit's default behavior.\r\n            }\r\n            catch(T exception)\r\n            {\r\n                return exception;\r\n            }\r\n            return null;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/xUnitExtensions/Skip.cs",
    "content": "﻿// Copyright (c) 2015 Andrew Arnott\r\n// Licensed under the Ms-PL\r\n\r\nnamespace Nancy.Tests.xUnitExtensions\r\n{\r\n    /// <summary>\r\n    /// Static methods for dynamically skipping tests identified with\r\n    /// the <see cref=\"SkippableFactAttribute\"/>.\r\n    /// </summary>\r\n    public static class Skip\r\n    {\r\n        /// <summary>\r\n        /// Throws an exception that results in a \"Skipped\" result for the test.\r\n        /// </summary>\r\n        /// <param name=\"condition\">The condition that must evaluate to <c>true</c> for the test to be skipped.</param>\r\n        /// <param name=\"reason\">The explanation for why the test is skipped.</param>\r\n        public static void If(bool condition, string reason = null)\r\n        {\r\n            if (condition)\r\n            {\r\n                throw new SkipException(reason);\r\n            }\r\n        }\r\n\r\n        /// <summary>\r\n        /// Throws an exception that results in a \"Skipped\" result for the test.\r\n        /// </summary>\r\n        /// <param name=\"condition\">The condition that must evaluate to <c>false</c> for the test to be skipped.</param>\r\n        /// <param name=\"reason\">The explanation for why the test is skipped.</param>\r\n        public static void IfNot(bool condition, string reason = null)\r\n        {\r\n            Skip.If(!condition, reason);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests/xUnitExtensions/SkipException.cs",
    "content": "﻿// Copyright (c) 2015 Andrew Arnott\r\n// Licensed under the Ms-PL\r\n\r\nnamespace Nancy.Tests.xUnitExtensions\r\n{\r\n    using System;\r\n\r\n    /// <summary>\r\n    /// The exception to throw to register a skipped test.\r\n    /// </summary>\r\n    public class SkipException : Exception\r\n    {\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"SkipException\"/> class.\r\n        /// </summary>\r\n        /// <param name=\"reason\">The reason the test is skipped.</param>\r\n        public SkipException(string reason)\r\n            : base(reason)\r\n        {\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/xUnitExtensions/SkippableFactAttribute.cs",
    "content": "﻿// Copyright (c) 2015 Andrew Arnott\r\n// Licensed under the Ms-PL\r\n\r\nnamespace Nancy.Tests.xUnitExtensions\r\n{\r\n    using System;\r\n    using Xunit;\r\n    using Xunit.Sdk;\r\n\r\n    /// <summary>\r\n    /// Attribute that is applied to a method to indicate that it is a fact that should\r\n    /// be run by the test runner.\r\n    /// The test may produce a \"skipped test\" result by calling\r\n    /// <see cref=\"Skip.If(bool, string)\"/> or otherwise throwing a <see cref=\"SkipException\"/>.\r\n    /// </summary>\r\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]\r\n    [XunitTestCaseDiscoverer(\"Xunit.Sdk.SkippableFactDiscoverer\", \"Xunit.SkippableFact.{Platform}\")]\r\n    public class SkippableFactAttribute : FactAttribute\r\n    {\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests/xUnitExtensions/UsingCultureAttribute.cs",
    "content": "﻿namespace Nancy.Tests.xUnitExtensions\r\n{\r\n    using System;\r\n    using System.Globalization;\r\n    using System.Reflection;\r\n    using System.Threading;\r\n    using Xunit.Sdk;\r\n\r\n    /// <summary>\r\n    /// Attribute that is applied to a method to indicate that it should be run using a particular\r\n    /// culture (and UI culture).\r\n    /// Applies the named culture before running the method and restores the original one after.\r\n    /// </summary>\r\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\r\n    public sealed class UsingCultureAttribute : BeforeAfterTestAttribute\r\n    {\r\n        private readonly string cultureName;\r\n\r\n        private CultureInfo originalCulture;\r\n        private CultureInfo originalUiCulture;\r\n\r\n        /// <summary>\r\n        /// Create an instance of <see cref=\"UsingCultureAttribute\"/> that will apply the\r\n        /// name culture during the execution of the decorated method.\r\n        /// </summary>\r\n        /// <param name=\"cultureName\">The name of the culture to use.</param>\r\n        /// <example>\r\n        ///   <code>\r\n        ///     [Fact]\r\n        ///     [UsingCulture(\"de-DE\")]\r\n        ///     public void Should_Behave_In_Some_Way()\r\n        ///     …\r\n        ///   </code>\r\n        /// </example>\r\n        public UsingCultureAttribute(string cultureName)\r\n        {\r\n            this.cultureName = cultureName;\r\n        }\r\n\r\n        /// <summary>\r\n        /// This method is called after the test method is executed. It restores the original\r\n        /// current culture and current UI culture in effect before the test method was run.\r\n        /// </summary>\r\n        /// <param name=\"methodUnderTest\">The method under test</param>\r\n        public override void After(MethodInfo methodUnderTest)\r\n        {\r\n#if CORE\r\n            CultureInfo.CurrentCulture = this.originalCulture;\r\n            CultureInfo.CurrentUICulture = this.originalUiCulture;\r\n#else\r\n            Thread.CurrentThread.CurrentCulture = this.originalCulture;\r\n            Thread.CurrentThread.CurrentUICulture = this.originalUiCulture;\r\n#endif\r\n        }\r\n\r\n        /// <summary>\r\n        /// This method is called before the test method is executed. It switches the current\r\n        /// culture and current UI culture to the culture chosen when this instance was created.\r\n        /// </summary>\r\n        /// <param name=\"methodUnderTest\">The method under test</param>\r\n        public override void Before(MethodInfo methodUnderTest)\r\n        {\r\n#if CORE\r\n            this.originalCulture = CultureInfo.CurrentCulture;\r\n            this.originalUiCulture = CultureInfo.CurrentUICulture;\r\n            CultureInfo.CurrentCulture = new CultureInfo(this.cultureName);\r\n            CultureInfo.CurrentUICulture = new CultureInfo(this.cultureName);\r\n#else\r\n            this.originalCulture = Thread.CurrentThread.CurrentCulture;\r\n            this.originalUiCulture = Thread.CurrentThread.CurrentUICulture;\r\n            Thread.CurrentThread.CurrentCulture = new CultureInfo(this.cultureName);\r\n            Thread.CurrentThread.CurrentUICulture = new CultureInfo(this.cultureName);\r\n#endif\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests.Functional/Hidden.txt",
    "content": "﻿Hidden from the content conventions"
  },
  {
    "path": "test/Nancy.Tests.Functional/Modules/AbsoluteUrlTestModule.cs",
    "content": "﻿namespace Nancy.Tests.Functional.Modules\r\n{\r\n    public class AbsoluteUrlTestModule : NancyModule\r\n    {\r\n        public AbsoluteUrlTestModule()\r\n        {\r\n            Get(\"/\", args => \"hi\");\r\n\r\n            Get(\"/querystring\", args => this.Request.Query.myKey);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests.Functional/Modules/CookieModule.cs",
    "content": "﻿namespace Nancy.Tests.Functional.Modules\r\n{\r\n    using Nancy.Cookies;\r\n\r\n    public class CookieModule : NancyModule\r\n    {\r\n        public CookieModule()\r\n        {\r\n            Get(\"/setcookie\", args =>\r\n            {\r\n                const string value = \"HakLqr1OEdi+kQ/s92Rzz9hV1w/vzGZKqWeMQRHRJlwhbbgP87UELJZlYDfbVVLo\";\r\n\r\n                var cookie = new NancyCookie(\"testcookie\", value);\r\n\r\n                var response = new Response();\r\n                response.WithCookie(cookie);\r\n                response.StatusCode = HttpStatusCode.OK;\r\n\r\n                return response;\r\n            });\r\n\r\n            Get(\"/getcookie\", args =>\r\n            {\r\n                const string value = \"HakLqr1OEdi+kQ/s92Rzz9hV1w/vzGZKqWeMQRHRJlwhbbgP87UELJZlYDfbVVLo\";\r\n\r\n                var cookie = Context.Request.Cookies[\"testcookie\"];\r\n\r\n                return string.Equals(cookie, value) ?\r\n                    HttpStatusCode.OK :\r\n                    HttpStatusCode.InternalServerError;\r\n            });\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests.Functional/Modules/JsonpTestModule.cs",
    "content": "﻿namespace Nancy.Tests.Functional.Modules\r\n{\r\n    public class JsonpTestModule : NancyModule\r\n    {\r\n        public JsonpTestModule() : base(\"/test\")\r\n        {\r\n            Get(\"/string\", args => \"Normal Response\");\r\n            Get(\"/json\", args => this.Response.AsJson(true));\r\n            Get(\"/{name}\", args => this.Response.AsJson(new { args.name }));\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests.Functional/Modules/PerRouteAuthModule.cs",
    "content": "﻿namespace Nancy.Tests.Functional.Modules\r\n{\r\n    using Nancy.Security;\r\n\r\n    public class PerRouteAuthModule : NancyModule\r\n    {\r\n        public PerRouteAuthModule()\r\n        {\r\n            Get(\"/nonsecured\", args => 200);\r\n\r\n            Get(\"/secured\", args =>\r\n            {\r\n                this.RequiresAuthentication();\r\n\r\n                return 200;\r\n            });\r\n\r\n            Get(\"/requiresclaims\", args =>\r\n            {\r\n                this.RequiresClaims(c => c.Type == \"test\", c => c.Type == \"test2\");\r\n\r\n                return 200;\r\n            });\r\n\r\n            Get(\"/requiresanyclaims\", args =>\r\n            {\r\n                this.RequiresAnyClaim(c => c.Type == \"test\", c => c.Type == \"test2\");\r\n\r\n                return 200;\r\n            });\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests.Functional/Modules/RazorTestModule.cs",
    "content": "﻿namespace Nancy.Tests.Functional.Modules\r\n{\r\n    public class RazorTestModule : NancyModule\r\n    {\r\n        public RazorTestModule()\r\n        {\r\n            Get(\"/razor-viewbag\", args =>\r\n            {\r\n                this.ViewBag.Name = \"Bob\";\r\n\r\n                return View[\"RazorPage\"];\r\n            });\r\n\r\n            Get(\"/razor-viewbag-serialized\", args =>\r\n            {\r\n                this.ViewBag.Name = \"Bob\";\r\n\r\n                var serialized = this.ViewBag.ToDictionary();\r\n\r\n                return serialized;\r\n            });\r\n\r\n            Get(\"/razor-partialnotfound\", args =>\r\n            {\r\n                this.ViewBag.Name = \"Bob\";\r\n\r\n                return View[\"RazorPageWithUnknownPartial\"];\r\n            });\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests.Functional/Modules/RazorWithTracingTestModule.cs",
    "content": "﻿namespace Nancy.Tests.Functional.Modules\r\n{\r\n    public class RazorWithTracingTestModule : NancyModule\r\n    {\r\n        public RazorWithTracingTestModule()\r\n        {\r\n            Get(\"/tracing/razor-viewbag\", args =>\r\n            {\r\n                this.ViewBag.Name = \"Bob\";\r\n\r\n                return View[\"RazorPage\"];\r\n            });\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests.Functional/Modules/SerializeTestModule.cs",
    "content": "﻿namespace Nancy.Tests.Functional.Modules\r\n{\r\n    public class SerializeTestModule : NancyModule\r\n    {\r\n        public SerializeTestModule()\r\n        {\r\n            Post(\"/serializedform\", args =>\r\n            {\r\n                var data = Request.Form.ToDictionary();\r\n\r\n                return data;\r\n            });\r\n\r\n            Get(\"/serializedquerystring\", args =>\r\n            {\r\n                var data = Request.Query.ToDictionary();\r\n\r\n                return data;\r\n            });\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests.Functional/Modules/SerializerTestModule.cs",
    "content": "﻿namespace Nancy.Tests.Functional.Modules\r\n{\r\n    using System;\r\n    using System.Globalization;\r\n    using Nancy.Extensions;\r\n    using Nancy.IO;\r\n    using Nancy.ModelBinding;\r\n\r\n    public class SerializerTestModule : NancyModule\r\n    {\r\n        public SerializerTestModule()\r\n        {\r\n            Get(\"/serializer/{date}\", args =>\r\n            {\r\n                var stringparamDate = (string)args.date;\r\n                var dateParsed = DateTime.ParseExact(stringparamDate, \"yyyyMMddHHmmss\", CultureInfo.InvariantCulture);\r\n                return new FakeSerializerModel() { CreatedOn = dateParsed };\r\n            });\r\n\r\n            Post(\"/serializer\", args =>\r\n            {\r\n                var model = new FakeSerializerModel { CreatedOn = new DateTime(2014, 01, 30, 0, 0, 0, DateTimeKind.Utc) };\r\n                this.BindTo(model);\r\n                return model;\r\n            });\r\n\r\n            Post(\"/serializer/date\", args =>\r\n            {\r\n                var s = this.Request.Body.AsString();\r\n                var model = this.Bind<FakeSerializerModel>();\r\n                return model;\r\n            });\r\n        }\r\n    }\r\n\r\n    public class FakeSerializerModel\r\n    {\r\n        public DateTime CreatedOn { get; set; }\r\n\r\n        public string Name { get; set; }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests.Functional/Modules/ThrowingModule.cs",
    "content": "﻿namespace Nancy.Tests.Functional.Modules\r\n{\r\n    using System;\r\n\r\n    public class ThrowingModule : NancyModule\r\n    {\r\n        public ThrowingModule()\r\n        {\r\n            Get(\"/\", args =>\r\n            {\r\n                throw new InvalidOperationException(\"Oh noes!\");\r\n                return 500;\r\n            });\r\n\r\n            this.OnError.AddItemToEndOfPipeline((context, ex) => new Error(ex.Message));\r\n        }\r\n\r\n        public class Error\r\n        {\r\n            public Error() : this(string.Empty)\r\n            {\r\n            }\r\n\r\n            public Error(string message)\r\n            {\r\n                this.Message = message;\r\n            }\r\n\r\n            public string Message { get; set; }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests.Functional/Nancy.Tests.Functional.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <TargetFrameworks>netcoreapp2.0;net452</TargetFrameworks>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <None Update=\"Content\\**\\*;Views\\**\\*\">\n      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>\n    </None>\n  </ItemGroup>\n\n  <ItemGroup Condition=\" '$(TargetFramework)' == 'net452' \">\n    <ProjectReference Include=\"../../src/Nancy.ViewEngines.Razor/Nancy.ViewEngines.Razor.csproj\" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "test/Nancy.Tests.Functional/Tests/AbsoluteUrlTests.cs",
    "content": "﻿namespace Nancy.Tests.Functional.Tests\r\n{\r\n    using System;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Testing;\r\n    using Nancy.Tests.Functional.Modules;\r\n\r\n    using Xunit;\r\n\r\n    public class AbsoluteUrlTests\r\n    {\r\n        private readonly ConfigurableBootstrapper bootstrapper;\r\n        private readonly Browser browser;\r\n\r\n        public AbsoluteUrlTests()\r\n        {\r\n            this.bootstrapper = new ConfigurableBootstrapper(\r\n                    configuration => configuration.Modules(new Type[] { typeof(AbsoluteUrlTestModule) }));\r\n\r\n            this.browser = new Browser(bootstrapper);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_Return_Response_From_Full_Url_String()\r\n        {\r\n            //Given, When\r\n            var result = await browser.Get(\"http://mydomain.com/\");\r\n\r\n            //Then\r\n            Assert.Equal(\"hi\", result.Body.AsString());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_Return_Response_From_Full_Url()\r\n        {\r\n            //Given\r\n            var url = new Url {Path = \"/\", Scheme = \"http\", HostName = \"mydomain.com\"};\r\n\r\n            //When\r\n            var result = await browser.Get(url);\r\n\r\n            //Then\r\n            Assert.Equal(\"hi\", result.Body.AsString());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_Return_QueryString_Values_From_Full_Url_String()\r\n        {\r\n            //Given, When\r\n            var result = await browser.Get(\"http://mydomain.com/querystring?myKey=myvalue\");\r\n\r\n            //Then\r\n            Assert.Equal(\"myvalue\", result.Body.AsString());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_Return_QueryString_Values_From_Full_Url()\r\n        {\r\n            //Given\r\n            var url = new Url { Path = \"/querystring\", Scheme = \"http\", HostName = \"mydomain.com\", Query = \"?myKey=myvalue\" };\r\n\r\n            //When\r\n            var result = await browser.Get(url);\r\n\r\n            //Then\r\n            Assert.Equal(\"myvalue\", result.Body.AsString());\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests.Functional/Tests/AsyncExceptionTests.cs",
    "content": "﻿namespace Nancy.Tests.Functional.Tests\r\n{\r\n    using System;\r\n    using System.Threading.Tasks;\r\n\r\n    using Nancy.Testing;\r\n    using Xunit;\r\n\r\n    public class AsyncExceptionTests\r\n    {\r\n        private readonly Browser browser;\r\n\r\n        public AsyncExceptionTests()\r\n        {\r\n            this.browser = new Browser(config =>\r\n            {\r\n                config.Module<MyModule>();\r\n                // explicitly declare the status code handler that throws, just\r\n                // in case it's not there for some other reason.\r\n                config.StatusCodeHandlers(new[] { typeof(PassThroughStatusCodeHandler)});\r\n            });\r\n        }\r\n\r\n        [Fact]\r\n        public async Task When_get_sync_then_should_throw()\r\n        {\r\n            var ex = await Assert.ThrowsAsync<Exception>(() => this.browser.Get(\"/sync\"));\r\n\r\n            // Unwrap exception from PassThroughStatusCodeHandler\r\n            ex = ex.InnerException.InnerException;\r\n\r\n            Assert.NotNull(ex);\r\n            Assert.IsType<Exception>(ex);\r\n            Assert.Equal(\"Derp\", ex.Message);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task When_get_async_then_should_throw()\r\n        {\r\n            var ex = await Assert.ThrowsAsync<Exception>(() => this.browser.Get(\"/async\"));\r\n\r\n            // Unwrap exception from PassThroughStatusCodeHandler\r\n            ex = ex.InnerException.InnerException;\r\n\r\n            Assert.NotNull(ex);\r\n            Assert.IsType<Exception>(ex);\r\n            Assert.Equal(\"Derp\", ex.Message);\r\n        }\r\n    }\r\n\r\n    public class MyModule : NancyModule\r\n    {\r\n        public MyModule()\r\n        {\r\n            Get(\"/sync\", args =>\r\n            {\r\n                throw new Exception(\"Derp\");\r\n                return 500;\r\n            });\r\n\r\n            Get(\"/async\", async args =>\r\n            {\r\n                throw new Exception(\"Derp\");\r\n                return await Task.FromResult(200);\r\n            });\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests.Functional/Tests/BasicRouteInvocationsFixture.cs",
    "content": "﻿namespace Nancy.Tests.Functional.Tests\r\n{\r\n    using System.Threading.Tasks;\r\n    using Nancy.Testing;\r\n\r\n    using Xunit;\r\n\r\n    public class BasicRouteInvocationsFixture\r\n    {\r\n        private readonly Browser browser;\r\n\r\n        public BasicRouteInvocationsFixture()\r\n        {\r\n            this.browser = new Browser(with => with.Module<BasicRouteInvocationsModule>());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_set_default_response_values_for_basic_get_request()\r\n        {\r\n            // Given\r\n            // When\r\n            var response = await this.browser.Get(\"/\");\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.OK, response.StatusCode);\r\n            Assert.Equal(\"text/plain; charset=utf-8\", response.ContentType);\r\n            Assert.Equal(\"Default get root\", response.Body.AsString());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_set_response_status_code_to_not_found_when_get_request_did_not_match()\r\n        {\r\n            // Given\r\n            // When\r\n            var response = await this.browser.Get(\"/invalid\");\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_set_default_response_values_for_basic_delete_request()\r\n        {\r\n            // Given\r\n            // When\r\n            var response = await this.browser.Delete(\"/\");\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.OK, response.StatusCode);\r\n            Assert.Equal(\"text/plain; charset=utf-8\", response.ContentType);\r\n            Assert.Equal(\"Default delete root\", response.Body.AsString());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_set_response_status_code_to_not_found_when_delete_request_did_not_match()\r\n        {\r\n            // Given\r\n            // When\r\n            var response = await this.browser.Delete(\"/invalid\");\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_set_default_response_values_for_basic_post_request()\r\n        {\r\n            // Given\r\n            // When\r\n            var response = await this.browser.Post(\"/\");\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.OK, response.StatusCode);\r\n            Assert.Equal(\"text/plain; charset=utf-8\", response.ContentType);\r\n            Assert.Equal(\"Default post root\", response.Body.AsString());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_set_response_status_code_to_not_found_when_post_request_did_not_match()\r\n        {\r\n            // Given\r\n            // When\r\n            var response = await this.browser.Post(\"/invalid\");\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_set_default_response_values_for_basic_put_request()\r\n        {\r\n            // Given\r\n            // When\r\n            var response = await this.browser.Put(\"/\");\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.OK, response.StatusCode);\r\n            Assert.Equal(\"text/plain; charset=utf-8\", response.ContentType);\r\n            Assert.Equal(\"Default put root\", response.Body.AsString());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_set_response_status_code_to_not_found_when_put_request_did_not_match()\r\n        {\r\n            // Given\r\n            // When\r\n            var response = await this.browser.Put(\"/invalid\");\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_set_default_response_values_for_basic_head_request()\r\n        {\r\n            // Given\r\n            // When\r\n            var response = await this.browser.Head(\"/\");\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.OK, response.StatusCode);\r\n            Assert.Equal(\"text/plain; charset=utf-8\", response.ContentType);\r\n            Assert.Equal(string.Empty, response.Body.AsString());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_set_response_status_code_to_not_found_when_head_request_did_not_match()\r\n        {\r\n            // Given\r\n            // When\r\n            var response = await this.browser.Head(\"/invalid\");\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);\r\n        }\r\n\r\n        public class BasicRouteInvocationsModule : NancyModule\r\n        {\r\n            public BasicRouteInvocationsModule()\r\n            {\r\n                Delete(\"/\", args =>\r\n                {\r\n                    return \"Default delete root\";\r\n                });\r\n\r\n                Get(\"/\", args =>\r\n                {\r\n                    return \"Default get root\";\r\n                });\r\n\r\n                Post(\"/\", args =>\r\n                {\r\n                    return \"Default post root\";\r\n                });\r\n\r\n                Put(\"/\", args =>\r\n                {\r\n                    return \"Default put root\";\r\n                });\r\n            }\r\n        }\r\n\r\n        public class BasicRouteInvocationsModuleWithHead : NancyModule\r\n        {\r\n            public BasicRouteInvocationsModuleWithHead()\r\n            {\r\n                Get(\"/\", args =>\r\n                {\r\n                    return \"Default get root\";\r\n                });\r\n\r\n                Head(\"/\", args =>\r\n                {\r\n                    return new Response()\r\n                    {\r\n                        StatusCode = HttpStatusCode.OK,\r\n                        ReasonPhrase = \"HEAD!\"\r\n                    };\r\n                });\r\n            }\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_use_head_response_values_for_basic_head_request()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.Module<BasicRouteInvocationsModuleWithHead>();\r\n                with.Configure(env =>\r\n                {\r\n                    env.Routing(explicitHeadRouting: true);\r\n                });\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Head(\"/\");\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.OK, response.StatusCode);\r\n            Assert.Equal(\"text/html\", response.ContentType);\r\n            Assert.Equal(string.Empty, response.Body.AsString());\r\n            Assert.Equal(\"HEAD!\", response.ReasonPhrase);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests.Functional/Tests/ContentNegotiationFixture.cs",
    "content": "namespace Nancy.Tests.Functional.Tests\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Cookies;\r\n    using Nancy.ErrorHandling;\r\n    using Nancy.IO;\r\n    using Nancy.Responses.Negotiation;\r\n    using Nancy.Testing;\r\n    using Nancy.Tests.Functional.Modules;\r\n    using Nancy.Tests.xUnitExtensions;\r\n    using Xunit;\r\n\r\n    public class ContentNegotiationFixture\r\n    {\r\n        [Fact]\r\n        public async Task Should_return_int_value_from_get_route_as_response_with_status_code_set_to_value()\r\n        {\r\n            // Given\r\n            var module = new ConfigurableNancyModule(with =>\r\n            {\r\n                with.Get(\"/int\", (x, m) => 200);\r\n            });\r\n\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.Module(module);\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/int\");\r\n\r\n            // Then\r\n            Assert.Equal((HttpStatusCode)200, response.StatusCode);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_string_value_from_get_route_as_response_with_content_set_as_value()\r\n        {\r\n            // Given\r\n            var module = new ConfigurableNancyModule(with =>\r\n            {\r\n                with.Get(\"/string\", (x, m) => \"hello\");\r\n            });\r\n\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.Module(module);\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/string\");\r\n\r\n            // Then\r\n            Assert.Equal(\"hello\", response.Body.AsString());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_httpstatuscode_value_from_get_route_as_response_with_content_set_as_value()\r\n        {\r\n            // Given\r\n            var module = new ConfigurableNancyModule(with =>\r\n            {\r\n                with.Get(\"/httpstatuscode\", (x, m) => HttpStatusCode.Accepted);\r\n            });\r\n\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.Module(module);\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/httpstatuscode\");\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_action_value_as_response_with_content_set_as_value()\r\n        {\r\n            // Given\r\n            var module = new ConfigurableNancyModule(with =>\r\n            {\r\n                with.Get(\"/action\", (x, m) =>\r\n                {\r\n                    Action<Stream> result = stream =>\r\n                    {\r\n                        var wrapper = new UnclosableStreamWrapper(stream);\r\n                        using (var writer = new StreamWriter(wrapper))\r\n                        {\r\n                            writer.Write(\"Hiya Nancy!\");\r\n                        }\r\n                    };\r\n\r\n                    return result;\r\n                });\r\n            });\r\n\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.Module(module);\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/action\");\r\n\r\n            // Then\r\n            Assert.Equal(\"Hiya Nancy!\", response.Body.AsString());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_add_negotiated_headers_to_response()\r\n        {\r\n            // Given\r\n\r\n            var module = new ConfigurableNancyModule(with =>\r\n            {\r\n                with.Get(\"/headers\", (x, m) =>\r\n                {\r\n                    var context =\r\n                        new NancyContext();\r\n\r\n                    var negotiator =\r\n                        new Negotiator(context);\r\n                    negotiator.WithHeader(\"foo\", \"bar\");\r\n\r\n                    return negotiator;\r\n                });\r\n            });\r\n\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.ResponseProcessor<TestProcessor>();\r\n\r\n                with.Module(module);\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/headers\");\r\n\r\n            // Then\r\n            Assert.True(response.Headers.ContainsKey(\"foo\"));\r\n            Assert.Equal(\"bar\", response.Headers[\"foo\"]);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_set_reason_phrase_on_response()\r\n        {\r\n            // Given\r\n            var module = new ConfigurableNancyModule(with =>\r\n            {\r\n                with.Get(\"/customPhrase\", (x, m) =>\r\n                {\r\n                    var context =\r\n                        new NancyContext();\r\n\r\n                    var negotiator =\r\n                        new Negotiator(context);\r\n                    negotiator.WithReasonPhrase(\"The test is passing!\").WithStatusCode(404);\r\n\r\n                    return negotiator;\r\n                });\r\n            });\r\n\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.StatusCodeHandler<DefaultStatusCodeHandler>();\r\n                with.ResponseProcessor<TestProcessor>();\r\n                with.Module(module);\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/customPhrase\");\r\n\r\n            // Then\r\n            Assert.Equal(\"The test is passing!\", response.ReasonPhrase);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_add_negotiated_content_headers_to_response()\r\n        {\r\n            // Given\r\n            var module = new ConfigurableNancyModule(with =>\r\n            {\r\n                with.Get(\"/headers\", (x, m) =>\r\n                {\r\n                    var context =\r\n                        new NancyContext();\r\n\r\n                    var negotiator =\r\n                        new Negotiator(context);\r\n                    negotiator.WithContentType(\"text/xml\");\r\n\r\n                    return negotiator;\r\n                });\r\n            });\r\n\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.ResponseProcessor<TestProcessor>();\r\n                with.Module(module);\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/headers\");\r\n\r\n            // Then\r\n            Assert.Equal(\"text/xml\", response.Context.Response.ContentType);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_apply_default_accept_when_no_accept_header_sent()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.ResponseProcessor<TestProcessor>();\r\n                with.Module(new ConfigurableNancyModule(x =>\r\n                {\r\n                    x.Get(\"/\", (parameters, module) =>\r\n                    {\r\n                        var context =\r\n                            new NancyContext();\r\n\r\n                        var negotiator =\r\n                            new Negotiator(context);\r\n\r\n                        return negotiator;\r\n                    });\r\n                }));\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/\");\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.OK, response.StatusCode);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_boost_html_priority_if_set_to_the_same_priority_as_others()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.ResponseProcessor<TestProcessor>();\r\n\r\n                with.Module(new ConfigurableNancyModule(x =>\r\n                {\r\n                    x.Get(\"/\", (parameters, module) =>\r\n                    {\r\n                        var context =\r\n                            new NancyContext();\r\n\r\n                        var negotiator =\r\n                            new Negotiator(context);\r\n\r\n                        negotiator.WithAllowedMediaRange(\"application/xml\");\r\n                        negotiator.WithAllowedMediaRange(\"text/html\");\r\n\r\n                        return negotiator;\r\n                    });\r\n                }));\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/\", with =>\r\n            {\r\n                with.Header(\"User-Agent\", \"Mozilla/5.0 (Windows; U; Windows NT 5.1; ru-RU) AppleWebKit/533.19.4 (KHTML, like Gecko) Version/5.0.3 Safari/533.19.4\");\r\n                with.Accept(\"application/xml\", 0.9m);\r\n                with.Accept(\"text/html\", 0.9m);\r\n            });\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.OK, response.StatusCode);\r\n            Assert.True(response.Body.AsString().Contains(\"text/html\"), \"Media type mismatch\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_override_with_extension()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.ResponseProcessor<TestProcessor>();\r\n\r\n                with.Module(new ConfigurableNancyModule(x =>\r\n                {\r\n                    x.Get(\"/test\", (parameters, module) =>\r\n                    {\r\n                        var context =\r\n                            new NancyContext();\r\n\r\n                        var negotiator =\r\n                            new Negotiator(context);\r\n\r\n                        return negotiator;\r\n                    });\r\n                }));\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/test.foo\", with =>\r\n            {\r\n                with.Header(\"User-Agent\", \"Mozilla/5.0 (Windows; U; Windows NT 5.1; ru-RU) AppleWebKit/533.19.4 (KHTML, like Gecko) Version/5.0.3 Safari/533.19.4\");\r\n                with.Accept(\"application/xml\", 0.9m);\r\n                with.Accept(\"text/html\", 0.9m);\r\n            });\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.OK, response.StatusCode);\r\n            Assert.True(response.Body.AsString().Contains(\"foo/bar\"), \"Media type mismatch\");\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_response_with_notacceptable_when_route_does_not_allow_any_of_the_accepted_formats()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.ResponseProcessor<TestProcessor>();\r\n\r\n                with.Module(new ConfigurableNancyModule(x =>\r\n                {\r\n                    x.Get(\"/test\", CreateNegotiatedResponse(config =>\r\n                    {\r\n                        config.WithAllowedMediaRange(\"application/xml\");\r\n                    }));\r\n                }));\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/test\", with =>\r\n            {\r\n                with.Accept(\"foo/bar\", 0.9m);\r\n            });\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_respond_with_notacceptable_when_no_processor_can_process_media_range()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.ResponseProcessor<NullProcessor>();\r\n                with.Module<NegotiationModule>();\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/invalid-view-name\", with => with.Accept(\"foo/bar\"));\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_that_contains_default_model_when_no_media_range_specific_model_was_declared()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.ResponseProcessor<ModelProcessor>();\r\n\r\n                with.Module(new ConfigurableNancyModule(x =>\r\n                {\r\n                    x.Get(\"/\", CreateNegotiatedResponse(config =>\r\n                    {\r\n                        config.WithModel(\"the model\");\r\n                        config.WithAllowedMediaRange(\"test/test\");\r\n                    }));\r\n                }));\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/\", with =>\r\n            {\r\n                with.Accept(\"test/test\", 0.9m);\r\n            });\r\n\r\n            // Then\r\n            Assert.Equal(\"the model\", response.Body.AsString());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_media_range_specific_model_when_declared()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.ResponseProcessor<ModelProcessor>();\r\n\r\n                with.Module(new ConfigurableNancyModule(x =>\r\n                {\r\n                    x.Get(\"/\", CreateNegotiatedResponse(config =>\r\n                    {\r\n                        config.WithModel(\"the model\");\r\n                        config.WithAllowedMediaRange(\"test/test\");\r\n                        config.WithMediaRangeModel(\"test/test\", \"media model\");\r\n                    }));\r\n                }));\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/\", with =>\r\n            {\r\n                with.Accept(\"test/test\", 0.9m);\r\n            });\r\n\r\n            // Then\r\n            Assert.Equal(\"media model\", response.Body.AsString());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_add_vary_accept_header()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.ResponseProcessors(typeof(XmlProcessor), typeof(JsonProcessor), typeof(TestProcessor));\r\n\r\n                with.Module(new ConfigurableNancyModule(x =>\r\n                {\r\n                    x.Get(\"/\", CreateNegotiatedResponse());\r\n                }));\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/\", with => with.Header(\"Accept\", \"application/json\"));\r\n\r\n            // Then\r\n            Assert.True(response.Headers.ContainsKey(\"Vary\"));\r\n            Assert.True(response.Headers[\"Vary\"].Contains(\"Accept\"));\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_add_link_header_for_matching_response_processors()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.ResponseProcessors(typeof(XmlProcessor), typeof(JsonProcessor), typeof(TestProcessor));\r\n\r\n                with.Module(new ConfigurableNancyModule(x =>\r\n                {\r\n                    x.Get(\"/\", CreateNegotiatedResponse());\r\n                }));\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/\");\r\n\r\n            // Then\r\n            var linkHeader = response.Headers[\"Link\"];\n            Assert.True(linkHeader.Contains(@\"</.foo>; rel=\"\"alternate\"\"; type=\"\"foo/bar\"\"\"),\n                        string.Format(\"'{0}' does not contain '{1}'\", linkHeader, @\"</.foo>; rel=\"\"alternate\"\"; type=\"\"foo/bar\"\"\"));\n            Assert.True(linkHeader.Contains(@\"</.json>; rel=\"\"alternate\"\"; type=\"\"application/json\"\"\"),\n                        string.Format(\"'{0}' does not contain '{1}'\", linkHeader, @\"</.json>; rel=\"\"alternate\"\"; type=\"\"application/json\"\"\"));\n            Assert.True(linkHeader.Contains(@\"</.xml>; rel=\"\"alternate\"\"; type=\"\"application/xml\"\"\"),\n                        string.Format(\"'{0}' does not contain '{1}'\", linkHeader, @\"</.xml>; rel=\"\"alternate\"\"; type=\"\"application/xml\"\"\"));\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_preserve_existing_link_header()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.ResponseProcessors(typeof(XmlProcessor), typeof(JsonLdProcessor));\r\n\r\n                with.Module(new ConfigurableNancyModule(x =>\r\n                {\r\n                    x.Get(\"/\", CreateNegotiatedResponse());\r\n                }));\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/\");\r\n\r\n            // Then\r\n            var linkHeader = response.Headers[\"Link\"];\n            Assert.True(linkHeader.Contains(@\"</context.jsonld>; rel=\"\"http://www.w3.org/ns/json-ld#context\"\"; type=\"\"application/ld+json\"\"\"),\n                        string.Format(\"'{0}' does not contain '{1}'\", linkHeader, @\"</context.jsonld>; rel=\"\"http://www.w3.org/ns/json-ld#context\"\"; type=\"\"application/ld+json\"\"\"));\n            Assert.True(linkHeader.Contains(@\"</.xml>; rel=\"\"alternate\"\"; type=\"\"application/xml\"\"\"),\n                        string.Format(\"'{0}' does not contain '{1}'\", linkHeader, @\"</.xml>; rel=\"\"alternate\"\"; type=\"\"application/xml\"\"\"));\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_set_negotiated_status_code_to_response_when_set_as_integer()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.ResponseProcessor<TestProcessor>();\r\n\r\n                with.Module(new ConfigurableNancyModule(x =>\r\n                {\r\n                    x.Get(\"/\", CreateNegotiatedResponse(config =>\r\n                    {\r\n                        config.WithStatusCode(507);\r\n                    }));\r\n                }));\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/\", with =>\r\n            {\r\n                with.Accept(\"test/test\", 0.9m);\r\n            });\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.InsufficientStorage, response.StatusCode);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_set_negotiated_status_code_to_response_when_set_as_httpstatuscode()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.ResponseProcessor<TestProcessor>();\r\n\r\n                with.Module(new ConfigurableNancyModule(x =>\r\n                {\r\n                    x.Get(\"/\", CreateNegotiatedResponse(config =>\r\n                    {\r\n                        config.WithStatusCode(HttpStatusCode.InsufficientStorage);\r\n                    }));\r\n                }));\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/\", with =>\r\n            {\r\n                with.Accept(\"test/test\", 0.9m);\r\n            });\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.InsufficientStorage, response.StatusCode);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_set_negotiated_cookies_to_response()\r\n        {\r\n            // Given\r\n            var negotiatedCookie =\r\n                new NancyCookie(\"test\", \"test\");\r\n\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.ResponseProcessor<TestProcessor>();\r\n\r\n                with.Module(new ConfigurableNancyModule(x =>\r\n                {\r\n                    x.Get(\"/\", CreateNegotiatedResponse(config =>\r\n                    {\r\n                        config.WithCookie(negotiatedCookie);\r\n                    }));\r\n                }));\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/\", with =>\r\n            {\r\n                with.Accept(\"test/test\", 0.9m);\r\n            });\r\n\r\n            // Then\r\n            Assert.Same(negotiatedCookie, response.Cookies.First());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_throw_exception_if_view_location_fails()\r\n        {\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.ResponseProcessor<ViewProcessor>();\r\n\r\n                with.Module(new ConfigurableNancyModule(x => x.Get(\"/FakeModuleInvalidViewName\", CreateNegotiatedResponse(neg => neg.WithView(\"blahblahblah\")))));\r\n            });\r\n\r\n            // When\r\n            var result = await RecordAsync.Exception(() => browser.Get(\r\n                        \"/FakeModuleInvalidViewName\", with =>\r\n                            { with.Accept(\"text/html\", 1.0m); })\r\n                );\r\n\r\n            // Then\r\n            Assert.NotNull(result);\r\n            Assert.Contains(\"Unable to locate requested view\", result.ToString());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_use_next_processor_if_processor_returns_null()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with =>\r\n                {\r\n                    with.ResponseProcessors(typeof(NullProcessor), typeof(TestProcessor));\r\n\r\n                    with.Module(new ConfigurableNancyModule(x =>\r\n                    {\r\n                        x.Get(\"/test\", CreateNegotiatedResponse(config =>\r\n                        {\r\n                            config.WithAllowedMediaRange(\"application/xml\");\r\n                        }));\r\n                    }));\r\n                });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/test\", with =>\r\n            {\r\n                with.Accept(\"application/xml\", 0.9m);\r\n            });\r\n\r\n            // Then\r\n            var bodyResult = response.Body.AsString();\r\n            Assert.True(bodyResult.StartsWith(\"application/xml\"), string.Format(\"Body should have started with 'application/xml' but was actually '{0}'\", bodyResult));\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"application/xhtml+xml; profile=\\\"http://www.wapforum. org/xhtml\\\"\")]\r\n        [InlineData(\"application/xhtml+xml; q=1; profile=\\\"http://www.wapforum. org/xhtml\\\"\")]\r\n        public async Task Should_not_throw_exception_because_of_uncommon_accept_header(string header)\r\n        {\r\n            // Given\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.ResponseProcessors(typeof(XmlProcessor), typeof(JsonProcessor), typeof(TestProcessor));\r\n\r\n                with.Module(new ConfigurableNancyModule(x =>\r\n                {\r\n                    x.Get(\"/\", CreateNegotiatedResponse());\r\n                }));\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/\", with =>\r\n            {\r\n                with.Header(\"Accept\", header);\r\n            });\r\n\r\n            // Then\r\n            Assert.Equal((HttpStatusCode)200, response.StatusCode);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_try_and_serve_view_with_invalid_name()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with => with.Module<NegotiationModule>());\r\n\r\n            // When\r\n            var result = await RecordAsync.Exception(() => browser.Get(\"/invalid-view-name\"));\r\n\r\n            // Then\r\n            Assert.True(result.ToString().Contains(\"Unable to locate requested view\"));\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_response_negotiated_based_on_media_range()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with => with.Module<NegotiationModule>());\r\n\r\n            // When\r\n            var result = await browser.Get(\"/negotiate\", with =>\r\n            {\r\n                with.Accept(\"text/html\");\r\n            });\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.SeeOther, result.StatusCode);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Can_negotiate_in_status_code_handler()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with => with.StatusCodeHandler<NotFoundStatusCodeHandler>());\r\n\r\n            // When\r\n            var result = await browser.Get(\"/not-found\", with => with.Accept(\"application/json\"));\r\n\r\n            var response = result.Body.DeserializeJson<NotFoundStatusCodeHandlerResult>();\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.OK, result.StatusCode);\r\n            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);\r\n            Assert.Equal(\"Not Found.\", response.Message);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Can_negotiate_in_error_pipeline()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with => with.Module<ThrowingModule>());\r\n\r\n            // When\r\n            var jsonResult = await browser.Get(\"/\", with => with.Accept(\"application/json\"));\r\n            var xmlResult = await browser.Get(\"/\", with => with.Accept(\"application/xml\"));\r\n\r\n            var jsonResponse = jsonResult.Body.DeserializeJson<ThrowingModule.Error>();\r\n            var xmlResponse = xmlResult.Body.DeserializeXml<ThrowingModule.Error>();\r\n\r\n            // Then\r\n            Assert.Equal(\"Oh noes!\", jsonResponse.Message);\r\n            Assert.Equal(\"Oh noes!\", xmlResponse.Message);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_negotiated_not_found_response_when_accept_header_is_html()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with => with.StatusCodeHandler<DefaultStatusCodeHandler>());\r\n            var contentType = \"text/html\";\r\n\r\n            // When\r\n            var result = await browser.Get(\"/not-found\", with => with.Accept(contentType));\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.NotFound, result.StatusCode);\r\n            Assert.Equal(contentType, result.ContentType);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_negotiated_not_found_response_when_accept_header_is_json()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with => with.StatusCodeHandler<DefaultStatusCodeHandler>());\r\n            var contentType = \"application/json\";\r\n\r\n            // When\r\n            var result = await browser.Get(\"/not-found\", with => with.Accept(contentType));\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.NotFound, result.StatusCode);\r\n            Assert.Equal(string.Format(\"{0}; charset=utf-8\", contentType), result.ContentType);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_negotiated_not_found_response_when_accept_header_is_xml()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with => with.StatusCodeHandler<DefaultStatusCodeHandler>());\r\n            var contentType = \"application/xml\";\r\n\r\n            // When\r\n            var result = await browser.Get(\"/not-found\", with => with.Accept(contentType));\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.NotFound, result.StatusCode);\r\n            Assert.Equal(contentType, result.ContentType);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_set_DefaultModel_when_null_was_returned_from_action()\r\n        {\r\n            // Given\r\n            var module = new ConfigurableNancyModule(with =>\r\n            {\r\n                with.Get(\"/null\", (x, m) => (object)null);\r\n            });\r\n\r\n            module.After += context => \r\n            {\r\n                if (context.NegotiationContext.DefaultModel == null)\r\n                {\r\n                    context.Response = new NotFoundResponse();\r\n                }\r\n            };\r\n\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.Module(module);\r\n            });\r\n\r\n            // When\r\n            var response = await browser.Get(\"/null\");\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);\r\n        }\r\n\r\n        private static Func<dynamic, NancyModule, Negotiator> CreateNegotiatedResponse(Action<Negotiator> action = null)\r\n        {\r\n            return (parameters, module) =>\r\n            {\r\n                var negotiator = new Negotiator(module.Context);\r\n\r\n                if (action != null)\r\n                {\r\n                    action.Invoke(negotiator);\r\n                }\r\n\r\n                return negotiator;\r\n            };\r\n        }\r\n\r\n        /// <summary>\r\n        /// Test response processor that will accept any type\r\n        /// and put the content type and model type into the\r\n        /// response body for asserting against.\r\n        /// Hacky McHackmeister but it works :-)\r\n        /// </summary>\r\n        public class TestProcessor : IResponseProcessor\r\n        {\r\n            private const string ResponseTemplate = \"{0}\\n{1}\";\r\n\r\n            public IEnumerable<Tuple<string, MediaRange>> ExtensionMappings\r\n            {\r\n                get\r\n                {\r\n                    yield return new Tuple<string, MediaRange>(\"foo\", \"foo/bar\");\r\n                }\r\n            }\r\n\r\n            public ProcessorMatch CanProcess(MediaRange requestedMediaRange, dynamic model, NancyContext context)\r\n            {\r\n                return new ProcessorMatch\r\n                {\r\n                    RequestedContentTypeResult = MatchResult.DontCare,\r\n                    ModelResult = MatchResult.DontCare\r\n                };\r\n            }\r\n\r\n            public Response Process(MediaRange requestedMediaRange, dynamic model, NancyContext context)\r\n            {\r\n                return string.Format(ResponseTemplate, requestedMediaRange, model == null ? \"None\" : model.GetType());\r\n            }\r\n        }\r\n\r\n        public class NullProcessor : IResponseProcessor\r\n        {\r\n            public IEnumerable<Tuple<string, MediaRange>> ExtensionMappings\r\n            {\r\n                get\r\n                {\r\n                    yield break;\r\n                }\r\n            }\r\n\r\n            public ProcessorMatch CanProcess(MediaRange requestedMediaRange, dynamic model, NancyContext context)\r\n            {\r\n                return new ProcessorMatch\r\n                {\r\n                    RequestedContentTypeResult = MatchResult.ExactMatch,\r\n                    ModelResult = MatchResult.ExactMatch\r\n                };\r\n            }\r\n\r\n            public Response Process(MediaRange requestedMediaRange, dynamic model, NancyContext context)\r\n            {\r\n                return null;\r\n            }\r\n        }\r\n\r\n        public class ModelProcessor : IResponseProcessor\r\n        {\r\n            public IEnumerable<Tuple<string, MediaRange>> ExtensionMappings\r\n            {\r\n                get\r\n                {\r\n                    yield return new Tuple<string, MediaRange>(\"foo\", \"foo/bar\");\r\n                }\r\n            }\r\n\r\n            public ProcessorMatch CanProcess(MediaRange requestedMediaRange, dynamic model, NancyContext context)\r\n            {\r\n                return new ProcessorMatch\r\n                {\r\n                    RequestedContentTypeResult = MatchResult.DontCare,\r\n                    ModelResult = MatchResult.DontCare\r\n                };\r\n            }\r\n\r\n            public Response Process(MediaRange requestedMediaRange, dynamic model, NancyContext context)\r\n            {\r\n                return (string)model;\r\n            }\r\n        }\r\n\r\n        public class NegotiationModule : NancyModule\r\n        {\r\n            public NegotiationModule()\r\n            {\r\n                Get(\"/invalid-view-name\", args =>\r\n                {\r\n                    return this.GetModel();\r\n                });\r\n\r\n                Get(\"/negotiate\", args =>\r\n                {\r\n                    return Negotiate\r\n                        .WithMediaRangeResponse(\"text/html\", Response.AsRedirect(\"/\"))\r\n                        .WithMediaRangeModel(\"application/json\", new { Name = \"Nancy\" });\r\n                });\r\n            }\r\n\r\n            private IEnumerable<Foo> GetModel()\r\n            {\r\n                yield return new Foo();\r\n            }\r\n\r\n            public class Foo\r\n            {\r\n            }\r\n        }\r\n\r\n        private class NotFoundStatusCodeHandler : IStatusCodeHandler\r\n        {\r\n            private readonly IResponseNegotiator responseNegotiator;\r\n\r\n            public NotFoundStatusCodeHandler(IResponseNegotiator responseNegotiator)\r\n            {\r\n                this.responseNegotiator = responseNegotiator;\r\n            }\r\n\r\n            public bool HandlesStatusCode(HttpStatusCode statusCode, NancyContext context)\r\n            {\r\n                return statusCode == HttpStatusCode.NotFound;\r\n            }\r\n\r\n            public void Handle(HttpStatusCode statusCode, NancyContext context)\r\n            {\r\n                var error = new NotFoundStatusCodeHandlerResult\r\n                {\r\n                    StatusCode = statusCode,\r\n                    Message = \"Not Found.\"\r\n                };\r\n\r\n                context.Response = this.responseNegotiator.NegotiateResponse(error, context);\r\n            }\r\n        }\r\n\r\n        private class NotFoundStatusCodeHandlerResult\r\n        {\r\n            public HttpStatusCode StatusCode { get; set; }\r\n\r\n            public string Message { get; set; }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests.Functional/Tests/CookieFixture.cs",
    "content": "﻿namespace Nancy.Tests.Functional.Tests\r\n{\r\n    using System.Threading.Tasks;\r\n    using Modules;\r\n\r\n    using Testing;\r\n    using Xunit;\r\n\r\n    public class CookieFixture\r\n    {\r\n        [Fact]\r\n        public async Task Cookie_should_decode_value_correctly()\r\n        {\r\n            // Given\r\n            var browser = new Browser(with => with.Module<CookieModule>());\r\n\r\n            // When\r\n            await browser.Get(\"/setcookie\");\r\n                \r\n            var result = await browser.Get(\"/getcookie\");\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.OK, result.StatusCode);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests.Functional/Tests/JsonLdProcessor.cs",
    "content": "﻿namespace Nancy.Tests.Functional.Tests\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.Linq;\r\n    using Nancy.Responses.Negotiation;\r\n\r\n    public class JsonLdProcessor : IResponseProcessor\r\n    {\r\n        private readonly ISerializer serializer;\r\n\r\n        public JsonLdProcessor(IEnumerable<ISerializer> serializers)\r\n        {\r\n            this.serializer = serializers.FirstOrDefault(x => x.CanSerialize(\"application/json\"));\r\n        }\r\n\r\n        public IEnumerable<Tuple<string, MediaRange>> ExtensionMappings\r\n        {\r\n            get { return new[] { new Tuple<string, MediaRange>(\"json\", new MediaRange(\"application/json\")) }; }\r\n        }\r\n\r\n        public ProcessorMatch CanProcess(MediaRange requestedMediaRange, dynamic model, NancyContext context)\r\n        {\r\n            return new ProcessorMatch\r\n            {\r\n                ModelResult = MatchResult.DontCare,\r\n                RequestedContentTypeResult = MatchResult.DontCare\r\n            };\r\n        }\r\n\r\n        public Response Process(MediaRange requestedMediaRange, dynamic model, NancyContext context)\r\n        {\r\n            return new Response\r\n            {\r\n                ContentType = \"application/json\",\r\n                Contents = stream => this.serializer.Serialize(\"application/json\", model, stream),\r\n                StatusCode = HttpStatusCode.OK\r\n            }.WithHeader(\"Link\", \"</context.jsonld>; rel=\\\"http://www.w3.org/ns/json-ld#context\\\"; type=\\\"application/ld+json\\\"\");\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests.Functional/Tests/JsonpTests.cs",
    "content": "﻿namespace Nancy.Tests.Functional.Tests\r\n{\r\n    using System;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Testing;\r\n    using Nancy.Tests.Functional.Modules;\r\n\r\n    using Xunit;\r\n\r\n    public class JsonpTests\r\n    {\r\n        private readonly INancyBootstrapper bootstrapper;\r\n\r\n        private readonly Browser browser;\r\n\r\n        public JsonpTests()\r\n        {\r\n            this.bootstrapper = new ConfigurableBootstrapper(\r\n                    configuration =>\r\n                        {\r\n                            configuration.Modules(new Type[] { typeof(JsonpTestModule) });\r\n                        });\r\n\r\n            this.browser = new Browser(bootstrapper);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Ensure_that_Jsonp_hook_does_not_affect_normal_responses()\r\n        {\r\n            var result = await browser.Get(\"/test/string\", c =>\r\n            {\r\n                c.HttpRequest();\r\n            });\r\n\r\n            Assert.Equal(HttpStatusCode.OK, result.StatusCode);\r\n            Assert.Equal(\"Normal Response\", result.Body.AsString());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Ensure_that_dynamic_string_parameters_are_serialized_as_strings()\r\n        {\r\n            var result = await browser.Get(\"/test/something\", c => c.HttpRequest());\r\n            var actual = result.Body.AsString();\r\n\r\n            Assert.Equal(@\"{\"\"name\"\":\"\"something\"\"}\", actual);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Ensure_that_Jsonp_hook_does_not_affect_a_normal_json_response()\r\n        {\r\n            var result = await browser.Get(\"/test/json\", c =>\r\n            {\r\n                c.HttpRequest();\r\n            });\r\n\r\n            Assert.Equal(HttpStatusCode.OK, result.StatusCode);\r\n            Assert.Equal(\"true\", result.Body.AsString());\r\n            Assert.Equal(\"application/json; charset=utf-8\", result.Context.Response.ContentType);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Ensure_that_Jsonp_hook_should_pad_a_json_response_when_callback_is_present()\r\n        {\r\n            var result = await browser.Get(\"/test/json\", with =>\r\n            {\r\n                with.HttpRequest();\r\n                with.Query(\"callback\", \"myCallback\");\r\n            });\r\n\r\n            Assert.Equal(HttpStatusCode.OK, result.StatusCode);\r\n            Assert.Equal(\"myCallback(true);\", result.Body.AsString());\r\n            Assert.Equal(\"application/javascript; charset=utf-8\", result.Context.Response.ContentType);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests.Functional/Tests/ManualStaticContentTests.cs",
    "content": "﻿namespace Nancy.Tests.Functional.Tests\r\n{\r\n    using System;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Testing;\r\n\r\n    using Xunit;\r\n\r\n    public class ManualStaticContentTests\r\n    {\r\n        private readonly INancyBootstrapper bootstrapper;\r\n\r\n        private readonly Browser browser;\r\n\r\n        public ManualStaticContentTests()\r\n        {\r\n            this.bootstrapper = new ConfigurableBootstrapper(\r\n                    configuration =>\r\n                        {\r\n                            configuration.ApplicationStartup((c, p) => StaticContent.Enable(p));\r\n                            configuration.Modules(ArrayCache.Empty<Type>());\r\n                        });\r\n\r\n            this.browser = new Browser(bootstrapper);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_serve_valid_static_content()\r\n        {\r\n            var response = await browser.Get(\r\n                @\"/Content/smiley.png\", \r\n                with =>\r\n                    {\r\n                        with.HttpRequest();\r\n                    });\r\n\r\n            Assert.Equal(HttpStatusCode.OK, response.StatusCode);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_404_if_content_not_found()\r\n        {\r\n            var response = await browser.Get(\r\n                @\"/Content/smiley2.png\",\r\n                with =>\r\n                {\r\n                    with.HttpRequest();\r\n                });\r\n\r\n            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_be_case_insensitive()\r\n        {\r\n            var response = await browser.Get(\r\n                @\"/cOntent/smiley.png\",\r\n                with =>\r\n                {\r\n                    with.HttpRequest();\r\n                });\r\n\r\n            Assert.Equal(HttpStatusCode.OK, response.StatusCode);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_allow_escaping_from_the_site_root()\r\n        {\r\n            var response = await browser.Get(\r\n                @\"/Content/../../../Tests/StaticContentTests.cs\",\r\n                with =>\r\n                {\r\n                    with.HttpRequest();\r\n                });\r\n\r\n            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_not_allow_escaping_from_the_content_root()\r\n        {\r\n            var response = await browser.Get(\r\n                @\"/Content/../hidden.txt\",\r\n                with =>\r\n                {\r\n                    with.HttpRequest();\r\n                });\r\n\r\n            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests.Functional/Tests/MethodRewriteFixture.cs",
    "content": "namespace Nancy.Tests.Functional.Tests\r\n{\r\n    using System;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Testing;\r\n    using Nancy.Tests.xUnitExtensions;\r\n    using Xunit;\r\n    using Xunit.Extensions;\r\n\r\n    public class MethodRewriteFixture\r\n    {\r\n        private readonly Browser browser;\r\n\r\n        public MethodRewriteFixture()\r\n        {\r\n            this.browser = new Browser(with =>\r\n            {\r\n                with.Module<MethodRewriteModule>();\r\n            });\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"delete\")]\r\n        [InlineData(\"dElEtE\")]\r\n        [InlineData(\"DELETE\")]\r\n        public async Task Should_rewrite_method_when_method_form_input_is_provided(string method)\r\n        {\r\n            var response = await this.browser.Post(\"/\", with =>\r\n            {\r\n                with.FormValue(\"_method\", method);\r\n            });\r\n\r\n            Assert.Equal(\"Delete route\", response.Body.AsString());\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"delete\")]\r\n        [InlineData(\"dElEtE\")]\r\n        [InlineData(\"DELETE\")]\r\n        public async Task Should_rewrite_method_when_x_http_method_override_form_input_is_provided(string method)\r\n        {\r\n            var response = await this.browser.Post(\"/\", with =>\r\n            {\r\n                with.FormValue(\"X-HTTP-Method-Override\", method);\r\n            });\r\n\r\n            Assert.Equal(\"Delete route\", response.Body.AsString());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_rewrite_method_when_x_http_method_header_input_is_provided()\r\n        {\r\n            var response = await this.browser.Post(\"/\", with =>\r\n            {\r\n                with.Header(\"X-HTTP-Method-Override\", \"DELETE\");\r\n            });\r\n\r\n            Assert.Equal(\"Delete route\", response.Body.AsString());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_throw_invalidoperationexception_when_both_method_and_x_http_method_override_form_inputs_are_specified()\r\n        {\r\n            await AssertAsync.Throws<InvalidOperationException>(async () => await this.browser.Post(\"/\", with =>\r\n            {\r\n                with.FormValue(\"_method\", \"DELETE\");\r\n                with.FormValue(\"X-HTTP-Method-Override\", \"DELETE\");\r\n            }));\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_throw_invalidoperationexception_when_both_x_http_method_override_form_input_and_header_are_specified()\r\n        {\r\n            await AssertAsync.Throws<InvalidOperationException>(async () => await this.browser.Post(\"/\", with =>\r\n            {\r\n                with.FormValue(\"X-HTTP-Method-Override\", \"DELETE\");\r\n                with.Header(\"X-HTTP-Method-Override\", \"DELETE\");\r\n            }));\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_throw_invalidoperationexception_when_both_method_inputs_and_x_http_method_override_header_are_specified()\r\n        {\r\n            await AssertAsync.Throws<InvalidOperationException>(async () => await this.browser.Post(\"/\", with =>\r\n            {\r\n                with.FormValue(\"_method\", \"DELETE\");\r\n                with.Header(\"X-HTTP-Method-Override\", \"DELETE\");\r\n            }));\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_throw_invalidoperationexception_when_both_method_input_and_x_http_method_override_input_and_header_are_specified()\r\n        {\r\n            await AssertAsync.Throws<InvalidOperationException>(async () => await this.browser.Post(\"/\", with =>\r\n            {\r\n                with.FormValue(\"_method\", \"DELETE\");\r\n                with.FormValue(\"X-HTTP-Method-Override\", \"DELETE\");\r\n                with.Header(\"X-HTTP-Method-Override\", \"DELETE\");\r\n            }));\r\n        }\r\n    }\r\n\r\n    public class MethodRewriteModule : NancyModule\r\n    {\r\n        public MethodRewriteModule()\r\n        {\r\n            Delete(\"/\", args =>\r\n            {\r\n                return \"Delete route\";\r\n            });\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests.Functional/Tests/ModelBindingTests.cs",
    "content": "﻿namespace Nancy.Tests.Functional.Tests\r\n{\r\n    using System.Collections.Generic;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.ModelBinding;\r\n    using Nancy.Testing;\r\n\r\n    using Xunit;\r\n\r\n    public class ModelBindingFixture\r\n    {\r\n        private readonly INancyBootstrapper bootstrapper;\r\n        private readonly Browser browser;\r\n\r\n        public ModelBindingFixture()\r\n        {\r\n            this.bootstrapper =\r\n                new ConfigurableBootstrapper(with => with.Modules(new[] { typeof(ModelBindingModule), typeof(MixedSourceModelBindingModule) }));\r\n\r\n            this.browser = new Browser(bootstrapper);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_be_able_to_modelbind_json_content_to_list()\r\n        {\r\n            // Given\r\n            const string body = \"[{ \\\"key1\\\": \\\"value1\\\" , \\\"key2\\\": \\\"value2\\\"},{ \\\"key1\\\": \\\"value1\\\" , \\\"key2\\\": \\\"value2\\\"}, { \\\"key1\\\": \\\"value1\\\" , \\\"key2\\\": \\\"value2\\\"}]\";\r\n\r\n            // When\r\n            var result = await this.browser.Post(\"/jsonlist\", with => with.Body(body, \"application/json\"));\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.OK, result.StatusCode);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_be_able_to_bind_body_and_other_sources_separately()\r\n        {\r\n            // Given\r\n            const string body = \"{ \\\"key1\\\": \\\"body\\\" , \\\"key2\\\": \\\"value2\\\"}\";\r\n\r\n            // When\r\n            var result = await this.browser.Put(\"/foo/param\", with => with.Body(body, \"application/json\"));\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.OK, result.StatusCode);\r\n        }\r\n    }\r\n\r\n    public class ModelBindingModule : NancyModule\r\n    {\r\n        public ModelBindingModule()\r\n        {\r\n            Post(\"/jsonlist\", args =>\r\n            {\r\n                var model = this.Bind<List<MyModel>>();\r\n\r\n                return (model.Count == 3) ?\r\n                    HttpStatusCode.OK :\r\n                    HttpStatusCode.InternalServerError;\r\n            });\r\n        }\r\n    }\r\n\r\n    public class MixedSourceModelBindingModule : NancyModule\r\n    {\r\n        public MixedSourceModelBindingModule()\r\n        {\r\n            Put(\"/foo/{key1}\", args =>\r\n            {\r\n                var bodyModel = this.Bind<MyModel>(new BindingConfig { BodyOnly = true });\r\n                var paramModel = this.Bind<ParamModel>();\r\n\r\n                return (bodyModel.key1 != paramModel.key1) ?\r\n                    HttpStatusCode.OK :\r\n                    HttpStatusCode.InternalServerError;\r\n            });\r\n        }\r\n    }\r\n\r\n    public class ParamModel\r\n    {\r\n        public string key1 { get; set; }\r\n    }\r\n\r\n    public class MyModel\r\n    {\r\n        public string key1 { get; set; }\r\n        public string key2 { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests.Functional/Tests/PartialViewTests.cs",
    "content": "﻿#if !CORE\r\nnamespace Nancy.Tests.Functional.Tests\r\n{\r\n    using System;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Testing;\r\n    using Nancy.Tests.Functional.Modules;\r\n    using Nancy.Tests.xUnitExtensions;\r\n    using Nancy.ViewEngines;\r\n    using Xunit;\r\n\r\n    public class PartialViewTests\r\n    {\r\n        private readonly INancyBootstrapper bootstrapper;\r\n\r\n        private readonly Browser browser;\r\n\r\n        public PartialViewTests()\r\n        {\r\n            this.bootstrapper = new ConfigurableBootstrapper(\r\n                    configuration => configuration.Modules(typeof(RazorTestModule)));\r\n\r\n            this.browser = new Browser(bootstrapper);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task When_Using_Partial_View_Then_First_Index_Of_ViewStart_Should_Equal_Last_Index()\r\n        {\r\n            // Given\r\n            // When\r\n            var response = await browser.Get(\r\n                @\"/razor-viewbag\",\r\n                with =>\r\n                {\r\n                    with.HttpRequest();\r\n                });\r\n\r\n            // Then\r\n            var body = response.Body.AsString();\r\n\r\n            var firstIndex = body.IndexOf(@\"Hello World, this is the View Start...\", StringComparison.Ordinal);\r\n            var lastIndex = body.LastIndexOf(@\"Hello World, this is the View Start...\", StringComparison.Ordinal);\r\n\r\n            // If the index is not the same then the string occurs twice...\r\n            Assert.Equal(firstIndex, lastIndex);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task When_Partial_View_Could_Not_Be_Found_An_Meaningful_Exception_Should_Be_Thrown()\r\n        {\r\n            var ex = await RecordAsync.Exception(async () =>\r\n            {\r\n                var response = await this.browser.Get(@\"/razor-partialnotfound\");\r\n\r\n                response.Body.AsString();\r\n            });\r\n\r\n            Assert.IsType<ViewNotFoundException>(ex.GetBaseException());\r\n        }\r\n    }\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "test/Nancy.Tests.Functional/Tests/PerRouteAuthFixture.cs",
    "content": "﻿namespace Nancy.Tests.Functional.Tests\r\n{\r\n    using System.Linq;\r\n    using System.Security.Claims;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Testing;\r\n    using Nancy.Tests.Functional.Modules;\r\n\r\n    using Xunit;\r\n\r\n    public class PerRouteAuthFixture\r\n    {\r\n        [Fact]\r\n        public async Task Should_allow_access_to_unsecured_route()\r\n        {\r\n            var browser = new Browser(with => with.Module<PerRouteAuthModule>());\r\n\r\n            var result = await browser.Get(\"/nonsecured\");\r\n\r\n            Assert.Equal(HttpStatusCode.OK, result.StatusCode);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_protect_secured_route()\r\n        {\r\n            var browser = new Browser(with => with.Module<PerRouteAuthModule>());\r\n\r\n            var result = await browser.Get(\"/secured\");\r\n\r\n            Assert.Equal(HttpStatusCode.Unauthorized, result.StatusCode);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_deny_if_claims_wrong()\r\n        {\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.RequestStartup((t, p, c) => c.CurrentUser = CreateFakeUser(\"test2\"));\r\n                with.Module<PerRouteAuthModule>();\r\n            });\r\n\r\n            var result = await browser.Get(\"/requiresclaims\");\r\n\r\n            Assert.Equal(HttpStatusCode.Forbidden, result.StatusCode);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_allow_if_claims_correct()\r\n        {\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.RequestStartup((t, p, c) => c.CurrentUser = CreateFakeUser(\"test\", \"test2\"));\r\n                with.Module<PerRouteAuthModule>();\r\n            });\r\n\r\n            var result = await browser.Get(\"/requiresclaims\");\r\n\r\n            Assert.Equal(HttpStatusCode.OK, result.StatusCode);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_deny_if_anyclaims_not_found()\r\n        {\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.RequestStartup((t, p, c) => c.CurrentUser = CreateFakeUser(\"test3\"));\r\n                with.Module<PerRouteAuthModule>();\r\n            });\r\n\r\n            var result = await browser.Get(\"/requiresanyclaims\");\r\n\r\n            Assert.Equal(HttpStatusCode.Forbidden, result.StatusCode);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_allow_if_anyclaim_found()\r\n        {\r\n            var browser = new Browser(with =>\r\n            {\r\n                with.RequestStartup((t, p, c) => c.CurrentUser = CreateFakeUser(\"test2\"));\r\n                with.Module<PerRouteAuthModule>();\r\n            });\r\n\r\n            var result = await browser.Get(\"/requiresanyclaims\");\r\n\r\n            Assert.Equal(HttpStatusCode.OK, result.StatusCode);\r\n        }\r\n\r\n        private static ClaimsPrincipal CreateFakeUser(params string[] claimTypes)\r\n        {\r\n            var claims = claimTypes.Select(claimType => new Claim(claimType, string.Empty)).ToList();\r\n            claims.Add(new Claim(ClaimTypes.NameIdentifier, \"user\"));\r\n\r\n            return new ClaimsPrincipal(new ClaimsIdentity(claims, \"test\"));\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Tests.Functional/Tests/RouteConstraintTests.cs",
    "content": "﻿namespace Nancy.Tests.Functional.Tests\r\n{\r\n    using System;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Routing.Constraints;\r\n    using Nancy.Testing;\r\n    using Xunit;\r\n\r\n    public class RouteConstraintTests\r\n    {\r\n        private readonly INancyBootstrapper bootstrapper;\r\n        private readonly Browser browser;\r\n        public static bool Invoked { get; set; }\r\n\r\n        public RouteConstraintTests()\r\n        {\r\n            Invoked = false;\r\n            this.bootstrapper = new ConfigurableBootstrapper(\r\n                configuration =>\r\n                {\r\n                    configuration.ApplicationStartup((c, p) => { });\r\n                    configuration.Modules(new Type[] { typeof(RouteConstraintsModule) });\r\n                    configuration.RouteSegmentConstraints(new[] { typeof(UltimateRouteSegmentConstraint), typeof(VersionRouteSegmentConstraint) });\r\n                });\r\n            this.browser = new Browser(this.bootstrapper);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task multiple_parameters_per_segment_should_support_constraints()\r\n        {\r\n            // Given\r\n            const string url = @\"/42...42\";\r\n            // When\r\n            var response = await this.browser.Get(url, with => { with.HttpRequest(); });\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.OK, response.StatusCode);\r\n            Assert.True(Invoked);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task versionsegmentrouteconstraint_should_match_on_version_numbers_on_segment_with_multiple_parameters()\r\n        {\r\n            // Given\r\n            const string url = @\"/4.1.2...4.1.5\";\r\n            // When\r\n            var response = await this.browser.Get(url, with => { with.HttpRequest(); with.Accept(\"application/json\");});\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.OK, response.StatusCode);\r\n            Assert.Equal(\"{\\\"left\\\":\\\"4.1.2\\\",\\\"right\\\":\\\"4.1.5\\\"}\", response.Body.AsString());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task versionsegmentrouteconstraint_should_match_on_valid_version_number()\r\n        {\r\n            // Given\r\n            const string url = @\"/version/4.1.2\";\r\n            // When\r\n            var response = await this.browser.Get(url, with => { with.HttpRequest(); with.Accept(\"application/json\"); });\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.OK, response.StatusCode);\r\n            Assert.Equal(\"{\\\"versionNumber\\\":\\\"4.1.2\\\"}\", response.Body.AsString());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task versionsegmentrouteconstraint_should_not_match_on_invalid_version_number()\r\n        {\r\n            // Given\r\n            const string url = @\"/version/4.1.\";\r\n            // When\r\n            var response = await this.browser.Get(url, with => { with.HttpRequest(); with.Accept(\"application/json\"); });\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.OK, response.StatusCode);\r\n            Assert.Equal(\"{\\\"invalidVersionNumber\\\":\\\"4.1.\\\"}\", response.Body.AsString());\r\n        }\r\n\r\n        public class UltimateRouteSegmentConstraint : RouteSegmentConstraintBase<int>\r\n        {\r\n            public override string Name\r\n            {\r\n                get { return \"correctanswer\"; }\r\n            }\r\n\r\n            protected override bool TryMatch(string constraint, string segment, out int matchedValue)\r\n            {\r\n                Invoked = true;\r\n                if (int.TryParse(segment, out matchedValue))\r\n                {\r\n                    return matchedValue == 42;\r\n                }\r\n                return false;\r\n            }\r\n        }\r\n    }\r\n    public class RouteConstraintsModule : NancyModule\r\n    {\r\n        public RouteConstraintsModule()\r\n        {\r\n            Get(\"/{left:correctanswer}...{right:correctanswer}\", args =>\r\n            {\r\n                return HttpStatusCode.OK;\r\n            });\r\n\r\n            // For testing VersionSegmentRouteConstraint\r\n            Get(\"/{left:version}...{right:version}\", args =>\r\n            {\r\n                return new { args.left, args.right};\r\n            });\r\n\r\n            // For testing VersionSegmentRouteConstraint\r\n            Get(\"/version/{versionNumber:version}\", args => new { versionNumber = args.versionNumber.ToString() });\r\n\r\n            // For testing VersionSegmentRouteConstraint - fallback for invalid version number\r\n            Get(\"/version/{invalidVersionNumber}\", args => new { args.invalidVersionNumber });\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests.Functional/Tests/SerializeTests.cs",
    "content": "﻿namespace Nancy.Tests.Functional.Tests\r\n{\r\n    using System;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Testing;\r\n    using Nancy.Tests.Functional.Modules;\r\n\r\n    using Xunit;\r\n\r\n    public class SerializeTests\r\n    {\r\n        private readonly INancyBootstrapper bootstrapper;\r\n\r\n        private readonly Browser browser;\r\n\r\n        public SerializeTests()\r\n        {\r\n            this.bootstrapper = new ConfigurableBootstrapper(\r\n                    configuration => configuration.Modules(new Type[] { typeof(SerializeTestModule) }));\r\n\r\n            this.browser = new Browser(bootstrapper);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_JSON_serialized_form()\r\n        {\r\n            //Given\r\n            var response = await browser.Post(\"/serializedform\", (with) =>\r\n            {\r\n                with.HttpRequest();\r\n                with.Accept(\"application/json\");\r\n                with.FormValue(\"SomeString\", \"Hi\");\r\n                with.FormValue(\"SomeInt\", \"1\");\r\n                with.FormValue(\"SomeBoolean\", \"true\");\r\n            });\r\n\r\n            //When\r\n            var actualModel = response.Body.DeserializeJson<EchoModel>();\r\n\r\n            //Then\r\n            Assert.Equal(\"Hi\", actualModel.SomeString);\r\n            Assert.Equal(1, actualModel.SomeInt);\r\n            Assert.True(actualModel.SomeBoolean);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_JSON_with_parameterised_constructor_from_serialized_form()\r\n        {\r\n            //Given\r\n            var response = await browser.Post(\"/serializedform\", (with) =>\r\n            {\r\n                with.HttpRequest();\r\n                with.Accept(\"application/json\");\r\n                with.FormValue(\"SomeString\", \"Hi\");\r\n                with.FormValue(\"SomeInt\", \"1\");\r\n                with.FormValue(\"SomeBoolean\", \"true\");\r\n            });\r\n\r\n            //When\r\n            var actualModel = response.Body.DeserializeJson<ParameterisedConstructorEchoModel>();\r\n\r\n            //Then\r\n            Assert.Equal(\"Hi\", actualModel.SomeString);\r\n            Assert.Equal(1, actualModel.SomeInt);\r\n            Assert.True(actualModel.SomeBoolean);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_JSON_serialized_querystring()\r\n        {\r\n            //Given\r\n            var response = await browser.Get(\"/serializedquerystring\", (with) =>\r\n            {\r\n                with.HttpRequest();\r\n                with.Accept(\"application/json\");\r\n                with.Query(\"SomeString\", \"Hi\");\r\n                with.Query(\"SomeInt\", \"1\");\r\n                with.Query(\"SomeBoolean\", \"true\");\r\n            });\r\n\r\n            //When\r\n            var actualModel = response.Body.DeserializeJson<EchoModel>();\r\n\r\n            //Then\r\n            Assert.Equal(\"Hi\", actualModel.SomeString);\r\n            Assert.Equal(1, actualModel.SomeInt);\r\n            Assert.True(actualModel.SomeBoolean);\r\n        }\r\n\r\n        public class EchoModel\r\n        {\r\n            public string SomeString { get; set; }\r\n            public int SomeInt { get; set; }\r\n            public bool SomeBoolean { get; set; }\r\n        }\r\n\r\n        public class ParameterisedConstructorEchoModel\r\n        {\r\n            public ParameterisedConstructorEchoModel(string someString, int someInt, bool someBoolean)\r\n            {\r\n                this.SomeString = someString;\r\n                this.SomeInt = someInt;\r\n                this.SomeBoolean = someBoolean;\r\n            }\r\n\r\n            public string SomeString { get; set; }\r\n            public int SomeInt { get; set; }\r\n            public bool SomeBoolean { get; set; }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests.Functional/Tests/SerializerTests.cs",
    "content": "﻿namespace Nancy.Tests.Functional.Tests\r\n{\r\n    using System;\r\n    using System.Globalization;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Configuration;\r\n    using Nancy.Json;\r\n    using Nancy.Testing;\r\n    using Nancy.Tests.Functional.Modules;\r\n\r\n    using Xunit;\r\n\r\n    public class SerializerTests\r\n    {\r\n        private ConfigurableBootstrapper bootstrapper;\r\n        private Browser browser;\r\n\r\n        public SerializerTests()\r\n        {\r\n            this.bootstrapper = new ConfigurableBootstrapper(\r\n                configuration =>\r\n                {\r\n                    configuration.Modules(new Type[] { typeof(SerializerTestModule) });\r\n                });\r\n\r\n            this.browser = new Browser(bootstrapper);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_Serialize_To_ISO8601()\r\n        {\r\n            //Given & When\r\n            var result = await browser.Get(\"/serializer/20131225121030\", with =>\r\n            {\r\n                with.Accept(\"application/json\");\r\n            });\r\n\r\n            //Then\r\n            var model = result.Body.AsString();\r\n            Assert.Equal(string.Format(\"{{\\\"createdOn\\\":\\\"2013-12-25T12:10:30.0000000{0}\\\",\\\"name\\\":null}}\",\r\n                GetTimezoneSuffix(new DateTime(2013, 12, 25, 12, 10, 30))), model);\r\n        }\r\n\r\n\r\n        [Fact]\r\n        public async Task Should_BindTo_Existing_Instance_Using_Body_Serializer()\r\n        {\r\n            // Given\r\n            var model = new FakeSerializerModel { Name = \"Marsellus Wallace\" };\r\n\r\n            // When\r\n            var result = await browser.Post(\"/serializer\", with =>\r\n                {\r\n                    with.JsonBody(model);\r\n                    with.Accept(\"application/json\");\r\n                });\r\n\r\n            var resultModel = result.Body.DeserializeJson<FakeSerializerModel>();\r\n\r\n            // Then\r\n            Assert.Equal(\"Marsellus Wallace\", resultModel.Name);\r\n            Assert.Equal(new DateTime(2014, 01, 30), resultModel.CreatedOn);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_BindTo_Existing_Instance_Using_Form()\r\n        {\r\n            // Given & When\r\n            var result = await browser.Post(\"/serializer\", with =>\r\n                {\r\n                    with.FormValue(\"Name\", \"Marsellus Wallace\");\r\n                    with.Accept(\"application/json\");\r\n                });\r\n\r\n            var resultModel = result.Body.DeserializeJson<FakeSerializerModel>();\r\n\r\n            // Then\r\n            Assert.Equal(\"Marsellus Wallace\", resultModel.Name);\r\n            Assert.Equal(new DateTime(2014, 01, 30), resultModel.CreatedOn);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_BindTo_Utc_by_Default()\r\n        {\r\n            // Given\r\n            var model = new FakeSerializerModel() { CreatedOn = new DateTime(2016, 05, 06, 7, 0, 0) };\r\n\r\n            //When\r\n            var result = await browser.Post(\"/serializer/date\", with =>\r\n            {\r\n                with.Body(\"{\\\"createdOn\\\":\\\"2016-05-06T09:00:00.0000000+02:00\\\",\\\"name\\\":null}\", \"application/json\");\r\n                with.Accept(\"application/json\");\r\n            });\r\n\r\n            var resultModel = result.Body.DeserializeJson<FakeSerializerModel>();\r\n\r\n            // Then\r\n            Assert.Equal(model.CreatedOn, resultModel.CreatedOn);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_BindTo_Local_With_GlobalConfigutation()\r\n        {\r\n            // Given\r\n            var model = new FakeSerializerModel() { CreatedOn = new DateTime(2016, 05, 06, 9, 0, 0) };\r\n\r\n            var bootstrapper = new ConfigurableBootstrapper(\r\n                configuration =>\r\n                {\r\n                    configuration.Configure(\r\n                        environment => environment.Globalization(supportedCultureNames: new[] { \"en-US\" }, dateTimeStyles: DateTimeStyles.AssumeLocal));\r\n                    configuration.Modules(new Type[] { typeof(SerializerTestModule) });\r\n                });\r\n\r\n            var browser = new Browser(bootstrapper);\r\n\r\n            //When\r\n            var result = await browser.Post(\"/serializer/date\", with =>\r\n            {\r\n                with.JsonBody(model);\r\n                with.Accept(\"application/json\");\r\n            });\r\n\r\n            var resultModel = result.Body.DeserializeJson<FakeSerializerModel>();\r\n\r\n            // Then\r\n            Assert.Equal(model.CreatedOn, resultModel.CreatedOn);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_Not_Serialize_Nulls_If_Configured()\r\n        {\r\n            // Given\r\n            var bootstrapper = new ConfigurableBootstrapper(\r\n                configuration =>\r\n                {\r\n                    configuration.Configure(\r\n                        environment => environment.Json(excludeNullValues:true));\r\n\r\n                    configuration.Modules(new Type[] { typeof(SerializerTestModule) });\r\n                });\r\n\r\n            var browser = new Browser(bootstrapper);\r\n\r\n            //When\r\n            var result = await browser.Post(\"/serializer/date\", with =>\r\n            {\r\n                with.Body(\"{\\\"createdOn\\\":\\\"2016-05-06T09:00:00.0000000+02:00\\\"}\", \"application/json\");\r\n                with.Accept(\"application/json\");\r\n            });\r\n\r\n            var body = result.Body.AsString();\r\n\r\n            Assert.Equal(\"{\\\"createdOn\\\":\\\"2016-05-06T07:00:00.0000000Z\\\"}\", body);\r\n        }\r\n\r\n        private static string GetTimezoneSuffix(DateTime value)\r\n        {\r\n            string suffix;\r\n            DateTime time = value.ToUniversalTime();\r\n            TimeSpan localTZOffset;\r\n            if (value >= time)\r\n            {\r\n                localTZOffset = value - time;\r\n                suffix = \"+\";\r\n            }\r\n            else\r\n            {\r\n                localTZOffset = time - value;\r\n                suffix = \"-\";\r\n            }\r\n            return suffix + localTZOffset.ToString(\"hh\") + \":\" + localTZOffset.ToString(\"mm\");\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.Tests.Functional/Tests/TracingSmokeTests.cs",
    "content": "﻿#if !CORE\r\nnamespace Nancy.Tests.Functional.Tests\r\n{\r\n    using System;\r\n    using System.Threading.Tasks;\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Testing;\r\n    using Nancy.Tests.Functional.Modules;\r\n\r\n    using Xunit;\r\n\r\n    public class TracingSmokeTests\r\n    {\r\n        private readonly INancyBootstrapper bootstrapper;\r\n\r\n        private readonly Browser browser;\r\n\r\n        public TracingSmokeTests()\r\n        {\r\n            this.bootstrapper = new ConfigurableBootstrapper(\r\n                    configuration => configuration.Modules(new Type[] { typeof(RazorWithTracingTestModule) }));\r\n\r\n            this.browser = new Browser(bootstrapper);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_render_content_from_viewbag()\r\n        {\r\n            // Given\r\n            // When\r\n            var response = await browser.Get(\r\n                @\"/tracing/razor-viewbag\",\r\n                with =>\r\n                {\r\n                    with.HttpRequest();\r\n                });\r\n\r\n            // Then\r\n            Assert.True(response.Body.AsString().Contains(@\"Hello Bob\"));\r\n        }\r\n    }\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "test/Nancy.Tests.Functional/Tests/ViewBagTests.cs",
    "content": "﻿#if !CORE\r\nnamespace Nancy.Tests.Functional.Tests\r\n{\r\n    using System.Threading.Tasks;\r\n    using Nancy.Bootstrapper;\r\n    using Nancy.Testing;\r\n    using Nancy.Tests.Functional.Modules;\r\n    using Xunit;\r\n\r\n    public class ViewBagTests\r\n    {\r\n        private readonly INancyBootstrapper bootstrapper;\r\n\r\n        private readonly Browser browser;\r\n\r\n        public ViewBagTests()\r\n        {\r\n            this.bootstrapper = new ConfigurableBootstrapper(\r\n                    configuration => configuration.Modules(typeof(RazorTestModule)));\r\n\r\n            this.browser = new Browser(bootstrapper);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_render_content_from_viewbag()\r\n        {\r\n            // Given\r\n            // When\r\n            var response = await browser.Get(\r\n                @\"/razor-viewbag\",\r\n                with =>\r\n                {\r\n                    with.HttpRequest();\r\n                });\r\n\r\n            // Then\r\n            Assert.True(response.Body.AsString().Contains(@\"Hello Bob\"));\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_render_content_from_viewbags()\r\n        {\r\n            // Given\r\n            // When\r\n            var response = await this.browser.Get(\r\n                @\"/razor-viewbag\",\r\n                with =>\r\n                {\r\n                    with.HttpRequest();\r\n                });\r\n\r\n            // Then\r\n            Assert.True(response.Body.AsString().Contains(@\"Hello Bob\"));\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_serialize_ViewBag()\r\n        {\r\n            // Given\r\n            var response = await this.browser.Get(\r\n                @\"/razor-viewbag-serialized\",\r\n                with =>\r\n                {\r\n                    with.HttpRequest();\r\n                    with.Accept(\"application/json\");\r\n                });\r\n\r\n            // When\r\n            var model = response.Body.DeserializeJson<ViewBagModel>();\r\n\r\n            // Then\r\n            Assert.Equal(\"Bob\", model.Name);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_return_200_on_head()\r\n        {\r\n            // Given\r\n            // When\r\n            var response = await this.browser.Head(@\"/razor-viewbag\");\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.OK, response.StatusCode);\r\n        }\r\n\r\n        public class ViewBagModel\r\n        {\r\n            public string Name { get; set; }\r\n        }\r\n    }\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "test/Nancy.Tests.Functional/Views/RazorPage.cshtml",
    "content": "﻿@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic>\r\n\r\nHello @ViewBag.Name\r\n\r\n@Html.Partial(\"_PartialTest.cshtml\")"
  },
  {
    "path": "test/Nancy.Tests.Functional/Views/RazorPageWithUnknownPartial.cshtml",
    "content": "﻿@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic>\r\n\r\nHello @ViewBag.Name\r\n\r\n@Html.Partial(\"_UnknownPartialTest.cshtml\")"
  },
  {
    "path": "test/Nancy.Tests.Functional/Views/_LayoutPage.cshtml",
    "content": "﻿@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<dynamic>\r\n<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\r\n<html>\r\n<head>\r\n    <title>Hello</title>\r\n</head>\r\n<body>\r\n    <h1>Hello World, this is the View Start...</h1>\r\n\r\n    @RenderBody()\r\n</body>\r\n</html>"
  },
  {
    "path": "test/Nancy.Tests.Functional/Views/_PartialTest.cshtml",
    "content": "﻿<h2>This is a partial view...</h2>"
  },
  {
    "path": "test/Nancy.Tests.Functional/Views/_ViewStart.cshtml",
    "content": "﻿@{\r\n    Layout = \"_LayoutPage.cshtml\";\r\n}"
  },
  {
    "path": "test/Nancy.Validation.DataAnnotations.Tests/DataAnnotationsValidatorFactoryFixture.cs",
    "content": "﻿namespace Nancy.Validation.DataAnnotations.Tests\r\n{\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Tests;\r\n\r\n    using Xunit;\r\n\r\n    public class DataAnnotationsValidatorFactoryFixture\r\n    {\r\n        private readonly DataAnnotationsValidatorFactory subject;\r\n\r\n        public DataAnnotationsValidatorFactoryFixture()\r\n        {\r\n            var factory =\r\n                A.Fake<IPropertyValidatorFactory>();\r\n\r\n            var adapter =\r\n                A.Fake<IValidatableObjectAdapter>();\r\n\r\n            this.subject =\r\n                new DataAnnotationsValidatorFactory(factory, adapter);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_provide_null_validator_when_no_rules_exist()\r\n        {\r\n            // Given, When\r\n            var result = this.subject.Create(typeof(string));\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Validation.DataAnnotations.Tests/DataAnnotationsValidatorFixture.cs",
    "content": "﻿namespace Nancy.Validation.DataAnnotations.Tests\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.ComponentModel;\r\n    using System.ComponentModel.DataAnnotations;\r\n    using System.Linq;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Tests;\r\n\r\n    using Xunit;\r\n\r\n    public class DataAnnotationsValidatorFixture\r\n    {\r\n        private readonly DataAnnotationsValidatorFactory factory;\r\n        public readonly IPropertyValidator propertyValidator1;\r\n        public readonly IPropertyValidator propertyValidator2;\r\n        public readonly IValidatableObjectAdapter validatableObjectAdapter;\r\n        public readonly IPropertyValidatorFactory validatorFactory;\r\n        public readonly DataAnnotationsValidator validator;\r\n\r\n        public DataAnnotationsValidatorFixture()\r\n        {\r\n            this.propertyValidator1 =\r\n                A.Fake<IPropertyValidator>();\r\n\r\n            this.propertyValidator2 =\r\n                A.Fake<IPropertyValidator>();\r\n\r\n            this.validatableObjectAdapter =\r\n                A.Fake<IValidatableObjectAdapter>();\r\n\r\n            this.validatorFactory =\r\n                A.Fake<IPropertyValidatorFactory>();\r\n\r\n            A.CallTo(() => this.validatorFactory.GetValidators(typeof(ModelUnderTest)))\r\n               .Returns(new[] { this.propertyValidator1, this.propertyValidator2 });\r\n\r\n            this.validator =\r\n                new DataAnnotationsValidator(typeof(ModelUnderTest), this.validatorFactory, this.validatableObjectAdapter);\r\n\r\n            var adapterFactory = new DefaultPropertyValidatorFactory(new IDataAnnotationsValidatorAdapter[]\r\n            {\r\n                new RangeValidatorAdapter(),\r\n                new RegexValidatorAdapter(),\r\n                new RequiredValidatorAdapter(),\r\n                new StringLengthValidatorAdapter(),\r\n                new OopsAdapter()\r\n            });\r\n\r\n            var adapter = A.Fake<IValidatableObjectAdapter>();\r\n\r\n            this.factory = new DataAnnotationsValidatorFactory(adapterFactory, adapter);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_get_property_validators_from_factory()\r\n        {\r\n            // Given\r\n            var instance = new ModelUnderTest();\r\n            var context = new NancyContext();\r\n\r\n            // When\r\n            this.validator.Validate(instance, context);\r\n\r\n            // Then\r\n            A.CallTo(() => this.validatorFactory.GetValidators(typeof(ModelUnderTest))).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_all_validators_returned_by_factory_with_instance_being_validated()\r\n        {\r\n            // Given\r\n            var instance = new ModelUnderTest();\r\n            var context = new NancyContext();\r\n\r\n            // When\r\n            this.validator.Validate(instance, context);\r\n\r\n            // Then\r\n            A.CallTo(() => this.propertyValidator1.Validate(instance, context)).MustHaveHappened();\r\n            A.CallTo(() => this.propertyValidator2.Validate(instance, context)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_validatable_object_adapter_with_instance_being_validated()\r\n        {\r\n            // Given\r\n            var instance = new ModelUnderTest();\r\n            var context = new NancyContext();\r\n\r\n            // When\r\n            this.validator.Validate(instance, context);\r\n\r\n            // Then\r\n            A.CallTo(() => this.validatableObjectAdapter.Validate(instance, context)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_contain_validation_results_from_all_validators()\r\n        {\r\n            // Given\r\n            var instance = new ModelUnderTest();\r\n            var context = new NancyContext();\r\n\r\n            var result1 = new ModelValidationError(\"Foo\", string.Empty);\r\n            var result2 = new ModelValidationError(\"Bar\", string.Empty);\r\n            var result3 = new ModelValidationError(\"Baz\", string.Empty);\r\n\r\n            A.CallTo(() => this.propertyValidator1.Validate(instance, context)).Returns(new[] { result1 });\r\n            A.CallTo(() => this.propertyValidator2.Validate(instance, context)).Returns(new[] { result2, result3 });\r\n\r\n            // When\r\n            var results = this.validator.Validate(instance, context);\r\n\r\n            // Then\r\n            results.Errors.Count().ShouldEqual(3);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_contain_validation_result_from_validatable_object_adapter()\r\n        {\r\n            // Given\r\n            var instance = new ModelUnderTest();\r\n            var result = new ModelValidationError(\"Foo\", string.Empty);\r\n            var context = new NancyContext();\r\n\r\n            A.CallTo(() => this.validatableObjectAdapter.Validate(instance, context)).Returns(new[] { result });\r\n\r\n            // When\r\n            var results = this.validator.Validate(instance, context);\r\n\r\n            // Then\r\n            results.Errors.Count().ShouldEqual(1);\r\n            results.Errors.Keys.Contains(\"Foo\").ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_descriptor_with_rules_from_all_validators()\r\n        {\r\n            // Given\r\n            var rule1 = new ModelValidationRule(string.Empty, s => string.Empty, new[] { \"One\" });\r\n            var rule2 = new ModelValidationRule(string.Empty, s => string.Empty, new[] { \"Two\" });\r\n            var rule3 = new ModelValidationRule(string.Empty, s => string.Empty, new[] { \"Three\" });\r\n\r\n            A.CallTo(() => this.propertyValidator1.GetRules()).Returns(new[] { rule1 });\r\n            A.CallTo(() => this.propertyValidator2.GetRules()).Returns(new[] { rule2, rule3 });\r\n\r\n            // When\r\n            var descriptor = this.validator.Description;\r\n\r\n            // Then\r\n            descriptor.Rules.Count().ShouldEqual(3);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_throw_when_no_validation_attributes_exist()\r\n        {\r\n            // Given, When\r\n            var ex = Record.Exception(() => this.factory.Create(typeof(string)));\r\n\r\n            // Then\r\n            ex.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_validation()\r\n        {\r\n            // Given\r\n            var subject = this.factory.Create(typeof(TestModel));\r\n            var instance = new TestModel { Age = \"yeah\" };\r\n\r\n            // When\r\n            var result = subject.Validate(instance, new NancyContext());\r\n\r\n            // Then\r\n            result.IsValid.ShouldBeFalse();\r\n            result.Errors.ShouldHaveCount(3);\r\n        }\r\n\r\n        [Fact]\r\n        public void Description_should_be_correct()\r\n        {\r\n            // Given, When\r\n            var subject = this.factory.Create(typeof(TestModel));\r\n\r\n            // Then\r\n            subject.Description.ShouldNotBeNull();\r\n            subject.Description.Rules.SelectMany(r => r.Value).ShouldHaveCount(10);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_read_range_annotation()\r\n        {\r\n            // Given, When\r\n            var subject = this.factory.Create(typeof(TestModel));\r\n\r\n            // Then\r\n            subject.Description.Rules.SelectMany(r => r.Value).ShouldHave(r => r.RuleType == \"Comparison\" && r.MemberNames.Contains(\"Value\"));\r\n            subject.Description.Rules.SelectMany(r => r.Value).ShouldHave(r => r.RuleType == \"Comparison\" && r.MemberNames.Contains(\"Value\"));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_read_derived_range_annotation()\r\n        {\r\n            // Given, When\r\n            var subject = this.factory.Create(typeof(TestModelWithDerivedDataAnnotations));\r\n\r\n            // Then\r\n            subject.Description.Rules.SelectMany(r => r.Value).ShouldHave(r => r.RuleType == \"Comparison\" && r.MemberNames.Contains(\"Value\"));\r\n            subject.Description.Rules.SelectMany(r => r.Value).ShouldHave(r => r.RuleType == \"Comparison\" && r.MemberNames.Contains(\"Value\"));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_read_regex_annotation()\r\n        {\r\n            // Given, When\r\n            var subject = this.factory.Create(typeof(TestModel));\r\n\r\n            // Then\r\n            subject.Description.Rules.SelectMany(r => r.Value).ShouldHave(r => r.RuleType == \"Regex\" && r.MemberNames.Contains(\"Age\"));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_read_derived_regex_annotation()\r\n        {\r\n            // Given, When\r\n            var subject = this.factory.Create(typeof(TestModelWithDerivedDataAnnotations));\r\n\r\n            // Then\r\n            subject.Description.Rules.SelectMany(r => r.Value).ShouldHave(r => r.RuleType == \"Regex\" && r.MemberNames.Contains(\"Age\"));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_read_required_annotation()\r\n        {\r\n            // Given, When\r\n            var subject = this.factory.Create(typeof(TestModel));\r\n\r\n            // Then\r\n            subject.Description.Rules.SelectMany(r => r.Value).ShouldHave(r => r.RuleType == \"NotNull\" && r.MemberNames.Contains(\"FirstName\"));\r\n            subject.Description.Rules.SelectMany(r => r.Value).ShouldHave(r => r.RuleType == \"NotEmpty\" && r.MemberNames.Contains(\"FirstName\"));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_read_derived_required_annotation()\r\n        {\r\n            // Given, When\r\n            var subject = this.factory.Create(typeof(TestModelWithDerivedDataAnnotations));\r\n\r\n            // Then\r\n            subject.Description.Rules.SelectMany(r => r.Value).ShouldHave(r => r.RuleType == \"NotNull\" && r.MemberNames.Contains(\"FirstName\"));\r\n            subject.Description.Rules.SelectMany(r => r.Value).ShouldHave(r => r.RuleType == \"NotEmpty\" && r.MemberNames.Contains(\"FirstName\"));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_read_string_length_annotation()\r\n        {\r\n            // Given, When\r\n            var subject = this.factory.Create(typeof(TestModel));\r\n\r\n            // Then\r\n            subject.Description.Rules.SelectMany(r => r.Value).ShouldHave(r => r.RuleType == \"StringLength\" && r.MemberNames.Contains(\"FirstName\"));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_read_derived_string_length_annotation()\r\n        {\r\n            // Given, When\r\n            var subject = this.factory.Create(typeof(TestModelWithDerivedDataAnnotations));\r\n\r\n            // Then\r\n            subject.Description.Rules.SelectMany(r => r.Value).ShouldHave(r => r.RuleType == \"StringLength\" && r.MemberNames.Contains(\"FirstName\"));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_custom_validator()\r\n        {\r\n            // Given, When\r\n            var subject = this.factory.Create(typeof(TestModel));\r\n\r\n            // Then\r\n            subject.Description.Rules.SelectMany(r => r.Value).ShouldHave(r => r.RuleType == \"Oops\" && r.MemberNames.Contains(string.Empty));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_display_attribute()\r\n        {\r\n            // Given\r\n            var subject = this.factory.Create(typeof(TestModel));\r\n            var instance = new TestModel { FirstName = \"name\", LastName = \"a long name\", Age = \"1\" };\r\n\r\n            // When\r\n            var result = subject.Validate(instance, new NancyContext());\r\n\r\n            // Then\r\n            result.IsValid.ShouldBeFalse();\r\n            result.Errors[\"LastName\"][0].ErrorMessage.ShouldContain(\"Last Name\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_displayname_attribute()\r\n        {\r\n            // Given\r\n            var subject = this.factory.Create(typeof(TestModel));\r\n            var instance = new TestModel { FirstName = \"a long name\", Age = \"1\" };\r\n\r\n            // When\r\n            var result = subject.Validate(instance, new NancyContext());\r\n\r\n            // Then\r\n            result.IsValid.ShouldBeFalse();\r\n            result.Errors[\"FirstName\"][0].ErrorMessage.ShouldContain(\"First Name\");\r\n        }\r\n\r\n        [OopsValidation]\r\n        private class TestModel : IValidatableObject\r\n        {\r\n            [DisplayName(\"First Name\")]\r\n            [Required]\r\n            [StringLength(5)]\r\n            public string FirstName { get; set; }\r\n\r\n            [Display(Name = \"Last Name\")]\r\n            [StringLength(5)]\r\n            public string LastName { get; set; }\r\n\r\n            [RegularExpression(\"\\\\d+\")]\r\n            [Required]\r\n            public string Age { get; set; }\r\n\r\n            [Range(0, 10)]\r\n            public int Value { get; set; }\r\n\r\n            public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)\r\n            {\r\n                return Enumerable.Empty<ValidationResult>();\r\n            }\r\n        }\r\n\r\n        public class ModelUnderTest\r\n        {\r\n        }\r\n\r\n        private class OopsValidationAttribute : ValidationAttribute\r\n        {\r\n            protected override ValidationResult IsValid(object value, ValidationContext validationContext)\r\n            {\r\n                return new ValidationResult(\"Oops\");\r\n            }\r\n        }\r\n\r\n        private class OopsAdapter : DataAnnotationsValidatorAdapter\r\n        {\r\n            public OopsAdapter()\r\n                : base(\"Oops\")\r\n            {\r\n            }\r\n\r\n            public override bool CanHandle(ValidationAttribute attribute)\r\n            {\r\n                return attribute.GetType() == typeof(OopsValidationAttribute);\r\n            }\r\n\r\n            protected override ModelValidationError GetValidationError(ValidationResult result, ValidationContext context, ValidationAttribute attribute)\r\n            {\r\n                return new ModelValidationError(new[] { string.Empty }, result.ErrorMessage);\r\n            }\r\n        }\r\n\r\n        private class TestModelWithDerivedDataAnnotations\r\n        {\r\n            [DerivedRequired]\r\n            [DerivedStringLength(5)]\r\n            public string FirstName { get; set; }\r\n\r\n            [DerivedRegularExpression(\"\\\\d+\")]\r\n            [DerivedRequired]\r\n            public string Age { get; set; }\r\n\r\n            [DerivedRange(0, 10)]\r\n            public int Value { get; set; }\r\n        }\r\n\r\n        public class DerivedRequiredAttribute : RequiredAttribute\r\n        {\r\n        }\r\n\r\n        public class DerivedStringLengthAttribute : StringLengthAttribute\r\n        {\r\n            public DerivedStringLengthAttribute(int maximumLength)\r\n                : base(maximumLength)\r\n            {\r\n            }\r\n        }\r\n\r\n        public class DerivedRegularExpressionAttribute : RegularExpressionAttribute\r\n        {\r\n            public DerivedRegularExpressionAttribute(string pattern)\r\n                : base(pattern)\r\n            {\r\n            }\r\n        }\r\n\r\n        public class DerivedRangeAttribute : RangeAttribute\r\n        {\r\n            public DerivedRangeAttribute(int minimum, int maximum)\r\n                : base(minimum, maximum)\r\n            {\r\n            }\r\n\r\n            public DerivedRangeAttribute(double minimum, double maximum)\r\n                : base(minimum, maximum)\r\n            {\r\n            }\r\n\r\n            public DerivedRangeAttribute(Type type, string minimum, string maximum)\r\n                : base(type, minimum, maximum)\r\n            {\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Validation.DataAnnotations.Tests/DefaultValidatableObjectAdapterFixture.cs",
    "content": "﻿namespace Nancy.Validation.DataAnnotations.Tests\r\n{\r\n    using System.Collections.Generic;\r\n    using System.ComponentModel.DataAnnotations;\r\n    using System.Linq;\r\n\r\n    using Nancy.Tests;\r\n\r\n    using Xunit;\r\n\r\n    public class DefaultValidatableObjectAdapterFixture\r\n    {\r\n        public readonly DefaultValidatableObjectAdapter validator;\r\n\r\n        public DefaultValidatableObjectAdapterFixture()\r\n        {\r\n            this.validator = new DefaultValidatableObjectAdapter();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_validate_on_instance()\r\n        {\r\n            // Given\r\n            var instance = new ModelUnderTest();\r\n\r\n            // When\r\n            this.validator.Validate(instance, new NancyContext());\r\n\r\n            // Then\r\n            instance.ValidatedWasInvoked.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_validate_with_instance()\r\n        {\r\n            // Given\r\n            var instance = new ModelUnderTest();\r\n\r\n            // When\r\n            this.validator.Validate(instance, new NancyContext());\r\n\r\n            // Then\r\n            instance.InstanceBeingValidated.ShouldBeSameAs(instance);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_validation_error_for_all_validation_results()\r\n        {\r\n            // Given\r\n            var result1 = new ValidationResult(\"Error1\", new[] { \"foo\" });\r\n            var result2 = new ValidationResult(\"Error2\", new[] { \"bar\", \"baz\" });\r\n\r\n            var instance = new ModelUnderTest\r\n            {\r\n                ExpectedResults = new[] {result1, result2}\r\n            };\r\n\r\n            // When\r\n            var results = this.validator.Validate(instance, new NancyContext());\r\n\r\n            // Then\r\n            results.Count().ShouldEqual(2);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_return_errors_if_model_not_implements_IValidatableObject()\r\n        {\r\n            // Given\r\n            var instance = new ModelNotImplementingIValidatableObject();\r\n\r\n            // When\r\n            var result = this.validator.Validate(instance, new NancyContext());\r\n\r\n            // Then\r\n            result.Count().ShouldEqual(0);\r\n        }\r\n\r\n        public class ModelUnderTest : IValidatableObject\r\n        {\r\n            public object InstanceBeingValidated { get; set; }\r\n\r\n            public bool ValidatedWasInvoked { get; set; }\r\n\r\n            public IEnumerable<ValidationResult> ExpectedResults { get; set; }\r\n\r\n            public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)\r\n            {\r\n                this.ValidatedWasInvoked = true;\r\n                this.InstanceBeingValidated = validationContext.ObjectInstance;\r\n                \r\n                return this.ExpectedResults ?? Enumerable.Empty<ValidationResult>();\r\n            }\r\n        }\r\n\r\n        public class ModelNotImplementingIValidatableObject\r\n        {\r\n            public int Value { get; set; }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Validation.DataAnnotations.Tests/Nancy.Validation.DataAnnotations.Tests.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <TargetFramework>net452</TargetFramework>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <Reference Include=\"System.ComponentModel.DataAnnotations\" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "test/Nancy.Validation.DataAnnotations.Tests/PropertyValidatorFixture.cs",
    "content": "﻿namespace Nancy.Validation.DataAnnotations.Tests\r\n{\r\n    using System.Collections.Generic;\r\n    using System.ComponentModel;\r\n    using System.ComponentModel.DataAnnotations;\r\n    using System.Linq;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Tests;\r\n\r\n    using Xunit;\r\n\r\n    public class PropertyValidatorFixture\r\n    {\r\n        private readonly Dictionary<ValidationAttribute, IEnumerable<IDataAnnotationsValidatorAdapter>> mappings;\r\n        private readonly IDataAnnotationsValidatorAdapter adapter1;\r\n        private readonly IDataAnnotationsValidatorAdapter adapter2;\r\n        private readonly PropertyDescriptor descriptor;\r\n        private readonly PropertyValidator validator;\r\n        private readonly ModelValidationError error1;\r\n        private readonly ModelValidationError error2;\r\n\r\n        public PropertyValidatorFixture()\r\n        {\r\n            this.adapter1 =\r\n                A.Fake<IDataAnnotationsValidatorAdapter>();\r\n\r\n            this.error1 =\r\n                new ModelValidationError(\"error1\", string.Empty);\r\n\r\n            A.CallTo(() => this.adapter1.Validate(A<object>._, A<ValidationAttribute>._, A<PropertyDescriptor>._, A<NancyContext>._))\r\n                .Returns(new[] {this.error1});\r\n\r\n            this.adapter2 = \r\n                A.Fake<IDataAnnotationsValidatorAdapter>();\r\n\r\n            this.error2 =\r\n                new ModelValidationError(\"error2\", string.Empty);\r\n\r\n            A.CallTo(() => this.adapter2.Validate(A<object>._, A<ValidationAttribute>._, A<PropertyDescriptor>._, A<NancyContext>._))\r\n                .Returns(new[] { this.error2 });\r\n\r\n            this.mappings =\r\n                new Dictionary<ValidationAttribute, IEnumerable<IDataAnnotationsValidatorAdapter>>\r\n                {\r\n                    {new RangeAttribute(1, 10), new[] {this.adapter1}},\r\n                    {new RequiredAttribute(), new[] {this.adapter2}}\r\n                };\r\n\r\n            var type =\r\n                typeof(Model);\r\n\r\n            this.descriptor = new AssociatedMetadataTypeTypeDescriptionProvider(type)\r\n                .GetTypeDescriptor(type)\r\n                .GetProperties()[0];\r\n\r\n            this.validator = new PropertyValidator\r\n            {\r\n                AttributeAdaptors = this.mappings,\r\n                Descriptor =this.descriptor\r\n            };\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_call_validate_on_each_validator_for_each_attribute_when_validate_is_invoked()\r\n        {\r\n            // Given\r\n            var context = new NancyContext();\r\n\r\n            // When\r\n            this.validator.Validate(null, context);\r\n\r\n            // Then\r\n            A.CallTo(() => this.adapter1.Validate(A<object>._, A<ValidationAttribute>._, A<PropertyDescriptor>._, A<NancyContext>._)).MustHaveHappened();\r\n            A.CallTo(() => this.adapter2.Validate(A<object>._, A<ValidationAttribute>._, A<PropertyDescriptor>._, A<NancyContext>._)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_pass_instance_to_validator_when_validate_is_invoked()\r\n        {\r\n            // Given\r\n            var instance = new Model();\r\n            var context = new NancyContext();\r\n\r\n            // When\r\n            this.validator.Validate(instance, context);\r\n\r\n            // Then\r\n            A.CallTo(() => this.adapter1.Validate(instance, A<ValidationAttribute>._, A<PropertyDescriptor>._, context)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_pass_attribute_to_validator_when_validate_is_invoked()\r\n        {\r\n            // Given\r\n            var instance = new Model();\r\n            var context = new NancyContext();\r\n\r\n            // When\r\n            this.validator.Validate(instance, context);\r\n\r\n            // Then\r\n            A.CallTo(() => this.adapter1.Validate(A<object>._, this.mappings.Keys.First(), A<PropertyDescriptor>._, A<NancyContext>._)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_pass_descriptor_to_validator_when_validate_is_invoked()\r\n        {\r\n            // Given\r\n            var instance = new Model();\r\n            var context = new NancyContext();\r\n\r\n            // When\r\n            this.validator.Validate(instance, context);\r\n\r\n            // Then\r\n            A.CallTo(() => this.adapter1.Validate(A<object>._, A<ValidationAttribute>._, this.descriptor, A<NancyContext>._)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_an_aggregated_list_of_model_validation_errors_from_all_adapters()\r\n        {\r\n            // Given\r\n            var instance = new Model();\r\n            var context = new NancyContext();\r\n\r\n            // When\r\n            var results = this.validator.Validate(instance, context);\r\n            \r\n            // Then\r\n            results.Contains(this.error1).ShouldBeTrue();\r\n            results.Contains(this.error2).ShouldBeTrue();\r\n        }\r\n\r\n        private class Model\r\n        {\r\n            public int Foo { get; set; }\r\n            public string Bar { get; set; }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Validation.FluentValidation.Tests/DefaultFluentAdapterFactoryFixture.cs",
    "content": "namespace Nancy.Validation.FluentValidation.Tests\r\n{\r\n    using FakeItEasy;\r\n\r\n    using global::FluentValidation.Validators;\r\n\r\n    using Nancy.Tests;\r\n\r\n    using Xunit;\r\n\r\n    public class DefaultFluentAdapterFactoryFixture\r\n    {\r\n        [Fact]\r\n        public void Should_return_adapter_that_can_handle_validator()\r\n        {\r\n            // Given\r\n            var validator = A.Fake<IPropertyValidator>();\r\n\r\n            var adapter1 = A.Fake<IFluentAdapter>();\r\n            A.CallTo(() => adapter1.CanHandle(A<IPropertyValidator>._)).Returns(false);\r\n\r\n            var adapter2 = A.Fake<IFluentAdapter>();\r\n            A.CallTo(() => adapter2.CanHandle(A<IPropertyValidator>._)).Returns(true);\r\n\r\n            var factory = CreateFactory(adapter1, adapter2);\r\n\r\n            // When\r\n            var result = factory.Create(validator);\r\n\r\n            // Then\r\n            result.ShouldBeSameAs(adapter2);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_pass_validator_to_canhandle_method_on_adapter()\r\n        {\r\n            var validator = A.Fake<IPropertyValidator>();\r\n            var adapter = A.Fake<IFluentAdapter>();\r\n\r\n            var factory = CreateFactory(adapter);\r\n\r\n            // When\r\n            factory.Create(validator);\r\n\r\n            // Then\r\n            A.CallTo(() => adapter.CanHandle(validator)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_fallback_adapter_when_no_other_adapter_can_handle_validator()\r\n        {\r\n            // Given\r\n            var validator = A.Fake<IPropertyValidator>();\r\n\r\n            var adapter1 = A.Fake<IFluentAdapter>();\r\n            A.CallTo(() => adapter1.CanHandle(A<IPropertyValidator>._)).Returns(false);\r\n\r\n            var adapter2 = A.Fake<IFluentAdapter>();\r\n            A.CallTo(() => adapter2.CanHandle(A<IPropertyValidator>._)).Returns(false);\r\n\r\n            var factory = CreateFactory(adapter1, adapter2);\r\n\r\n            // When\r\n            var result = factory.Create(validator);\r\n\r\n            // Then\r\n            result.ShouldBeOfType<FallbackAdapter>();\r\n        }\r\n\r\n        private static DefaultFluentAdapterFactory CreateFactory(params IFluentAdapter[] adapters)\r\n        {\r\n            return new DefaultFluentAdapterFactory(adapters);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Validation.FluentValidation.Tests/EmailAdapterFixture.cs",
    "content": "﻿namespace Nancy.Validation.FluentValidation.Tests\r\n{\r\n    using global::FluentValidation.Internal;\r\n    using global::FluentValidation.Validators;\r\n\r\n    public class EmailAdapterFixture\r\n    {\r\n        public EmailAdapterFixture()\r\n        {\r\n            //var member =\r\n            //    typeof (ClassUnderTest).GetProperty(\"Email\");\r\n\r\n            //var rule = \r\n            //    new PropertyRule(member, )\r\n        }\r\n\r\n        private class ClassUnderTest\r\n        {\r\n            public string Email { get; set; }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Validation.FluentValidation.Tests/FluentValidationValidatorFactoryFixture.cs",
    "content": "﻿namespace Nancy.Validation.FluentValidation.Tests\r\n{\r\n    using FakeItEasy;\r\n\r\n    using global::FluentValidation;\r\n\r\n    using Nancy.Tests;\r\n\r\n    using Xunit;\r\n\r\n    public class FluentValidationValidatorFactoryFixture\r\n    {\r\n        private readonly FluentValidationValidatorFactory factory;\r\n\r\n        public FluentValidationValidatorFactoryFixture()\r\n        {\r\n            var adapterFactory = \r\n                A.Fake<IFluentAdapterFactory>();\r\n\r\n            var validators = \r\n                new IValidator[] {new ClassUnderTestValidator(), new NeverBeUsedTestValidator()};\r\n\r\n            this.factory = \r\n                new FluentValidationValidatorFactory(adapterFactory, validators);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_instance_when_validator_was_found_for_type()\r\n        {\r\n            // Given\r\n            // When\r\n            var instance = this.factory.Create(typeof(ClassUnderTest));\r\n\r\n            // Then\r\n            instance.ShouldNotBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_when_no_validator_was_found_for_type()\r\n        {\r\n            // Given\r\n            // When\r\n            var instance = this.factory.Create(typeof(string));\r\n\r\n            // Then\r\n            instance.ShouldBeNull();\r\n        }\r\n\r\n        public class ClassUnderTest\r\n        {\r\n        }\r\n\r\n        public class ClassUnderTestValidator : AbstractValidator<ClassUnderTest>\r\n        {\r\n        }\r\n\r\n        public class NeverBeUsedTestValidator : AbstractValidator<int>\r\n        {\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.Validation.FluentValidation.Tests/Nancy.Validation.FluentValidation.Tests.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <TargetFrameworks>netcoreapp2.0;net452</TargetFrameworks>\n  </PropertyGroup>\n</Project>\n"
  },
  {
    "path": "test/Nancy.ViewEngines.DotLiquid.Tests/DotLiquidViewEngineFixture.cs",
    "content": "﻿namespace Nancy.ViewEngines.DotLiquid.Tests\r\n{\r\n    using System;\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using Configuration;\r\n    using FakeItEasy;\r\n\r\n    using global::DotLiquid;\r\n    using global::DotLiquid.NamingConventions;\r\n\r\n    using Nancy.Tests;\r\n\r\n    using Xunit;\r\n\r\n    public class DotLiquidViewEngineFixture\r\n    {\r\n        private readonly IRenderContext renderContext;\r\n        private readonly IFileSystemFactory factory;\r\n        private readonly DotLiquidViewEngine engine;\r\n        private readonly DotLiquidViewEngine engineCSharp;\r\n\r\n        private readonly INancyEnvironment environment;\r\n\r\n        public DotLiquidViewEngineFixture()\r\n        {\r\n            this.environment = new DefaultNancyEnvironment();\r\n            this.environment.AddValue(ViewConfiguration.Default);\r\n\r\n            this.factory = A.Fake<IFileSystemFactory>();\r\n            this.engine = new DotLiquidViewEngine(this.factory, new RubyNamingConvention());\r\n            this.engineCSharp = new DotLiquidViewEngine(this.factory, new CSharpNamingConvention());\r\n\r\n            var cache = A.Fake<IViewCache>();\r\n            A.CallTo(() => cache.GetOrAdd(A<ViewLocationResult>.Ignored, A<Func<ViewLocationResult, Template>>.Ignored))\r\n                .ReturnsLazily(x =>\r\n                {\r\n                    var result = x.GetArgument<ViewLocationResult>(0);\r\n                    return x.GetArgument<Func<ViewLocationResult, Template>>(1).Invoke(result);\r\n                });\r\n            var context = new NancyContext();\r\n\r\n            this.renderContext = A.Fake<IRenderContext>();\r\n            A.CallTo(() => this.renderContext.ViewCache).Returns(cache);\r\n            A.CallTo(() => this.renderContext.Context).Returns(context);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_retrieve_filesystem_from_factory_when_engine_is_initialized()\r\n        {\r\n            // Given\r\n            var context = this.CreateContext();\r\n\r\n            // When\r\n            this.engine.Initialize(context);\r\n\r\n            // Then\r\n            A.CallTo(() => this.factory.GetFileSystem(context, A<IEnumerable<string>>._)).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_support_files_with_the_liquid_extensions()\r\n        {\r\n            // Given\r\n            // When\r\n            var extensions = this.engine.Extensions;\r\n\r\n            // Then\r\n            extensions.ShouldHaveCount(1);\r\n            extensions.ShouldEqualSequence(new[] { \"liquid\" });\r\n        }\r\n\r\n        [Fact]\r\n        public void RenderView_should_render_to_stream()\r\n        {\r\n            // Given\r\n            var location = new ViewLocationResult(\r\n                string.Empty,\r\n                string.Empty,\r\n                \"liquid\",\r\n                () => new StringReader(@\"{% assign name = 'test' %}<h1>Hello Mr. {{ name }}</h1>\")\r\n            );\r\n\r\n            var currentStartupContext =\r\n                this.CreateContext(location);\r\n\r\n            this.engine.Initialize(currentStartupContext);\r\n\r\n            var stream = new MemoryStream();\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, null, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            stream.ShouldEqual(\"<h1>Hello Mr. test</h1>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void RenderView_with_uppercase_filter_should_return_uppercase_string()\r\n        {\r\n            // Given\r\n            var location = new ViewLocationResult(\r\n                string.Empty,\r\n                string.Empty,\r\n                \"liquid\",\r\n                () => new StringReader(@\"{% assign name = 'Test' %}<h1>Hello Mr. {{ name | upcase }}</h1>\")\r\n            );\r\n\r\n            var currentStartupContext =\r\n                this.CreateContext(location);\r\n\r\n            this.engine.Initialize(currentStartupContext);\r\n\r\n            var stream = new MemoryStream();\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, null, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            stream.ShouldEqual(\"<h1>Hello Mr. TEST</h1>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void RenderView_with_lowercase_filter_should_return_lowercase_string()\r\n        {\r\n            // Given\r\n            var location = new ViewLocationResult(\r\n                string.Empty,\r\n                string.Empty,\r\n                \"liquid\",\r\n                () => new StringReader(@\"{% assign name = 'Test' %}<h1>Hello Mr. {{ name | downcase }}</h1>\")\r\n            );\r\n\r\n            var currentStartupContext =\r\n                this.CreateContext(location);\r\n\r\n            this.engine.Initialize(currentStartupContext);\r\n\r\n            var stream = new MemoryStream();\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, null, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            stream.ShouldEqual(\"<h1>Hello Mr. test</h1>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void RenderView_with_uppercase_filter_should_return_uppercase_string_using_csharp_convention()\r\n        {\r\n            // Given\r\n            var location = new ViewLocationResult(\r\n                string.Empty,\r\n                string.Empty,\r\n                \"liquid\",\r\n                () => new StringReader(@\"{% assign name = 'Test' %}<h1>Hello Mr. {{ name | Upcase }}</h1>\")\r\n            );\r\n\r\n            var currentStartupContext =\r\n                this.CreateContext(location);\r\n\r\n            this.engineCSharp.Initialize(currentStartupContext);\r\n\r\n            var stream = new MemoryStream();\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, null, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            stream.ShouldEqual(\"<h1>Hello Mr. TEST</h1>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void RenderView_with_lowercase_filter_should_return_lowercase_string_using_csharp_convention()\r\n        {\r\n            // Given\r\n            var location = new ViewLocationResult(\r\n                string.Empty,\r\n                string.Empty,\r\n                \"liquid\",\r\n                () => new StringReader(@\"{% assign name = 'Test' %}<h1>Hello Mr. {{ name | Downcase }}</h1>\")\r\n            );\r\n\r\n            var currentStartupContext =\r\n                this.CreateContext(location);\r\n\r\n            this.engineCSharp.Initialize(currentStartupContext);\r\n\r\n            var stream = new MemoryStream();\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, null, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            stream.ShouldEqual(\"<h1>Hello Mr. test</h1>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void When_passing_a_null_model_should_return_an_empty_string()\r\n        {\r\n            // Given\r\n            var location = new ViewLocationResult(\r\n                string.Empty,\r\n                string.Empty,\r\n                \"liquid\",\r\n                () => new StringReader(@\"<h1>Hello Mr. {{ Model.name }}</h1>\")\r\n            );\r\n\r\n            var currentStartupContext =\r\n                this.CreateContext(location);\r\n\r\n            this.engine.Initialize(currentStartupContext);\r\n\r\n            var stream = new MemoryStream();\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, null, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            stream.ShouldEqual(\"<h1>Hello Mr. </h1>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void RenderView_should_accept_a_model_and_read_from_it_into_the_stream()\r\n        {\r\n            // Given\r\n            var location = new ViewLocationResult(\r\n                string.Empty,\r\n                string.Empty,\r\n                \"liquid\",\r\n                () => new StringReader(@\"<h1>Hello Mr. {{ Model.name }}</h1>\")\r\n            );\r\n\r\n            var currentStartupContext =\r\n                this.CreateContext(location);\r\n\r\n            this.engine.Initialize(currentStartupContext);\r\n            var stream = new MemoryStream();\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, new { name = \"test\" }, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            stream.ShouldEqual(\"<h1>Hello Mr. test</h1>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void RenderView_should_expose_ViewBag_to_the_template()\r\n        {\r\n            // Given\r\n            var location = new ViewLocationResult(\r\n                string.Empty,\r\n                string.Empty,\r\n                \"liquid\",\r\n                () => new StringReader(@\"<h1>Hello Mr. {{ ViewBag.Name }}</h1>\")\r\n            );\r\n\r\n            var currentStartupContext =\r\n                this.CreateContext(location);\r\n\r\n            this.engine.Initialize(currentStartupContext);\r\n            var stream = new MemoryStream();\r\n            this.renderContext.Context.ViewBag.Name = \"test\";\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, new { name = \"incorrect\" }, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            stream.ShouldEqual(\"<h1>Hello Mr. test</h1>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void when_calling_a_missing_member_should_return_an_empty_string()\r\n        {\r\n            // Given\r\n            var location = new ViewLocationResult(\r\n                string.Empty,\r\n                string.Empty,\r\n                \"liquid\",\r\n                () => new StringReader(@\"<h1>Hello Mr. {{ Model.name }}</h1>\")\r\n            );\r\n\r\n            var currentStartupContext =\r\n                this.CreateContext(location);\r\n\r\n            this.engine.Initialize(currentStartupContext);\r\n            var stream = new MemoryStream();\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, new { lastname = \"test\" }, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            stream.ShouldEqual(\"<h1>Hello Mr. </h1>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Syntax_errors_should_return_500()\r\n        {\r\n            // Given\r\n            var location = new ViewLocationResult(\r\n                string.Empty,\r\n                string.Empty,\r\n                \"liquid\",\r\n                () => new StringReader(@\"{% if true %}{% end %}\")\r\n            );\r\n\r\n            var currentStartupContext =\r\n                this.CreateContext(location);\r\n\r\n            this.engine.Initialize(currentStartupContext);\r\n            var stream = new MemoryStream();\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, null, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            response.StatusCode.ShouldEqual(HttpStatusCode.InternalServerError);\r\n        }\r\n\r\n        [Fact]\r\n        public void When_rendering_model_inheriting_drop_should_preserve_camel_case()\r\n        {\r\n            // Writing the test name in snake_case is slightly ironic, no?\r\n\r\n            // Given\r\n            var location = new ViewLocationResult(\r\n                string.Empty,\r\n                string.Empty,\r\n                \"liquid\",\r\n                () => new StringReader(@\"{{ Model.CamelCase }}\")\r\n            );\r\n\r\n            var currentStartupContext =\r\n                this.CreateContext(location);\r\n\r\n            this.engine.Initialize(currentStartupContext);\r\n            var stream = new MemoryStream();\r\n\r\n            // When\r\n            var dropModel = new DropModel() { CamelCase = \"Hello Jamie!\" };\r\n            var response = this.engine.RenderView(location, dropModel, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            stream.ShouldEqual(\"Hello Jamie!\");\r\n        }\r\n\r\n        [Fact]\r\n        public void RenderView_should_accept_a_model_with_a_list_and_iterate_over_it()\r\n        {\r\n            // Given\r\n            var location = new ViewLocationResult(\r\n                string.Empty,\r\n                string.Empty,\r\n                \"liquid\",\r\n                () => new StringReader(@\"<ul>{% for item in Model.Items %}<li>{{ item.Name }}</li>{% endfor %}</ul>\")\r\n            );\r\n\r\n            var currentStartupContext =\r\n                this.CreateContext(location);\r\n\r\n            this.engine.Initialize(currentStartupContext);\r\n            var stream = new MemoryStream();\r\n\r\n            IList<Article> articles = new List<Article>() {\r\n                new Article {Name = \"Hello\"},\r\n                new Article {Name = \"Jamie!\"},\r\n                new Article {Name = \"You're fun!\"}\r\n            };\r\n\r\n            var menu = new Magazine() { Items = articles };\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, menu, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            stream.ShouldEqual(\"<ul><li>Hello</li><li>Jamie!</li><li>You're fun!</li></ul>\");\r\n        }\r\n\r\n        private ViewEngineStartupContext CreateContext(params ViewLocationResult[] results)\r\n        {\r\n            var viewLocationProvider = A.Fake<IViewLocationProvider>();\r\n            A.CallTo(() => viewLocationProvider.GetLocatedViews(A<IEnumerable<string>>._))\r\n                                               .Returns(results);\r\n\r\n            var viewEngine = A.Fake<IViewEngine>();\r\n            A.CallTo(() => viewEngine.Extensions).Returns(new[] { \"liquid\" });\r\n\r\n            var viewLocator = new DefaultViewLocator(viewLocationProvider, new[] { viewEngine }, this.environment);\r\n\r\n            var startupContext = new ViewEngineStartupContext(\r\n                null,\r\n                viewLocator);\r\n\r\n            return startupContext;\r\n        }\r\n    }\r\n\r\n    public class Magazine\r\n    {\r\n        public IList<Article> Items { get; set; }\r\n    }\r\n\r\n    public class Article : Drop\r\n    {\r\n        public string Name { get; set; }\r\n    }\r\n\r\n    public class DropModel : Drop\r\n    {\r\n        public string CamelCase { get; set; }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.DotLiquid.Tests/DynamicDropFixture.cs",
    "content": "namespace Nancy.ViewEngines.DotLiquid.Tests\r\n{\r\n    using System.Dynamic;\r\n\r\n    using Nancy.Tests;\r\n\r\n    using Xunit;\r\n\r\n    public class DynamicDropFixture\r\n    {\r\n        [Fact]\r\n        public void Should_return_null_when_model_is_null()\r\n        {\r\n            // Given\r\n            var drop = new DynamicDrop(null);\r\n\r\n            // When\r\n            var result = drop.BeforeMethod(string.Empty);\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_when_property_name_is_empty()\r\n        {\r\n            // Given\r\n            var drop = new DynamicDrop(new object());\r\n\r\n            // When\r\n            var result = drop.BeforeMethod(string.Empty);\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_when_property_name_is_null()\r\n        {\r\n            // Given\r\n            var drop = new DynamicDrop(new object());\r\n\r\n            // When\r\n            var result = drop.BeforeMethod(null);\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_when_called_with_invalid_property_name_and_model_is_expandoobject()\r\n        {\r\n            // Given\r\n            dynamic model = new ExpandoObject();\r\n            model.Name = \"Nancy\";\r\n\r\n            var drop = new DynamicDrop(model);\r\n\r\n            // When\r\n            var result = drop.BeforeMethod(\"age\");\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_model_value_when_property_name_is_valid_and_model_is_expandoobject()\r\n        {\r\n            // Given\r\n            dynamic model = new ExpandoObject();\r\n            model.Name = \"Nancy\";\r\n\r\n            var drop = new DynamicDrop(model);\r\n\r\n            // When\r\n            var result = drop.BeforeMethod(\"Name\");\r\n\r\n            // Then\r\n            result.ShouldEqual(\"Nancy\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_model_value_when_property_name_is_wrong_case_and_model_is_expandoobject()\r\n        {\r\n            // Given\r\n            dynamic model = new ExpandoObject();\r\n            model.Name = \"Nancy\";\r\n\r\n            var drop = new DynamicDrop(model);\r\n\r\n            // When\r\n            var result = drop.BeforeMethod(\"name\");\r\n\r\n            // Then\r\n            result.ShouldEqual(\"Nancy\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_when_called_with_invalid_property_name_and_model_is_dynamicdictionary()\r\n        {\r\n            // Given\r\n            var model = new DynamicDictionary();\r\n            model[\"Name\"] = \"Nancy\";\r\n\r\n            var drop = new DynamicDrop(model);\r\n\r\n            // When\r\n            var result = drop.BeforeMethod(\"age\");\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_model_value_when_property_name_is_valid_and_model_is_dynamicdictionary()\r\n        {\r\n            // Given\r\n            var model = new DynamicDictionary();\r\n            model[\"Name\"] = \"Nancy\";\r\n\r\n            var drop = new DynamicDrop(model);\r\n\r\n            // When\r\n            var result = drop.BeforeMethod(\"Name\");\r\n\r\n            // Then\r\n            result.ShouldEqual(\"Nancy\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_unwrap_dynamicdictionaryvalue_when_model_is_dynamicdictionary()\r\n        {\r\n            // Given\r\n            var model = new DynamicDictionary();\r\n            model[\"Name\"] = \"Nancy\";\r\n\r\n            var drop = new DynamicDrop(model);\r\n\r\n            // When\r\n            var result = drop.BeforeMethod(\"Name\");\r\n\r\n            // Then\r\n            result.ShouldBeOfType<string>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_null_when_called_with_invalid_property_name_and_model_is_object()\r\n        {\r\n            // Given\r\n            var model = new FakeModel { Name = \"Nancy\" };\r\n            var drop = new DynamicDrop(model);\r\n\r\n            // When\r\n            var result = drop.BeforeMethod(\"age\");\r\n\r\n            // Then\r\n            result.ShouldBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_model_value_when_property_name_is_valid_and_model_is_object()\r\n        {\r\n            // Given\r\n            var model = new FakeModel { Name = \"Nancy\" };\r\n            var drop = new DynamicDrop(model);\r\n\r\n            // When\r\n            var result = drop.BeforeMethod(\"Name\");\r\n\r\n            // Then\r\n            result.ShouldEqual(\"Nancy\");\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.DotLiquid.Tests/FakeModel.cs",
    "content": "﻿namespace Nancy.ViewEngines.DotLiquid.Tests\r\n{\r\n    public class FakeModel\r\n    {\r\n        public string Name { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.ViewEngines.DotLiquid.Tests/Functional/PartialRenderingFixture.cs",
    "content": "namespace Nancy.ViewEngines.DotLiquid.Tests.Functional\r\n{\r\n    using System.Threading.Tasks;\r\n    using Nancy.Testing;\r\n\r\n    using Xunit;\r\n\r\n    public class PartialRenderingFixture\r\n    {\r\n        private readonly Browser browser;\r\n\r\n        public PartialRenderingFixture()\r\n        {\r\n            var bootstrapper = new ConfigurableBootstrapper(with => {\r\n                with.Module<PartialRenderingModule>();\r\n            });\r\n\r\n            this.browser =\r\n                new Browser(bootstrapper);\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_render_view_with_unquoted_partial()\r\n        {\r\n            // Given\r\n            // When\r\n            var result = await this.browser.Get(\"/unquotedpartial\");\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.OK, result.StatusCode);\r\n            Assert.Equal(\"This content is from the partial\", result.Body.AsString());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_render_view_with_singlequoted_partial()\r\n        {\r\n            // Given\r\n            // When\r\n            var result = await this.browser.Get(\"/singlequotedpartial\");\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.OK, result.StatusCode);\r\n            Assert.Equal(\"This content is from the partial\", result.Body.AsString());\r\n        }\r\n\r\n        [Fact]\r\n        public async Task Should_render_view_with_doublequoted_partial()\r\n        {\r\n            // Given\r\n            // When\r\n            var result = await this.browser.Get(\"/doublequotedpartial\");\r\n\r\n            // Then\r\n            Assert.Equal(HttpStatusCode.OK, result.StatusCode);\r\n            Assert.Equal(\"This content is from the partial\", result.Body.AsString());\r\n        }\r\n    }\r\n\r\n    public class PartialRenderingModule : NancyModule\r\n    {\r\n        public PartialRenderingModule()\r\n        {\r\n            Get(\"/unquotedpartial\", args => View[\"unquotedpartial\"]);\r\n\r\n            Get(\"/doublequotedpartial\", args => View[\"doublequotedpartial\"]);\r\n\r\n            Get(\"/singlequotedpartial\", args => View[\"singlequotedpartial\"]);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.DotLiquid.Tests/LiquidNancyFileSystemFixture.cs",
    "content": "namespace Nancy.ViewEngines.DotLiquid.Tests\r\n{\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using Configuration;\r\n    using FakeItEasy;\r\n\r\n    using global::DotLiquid;\r\n    using global::DotLiquid.Exceptions;\r\n\r\n    using Nancy.Tests;\r\n\r\n    using Xunit;\r\n    using Xunit.Extensions;\r\n\r\n    public class LiquidNancyFileSystemFixture\r\n    {\r\n        private readonly INancyEnvironment environment;\r\n\r\n        public LiquidNancyFileSystemFixture()\r\n        {\r\n            this.environment = new DefaultNancyEnvironment();\r\n            this.environment.AddValue(ViewConfiguration.Default);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_locate_template_with_single_quoted_name()\r\n        {\r\n            // Given\r\n            Context context;\r\n            var fileSystem = this.CreateFileSystem(out context,\r\n                new ViewLocationResult(\"views\", \"partial\", \"liquid\", () => new StringReader(\"The correct view\")));\r\n\r\n            // When\r\n            var result = fileSystem.ReadTemplateFile(context, \"'views/partial'\");\r\n\r\n            // Then\r\n            result.ShouldEqual(\"The correct view\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_locate_template_with_double_quoted_name()\r\n        {\r\n            // Given\r\n            Context context;\r\n            var fileSystem = this.CreateFileSystem(out context,\r\n                new ViewLocationResult(\"views\", \"partial\", \"liquid\", () => new StringReader(\"The correct view\")));\r\n\r\n            // When\r\n            var result = fileSystem.ReadTemplateFile(context, @\"\"\"views/partial\"\"\");\r\n\r\n            // Then\r\n            result.ShouldEqual(\"The correct view\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_locate_template_with_unquoted_name()\r\n        {\r\n            // Given\r\n            Context context;\r\n            var fileSystem = this.CreateFileSystem(out context,\r\n                new ViewLocationResult(\"views\", \"partial\", \"liquid\", () => new StringReader(\"The correct view\")));\r\n\r\n            // When\r\n            var result = fileSystem.ReadTemplateFile(context, \"views/partial\");\r\n\r\n            // Then\r\n            result.ShouldEqual(\"The correct view\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_locate_templates_that_does_not_have_liquid_extension()\r\n        {\r\n            // Given\r\n            Context context;\r\n            var fileSystem = this.CreateFileSystem(out context,\r\n                new ViewLocationResult(\"views\", \"partial\", \"cshtml\", () => null));\r\n\r\n            // When\r\n            var exception = Record.Exception(() => fileSystem.ReadTemplateFile(context, \"views/partial\"));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<FileSystemException>();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"partial\")]\r\n        [InlineData(\"paRTial\")]\r\n        [InlineData(\"PARTIAL\")]\r\n        public void Should_ignore_casing_of_template_name(string templateName)\r\n        {\r\n            // Given\r\n            Context context;\r\n            var fileSystem = this.CreateFileSystem(out context,\r\n                new ViewLocationResult(\"views\", \"partial\", \"liquid\", () => new StringReader(\"The correct view\")));\r\n\r\n            // When\r\n            var result = fileSystem.ReadTemplateFile(context, string.Concat(\"views/\", templateName));\r\n\r\n            // Then\r\n            result.ShouldEqual(\"The correct view\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_support_locating_template_when_template_name_contains_liquid_extension()\r\n        {\r\n            // Given\r\n            Context context;\r\n            var fileSystem = this.CreateFileSystem(out context,\r\n                new ViewLocationResult(\"views\", \"partial\", \"liquid\", () => new StringReader(\"The correct view\")));\r\n\r\n            // When\r\n            var result = fileSystem.ReadTemplateFile(context, \"views/partial.liquid\");\r\n\r\n            // Then\r\n            result.ShouldEqual(\"The correct view\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_support_locating_template_when_template_name_does_not_contains_liquid_extension()\r\n        {\r\n            // Given\r\n            Context context;\r\n            var fileSystem = this.CreateFileSystem(out context,\r\n                new ViewLocationResult(\"views\", \"partial\", \"liquid\", () => new StringReader(\"The correct view\")));\r\n\r\n            // When\r\n            var result = fileSystem.ReadTemplateFile(context, \"views/partial\");\r\n\r\n            // Then\r\n            result.ShouldEqual(\"The correct view\");\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"liquid\")]\r\n        [InlineData(\"liqUID\")]\r\n        [InlineData(\"LIQUID\")]\r\n        public void Should_ignore_extension_casing_when_template_name_contains_liquid_extension(string extension)\r\n        {\r\n            // Given\r\n            Context context;\r\n            var fileSystem = this.CreateFileSystem(out context,\r\n                new ViewLocationResult(\"views\", \"partial\", \"liquid\", () => new StringReader(\"The correct view\")));\r\n\r\n            // When\r\n            var result = fileSystem.ReadTemplateFile(context, string.Concat(\"views/partial.\", extension));\r\n\r\n            // Then\r\n            result.ShouldEqual(\"The correct view\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_not_locate_view_when_template_location_not_specified()\r\n        {\r\n            // Given\r\n            Context context;\r\n            var fileSystem = this.CreateFileSystem(out context,\r\n                new ViewLocationResult(\"views\", \"partial\", \"liquid\", () => null));\r\n\r\n            // When\r\n            var exception = Record.Exception(() => fileSystem.ReadTemplateFile(context, \"partial\"));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<FileSystemException>();\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"views\", \"Located in views/\")]\r\n        [InlineData(\"views/shared\", \"Located in views/shared\")]\r\n        public void Should_locate_templates_with_correct_location_specified(string location, string expectedResult)\r\n        {\r\n            // Given\r\n            Context context;\r\n            var fileSystem = this.CreateFileSystem(out context,\r\n                new ViewLocationResult(location, \"partial\", \"liquid\", () => new StringReader(expectedResult)));\r\n\r\n            // When\r\n            var result = fileSystem.ReadTemplateFile(context, string.Concat(location, \"/partial\"));\r\n\r\n            // Then\r\n            result.ShouldEqual(expectedResult);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"views\")]\r\n        [InlineData(\"viEws\")]\r\n        [InlineData(\"VIEWS\")]\r\n        public void Should_ignore_case_of_location_when_locating_template(string location)\r\n        {\r\n            // Given\r\n            Context context;\r\n            var fileSystem = this.CreateFileSystem(out context,\r\n                new ViewLocationResult(location, \"partial\", \"liquid\", () => new StringReader(\"The correct view\")));\r\n\r\n            // When\r\n            var result = fileSystem.ReadTemplateFile(context, string.Concat(location, \"/partial\"));\r\n\r\n            // Then\r\n            result.ShouldEqual(\"The correct view\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_support_backslashes_as_location_seperator()\r\n        {\r\n            // Given\r\n            Context context;\r\n            var fileSystem = this.CreateFileSystem(out context,\r\n                new ViewLocationResult(@\"views/shared\", \"partial\", \"liquid\", () => new StringReader(\"The correct view\")));\r\n\r\n            // When\r\n            var result = fileSystem.ReadTemplateFile(context, @\"views\\shared\\partial\");\r\n\r\n            // Then\r\n            result.ShouldEqual(\"The correct view\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_support_forward_slashes_as_location_seperator()\r\n        {\r\n            // Given\r\n            Context context;\r\n            var fileSystem = this.CreateFileSystem(out context,\r\n                new ViewLocationResult(@\"views/shared\", \"partial\", \"liquid\", () => new StringReader(\"The correct view\")));\r\n\r\n            // When\r\n            var result = fileSystem.ReadTemplateFile(context, @\"views/shared/partial\");\r\n\r\n            // Then\r\n            result.ShouldEqual(\"The correct view\");\r\n        }\r\n\r\n        private LiquidNancyFileSystem CreateFileSystem(out Context context, params ViewLocationResult[] viewLocationResults)\r\n        {\r\n            var viewLocationProvider = A.Fake<IViewLocationProvider>();\r\n            A.CallTo(() => viewLocationProvider.GetLocatedViews(A<IEnumerable<string>>._))\r\n                                               .Returns(viewLocationResults);\r\n\r\n            var viewEngine = A.Fake<IViewEngine>();\r\n            A.CallTo(() => viewEngine.Extensions).Returns(new[] { \"liquid\" });\r\n\r\n            var viewLocator = new DefaultViewLocator(viewLocationProvider, new[] { viewEngine }, this.environment);\r\n\r\n            var startupContext = new ViewEngineStartupContext(\r\n                null,\r\n                viewLocator);\r\n\r\n            var renderContext = A.Fake<IRenderContext>();\r\n            A.CallTo(() => renderContext.LocateView(A<string>.Ignored, A<object>.Ignored))\r\n                .ReturnsLazily(x => viewLocator.LocateView(x.Arguments.Get<string>(0), null));\r\n\r\n            context = new Context(new List<Hash>(), new Hash(),\r\n                Hash.FromAnonymousObject(new { nancy = renderContext }), false);\r\n\r\n            return new LiquidNancyFileSystem(startupContext, new[] { \"liquid\" });\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.DotLiquid.Tests/Nancy.ViewEngines.DotLiquid.Tests.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <TargetFramework>net452</TargetFramework>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <None Update=\"Views\\**\\*\">\n      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>\n    </None>\n  </ItemGroup>\n\n  <ItemGroup>\n    <PackageReference Include=\"DotLiquid\" Version=\"2.0.64\" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "test/Nancy.ViewEngines.DotLiquid.Tests/Properties/AssemblyInfo.cs",
    "content": "﻿using Xunit;\r\n\r\n[assembly: CollectionBehavior(DisableTestParallelization = true)]"
  },
  {
    "path": "test/Nancy.ViewEngines.DotLiquid.Tests/Views/doublequotedpartial.liquid",
    "content": "﻿{% include \"views/partial.liquid\" %}"
  },
  {
    "path": "test/Nancy.ViewEngines.DotLiquid.Tests/Views/partial.liquid",
    "content": "﻿This content is from the partial"
  },
  {
    "path": "test/Nancy.ViewEngines.DotLiquid.Tests/Views/singlequotedpartial.liquid",
    "content": "﻿{% include 'views/partial.liquid' %}"
  },
  {
    "path": "test/Nancy.ViewEngines.DotLiquid.Tests/Views/unquotedpartial.liquid",
    "content": "﻿{% include views/partial.liquid %}"
  },
  {
    "path": "test/Nancy.ViewEngines.Markdown.Tests/Markdown/home.md",
    "content": "@Master['master']\r\n\r\n@Section['Content']\r\n\r\nA First Level Header in Page\r\n====================\r\n\r\nA Second Level Header in Page\r\n---------------------\r\n\r\nNow is the time for all good men to come to\r\nthe aid of their country. This is just a\r\nregular paragraph.\r\n\r\nThe quick brown fox jumped over the lazy\r\ndog's back.\r\n\r\n### Header 3\r\n\r\n> This is a blockquote.\r\n> \r\n> This is the second paragraph in the blockquote.\r\n>\r\n> ## This is an H2 in a blockquote\r\n\r\nMy name is @Model.FullName and I come from the model\r\n\r\n@Partial['partial'];\r\n\r\n@EndSection\r\n\r\n\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Markdown.Tests/Markdown/htmlmaster.html",
    "content": "﻿<!DOCTYPE html>\r\n\r\n<html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n    <meta charset=\"utf-8\" />\r\n    <title></title>\r\n</head>\r\n<body>\r\n    @Section['Content'];\r\n</body>\r\n</html>"
  },
  {
    "path": "test/Nancy.ViewEngines.Markdown.Tests/Markdown/master.md",
    "content": "﻿<!DOCTYPE html>\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n    <title>Markdown Engine Demo</title>\r\n    <link href=\"/Content/main.css\" type=\"text/css\" rel=\"stylesheet\" />\r\n</head>\r\n<body>\r\n\r\n#Markdown Engine Demo\r\n\r\nThis text is in the master page\r\n\r\n@Section['Content']\r\n\r\n**What does Samuel L Jackson think?**\r\n\r\nMy money's in that office, right? If she start giving me some bullshit about it ain't there, and we got to go someplace else and get it, I'm gonna shoot you in the head then and there. Then I'm gonna shoot that bitch in the kneecaps, find out where my goddamn money is. She gonna tell me too. Hey, look at me when I'm talking to you, motherfucker. You listen: we go in there, and that nigga Winston or anybody else is in there, you the first motherfucker to get shot. You understand?\r\n<script type='text/javascript' src='http://code.jquery.com/jquery-latest.min.js'></script>\r\n</body>\r\n</html>"
  },
  {
    "path": "test/Nancy.ViewEngines.Markdown.Tests/Markdown/partial.markdown",
    "content": "﻿####This is from a partial\r\n\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Markdown.Tests/Markdown/standalone.md",
    "content": "﻿<!DOCTYPE html>\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n    <title>Markdown Engine Demo</title>\r\n    <link href=\"/Content/main.css\" type=\"text/css\" rel=\"stylesheet\" />\r\n</head>\r\n<body>\r\nBacon ipsum dolor sit amet strip steak frankfurter bacon corned beef tenderloin chuck, prosciutto beef turkey tri-tip. Prosciutto spare ribs strip steak pork loin bresaola, pork chop sausage. Tri-tip salami ham hock pork pork belly fatback bresaola prosciutto turducken sirloin pork loin andouille sausage. Drumstick sausage tri-tip filet mignon doner corned beef kielbasa, chuck swine shank salami. Prosciutto pork chop biltong cow, leberkas ham hock ground round swine sausage ball tip tenderloin. Turducken pork chop ball tip, short loin frankfurter jowl pig. Prosciutto tail tri-tip, pancetta meatloaf doner ham flank venison pork loin filet mignon sausage.\r\n</body>\r\n</html>"
  },
  {
    "path": "test/Nancy.ViewEngines.Markdown.Tests/Markdown/viewwithhtmlmaster.md",
    "content": "﻿@Master['htmlmaster']\r\n\r\n@Section['Content']\r\n\r\nBacon ipsum dolor sit amet tongue biltong pig brisket, beef corned beef swine rump. Drumstick beef ribs jowl, shoulder swine spare ribs ham hock chicken biltong salami doner chuck venison. Beef ribs bresaola ham andouille filet mignon frankfurter t-bone pancetta tongue tail sirloin kielbasa pork chop bacon. Beef leberkas shoulder ground round tenderloin bacon rump sausage pork belly. Tail short ribs hamburger jowl cow bacon sirloin spare ribs capicola, pig biltong drumstick rump chicken. Chuck kielbasa hamburger, ham hock swine flank boudin shoulder shankle tri-tip leberkas.\r\n\r\n@EndSection"
  },
  {
    "path": "test/Nancy.ViewEngines.Markdown.Tests/MarkdownViewEngineFixture.cs",
    "content": "﻿namespace Nancy.ViewEngines.Markdown.Tests\r\n{\r\n    using System;\r\n    using System.IO;\r\n    using System.Linq;\r\n\r\n    using FakeItEasy;\r\n\r\n    using Nancy.Tests;\r\n    using Nancy.ViewEngines.SuperSimpleViewEngine;\r\n\r\n    using Xunit;\r\n\r\n    public class MarkdownViewEngineFixture\r\n    {\r\n        private readonly MarkDownViewEngine viewEngine;\r\n        private readonly IRenderContext renderContext;\r\n        private readonly IRootPathProvider rootPathProvider;\r\n        private readonly FileSystemViewLocationProvider fileSystemViewLocationProvider;\r\n\r\n        public MarkdownViewEngineFixture()\r\n        {\r\n            this.renderContext = A.Fake<IRenderContext>();\r\n            this.viewEngine = new MarkDownViewEngine(new SuperSimpleViewEngine(Enumerable.Empty<ISuperSimpleViewEngineMatcher>()));\r\n\r\n            this.rootPathProvider = A.Fake<IRootPathProvider>();\r\n\r\n            A.CallTo(() => this.rootPathProvider.GetRootPath()).Returns(Path.Combine(Environment.CurrentDirectory, \"Markdown\"));\r\n\r\n            this.fileSystemViewLocationProvider = new FileSystemViewLocationProvider(this.rootPathProvider, new DefaultFileSystemReader());\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_Markdown()\r\n        {\r\n            // Given\r\n            const string markdown = @\"#Header1\r\n##Header2\r\n###Header3\r\nHi there!\r\n> This is a blockquote.\";\r\n\r\n            var location = new ViewLocationResult(\r\n                string.Empty,\r\n                string.Empty,\r\n                \"md\",\r\n                () => new StringReader(markdown)\r\n            );\r\n\r\n            var html = this.viewEngine.ConvertMarkdown(location);\r\n\r\n            var stream = new MemoryStream();\r\n\r\n            A.CallTo(() => this.renderContext.ViewCache.GetOrAdd(location, A<Func<ViewLocationResult, string>>.Ignored))\r\n             .Returns(html);\r\n\r\n            // When\r\n            var response = this.viewEngine.RenderView(location, null, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            var result = ReadAll(stream);\r\n            result.ShouldEqual(html);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_masterpage()\r\n        {\r\n            //Given, When\r\n            var result = SetupCallAndReadViewWithMasterPage();\r\n\r\n            //Then\r\n            result.ShouldContain(\"What does Samuel L Jackson think?\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_render_model()\r\n        {\r\n            //Given, When\r\n            var result = SetupCallAndReadViewWithMasterPage(useModel: true);\r\n\r\n            //Then\r\n            result.ShouldContain(\"My name is Vincent Vega and I come from the model\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_handle_script_tags_before_body_tag()\r\n        {\r\n            //Given, When\r\n            const string expected = @\"<script type='text/javascript' src='http://code.jquery.com/jquery-latest.min.js'></script>\";\r\n\r\n            var result = SetupCallAndReadViewWithMasterPage();\r\n\r\n            //Then\r\n            result.ShouldContain(expected);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_convert_markdown_in_master()\r\n        {\r\n            //Given, When\r\n            var result = SetupCallAndReadViewWithMasterPage();\r\n\r\n            //Then\r\n            result.ShouldContain(\"<h1>Markdown Engine Demo</h1>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_convert_partial_views_with_markdown_content()\r\n        {\r\n            //Given, When\r\n            var result = SetupCallAndReadViewWithMasterPage();\r\n\r\n            //Then\r\n            result.ShouldContain(\"<h4>This is from a partial</h4>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_convert_standalone()\r\n        {\r\n            var location = FindView(\"standalone\");\r\n\r\n            var result = this.viewEngine.ConvertMarkdown(location);\r\n\r\n            Assert.True(result.StartsWith(\"<!DOCTYPE html>\"));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_convert_view()\r\n        {\r\n            var location = FindView(\"home\");\r\n            var result = this.viewEngine.ConvertMarkdown(location);\r\n\r\n            result.ShouldStartWith(\"@Master['master']\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_convert_standalone_view_with_no_master()\r\n        {\r\n            var location = FindView(\"standalone\");\r\n\r\n            var html = this.viewEngine.ConvertMarkdown(location);\r\n\r\n            A.CallTo(() => this.renderContext.ViewCache.GetOrAdd(location, A<Func<ViewLocationResult, string>>.Ignored))\r\n             .Returns(html);\r\n\r\n            var stream = new MemoryStream();\r\n\r\n            var response = this.viewEngine.RenderView(location, null, this.renderContext);\r\n\r\n            response.Contents.Invoke(stream);\r\n\r\n            var result = ReadAll(stream);\r\n\r\n            Assert.True(result.StartsWith(\"<!DOCTYPE html>\"));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_use_HTML_MasterPage()\r\n        {\r\n            var location = FindView(\"viewwithhtmlmaster\");\r\n\r\n            var masterLocation = FindView(\"htmlmaster\");\r\n\r\n            var html = this.viewEngine.ConvertMarkdown(location);\r\n\r\n            A.CallTo(() => this.renderContext.ViewCache.GetOrAdd(location, A<Func<ViewLocationResult, string>>.Ignored))\r\n             .Returns(html);\r\n\r\n            A.CallTo(() => this.renderContext.LocateView(\"htmlmaster\", A<object>.Ignored)).Returns(masterLocation);\r\n\r\n            var stream = new MemoryStream();\r\n\r\n\r\n            var response = this.viewEngine.RenderView(location, null, this.renderContext);\r\n\r\n            response.Contents.Invoke(stream);\r\n\r\n            var result = ReadAll(stream);\r\n\r\n            result.ShouldStartWith(\"<!DOCTYPE html>\");\r\n            result.ShouldContain(\"<p>Bacon ipsum dolor\");\r\n        }\r\n\r\n        private string SetupCallAndReadViewWithMasterPage(bool useModel = false)\r\n        {\r\n            var location = FindView(\"home\");\r\n\r\n            var masterLocation = FindView(\"master\");\r\n\r\n            var partialLocation = FindView(\"partial\");\r\n\r\n            var html = this.viewEngine.ConvertMarkdown(location);\r\n\r\n            A.CallTo(() => this.renderContext.ViewCache.GetOrAdd(location, A<Func<ViewLocationResult, string>>.Ignored))\r\n             .Returns(html);\r\n\r\n            A.CallTo(() => this.renderContext.LocateView(\"master\", A<object>.Ignored)).Returns(masterLocation);\r\n\r\n            A.CallTo(() => this.renderContext.LocateView(\"partial\", A<object>.Ignored)).Returns(partialLocation);\r\n\r\n            var stream = new MemoryStream();\r\n\r\n            var model = useModel ? new UserModel(\"Vincent\", \"Vega\") : null;\r\n\r\n            var response = this.viewEngine.RenderView(location, model, this.renderContext);\r\n\r\n            response.Contents.Invoke(stream);\r\n\r\n            return ReadAll(stream);\r\n        }\r\n\r\n        private static string ReadAll(Stream stream)\r\n        {\r\n            stream.Position = 0;\r\n            using (var reader = new StreamReader(stream))\r\n            {\r\n                return reader.ReadToEnd();\r\n            }\r\n        }\r\n\r\n        private ViewLocationResult FindView(string viewName)\r\n        {\r\n            var location = this.fileSystemViewLocationProvider.GetLocatedViews(new[] { \"md\", \"markdown\", \"html\" }).First(r => r.Name == viewName);\r\n            return location;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Markdown.Tests/MarkdownViewengineRenderFixture.cs",
    "content": "﻿namespace Nancy.ViewEngines.Markdown.Tests\r\n{\r\n    using Nancy.Tests;\r\n\r\n    using Xunit;\r\n\r\n    public class MarkdownViewengineRenderFixture\r\n    {\r\n        [Fact]\r\n        public void Should_handle_onload_and_css_attributes_on_body_tag()\r\n        {\r\n            //Given\r\n            var html = @\"<!DOCTYPE html><html xmlns='http://www.w3.org/1999/xhtml'><head></head><body class='mybodyclass'>#Markdown</body></html>\";\r\n\r\n            var expected = @\"<!DOCTYPE html><html xmlns='http://www.w3.org/1999/xhtml'><head></head><body class='mybodyclass'><h1>Markdown</h1></body></html>\";\r\n\r\n            //When            \r\n            var result = MarkdownViewengineRender.RenderMasterPage(html);\r\n\r\n            //Then\r\n            result.ShouldEqual(expected);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_handle_empty_body_tag()\r\n        {\r\n            //Given\r\n            var html = @\"<!DOCTYPE html><html xmlns='http://www.w3.org/1999/xhtml'><head></head><body>#Markdown</body></html>\";\r\n\r\n            var expected = @\"<!DOCTYPE html><html xmlns='http://www.w3.org/1999/xhtml'><head></head><body><h1>Markdown</h1></body></html>\";\r\n\r\n            //When            \r\n            var result = MarkdownViewengineRender.RenderMasterPage(html);\r\n\r\n            //Then\r\n            result.ShouldEqual(expected);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Markdown.Tests/Nancy.ViewEngines.Markdown.Tests.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <TargetFramework>net452</TargetFramework>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <None Update=\"Markdown\\**\\*\">\n      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>\n    </None>\n  </ItemGroup>\n\n  <ItemGroup>\n    <PackageReference Include=\"MarkdownSharp\" Version=\"1.13.0\" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Markdown.Tests/UserModel.cs",
    "content": "﻿namespace Nancy.ViewEngines.Markdown.Tests\r\n{\r\n    public class UserModel\r\n    {\r\n        public string FirstName { get; private set; }\r\n\r\n        public string LastName { get; private set; }\r\n\r\n        public string FullName { get { return FirstName + \" \" + LastName; } }\r\n\r\n        /// <summary>\r\n        /// Initializes a new instance of the <see cref=\"T:System.Object\"/> class.\r\n        /// </summary>\r\n        public UserModel(string firstName, string lastName)\r\n        {\r\n            this.FirstName = firstName;\r\n            this.LastName = lastName;\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests/GreetingViewBase.cs",
    "content": "namespace Nancy.ViewEngines.Razor.Tests\r\n{\r\n    public abstract class GreetingViewBase : NancyRazorViewBase\r\n    {\r\n        public string Greet()\r\n        {\r\n            return \"Hi, Nancy!\";\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests/Nancy.ViewEngines.Razor.Tests.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <TargetFramework>net452</TargetFramework>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <None Update=\"TestViews\\**\\*\">\n      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>\n    </None>\n  </ItemGroup>\n\n  <ItemGroup>\n    <ProjectReference Include=\"../../src/Nancy.ViewEngines.Razor/Nancy.ViewEngines.Razor.csproj\" />\n    <ProjectReference Include=\"../Nancy.ViewEngines.Razor.Tests.Models/Nancy.ViewEngines.Razor.Tests.Models.csproj\" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests/RazorViewEngineFixture.cs",
    "content": "﻿namespace Nancy.ViewEngines.Razor.Tests\r\n{\r\n    using System;\r\n    using System.CodeDom;\r\n    using System.CodeDom.Compiler;\r\n    using System.Dynamic;\r\n    using System.IO;\r\n    using System.Linq;\r\n    using System.Text;\r\n    using FakeItEasy;\r\n    using Microsoft.CSharp;\r\n    using Nancy.Configuration;\r\n    using Nancy.Tests;\r\n    using Nancy.ViewEngines.Razor.Tests.Models;\r\n    using Xunit;\r\n\r\n    public class RazorViewEngineFixture\r\n    {\r\n        private readonly RazorViewEngine engine;\r\n        private readonly IRenderContext renderContext;\r\n        private readonly IRazorConfiguration configuration;\r\n        private readonly FileSystemViewLocationProvider fileSystemViewLocationProvider;\r\n        private readonly IRootPathProvider rootPathProvider;\r\n\r\n        public RazorViewEngineFixture()\r\n        {\r\n            var assemblyCatalog = new AppDomainAssemblyCatalog();\r\n\r\n            var environment = new DefaultNancyEnvironment();\r\n            environment.Tracing(\r\n                enabled: true,\r\n                displayErrorTraces: true);\r\n\r\n            this.configuration = A.Fake<IRazorConfiguration>();\r\n            this.engine = new RazorViewEngine(this.configuration, environment, assemblyCatalog);\r\n            A.CallTo(() => this.configuration.GetAssemblyNames()).Returns(new[] { \"Nancy.ViewEngines.Razor.Tests.Models\" });\r\n\r\n            var cache = A.Fake<IViewCache>();\r\n            A.CallTo(() => cache.GetOrAdd(A<ViewLocationResult>.Ignored, A<Func<ViewLocationResult, Func<INancyRazorView>>>.Ignored))\r\n                .ReturnsLazily(x =>\r\n                {\r\n                    var result = x.GetArgument<ViewLocationResult>(0);\r\n                    return x.GetArgument<Func<ViewLocationResult, Func<INancyRazorView>>>(1).Invoke(result);\r\n                });\r\n\r\n            this.renderContext = A.Fake<IRenderContext>();\r\n            A.CallTo(() => this.renderContext.ViewCache).Returns(cache);\r\n            A.CallTo(() => this.renderContext.LocateView(A<string>.Ignored, A<object>.Ignored))\r\n                .ReturnsLazily(x =>\r\n                {\r\n                    var viewName = x.GetArgument<string>(0);\r\n                    return FindView(viewName);\r\n                });\r\n\r\n            this.rootPathProvider = A.Fake<IRootPathProvider>();\r\n            A.CallTo(() => this.rootPathProvider.GetRootPath()).Returns(Path.Combine(Environment.CurrentDirectory, \"TestViews\"));\r\n\r\n            this.fileSystemViewLocationProvider = new FileSystemViewLocationProvider(this.rootPathProvider, new DefaultFileSystemReader());\r\n        }\r\n\r\n        [Fact]\r\n        public void GetCompiledView_should_render_to_stream()\r\n        {\r\n            // Given\r\n            var location = new ViewLocationResult(\r\n                string.Empty,\r\n                string.Empty,\r\n                \"cshtml\",\r\n                () => new StringReader(@\"@{var x = \"\"test\"\";}<h1>Hello Mr. @x</h1>\")\r\n            );\r\n\r\n            var stream = new MemoryStream();\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, null, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            stream.ShouldEqual(\"<h1>Hello Mr. test</h1>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_render_view_with_partial_to_stream()\r\n        {\r\n            // Given\r\n            var location = new ViewLocationResult(\r\n                string.Empty,\r\n                string.Empty,\r\n                \"cshtml\",\r\n                () => new StringReader(@\"@{var x = \"\"test\"\";}<h1>Hello Mr. @x</h1> @Html.Partial(\"\"partial.cshtml\"\")\")\r\n            );\r\n\r\n            var partialLocation = new ViewLocationResult(\r\n                string.Empty,\r\n                \"partial.cshtml\",\r\n                \"cshtml\",\r\n                () => new StringReader(@\"this is partial\")\r\n            );\r\n\r\n            A.CallTo(() => this.renderContext.LocateView(\"partial.cshtml\", null)).Returns(partialLocation);\r\n\r\n            var stream = new MemoryStream();\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, null, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            stream.ShouldEqual(\"<h1>Hello Mr. test</h1> this is partial\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_support_files_with_the_razor_extensions()\r\n        {\r\n            // Given, When\r\n            var extensions = this.engine.Extensions;\r\n\r\n            // Then\r\n            extensions.ShouldHaveCount(1);\r\n            extensions.ShouldEqualSequence(new[] { \"cshtml\" });\r\n        }\r\n\r\n        [Fact]\r\n        public void RenderView_should_accept_a_model_and_read_from_it_into_the_stream()\r\n        {\r\n            // Given\r\n            var location = new ViewLocationResult(\r\n                string.Empty,\r\n                string.Empty,\r\n                \"cshtml\",\r\n                () => new StringReader(@\"<h1>Hello Mr. @Model.Name</h1>\")\r\n            );\r\n\r\n            var stream = new MemoryStream();\r\n\r\n            dynamic model = new ExpandoObject();\r\n            model.Name = \"test\";\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, model, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            stream.ShouldEqual(\"<h1>Hello Mr. test</h1>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void RenderView_csharp_should_use_model_directive_for_strongly_typed_view()\r\n        {\r\n            // Given\r\n            var location = FindView(\"ViewThatUsesModelCSharp\");\r\n\r\n            var stream = new MemoryStream();\r\n\r\n            var model = new DateTime(2000, 1, 1);\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, model, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            stream.ShouldEqual(\"<h1>Hello at \" + model.ToString(\"MM/dd/yyyy\") + \"</h1>\", true);\r\n        }\r\n\r\n        [Fact]\r\n        public void RenderView_csharp_should_be_able_to_use_a_model_from_another_assembly()\r\n        {\r\n            // Given\r\n            var view = new StringBuilder()\r\n                .AppendLine(\"@model Nancy.ViewEngines.Razor.Tests.Models.Person\")\r\n                .Append(\"<h1>Hello Mr. @Model.Name</h1>\");\r\n\r\n            var location = new ViewLocationResult(\r\n                string.Empty,\r\n                string.Empty,\r\n                \"cshtml\",\r\n                () => new StringReader(view.ToString())\r\n            );\r\n\r\n            var stream = new MemoryStream();\r\n\r\n            var model = new Person { Name = \"Jeff\" };\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, model, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            stream.ShouldEqual(\"<h1>Hello Mr. Jeff</h1>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void RenderView_csharp_should_be_able_to_use_a_using_statement()\r\n        {\r\n            // Given\r\n            var view = new StringBuilder()\r\n                .AppendLine(\"@model Nancy.ViewEngines.Razor.Tests.Models.Person\")\r\n                .AppendLine(\"@using Nancy.ViewEngines.Razor.Tests.Models\")\r\n                .AppendLine(@\"@{ var hobby = new Hobby { Name = \"\"Music\"\" }; }\")\r\n                .Append(\"<h1>Mr. @Model.Name likes @hobby.Name!</h1>\");\r\n\r\n            var location = new ViewLocationResult(\r\n                string.Empty,\r\n                string.Empty,\r\n                \"cshtml\",\r\n                () => new StringReader(view.ToString())\r\n            );\r\n\r\n            var stream = new MemoryStream();\r\n\r\n            var model = new Person { Name = \"Jeff\" };\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, model, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            stream.ShouldEqual(\"<h1>Mr. Jeff likes Music!</h1>\", true);\r\n        }\r\n\r\n        [Fact]\r\n        public void RenderView_csharp_should_be_able_to_find_the_model_when_a_null_model_is_passed()\r\n        {\r\n            var view = new StringBuilder()\r\n                .AppendLine(\"@model Nancy.ViewEngines.Razor.Tests.Models.Person\")\r\n                .AppendLine(@\"@{ var hobby = new Hobby { Name = \"\"Music\"\" }; }\")\r\n                .Append(\"<h1>Mr. Somebody likes @hobby.Name!</h1>\");\r\n\r\n            var location = new ViewLocationResult(\r\n                string.Empty,\r\n                string.Empty,\r\n                \"cshtml\",\r\n                () => new StringReader(view.ToString())\r\n            );\r\n\r\n            var stream = new MemoryStream();\r\n\r\n            A.CallTo(() => this.configuration.AutoIncludeModelNamespace).Returns(true);\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, null, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            stream.ShouldEqual(\"<h1>Mr. Somebody likes Music!</h1>\", true);\r\n        }\r\n\r\n        [Fact]\r\n        public void RenderView_csharp_should_include_namespace_of_model_if_specified_in_the_configuration()\r\n        {\r\n            // Given\r\n            var view = new StringBuilder()\r\n                .AppendLine(\"@model Nancy.ViewEngines.Razor.Tests.Models.Person\")\r\n                .AppendLine(@\"@{ var hobby = new Hobby { Name = \"\"Music\"\" }; }\")\r\n                .Append(\"<h1>Mr. @Model.Name likes @hobby.Name!</h1>\");\r\n\r\n            var location = new ViewLocationResult(\r\n                string.Empty,\r\n                string.Empty,\r\n                \"cshtml\",\r\n                () => new StringReader(view.ToString())\r\n            );\r\n\r\n            var stream = new MemoryStream();\r\n\r\n            var model = new Person { Name = \"Jeff\" };\r\n\r\n            A.CallTo(() => this.configuration.AutoIncludeModelNamespace).Returns(true);\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, model, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            stream.ShouldEqual(\"<h1>Mr. Jeff likes Music!</h1>\", true);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_render_view_with_layout_to_stream()\r\n        {\r\n            // Given\r\n            var location = FindView(\"ViewThatUsesLayout\");\r\n\r\n            var stream = new MemoryStream();\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, null, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            var output = ReadAll(stream);\r\n            output.ShouldContainInOrder(\"<h1>SimplyLayout</h1>\", \"<div>ViewThatUsesLayout</div>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_render_view_with_model_and_layout_to_stream()\r\n        {\r\n            // Given\r\n            var location = FindView(\"ViewThatUsesLayoutAndModel\");\r\n\r\n            var stream = new MemoryStream();\r\n\r\n            dynamic model = new ExpandoObject();\r\n            model.Name = \"my test\";\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, model, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            var output = ReadAll(stream);\r\n            output.ShouldContainInOrder(\"<h1>SimplyLayout</h1>\", \"<div>ViewThatUsesLayoutAndModel: my test</div>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_render_view_with_layout_and_section_to_stream()\r\n        {\r\n            // Given\r\n            var location = FindView(\"ViewThatUsesLayoutAndSection\");\r\n\r\n            var stream = new MemoryStream();\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, null, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            var output = ReadAll(stream);\r\n            output.ShouldContainInOrder(\"<h1>SimplyLayout</h1>\",\r\n                                        \"<div>First section in ViewThatUsesLayoutAndSection</div>\",\r\n                                        \"<div>ViewThatUsesLayoutAndSection</div>\");\r\n        }\r\n\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_render_view_with_layout_and_many_sections_to_stream()\r\n        {\r\n            // Given\r\n            var location = FindView(\"ViewThatUsesLayoutAndManySection\");\r\n\r\n            var stream = new MemoryStream();\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, null, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            var output = ReadAll(stream);\r\n            output.ShouldContainInOrder(\"<h1>SimplyLayout</h1>\",\r\n                                        \"<div>First section in ViewThatUsesLayoutAndManySection</div>\",\r\n                                        \"<div>Second section in ViewThatUsesLayoutAndManySection</div>\",\r\n                                        \"<div>ViewThatUsesLayoutAndManySection</div>\",\r\n                                        \"<div>Third section in ViewThatUsesLayoutAndManySection</div>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_render_view_with_layout_and_optional_section_to_stream()\r\n        {\r\n            // Given\r\n            var location = FindView(\"ViewThatUsesLayoutAndOptionalSection\");\r\n\r\n            var stream = new MemoryStream();\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, null, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            var output = ReadAll(stream);\r\n            output.ShouldContainInOrder(\"<h1>SimplyLayout</h1>\",\r\n                                        \"<div>ViewThatUsesLayoutAndOptionalSection</div>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_render_view_with_layout_and_optional_section_with_default_to_stream()\r\n        {\r\n            // Given\r\n            var location = FindView(\"ViewThatUsesLayoutAndOptionalSectionWithDefaults\");\r\n            var stream = new MemoryStream();\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, null, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            var output = ReadAll(stream);\r\n            output.ShouldContainInOrder(\"<h1>SectionWithDefaultsLayout</h1>\",\r\n                                        \"<div>OptionalSectionDefault</div>\",\r\n                                        \"<div>ViewThatUsesLayoutAndOptionalSectionWithDefaults</div>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_render_view_with_layout_and_optional_section_overriding_the_default_to_stream()\r\n        {\r\n            // Given\r\n            var location = FindView(\"ViewThatUsesLayoutAndOptionalSectionOverridingDefaults\");\r\n            var stream = new MemoryStream();\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, null, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            var output = ReadAll(stream);\r\n            output.ShouldContainInOrder(\"<h1>SectionWithDefaultsLayout</h1>\",\r\n                                        \"<div>OptionalSectionOverride</div>\",\r\n                                        \"<div>ViewThatUsesLayoutAndOptionalSectionOverridingDefaults</div>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_render_view_with_helper_to_steam()\r\n        {\r\n            // Given\r\n            var location = FindView(\"ViewThatUsesHelper\");\r\n\r\n            var stream = new MemoryStream();\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, null, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            var output = ReadAll(stream);\r\n            output.ShouldContainInOrder(\"<h1>SimplyLayout</h1>\", \"<div>ViewThatUsesHelper</div>\", \"<p class=\\\"className\\\"></p>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_custom_view_base_with_csharp_views()\r\n        {\r\n            // Given\r\n            var view = new StringBuilder()\r\n                .AppendLine(\"@inherits Nancy.ViewEngines.Razor.Tests.GreetingViewBase\")\r\n                .Append(\"<h1>@Greet()</h1>\");\r\n\r\n            var location = new ViewLocationResult(\r\n                string.Empty,\r\n                string.Empty,\r\n                \"cshtml\",\r\n                () => new StringReader(view.ToString())\r\n            );\r\n\r\n            var stream = new MemoryStream();\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, null, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            var output = ReadAll(stream).Trim();\r\n            output.ShouldEqual(\"<h1>Hi, Nancy!</h1>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_render_attributes_with_code_inside()\r\n        {\r\n            var location = FindView(\"ViewThatUsesAttributeWithCodeInside\");\r\n            var stream = new MemoryStream();\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, new TestModel { Name = \"Bob\", Slug = \"BobSlug\" }, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            var output = ReadAll(stream);\r\n            output.ShouldContain(\"<a href=\\\"BobSlug\\\">Bob</a>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_render_compilation_source_on_compilation_error()\r\n        {\r\n            // Given\r\n            var view = new StringBuilder()\r\n                .AppendLine(\"@using Nancy.ViewEngines.Razor.Tests.GreetingViewBase\")\r\n                .Append(\"<h1>@Greet(</h1>\");\r\n\r\n            var location = new ViewLocationResult(\r\n                string.Empty,\r\n                string.Empty,\r\n                \"cshtml\",\r\n                () => new StringReader(view.ToString())\r\n            );\r\n\r\n            var stream = new MemoryStream();\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, null, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            var output = ReadAll(stream);\r\n            output.ShouldContain(\"namespace RazorOutput {\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_render_attributes_with_dynamic_null_inside()\r\n        {\r\n            // Given\r\n            var location = FindView(\"ViewThatUsesAttributeWithDynamicNullInside\");\r\n            var stream = new MemoryStream();\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, null, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            var output = ReadAll(stream);\r\n            output.ShouldContain(\"<input value=\\\"\\\" />\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_render_attributes_with_HtmlString_inside()\r\n        {\r\n            // Given\r\n            var location = FindView(\"ViewThatUsesAttributeWithHtmlStringInside\");\r\n            var stream = new MemoryStream();\r\n            const string PHRASE = \"Slugs & bugs are secret spies on gardeners, but <strong>no one</strong> knows who they spy for\";\r\n            const string PHRASE_RESULT = \"Slugs &amp; bugs are secret spies on gardeners, but &lt;strong&gt;no one&lt;/strong&gt; knows who they spy for\";\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, PHRASE, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            var output = ReadAll(stream);\r\n            output.ShouldContain(string.Format(\"<input value=\\\"{0}\\\" />\", PHRASE_RESULT));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_render_attributes_with_RawHtmlString_inside()\r\n        {\r\n            // Given\r\n            var location = FindView(\"ViewThatUsesAttributeWithRawHtmlStringInside\");\r\n            var stream = new MemoryStream();\r\n            const string PHRASE = \"Slugs & bugs are secret spies on gardeners, but <strong>no one</strong> knows who they spy for\";\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, PHRASE, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            var output = ReadAll(stream);\r\n            output.ShouldContain(string.Format(\"<input value=\\\"{0}\\\" />\", PHRASE));\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_render_attributes_with_NonEncodedHtmlString_inside()\r\n        {\r\n            // Given\r\n            var location = FindView(\"ViewThatUsesAttributeWithNonEncodedHtmlStringInside\");\r\n            var stream = new MemoryStream();\r\n            const string PHRASE = \"Slugs are secret spies on gardeners, but no one knows who they spy for\";\r\n\r\n            // When\r\n            var response = this.engine.RenderView(location, new NonEncodedHtmlString(PHRASE), this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            var output = ReadAll(stream);\r\n            output.ShouldContain(string.Format(\"<input value=\\\"{0}\\\" />\", PHRASE));\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(typeof(string))]\r\n        [InlineData(typeof(byte))]\r\n        [InlineData(typeof(sbyte))]\r\n        [InlineData(typeof(short))]\r\n        [InlineData(typeof(ushort))]\r\n        [InlineData(typeof(int))]\r\n        [InlineData(typeof(uint))]\r\n        [InlineData(typeof(long))]\r\n        [InlineData(typeof(ulong))]\r\n        [InlineData(typeof(float))]\r\n        [InlineData(typeof(double))]\r\n        [InlineData(typeof(decimal))]\r\n        [InlineData(typeof(char))]\r\n        [InlineData(typeof(bool))]\r\n        [InlineData(typeof(object))]\r\n        [InlineData(typeof(Tuple<string>))]\r\n        [InlineData(typeof(Tuple<Tuple<string>>))]\r\n        [InlineData(typeof(Tuple<string, int>))]\r\n        [InlineData(typeof(Tuple<string, Tuple<int>>))]\r\n        [InlineData(typeof(Tuple<string, Tuple<int>, int>))]\r\n        [InlineData(typeof(Tuple<string, Tuple<int, string>, Tuple<int>, int>))]\r\n        [InlineData(typeof(Tuple<string, Tuple<int, string>, Tuple<int>, int, Tuple<string, Tuple<int, int>>>))]\r\n        [InlineData(typeof(int[]))]\r\n        [InlineData(typeof(int[,]))]\r\n        [InlineData(typeof(int[, , , ,]))]\r\n        [InlineData(typeof(int[][]))]\r\n        [InlineData(typeof(int[][, ,][]))]\r\n        [InlineData(typeof(Tuple<int, string>[][, ,][]))]\r\n        [InlineData(typeof(Tuple<int, int[][, ,][], string>))]\r\n        public void Should_be_able_to_render_csharp_view_with_generic_model(Type expectedType)\r\n        {\r\n            // Given\r\n            var location = CreateViewLocationWithModel(expectedType, new CSharpCodeProvider(), \"model\");\r\n\r\n            // When\r\n            var stream = new MemoryStream();\r\n            var response = this.engine.RenderView(location, null, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n\r\n            // Then\r\n            stream.ShouldEqual(expectedType.FullName, true);\r\n        }\r\n\r\n        private static ViewLocationResult CreateViewLocationWithModel(Type expectedType, CodeDomProvider provider, string modelDirective)\r\n        {\r\n            var codeTypeRef = new CodeTypeReference(expectedType);\r\n            var modelType = provider.GetTypeOutput(codeTypeRef);\r\n\r\n            var modelTypeCode = BuildCodeExtractingModelType(provider);\r\n\r\n            var view = string.Format(\"@{0} {1}\\n\\n@{2}\", modelDirective, modelType, modelTypeCode);\r\n\r\n            return new ViewLocationResult(\r\n                string.Empty,\r\n                string.Empty,\r\n                string.Concat(provider.FileExtension, \"html\"),\r\n                () => new StringReader(view)\r\n                );\r\n        }\r\n\r\n        private static string BuildCodeExtractingModelType(CodeDomProvider provider)\r\n        {\r\n            var getType = new CodeMethodInvokeExpression\r\n                (\r\n                    new CodeThisReferenceExpression(),\r\n                    \"GetType\"\r\n                );\r\n\r\n            var baseType = new CodeFieldReferenceExpression\r\n                (\r\n                    getType,\r\n                    \"BaseType\"\r\n                );\r\n\r\n            var getFirstGenericArgument = new CodeArrayIndexerExpression\r\n                (\r\n                    new CodeMethodInvokeExpression\r\n                        (\r\n                        baseType,\r\n                        \"GetGenericArguments\"\r\n                        ),\r\n                    new CodePrimitiveExpression(0)\r\n                );\r\n\r\n            var fullName = new CodeFieldReferenceExpression\r\n                (\r\n                    getFirstGenericArgument,\r\n                    \"FullName\"\r\n                );\r\n\r\n            string modelTypeCode;\r\n            using (var writer = new StringWriter())\r\n            {\r\n                provider.GenerateCodeFromExpression(fullName, writer, new CodeGeneratorOptions());\r\n                modelTypeCode = writer.ToString();\r\n            }\r\n            return modelTypeCode;\r\n        }\r\n\r\n        private static string ReadAll(Stream stream)\r\n        {\r\n            stream.Position = 0;\r\n            using (var reader = new StreamReader(stream))\r\n            {\r\n                return reader.ReadToEnd();\r\n            }\r\n        }\r\n\r\n        private ViewLocationResult FindView(string viewName)\r\n        {\r\n            var location = this.fileSystemViewLocationProvider.GetLocatedViews(new[] { \"cshtml\", \"vbhtml\" }).FirstOrDefault(r => r.Name == viewName);\r\n            return location;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests/TestModel.cs",
    "content": "﻿namespace Nancy.ViewEngines.Razor.Tests\r\n{\r\n    public class TestModel\r\n    {\r\n        public string Slug { get; set; }\r\n\r\n        public string Name { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests/TestViews/Layouts/LayoutWithManySections.cshtml",
    "content": "﻿<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\r\n<html>\r\n\t<head>\r\n\t\t<title></title>\r\n\t</head>\r\n\t<body>\r\n\t<h1>SimplyLayout</h1>\r\n\t<div>\r\n\t\t@RenderSection(\"FirstSection\")\r\n\t</div>\r\n\t<div>\r\n\t\t@RenderSection(\"SecondSection\")\r\n\t</div>\r\n\t<div>\r\n\t\t@RenderBody()\r\n\t</div>\t\r\n\t<div>\r\n\t\t@RenderSection(\"ThirdSection\")\r\n\t</div>\r\n\t</body>\r\n</html>"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests/TestViews/Layouts/LayoutWithOptionalSection.cshtml",
    "content": "﻿<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\r\n<html>\r\n\t<head>\r\n\t\t<title></title>\r\n\t</head>\r\n\t<body>\r\n\t<h1>SimplyLayout</h1>\r\n\t<div>\r\n\t\t@RenderSection(\"FirstSection\", required: false)\r\n\t</div>\r\n\t<div>\r\n\t\t@RenderBody()\r\n\t</div>\t\r\n\t</body>\r\n</html>"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests/TestViews/Layouts/LayoutWithOptionalSectionWithDefaults.cshtml",
    "content": "﻿<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\r\n<html>\r\n\t<head>\r\n\t\t<title></title>\r\n\t</head>\r\n\t<body>\r\n\t<h1>SectionWithDefaultsLayout</h1>\r\n\t<div>\r\n\t@if (IsSectionDefined(\"FirstSection\")) {\r\n\t@RenderSection(\"FirstSection\", required: false)\r\n\t} else {\r\n\t<div>OptionalSectionDefault</div>\r\n\t}\r\n\t</div>\r\n\t<div>\r\n\t\t@RenderBody()\r\n\t</div>\t\r\n\t</body>\r\n</html>"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests/TestViews/Layouts/LayoutWithSection.cshtml",
    "content": "﻿<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\r\n<html>\r\n\t<head>\r\n\t\t<title></title>\r\n\t</head>\r\n\t<body>\r\n\t<h1>SimplyLayout</h1>\r\n\t<div>\r\n\t\t@RenderSection(\"FirstSection\")\r\n\t</div>\r\n\t<div>\r\n\t\t@RenderBody()\r\n\t</div>\t\r\n\t</body>\r\n</html>"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests/TestViews/Layouts/SimplyLayout.cshtml",
    "content": "﻿<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\r\n<html>\r\n\t<head>\r\n\t\t<title></title>\r\n\t</head>\r\n\t<body>\r\n\t<h1>SimplyLayout</h1>\r\n\t<div>\r\n\t\t@RenderBody()\r\n\t</div>\t\r\n\t</body>\r\n</html>"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests/TestViews/ViewThatUsesAttributeWithCodeInside.cshtml",
    "content": "﻿<!DOCTYPE html>\r\n\r\n<html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n    <meta charset=\"utf-8\" />\r\n    <title></title>\r\n</head>\r\n<body>\r\n    <a href=\"@Model.Slug\">@Model.Name</a>\r\n</body>\r\n</html>"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests/TestViews/ViewThatUsesAttributeWithDynamicNullInside.cshtml",
    "content": "﻿<input value=\"@ViewBag.NothingToSeeHere\" />"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests/TestViews/ViewThatUsesAttributeWithHtmlStringInside.cshtml",
    "content": "﻿<input value=\"@Model\" />"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests/TestViews/ViewThatUsesAttributeWithNonEncodedHtmlStringInside.cshtml",
    "content": "﻿<input value=\"@Model\" />"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests/TestViews/ViewThatUsesAttributeWithRawHtmlStringInside.cshtml",
    "content": "﻿<input value=\"@Html.Raw(Model)\" />"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests/TestViews/ViewThatUsesHelper.cshtml",
    "content": "﻿@{\r\n    Layout = \"SimplyLayout\";\r\n}\r\n\r\n<div>ViewThatUsesHelper</div>\r\n\r\n@test(\"className\")\r\n\r\n@helper test(string className)\r\n{\r\n    <p class=\"@className\"></p>\r\n}"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests/TestViews/ViewThatUsesLayout.cshtml",
    "content": "﻿@{\r\n    Layout = \"SimplyLayout\";\r\n}\r\n\r\n<div>ViewThatUsesLayout</div>"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests/TestViews/ViewThatUsesLayoutAndManySection.cshtml",
    "content": "﻿@{\r\n    Layout = \"LayoutWithManySections\";\r\n}\r\n\r\n@section FirstSection {\r\n    <div>First section in ViewThatUsesLayoutAndManySection</div>\r\n}\r\n\r\n@section SecondSection {\r\n    <div>Second section in ViewThatUsesLayoutAndManySection</div>\r\n}\r\n\r\n@section ThirdSection {\r\n    <div>Third section in ViewThatUsesLayoutAndManySection</div>\r\n}\r\n\r\n<div>ViewThatUsesLayoutAndManySection</div>"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests/TestViews/ViewThatUsesLayoutAndModel.cshtml",
    "content": "﻿@{\r\n    Layout = \"SimplyLayout\";\r\n}\r\n\r\n<div>ViewThatUsesLayoutAndModel: @Model.Name</div>"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests/TestViews/ViewThatUsesLayoutAndOptionalSection.cshtml",
    "content": "﻿@{\r\n    Layout = \"LayoutWithOptionalSection\";\r\n}\r\n\r\n<div>ViewThatUsesLayoutAndOptionalSection</div>"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests/TestViews/ViewThatUsesLayoutAndOptionalSectionOverridingDefaults.cshtml",
    "content": "﻿@{\r\n    Layout = \"LayoutWithOptionalSectionWithDefaults\";\r\n}\r\n@section FirstSection {\r\n    <div>OptionalSectionOverride</div>\r\n}\r\n<div>ViewThatUsesLayoutAndOptionalSectionOverridingDefaults</div>"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests/TestViews/ViewThatUsesLayoutAndOptionalSectionWithDefaults.cshtml",
    "content": "﻿@{\r\n    Layout = \"LayoutWithOptionalSectionWithDefaults\";\r\n}\r\n\r\n<div>ViewThatUsesLayoutAndOptionalSectionWithDefaults</div>"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests/TestViews/ViewThatUsesLayoutAndSection.cshtml",
    "content": "﻿@{\r\n    Layout = \"LayoutWithSection\";\r\n}\r\n\r\n@section FirstSection {\r\n    <div>First section in ViewThatUsesLayoutAndSection</div>\r\n}\r\n\r\n\r\n<div>ViewThatUsesLayoutAndSection</div>"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests/TestViews/ViewThatUsesModelCSharp.cshtml",
    "content": "﻿@model System.DateTime\r\n\r\n<h1>Hello at @Model.ToString(\"MM/dd/yyyy\")</h1>"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests/TestViews/ViewThatUsesModelVB.vbhtml",
    "content": "﻿@ModelType System.DateTime\r\n\r\n<h1>Hello at @Model.ToString(\"MM/dd/yyyy\")</h1>"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests/TextResourceFinderFixture.cs",
    "content": "﻿namespace Nancy.ViewEngines.Razor.Tests\r\n{\r\n    using System;\r\n    using FakeItEasy;\r\n    using Nancy.Localization;\r\n    using Nancy.Tests;\r\n    using Xunit;\r\n\r\n    public class TextResourceFinderFixture\r\n    {\r\n        private readonly dynamic finder;\r\n        private readonly ITextResource textResource;\r\n        private readonly NancyContext context;\r\n\r\n\r\n        public TextResourceFinderFixture()\r\n        {\r\n            this.context = A.Dummy<NancyContext>();\r\n            this.textResource = A.Fake<ITextResource>();\r\n            this.finder = new TextResourceFinder(textResource, context);\r\n        }\r\n\r\n        [Theory]\r\n        [InlineData(\"foo\")]\r\n        [InlineData(\"bar\")]\r\n        public void Should_return_result_of_text_resource(string text)\r\n        {\r\n            // Given\r\n            A.CallTo(() => this.textResource[\"name\", this.context]).Returns(text);\r\n\r\n            // When\r\n            var result = (string)finder.name;\r\n\r\n            // Then\r\n            result.ShouldEqual(text);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_text_resource_with_context()\r\n        {\r\n            // Given\r\n            // When\r\n            var result = (string)finder.name;\r\n\r\n            // Then\r\n            A.CallTo(() => this.textResource[\"name\", this.context]).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_text_resource_with_member_name_when_not_chained()\r\n        {\r\n            // Given\r\n            // When\r\n            var result = (string)finder.foo;\r\n\r\n            // Then\r\n            A.CallTo(() => this.textResource[\"foo\", this.context]).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_invoke_text_resource_with_member_name_when_chained()\r\n        {\r\n            // Given\r\n            // When\r\n            var result = (string)finder.foo.bar.other;\r\n\r\n            // Then\r\n            A.CallTo(() => this.textResource[\"foo.bar.other\", this.context]).MustHaveHappened();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_invalidoperationexception_when_trying_to_cast_to_anything_but_string()\r\n        {\r\n            // Given\r\n            // When\r\n            var exception = Record.Exception(() => (decimal) finder.name);\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<InvalidOperationException>();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests.Models/Hobby.cs",
    "content": "﻿namespace Nancy.ViewEngines.Razor.Tests.Models\r\n{\r\n    public class Hobby\r\n    {\r\n        public string Name { get; set; }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests.Models/Nancy.ViewEngines.Razor.Tests.Models.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <PropertyGroup>\n    <TargetFramework>net452</TargetFramework>\n  </PropertyGroup>\n</Project>\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Razor.Tests.Models/Person.cs",
    "content": "﻿namespace Nancy.ViewEngines.Razor.Tests.Models\r\n{\r\n    public class Person\r\n    {\r\n        public string Name { get; set; }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/App.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n\r\n<configuration>\r\n  <configSections>\r\n    <section name=\"spark\" type=\"Spark.Configuration.SparkSectionHandler, Spark\" />\r\n  </configSections>\r\n\r\n  <spark>\r\n    <compilation debug=\"true\" defaultLanguage=\"CSharp\" />\r\n    <pages automaticEncoding=\"false\">\r\n      <resources>\r\n        <add match=\"~/content\" location=\"http://cdn.example.com/mysite\" />\r\n      </resources>\r\n    </pages>\r\n  </spark>\r\n</configuration>\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/Nancy.ViewEngines.Spark.Tests.csproj",
    "content": "<Project Sdk=\"Microsoft.NET.Sdk\">\r\n  <PropertyGroup>\r\n    <TargetFramework>net452</TargetFramework>\r\n  </PropertyGroup>\r\n\r\n  <ItemGroup>\r\n    <None Update=\"ShadeViews\\**\\*\">\r\n      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>\r\n    </None>\r\n    <None Update=\"TestViews\\**\\*\">\r\n      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>\r\n    </None>\r\n  </ItemGroup>\r\n\r\n</Project>\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/NancyViewFolderFixture.cs",
    "content": "namespace Nancy.ViewEngines.Spark.Tests\r\n{\r\n    using System.Collections.Generic;\r\n    using System.IO;\r\n    using Configuration;\r\n    using FakeItEasy;\r\n    using Nancy.Tests;\r\n    using Xunit;\r\n\r\n    public class NancyViewFolderFixture\r\n    {\r\n        private readonly IViewCache cache;\r\n        private readonly INancyEnvironment environment;\r\n\r\n        public NancyViewFolderFixture()\r\n        {\r\n            this.cache = A.Fake<IViewCache>();\r\n            this.environment = new DefaultNancyEnvironment();\r\n            this.environment.AddValue(ViewConfiguration.Default);\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_throw_filenotfoundexception_when_view_source_cannot_be_returned_for_view()\r\n        {\r\n            // Given\r\n            var viewFolder = CreateViewFolder(new ViewLocationResult(\r\n                string.Empty,\r\n                \"view\",\r\n                \"spark\",\r\n                () => new StreamReader(new MemoryStream())));\r\n\r\n            // When\r\n            var exception = Record.Exception(() => viewFolder.GetViewSource(\"notfound.spark\"));\r\n\r\n            // Then\r\n            exception.ShouldBeOfType<FileNotFoundException>();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_get_view_source_for_view_without_location()\r\n        {\r\n            // Given\r\n            var viewFolder = CreateViewFolder(new ViewLocationResult(\r\n                string.Empty,\r\n                \"view\",\r\n                \"spark\",\r\n                () => new StreamReader(new MemoryStream())));\r\n\r\n            // When\r\n            var result = viewFolder.GetViewSource(\"view.spark\");\r\n\r\n            // Then\r\n            result.ShouldNotBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_get_view_source_for_view_with_location()\r\n        {\r\n            // Given\r\n            var viewFolder = CreateViewFolder(new ViewLocationResult(\r\n                \"location\",\r\n                \"view\",\r\n                \"spark\",\r\n                () => new StreamReader(new MemoryStream())));\r\n\r\n            // When\r\n            var result = viewFolder.GetViewSource(\"location/view.spark\");\r\n\r\n            // Then\r\n            result.ShouldNotBeNull();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_for_hashview_when_matching_views_without_location()\r\n        {\r\n            // Given\r\n            var viewFolder = CreateViewFolder(new ViewLocationResult(\r\n                string.Empty,\r\n                \"view\",\r\n                \"spark\",\r\n                () => new StreamReader(new MemoryStream())));\r\n\r\n            // When\r\n            var result = viewFolder.HasView(\"view.spark\");\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_return_true_for_hashview_when_matching_views_with_location()\r\n        {\r\n            // Given\r\n            var viewFolder = CreateViewFolder(new ViewLocationResult(\r\n                \"location\",\r\n                \"view\",\r\n                \"spark\",\r\n                () => new StreamReader(new MemoryStream())));\r\n\r\n            // When\r\n            var result = viewFolder.HasView(\"location/view.spark\");\r\n\r\n            // Then\r\n            result.ShouldBeTrue();\r\n        }\r\n\r\n        private NancyViewFolder CreateViewFolder(params ViewLocationResult[] results)\r\n        {\r\n            var context =\r\n                this.CreateContext(results);\r\n\r\n            return new NancyViewFolder(context, this.environment);\r\n        }\r\n\r\n        private ViewEngineStartupContext CreateContext(params ViewLocationResult[] results)\r\n        {\r\n            var viewLocationProvider = A.Fake<IViewLocationProvider>();\r\n            A.CallTo(() => viewLocationProvider.GetLocatedViews(A<IEnumerable<string>>._))\r\n                                               .Returns(results);\r\n\r\n            var viewEngine = A.Fake<IViewEngine>();\r\n            A.CallTo(() => viewEngine.Extensions).Returns(new[] { \"liquid\" });\r\n\r\n            var viewLocator = new DefaultViewLocator(viewLocationProvider, new[] { viewEngine }, this.environment);\r\n\r\n            var startupContext = new ViewEngineStartupContext(\r\n                this.cache,\r\n                viewLocator);\r\n\r\n            return startupContext;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/ShadeViews/Features/ShadeCodeMayBeDashOrAtBraced.shade",
    "content": "﻿\r\nuse namespace=\"System.Linq\"\r\n\r\n@{ \r\n  var words = \"Welcome to the Machine\"\r\n    .Split((char)' ')\r\n    .Select(word => new string(word.Reverse().ToArray()))\r\n    .ToArray();\r\n}\r\n\r\ndiv\r\n  ul\r\n    - foreach(var word in words) {\r\n      li =word\r\n    - }\r\n    li =Clean(Directory.GetCurrentDirectory())\r\n\r\ndiv.copyright\r\n  p.small |Copyright (c) ${DateTime.Now.Year} SparkViewEngine\r\n\r\n\r\nuse namespace=\"System\"\r\nuse namespace=\"System.Diagnostics\"\r\nuse namespace=\"System.IO\"\r\n\r\nmacro name=\"Clean\" folder=\"string\"\r\n  for each=\"var file in Directory.GetFiles(folder)\"\r\n    - Console.WriteLine(file);\r\n    SimpleValue foo=\"file\"\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/ShadeViews/Features/ShadeElementsMayStackOnOneLine.shade",
    "content": "﻿\r\nhtml\r\n  head title |offset test\r\n  body div.container h1#top |offset test\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/ShadeViews/Features/ShadeEvaluatesExpressions.shade",
    "content": "﻿\r\np\r\n  span =5+3\r\n  span\r\n    =(3\r\n  -1)\r\n    | and \r\n    =42/6\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/ShadeViews/Features/ShadeFileRenders.shade",
    "content": "﻿\r\nhtml\r\n  head\r\n    title |offset test\r\n  body\r\n    .container\r\n      h1#top |offset test\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/ShadeViews/Features/ShadeSupportsAttributesAndMayTreatSomeElementsAsSpecialNodes.shade",
    "content": "﻿\r\nuse namespace=\"System.Collections.Generic\"\r\nvar words=\"'Welcome to the Machine'.Split((char)' ')\"\r\n\r\n|!{Show(words)}\r\np\r\n  SimpleValue foo=\"words.Length\"\r\n\r\nmacro name=\"Show\" data=\"IEnumerable<string>\"\r\n  ul.nav\r\n    li each=\"var x in data\" =x\r\n\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/ShadeViews/Features/ShadeTextMayContainExpressions.shade",
    "content": "﻿\r\np\r\n    span =5+3\r\n    span |${3 \r\n  -1} and ${42/6}\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/ShadeViews/Features/ShadeThatUsesApplicationLayout.shade",
    "content": "﻿set title='\"Child View That Expects Application Layout by default\"'\r\nh1 =title\r\nvar x=\"5\" y=\"10\" rowclass='new[] {\"bar\", \"bar-alt\"}'\r\ndiv |Hello Spark\r\nvar z=\"x+y\"\r\nh3 =z\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/ShadeViews/Shared/Application.shade",
    "content": "﻿html\r\n  head\r\n    global title='\"Default Title\"' type=\"string\"\r\n    title =title\r\n    use content=\"head\"\r\n  body\r\n    div#header\r\n      use content=\"header\"\r\n        div |main application header by default\r\n    div#main\r\n      use content=\"view\"\r\n    div#footer\r\n      use content=\"footer\"\r\n        div |main application footer by default\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/ShadeViews/Shared/_SimpleValue.spark",
    "content": "<span>${foo}</span>\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/SparkViewEngineFixture.cs",
    "content": "﻿namespace Nancy.ViewEngines.Spark.Tests\r\n{\r\n    using System;\r\n    using System.Globalization;\r\n    using System.IO;\r\n    using System.Threading;\r\n    using Configuration;\r\n    using FakeItEasy;\r\n    using global::Spark;\r\n    using Nancy.Tests;\r\n    using Nancy.ViewEngines.Spark.Tests.ViewModels;\r\n    using Xunit;\r\n\r\n    public class SparkViewEngineFixture\r\n    {\r\n        private readonly IRenderContext renderContext;\r\n        private string output;\r\n        private FileSystemViewLocationProvider fileSystemViewLocationProvider;\r\n        private readonly IRootPathProvider rootPathProvider;\r\n        private readonly INancyEnvironment environment;\r\n\r\n        public SparkViewEngineFixture()\r\n        {\r\n            this.rootPathProvider = A.Fake<IRootPathProvider>();\r\n            A.CallTo(() => this.rootPathProvider.GetRootPath()).Returns(Path.Combine(Environment.CurrentDirectory, \"TestViews\"));\r\n\r\n            this.fileSystemViewLocationProvider = new FileSystemViewLocationProvider(this.rootPathProvider, new DefaultFileSystemReader());\r\n\r\n            this.renderContext = A.Fake<IRenderContext>();\r\n\r\n            var cache = A.Fake<IViewCache>();\r\n            A.CallTo(() => cache.GetOrAdd(A<ViewLocationResult>.Ignored, A<Func<ViewLocationResult, ISparkViewEntry>>.Ignored))\r\n                .ReturnsLazily(x => {\r\n                    var result = x.GetArgument<ViewLocationResult>(0);\r\n                    return x.GetArgument<Func<ViewLocationResult, ISparkViewEntry>>(1).Invoke(result);\r\n                });\r\n\r\n            A.CallTo(() => this.renderContext.ViewCache).Returns(cache);\r\n\r\n            this.environment = new DefaultNancyEnvironment();\r\n            this.environment.AddValue(ViewConfiguration.Default);\r\n        }\r\n\r\n        [Fact]\r\n        public void Application_dot_spark_should_be_used_as_the_master_layout_if_present()\r\n        {\r\n            //Given, When\r\n            this.FindViewAndRender(\"ViewThatUsesApplicationLayout\");\r\n\r\n            //Then\r\n            this.output.ShouldContainInOrder(\r\n                \"<title>Child View That Expects Application Layout by default</title>\",\r\n                \"<div>main application header by default</div>\",\r\n                \"<h1>Child View That Expects Application Layout by default</h1>\",\r\n                \"<div>main application footer by default</div>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_html_encode_using_H_function_from_views()\r\n        {\r\n            //Given, When\r\n            this.FindViewAndRender(\"ViewThatUsesHtmlEncoding\");\r\n\r\n            //Then\r\n            this.output.Replace(\" \", \"\").Replace(\"\\r\", \"\").Replace(\"\\n\", \"\")\r\n                .ShouldEqual(\"<div>&lt;div&gt;&amp;lt;&amp;gt;&lt;/div&gt;</div>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_html_encode_null_using_H_function_from_views()\r\n        {\r\n            //Given, When\r\n            this.FindViewAndRender(\"ViewThatUsesNullHtmlEncoding\");\r\n\r\n            //Then\r\n            this.output.ShouldEqual(\"<div></div>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_provide_global_setting_for_views()\r\n        {\r\n            //Given, When\r\n            this.FindViewAndRender(\"ViewThatChangesGlobalSettings\");\r\n\r\n            //Then\r\n            this.output.ShouldContainInOrder(\r\n                \"<div>default: Global set test</div>\",\r\n                \"<div>7==7</div>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_render_a_child_view_with_a_master_layout()\r\n        {\r\n            //Given, When\r\n            this.FindViewAndRender(\"ViewThatExpectsALayout\");\r\n\r\n            //Then\r\n            this.output.ShouldContainInOrder(\r\n                \"<title>Child View That Expects A Layout</title>\",\r\n                \"<div>no header by default</div>\",\r\n                \"<h1>Child View That Expects A Layout</h1>\",\r\n                \"<div>no footer by default</div>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_render_a_plain_view()\r\n        {\r\n            //Given, When\r\n            this.FindViewAndRender(\"Index\");\r\n\r\n            //Then\r\n            this.output.ShouldEqual(\"<div>index</div>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_render_a_subfolder_view()\r\n        {\r\n            var viewLocationResult = new ViewLocationResult(\"Stub\\\\Subfolder\", \"Subfolderview\", \"spark\", GetEmptyContentReader());\r\n            this.FindViewAndRender<dynamic>(\"subfolder\\\\Subfolderview\", null, viewLocationResult);\r\n\r\n            //Then\r\n            this.output.ShouldEqual(\"<div>Subfolder</div>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_render_a_view_even_with_null_view_model()\r\n        {\r\n            //Given, When\r\n            this.FindViewAndRender(\"ViewThatUsesANullViewModel\");\r\n\r\n            //Then\r\n            this.output.ShouldContain(\"<div>nothing</div>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_render_a_view_with_a_strongly_typed_model()\r\n        {\r\n            //Given, When\r\n            this.FindViewAndRender(\"ViewThatUsesViewModel\", new FakeViewModel {Text = \"Spark\"});\r\n\r\n            //Then\r\n            this.output.ShouldContain(\"<div>Spark</div>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_render_partials_that_share_state()\r\n        {\r\n            //Given\r\n\r\n            // When\r\n            this.FindViewAndRender(\"ViewThatRendersPartialsThatShareState\");\r\n\r\n            //Then\r\n            this.output.ShouldContainInOrder(\r\n                \"<div>start</div>\",\r\n                \"<div>lion</div>\",\r\n                \"<div>elephant</div>\",\r\n                \"<div>The Target</div>\",\r\n                \"<div>Willow</div>\",\r\n                \"<div>middle</div>\",\r\n                \"<ul>\",\r\n                \"<li>one</li>\",\r\n                \"<li>three</li>\",\r\n                \"<li>two</li>\",\r\n                \"</ul>\",\r\n                \"alphabetagammadelta\",\r\n                \"<div>end</div>\");\r\n            this.output.ShouldNotContain(\"foo2\");\r\n            this.output.ShouldNotContain(\"bar4\");\r\n            this.output.ShouldNotContain(\"quux7\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_use_a_partial_file_explicitly()\r\n        {\r\n            //Given, When\r\n            this.FindViewAndRender(\"ViewThatUsesPartial\");\r\n\r\n            //Then\r\n            this.output.ShouldContainInOrder(\r\n                \"<ul>\",\r\n                \"<li>Partial where x=\\\"lion\\\"</li>\",\r\n                \"<li>Partial where x=\\\"hippo\\\"</li>\",\r\n                \"<li>Partial where x=\\\"elephant\\\"</li>\",\r\n                \"<li>Partial where x=\\\"giraffe\\\"</li>\",\r\n                \"<li>Partial where x=\\\"whale\\\"</li>\",\r\n                \"</ul>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_use_a_partial_file_implicitly()\r\n        {\r\n            //Given, Then\r\n            this.FindViewAndRender(\"ViewThatUsesPartialImplicitly\");\r\n\r\n            //Then\r\n            this.output.ShouldContainInOrder(\r\n                \"<li class=\\\"odd\\\">lion</li>\",\r\n                \"<li class=\\\"even\\\">hippo</li>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_use_foreach_construct_in_the_view()\r\n        {\r\n            //Given, When\r\n            this.FindViewAndRender(\"ViewThatUsesForeach\");\r\n\r\n            //Then\r\n            this.output.ShouldContainInOrder(\r\n                \"<li class=\\\"odd\\\">1: foo</li>\",\r\n                \"<li class=\\\"even\\\">2: bar</li>\",\r\n                \"<li class=\\\"odd\\\">3: baz</li>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_be_able_to_use_namespaces_directly()\r\n        {\r\n            //Given, When\r\n            this.FindViewAndRender(\"ViewThatUsesNamespaces\");\r\n\r\n            //Then\r\n            this.output.ShouldContainInOrder(\r\n                \"<div>Foo</div>\",\r\n                \"<div>Bar</div>\",\r\n                \"<div>Hello</div>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_capture_named_content_areas_and_render_in_the_correct_order()\r\n        {\r\n            //Given, When\r\n            this.FindViewAndRender(\"ViewThatUsesAllNamedContentAreas\");\r\n\r\n            //Then\r\n            this.output.ShouldContainInOrder(\r\n                \"<div>Funny, we can put the header anywhere we like with a name</div>\",\r\n                \"<div>OK - this is the main content by default because it is not contained</div>\",\r\n                \"<div>Here is some footer stuff defined at the top</div>\",\r\n                \"<div>Much better place for footer stuff - or is it?</div>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_substitute_tilde_in_resource_url_with_parse_result_from_Render_Context()\r\n        {\r\n            //Given\r\n            A.CallTo(() => this.renderContext.ParsePath(\"~/\"))\r\n                .Returns(\"/mysensationalrootfolder/\");\r\n\r\n            //When\r\n            this.FindViewAndRender(\"ViewThatUsesTildeSubstitution\");\r\n\r\n            //Then\r\n            this.output.ShouldContain(@\"<script type=\"\"text/javascript\"\" src=\"\"/mysensationalrootfolder/scripts/test.js\"\"/>\");\r\n        }\r\n\r\n#if !__MonoCS__\r\n        [Fact]\r\n        public void Should_allow_overriding_of_tilde_substitiution_with_resource_paths_from_config()\r\n        {\r\n            //Given\r\n            A.CallTo(() => this.renderContext.ParsePath(\"~/\"))\r\n                .Returns(\"/mysensationalrootfolder/\");\r\n\r\n            //When\r\n            this.FindViewAndRender(\"ViewThatUsesTildeSubstitutionWithSparkReplace\");\r\n\r\n            //Then\r\n            this.output.ShouldContain(@\"<script type=\"\"text/javascript\"\" src=\"\"http://cdn.example.com/mysite/scripts/test.js\"\"/>\");\r\n        }\r\n#endif\r\n\r\n        [Fact]\r\n        public void Should_support_files_with_the_spark_extensions()\r\n        {\r\n            // Given\r\n            var engine = this.CreateDefaultSparkEngine();\r\n\r\n            //When\r\n            var extensions = engine.Extensions;\r\n\r\n            // Then\r\n            extensions.ShouldHaveCount(2);\r\n            extensions.ShouldEqualSequence(new[] { \"spark\", \"shade\" });\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_use_application_dot_shade_as_the_master_layout_if_present()\r\n        {\r\n            //Given,\r\n            const string viewName = \"ShadeThatUsesApplicationLayout\";\r\n            var viewLocationResult = GetShadeViewLocation(viewName);\r\n\r\n            //When\r\n            this.FindViewAndRender(viewName, viewLocationResult);\r\n\r\n            //Then\r\n            this.output.ShouldContainInOrder(\r\n                \"<title>Child View That Expects Application Layout by default</title>\",\r\n                \"<div>main application header by default</div>\",\r\n                \"<h1>Child View That Expects Application Layout by default</h1>\",\r\n                \"<div>Hello Spark</div>\",\r\n                \"<h3>15</h3>\",\r\n                \"<div>main application footer by default</div>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_render_a_shade_file()\r\n        {\r\n            //Given\r\n            const string viewName = \"ShadeFileRenders\";\r\n            var viewLocationResult = GetShadeViewLocation(viewName);\r\n\r\n            //When\r\n            this.FindViewAndRender(viewName, viewLocationResult);\r\n\r\n            //Then\r\n            this.output.ShouldContainInOrder(\r\n                \"<html>\",\r\n                \"<head>\",\r\n                \"<title>\",\r\n                \"offset test\",\r\n                \"</title>\",\r\n                \"<body>\",\r\n                \"<div class=\\\"container\\\">\",\r\n                \"<h1 id=\\\"top\\\">\",\r\n                \"offset test\",\r\n                \"</h1>\",\r\n                \"</div>\",\r\n                \"</body>\",\r\n                \"</html>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_evaluate_expressions_in_shade()\r\n        {\r\n            //Given\r\n            const string viewName = \"ShadeEvaluatesExpressions\";\r\n            var viewLocationResult = GetShadeViewLocation(viewName);\r\n\r\n            //When\r\n            this.FindViewAndRender(viewName, viewLocationResult);\r\n\r\n            //Then\r\n            this.output.ShouldContainInOrder(\r\n                \"<p>\",\r\n                \"<span>\",\r\n                \"8\",\r\n                \"</span>\",\r\n                \"<span>\",\r\n                \"2\", \" and \", \"7\",\r\n                \"</span>\",\r\n                \"</p>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_dash_or_braced_code_recognition_in_shade()\r\n        {\r\n            //Given\r\n            const string viewName = \"ShadeCodeMayBeDashOrAtBraced\";\r\n            var viewLocationResult = GetShadeViewLocation(viewName);\r\n\r\n            //When\r\n            this.FindViewAndRender(viewName, viewLocationResult);\r\n\r\n            //Then\r\n            this.output.ShouldContainInOrder(\r\n                \"<ul>\",\r\n                \"<li>emocleW</li>\",\r\n                \"<li>ot</li>\",\r\n                \"<li>eht</li>\",\r\n                \"<li>enihcaM</li>\",\r\n                \"</ul>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_text_to_contain_expressions_in_shade()\r\n        {\r\n            //Given\r\n            const string viewName = \"ShadeTextMayContainExpressions\";\r\n            var viewLocationResult = GetShadeViewLocation(viewName);\r\n\r\n            //When\r\n            this.FindViewAndRender(viewName, viewLocationResult);\r\n\r\n            //Then\r\n            this.output.ShouldContainInOrder(\r\n                \"<p>\",\r\n                \"<span>8</span>\",\r\n                \"<span>2 and 7</span>\",\r\n                \"</p>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_support_attributes_and_treat_some_as_special_nodes_like_partials_in_shade()\r\n        {\r\n            //Given\r\n            const string viewName = \"ShadeSupportsAttributesAndMayTreatSomeElementsAsSpecialNodes\";\r\n            var viewLocationResult = GetShadeViewLocation(viewName);\r\n\r\n            //When\r\n            this.FindViewAndRender(viewName, viewLocationResult);\r\n\r\n            //Then\r\n            this.output.ShouldContainInOrder(\r\n                \"<ul class=\\\"nav\\\">\",\r\n                \"<li>Welcome</li>\",\r\n                \"<li>to</li>\",\r\n                \"<li>the</li>\",\r\n                \"<li>Machine</li>\",\r\n                \"</ul>\",\r\n                \"<p>\",\r\n                \"<span>4</span>\",\r\n                \"</p>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_elements_to_stack_on_one_line_in_shade()\r\n        {\r\n            //Given\r\n            const string viewName = \"ShadeElementsMayStackOnOneLine\";\r\n            var viewLocationResult = GetShadeViewLocation(viewName);\r\n\r\n            //When\r\n            this.FindViewAndRender(viewName, viewLocationResult);\r\n\r\n            //Then\r\n            this.output.ShouldContainInOrder(\r\n                \"<html>\",\r\n                \"<head>\",\r\n                \"<title>\",\r\n                \"offset test\",\r\n                \"</title>\",\r\n                \"<body>\",\r\n                \"<div class=\\\"container\\\">\",\r\n                \"<h1 id=\\\"top\\\">\",\r\n                \"offset test\",\r\n                \"</h1>\",\r\n                \"</div>\",\r\n                \"</body>\",\r\n                \"</html>\");\r\n        }\r\n\r\n        [Fact]\r\n        public void Should_allow_using_viewdata_tag_for_retrieving_values_from_ViewBag()\r\n        {\r\n            // Given\r\n            var nancyContext = new NancyContext();\r\n            nancyContext.ViewBag[\"foo\"] = \"bar\";\r\n            A.CallTo(() => renderContext.Context).Returns(nancyContext);\r\n\r\n            // When\r\n            FindViewAndRender(\"ViewThatUsesViewDataForViewBag\");\r\n\r\n            // Then\r\n            this.output.ShouldContain(\"<div>bar</div>\");\r\n        }\r\n\r\n        private ViewLocationResult GetShadeViewLocation(string viewName)\r\n        {\r\n            A.CallTo(() => this.rootPathProvider.GetRootPath()).Returns(Path.Combine(Environment.CurrentDirectory, \"ShadeViews\"));\r\n            this.fileSystemViewLocationProvider = new FileSystemViewLocationProvider(this.rootPathProvider, new DefaultFileSystemReader());\r\n            var viewLocationResult = new ViewLocationResult(\"Features\", viewName, \"shade\", GetEmptyContentReader());\r\n            return viewLocationResult;\r\n        }\r\n\r\n        private void FindViewAndRender<T>(string viewName, T viewModel, ViewLocationResult viewLocationResult = null) where T : class\r\n        {\r\n            if (viewLocationResult == null)\r\n            {\r\n                viewLocationResult = new ViewLocationResult(\"Stub\", viewName, \"spark\", GetEmptyContentReader());\r\n            }\r\n\r\n            var stream = new MemoryStream();\r\n            var engine = this.CreateDefaultSparkEngine();\r\n\r\n            var locator = new DefaultViewLocator(this.fileSystemViewLocationProvider, new[] { engine }, this.environment);\r\n\r\n            var context = new ViewEngineStartupContext(\r\n                                    A.Fake<IViewCache>(),\r\n                                    locator);\r\n\r\n            engine.Initialize(context);\r\n\r\n            //When\r\n            var response = engine.RenderView(viewLocationResult, viewModel, this.renderContext);\r\n            response.Contents.Invoke(stream);\r\n            stream.Position = 0;\r\n            using (var reader = new StreamReader(stream))\r\n            {\r\n                this.output = reader.ReadToEnd();\r\n            }\r\n        }\r\n\r\n        private IViewEngine CreateDefaultSparkEngine()\r\n        {\r\n            return new Spark.SparkViewEngine(new DefaultRootPathProvider(), this.environment);\r\n        }\r\n\r\n        private void FindViewAndRender(string viewName)\r\n        {\r\n            this.FindViewAndRender<dynamic>(viewName, null);\r\n        }\r\n\r\n        private void FindViewAndRender(string viewName, ViewLocationResult viewLocationResult)\r\n        {\r\n            this.FindViewAndRender<dynamic>(viewName, null, viewLocationResult);\r\n        }\r\n\r\n        private static Func<TextReader> GetEmptyContentReader()\r\n        {\r\n            return () => new StreamReader(new MemoryStream());\r\n        }\r\n\r\n        public class ScopedCulture : IDisposable\r\n        {\r\n            private readonly CultureInfo savedCulture;\r\n\r\n            public ScopedCulture(CultureInfo culture)\r\n            {\r\n                this.savedCulture = Thread.CurrentThread.CurrentCulture;\r\n                Thread.CurrentThread.CurrentCulture = culture;\r\n            }\r\n\r\n            public void Dispose()\r\n            {\r\n                Thread.CurrentThread.CurrentCulture = this.savedCulture;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Layouts/anotherLayout.spark",
    "content": "﻿<div>Another Layout</div>"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Shared/Application.spark",
    "content": "﻿<html>\r\n  <head>\r\n    <global title='\"Default Title\"' type=\"string\"/>\r\n    <title>${title}</title>\r\n    <use content=\"head\" />\r\n  </head>\r\n  <body>\r\n    <div id=\"header\">\r\n      <use content=\"header\">\r\n        <div>main application header by default</div>\r\n      </use>\r\n    </div>\r\n    <div id=\"main\">\r\n      <use content=\"view\"/>\r\n    </div>\r\n    <div id=\"footer\">\r\n      <use content=\"footer\">\r\n        <div>main application footer by default</div>\r\n      </use>\r\n    </div>\r\n  </body>\r\n</html>\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Shared/Partial.spark",
    "content": "﻿<li>Partial where x=\"${x}\"</li>"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Shared/elementLayout.spark",
    "content": "﻿<div>Element Layout</div>"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Shared/layout.spark",
    "content": "﻿<html>\r\n  <head>\r\n    <global title='\"Default Title\"' type=\"string\"/>\r\n    <title>${title}</title>\r\n  </head>\r\n  <body>\r\n    <div id=\"header\">\r\n      <use content=\"header\">\r\n        <div>no header by default</div>\r\n      </use>\r\n    </div>\r\n    <div id=\"main\">\r\n      <use content=\"view\"/>\r\n    </div>\r\n    <div id=\"footer\">\r\n      <use content=\"footer\">\r\n        <div>no footer by default</div>\r\n      </use>\r\n    </div>\r\n  </body>\r\n</html>\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Stub/Index.spark",
    "content": "﻿<use master=\"\" /><div>index</div>"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Stub/List.spark",
    "content": "﻿<div>list</div>"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Stub/PartialTarget.spark",
    "content": "﻿\r\n<div once=\"carnivor\">tiger</div>\r\n<div once=\"herbivore\">elephant</div>\r\n<div>The Target</div>\r\n\r\n<content name=\"list\"><li>three</li></content>\r\n\r\n<content name=\"chunk1\">beta</content>\r\n<content name=\"chunk2\">gamma</content>\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Stub/Subfolder/Subfolderview.spark",
    "content": "﻿<use master=\"\" /><div>Subfolder</div>"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Stub/ViewThatChangesGlobalSettings.spark",
    "content": "﻿<use master=\"\" />\r\n<div>default: ${title}</div>\r\n<set title='2+5'/>\r\n<div>7==${title}</div>\r\n\r\n<global title='\"Global set test\"'/>\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Stub/ViewThatExpectsALayout.spark",
    "content": "﻿<use master=\"layout\" />\r\n<set title='\"Child View That Expects A Layout\"' />\r\n<h1>${title}</h1>\r\n<var x=\"5\" y=\"10\" rowclass='new[] {\"bar\", \"bar-alt\"}' />\r\n<div>Hello Spark</div>\r\n<var z=\"x+y\" />\r\n<h3>${z}</h3>\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Stub/ViewThatRendersPartialsThatShareState.spark",
    "content": "﻿<div>start</div>\r\n<div once=\"carnivor\">lion</div>\r\n<content name=\"list\"><li>one</li></content>\r\n<content name=\"chunk1\">alpha</content>\r\n<div><use file='PartialTarget' /></div>\r\n<content name=\"chunk2\">delta</content>\r\n<content name=\"list\"><li>two</li></content>\r\n<div once=\"herbivore\">hippo</div>\r\n<div once=\"carnivor\">leopard</div>\r\n<div once=\"plant\">Willow</div>\r\n<div once=\"plant\">Oak</div>\r\n<div>middle</div>\r\n\r\n<ul>\r\n<use content=\"list\"/>\r\n</ul>\r\n\r\n<use content=\"chunk1\"/><use content=\"chunk2\"/>\r\n<div>end</div>\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Stub/ViewThatUsesANullViewModel.spark",
    "content": "﻿<viewdata model=\"string\"/>\r\n<div>${Model ?? \"nothing\"}</div>"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Stub/ViewThatUsesAllNamedContentAreas.spark",
    "content": "﻿<use master=\"layout\" />\r\n<div>\r\n  <content name=\"footer\">\r\n    <div>Here is some footer stuff defined at the top</div>\r\n  </content>\r\n  <div>OK - this is the main content by default because it is not contained</div>\r\n  <content name=\"header\">\r\n    <div>Funny, we can put the header anywhere we like with a name</div>\r\n    <content name=\"footer\">\r\n      <div>Much better place for footer stuff - or is it?</div>\r\n    </content>\r\n  </content>\r\n</div>\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Stub/ViewThatUsesAnonymousViewModel.spark",
    "content": "\r\n<p>${#Foo} ${#Bar.Text}</p>\r\n\r\n\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Stub/ViewThatUsesApplicationLayout.spark",
    "content": "﻿<set title='\"Child View That Expects Application Layout by default\"' />\r\n<h1>${title}</h1>\r\n<var x=\"5\" y=\"10\" rowclass='new[] {\"bar\", \"bar-alt\"}' />\r\n<div>Hello Spark</div>\r\n<var z=\"x+y\" />\r\n<h3>${z}</h3>\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Stub/ViewThatUsesForeach.spark",
    "content": "﻿<html>\r\n  <head>\r\n    <title>View that uses foreach</title>\r\n  </head>\r\n  <body>\r\n    <h1>View that uses foreach</h1>\r\n    <div>${System.DateTime.Now}</div>\r\n    <var items=\"new[]{'foo','bar','baz'}\" />\r\n    <ul>\r\n      <var css=\"new[]{'even','odd'}\" i=\"0\">\r\n        <for each=\"var item in items\" i=\"i+1\">\r\n          <li class=\"${css[i%2]}\">${i}: ${item}</li>\r\n        </for>\r\n      </var>\r\n    </ul>\r\n  </body>\r\n</html>\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Stub/ViewThatUsesFormatting.spark",
    "content": "﻿<div>${#Number \"#,##0.00\"}</div>\r\n<div>${#Date 'yyyy/MM/dd'}</div>"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Stub/ViewThatUsesHtmlEncoding.spark",
    "content": "﻿<use master=\"\" /><div>${H(SomeHtml())}</div>\r\n\r\n<macro name=\"SomeHtml\">\r\n  <div>&lt;&gt;</div>\r\n</macro>\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Stub/ViewThatUsesNamespaces.spark",
    "content": "﻿<use namespace=\"System.Collections.Generic\"/>\r\n\r\n<var args='new List[[string]] { \"Foo\",\"Bar\" }' fakeViewModel='new FakeViewModel {Text=\"Hello\"}'/>\r\n\r\n<for each='var arg in args'>\r\n  <div>${arg}</div>\r\n  <use namespace=\"Nancy.ViewEngines.Spark.Tests.ViewModels\"/>\r\n</for>\r\n\r\n<div>${fakeViewModel.Text}</div>\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Stub/ViewThatUsesNullHtmlEncoding.spark",
    "content": "﻿<use master=\"\" /><div>${H(null)}</div>"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Stub/ViewThatUsesPartial.spark",
    "content": "﻿<ul>\r\n\t<var x='\"lion\"'>\r\n\t\t<use file='partial'/>\r\n\t</var>\r\n\t<for each='var x in new[] {\"hippo\",\"elephant\",\"giraffe\"}'>\r\n\t\t<use file='partial'/>\r\n\t</for>\r\n\t<var x='\"whale\"'>\r\n\t\t<use file='partial'/>\r\n\t</var>\r\n</ul>\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Stub/ViewThatUsesPartialImplicitly.spark",
    "content": "﻿<ul>\r\n  <var i='0' styles='new string[] {\"even\", \"odd\"}' />\r\n  <for each='var rowText in new[] {\"lion\", \"hippo\"}' i='i+1'>\r\n    <Row css='styles[i%2]' />\r\n  </for>\r\n</ul>\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Stub/ViewThatUsesTildeSubstitution.spark",
    "content": "﻿<content:head>\r\n    <script type=\"text/javascript\" src=\"~/scripts/test.js\" />\r\n</content:head>\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Stub/ViewThatUsesTildeSubstitutionWithSparkReplace.spark",
    "content": "﻿<content:head>\r\n    <script type=\"text/javascript\" src=\"~/content/scripts/test.js\" />\r\n</content:head>\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Stub/ViewThatUsesViewDataForViewBag.spark",
    "content": "﻿<viewdata foo=\"string\"/>\r\n<div>${foo}</div>\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Stub/ViewThatUsesViewModel.spark",
    "content": "﻿<viewdata model=\"Nancy.ViewEngines.Spark.Tests.ViewModels.FakeViewModel\"/>\r\n<div>${Model.Text}</div>\r\n"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/TestViews/Stub/_Row.spark",
    "content": "﻿<li class=\"${css}\">${rowText}</li>"
  },
  {
    "path": "test/Nancy.ViewEngines.Spark.Tests/ViewModels/FakeViewModel.cs",
    "content": "﻿namespace Nancy.ViewEngines.Spark.Tests.ViewModels\r\n{\r\n    using System;\r\n\r\n    public class FakeViewModel\r\n    {\r\n        public string Text { get; set; }\r\n\r\n        public double Number { get; set; }\r\n\r\n        public DateTime Date { get; set; }\r\n    }\r\n}"
  },
  {
    "path": "tools/xunit/HTML.xslt",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n<xsl:stylesheet version=\"2.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\r\n  <xsl:output method=\"html\"/>\r\n  <xsl:key name=\"tests-by-class\" match=\"collection/test\" use=\"@type\" />\r\n  <xsl:template match=\"/\">\r\n    <xsl:text disable-output-escaping=\"yes\"><![CDATA[<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">]]></xsl:text>\r\n    <html>\r\n      <head>\r\n        <title>xUnit.net Test Results</title>\r\n        <style type=\"text/css\">\r\n          body { font-family: Calibri, Verdana, Arial, sans-serif; background-color: White; color: Black; }\r\n          h2,h3,h4,h5 { margin: 0; padding: 0; }\r\n          h3 { font-weight: normal; }\r\n          h4 { margin: 0.5em 0; }\r\n          h5 { font-weight: normal; font-style: italic; margin-bottom: 0.75em; }\r\n          h6 { font-size: 0.9em; font-weight: bold; margin: 0.5em 0 0 0.75em; padding: 0; }\r\n          pre,table { font-family: Consolas; font-size: 0.8em; margin: 0 0 0 1em; padding: 0; }\r\n          table { padding-bottom: 0.25em; }\r\n          th { padding: 0 0.5em; border-right: 1px solid #bbb; text-align: left; }\r\n          td { padding-left: 0.5em; }\r\n          .divided { border-top: solid 1px #f0f5fa; padding-top: 0.5em; }\r\n          .row, .altrow { padding: 0.1em 0.3em; }\r\n          .row { background-color: #f0f5fa; }\r\n          .altrow { background-color: #e1ebf4; }\r\n          .success, .failure, .skipped { font-family: Arial Unicode MS; font-weight: normal; float: left; width: 1em; display: block; }\r\n          .success { color: #0c0; }\r\n          .failure { color: #c00; }\r\n          .skipped { color: #cc0; }\r\n          .timing { float: right; }\r\n          .indent { margin: 0.25em 0 0.5em 2em; }\r\n          .clickable { cursor: pointer; }\r\n          .testcount { font-size: 85%; }\r\n        </style>\r\n        <script language=\"javascript\">\r\n          function ToggleClass(id) {\r\n            var elem = document.getElementById(id);\r\n            if (elem.style.display == \"none\") {\r\n              elem.style.display = \"block\";\r\n            }\r\n            else {\r\n              elem.style.display = \"none\";\r\n            }\r\n          }\r\n        </script>\r\n      </head>\r\n      <body>\r\n        <h3 class=\"divided\">\r\n          <b>Assemblies Run</b>\r\n        </h3>\r\n        <xsl:apply-templates select=\"//assembly\"/>\r\n        <h3 class=\"divided\">\r\n          <b>Summary</b>\r\n        </h3>\r\n        <div>\r\n          Tests run: <a href=\"#all\"><b><xsl:value-of select=\"sum(//assembly/@total)\"/></b></a> &#160;\r\n          <xsl:if test=\"sum(//assembly/@errors) > 0\">\r\n            Errors: <a href=\"#errors\"><b><xsl:value-of select=\"sum(//assembly/@errors)\"/></b></a>,\r\n          </xsl:if>\r\n          <xsl:if test=\"sum(//assembly/@failed) > 0\">\r\n            Failures: <a href=\"#failures\"><b><xsl:value-of select=\"sum(//assembly/@failed)\"/></b></a>,\r\n          </xsl:if>\r\n          <xsl:if test=\"sum(//assembly/@skipped) > 0\">\r\n            Skipped: <a href=\"#skipped\"><b><xsl:value-of select=\"sum(//assembly/@skipped)\"/></b></a>,\r\n          </xsl:if>\r\n          Run time: <b><xsl:value-of select=\"format-number(sum(//assembly/@time), '0.000')\"/>s</b>\r\n        </div>\r\n        <xsl:if test=\"//assembly/errors/error\">\r\n          <br />\r\n          <h2>\r\n            <a id=\"errors\"></a>Errors\r\n          </h2>\r\n          <xsl:apply-templates select=\"//assembly/errors\"/>\r\n        </xsl:if>\r\n        <xsl:if test=\"//assembly/collection/test[@result='Fail']\">\r\n          <br />\r\n          <h2>\r\n            <a id=\"failures\"></a>Failed tests\r\n          </h2>\r\n          <xsl:apply-templates select=\"//assembly/collection/test[@result='Fail']\">\r\n            <xsl:sort select=\"@name\"/>\r\n          </xsl:apply-templates>\r\n        </xsl:if>\r\n        <xsl:if test=\"//assembly/collection/failures/failure\">\r\n          <br />\r\n          <h2>\r\n            <a id=\"failures\"></a>Collection failures\r\n          </h2>\r\n          <xsl:apply-templates select=\"//assembly/collection/failures\">\r\n            <xsl:sort select=\"../@name\"/>\r\n          </xsl:apply-templates>\r\n        </xsl:if>\r\n        <xsl:if test=\"//assembly/@skipped > 0\">\r\n          <br />\r\n          <h2>\r\n            <a id=\"skipped\"></a>Skipped tests\r\n          </h2>\r\n          <xsl:apply-templates select=\"//assembly/collection/test[@result='Skip']\">\r\n            <xsl:sort select=\"@name\"/>\r\n          </xsl:apply-templates>\r\n        </xsl:if>\r\n        <br />\r\n        <h2>\r\n          <a id=\"all\"></a>All tests\r\n        </h2>\r\n        <h5>Click test class name to expand/collapse test details</h5>\r\n\r\n        <xsl:for-each select=\"//assembly/collection/test[count(. | key('tests-by-class', @type)[1]) = 1]\">\r\n          <xsl:sort select=\"@type\" />\r\n          <h3>\r\n            <span class=\"timing\">\r\n              <xsl:value-of select=\"format-number(sum(key('tests-by-class', @type)/@time), '0.000')\"/>s\r\n            </span>\r\n            <span class=\"clickable\">\r\n              <xsl:attribute name=\"onclick\">ToggleClass('class<xsl:value-of select=\"generate-id()\"/>')</xsl:attribute>\r\n              <xsl:attribute name=\"ondblclick\">ToggleClass('class<xsl:value-of select=\"generate-id()\"/>')</xsl:attribute>\r\n              <xsl:if test=\"count(key('tests-by-class', @type)[@result='Fail']) > 0\">\r\n                <span class=\"failure\">&#x2718;</span>\r\n              </xsl:if>\r\n              <xsl:if test=\"count(key('tests-by-class', @type)[@result='Fail']) = 0\">\r\n                <span class=\"success\">&#x2714;</span>\r\n              </xsl:if>\r\n              &#160;<xsl:value-of select=\"@type\"/>\r\n              &#160;<span class=\"testcount\">\r\n                (<xsl:value-of select=\"count(key('tests-by-class', @type))\"/>&#160;test<xsl:if test=\"count(key('tests-by-class', @type)) > 1\">s</xsl:if>)\r\n              </span>\r\n            </span>\r\n            <br clear=\"all\" />\r\n          </h3>\r\n          <div class=\"indent\">\r\n            <xsl:if test=\"count(key('tests-by-class', @type)[@result='Fail']) = 0\">\r\n              <xsl:attribute name=\"style\">display: none;</xsl:attribute>\r\n            </xsl:if>\r\n            <xsl:attribute name=\"id\">class<xsl:value-of select=\"generate-id()\"/></xsl:attribute>\r\n            <xsl:apply-templates select=\"key('tests-by-class', @type)\">\r\n              <xsl:sort select=\"@name\"/>\r\n            </xsl:apply-templates>\r\n          </div>\r\n        </xsl:for-each>\r\n      </body>\r\n    </html>\r\n  </xsl:template>\r\n\r\n  <xsl:template match=\"assembly\">\r\n    <div>\r\n      <xsl:value-of select=\"@name\"/>\r\n    </div>\r\n  </xsl:template>\r\n\r\n  <xsl:template match=\"test\">\r\n    <div>\r\n      <xsl:attribute name=\"class\"><xsl:if test=\"(position() mod 2 = 0)\">alt</xsl:if>row</xsl:attribute>\r\n      <xsl:if test=\"@result!='Skip'\">\r\n        <span class=\"timing\">\r\n          <xsl:value-of select=\"@time\"/>s\r\n        </span>\r\n      </xsl:if>\r\n      <xsl:if test=\"@result='Skip'\">\r\n        <span class=\"timing\">Skipped</span>\r\n        <span class=\"skipped\">&#x2762;</span>\r\n      </xsl:if>\r\n      <xsl:if test=\"@result='Fail'\">\r\n        <span class=\"failure\">&#x2718;</span>\r\n      </xsl:if>\r\n      <xsl:if test=\"@result='Pass'\">\r\n        <span class=\"success\">&#x2714;</span>\r\n      </xsl:if>\r\n      &#160;<xsl:value-of select=\"@name\"/>\r\n      <br clear=\"all\" />\r\n      <xsl:if test=\"child::node()/message\">\r\n        <pre><xsl:value-of select=\"child::node()/message\"/></pre>\r\n      </xsl:if>\r\n      <xsl:if test=\"failure/stack-trace\">\r\n        <pre><xsl:value-of select=\"failure/stack-trace\"/></pre>\r\n      </xsl:if>\r\n      <xsl:if test=\"output\">\r\n        <h6>Output:</h6>\r\n        <pre><xsl:value-of select=\"output\"/></pre>\r\n      </xsl:if>\r\n      <xsl:if test=\"traits\">\r\n        <h6>Traits:</h6>\r\n        <table cellspacing=\"0\" cellpadding=\"0\">\r\n          <xsl:apply-templates select=\"traits/trait\"/>\r\n        </table>\r\n      </xsl:if>\r\n    </div>\r\n  </xsl:template>\r\n\r\n  <xsl:template match=\"trait\">\r\n    <tr>\r\n      <th><xsl:value-of select=\"@name\"/></th>\r\n      <td><xsl:value-of select=\"@value\"/></td>\r\n    </tr>\r\n  </xsl:template>\r\n\r\n  <xsl:template match=\"failures\">\r\n    <h4><xsl:value-of select=\"../@name\"/></h4>\r\n    <xsl:for-each select=\"failure\">\r\n      <div>\r\n        <xsl:attribute name=\"class\"><xsl:if test=\"(position() mod 2 = 0)\">alt</xsl:if>row</xsl:attribute>\r\n        <span class=\"failure\">&#x2718;</span><br clear=\"all\"/>\r\n        <xsl:if test=\"child::node()/message\">\r\n          <pre><xsl:value-of select=\"child::node()/message\"/></pre>\r\n        </xsl:if>\r\n        <xsl:if test=\"stack-trace\">\r\n          <pre><xsl:value-of select=\"stack-trace\"/></pre>\r\n        </xsl:if>\r\n      </div>\r\n    </xsl:for-each>\r\n  </xsl:template>\r\n\r\n  <xsl:template match=\"errors\">\r\n    <xsl:for-each select=\"error\">\r\n      <div>\r\n        <xsl:attribute name=\"class\">\r\n          <xsl:if test=\"(position() mod 2 = 0)\">alt</xsl:if>row\r\n        </xsl:attribute>\r\n        <span class=\"failure\">&#x2718;</span>\r\n        <xsl:if test=\"@type='assembly-cleanup'\">Test Assembly Cleanup</xsl:if>\r\n        <xsl:if test=\"@type='test-collection-cleanup'\">Test Collection Cleanup</xsl:if>\r\n        <xsl:if test=\"@type='test-class-cleanup'\">Test Class Cleanup</xsl:if>\r\n        <xsl:if test=\"@type='test-method-cleanup'\">Test Method Cleanup</xsl:if>\r\n        <xsl:if test=\"@type='test-case-cleanup'\">Test Case Cleanup</xsl:if>\r\n        <xsl:if test=\"@type='test-cleanup'\">Test Cleanup</xsl:if>\r\n        <xsl:if test=\"@type='fatal'\">Fatal Error</xsl:if>\r\n        <xsl:if test=\"@name\">\r\n          (<xsl:value-of select=\"@name\"/>)\r\n        </xsl:if>\r\n        <br clear=\"all\"/>\r\n        <xsl:if test=\"child::node()/message\">\r\n          <pre><xsl:value-of select=\"child::node()/message\"/></pre>\r\n        </xsl:if>\r\n        <xsl:if test=\"stack-trace\">\r\n          <pre><xsl:value-of select=\"stack-trace\"/></pre>\r\n        </xsl:if>\r\n      </div>\r\n    </xsl:for-each>\r\n  </xsl:template>\r\n\r\n</xsl:stylesheet>"
  },
  {
    "path": "tools/xunit/NUnitXml.xslt",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\r\n  <xsl:output cdata-section-elements=\"message stack-trace\"/>\r\n\r\n  <xsl:template match=\"/\">\r\n    <xsl:apply-templates/>\r\n  </xsl:template>\r\n\r\n  <xsl:template match=\"assemblies\">\r\n    <test-results name=\"Test results\">\r\n      <xsl:attribute name=\"date\">\r\n        <xsl:value-of select=\"assembly[1]/@run-date\"/>\r\n      </xsl:attribute>\r\n      <xsl:attribute name=\"time\">\r\n        <xsl:value-of select=\"assembly[1]/@run-time\"/>\r\n      </xsl:attribute>\r\n      <xsl:attribute name=\"total\">\r\n        <xsl:value-of select=\"sum(assembly/@total)\"/>\r\n      </xsl:attribute>\r\n      <xsl:attribute name=\"failures\">\r\n        <xsl:value-of select=\"sum(assembly/@failed)\"/>\r\n      </xsl:attribute>\r\n      <xsl:attribute name=\"not-run\">\r\n        <xsl:value-of select=\"sum(assembly/@skipped)\"/>\r\n      </xsl:attribute>\r\n      <test-suite name=\"xUnit.net Tests\">\r\n        <xsl:attribute name=\"success\">\r\n          <xsl:if test=\"sum(assembly/@failed) > 0\">False</xsl:if>\r\n          <xsl:if test=\"sum(assembly/@failed) = 0\">True</xsl:if>\r\n        </xsl:attribute>\r\n        <xsl:attribute name=\"time\">\r\n          <xsl:value-of select=\"sum(assembly/@time)\"/>\r\n        </xsl:attribute>\r\n        <results>\r\n          <xsl:apply-templates select=\"assembly\"/>\r\n        </results>\r\n      </test-suite>\r\n    </test-results>\r\n  </xsl:template>\r\n\r\n  <xsl:template match=\"assembly\">\r\n    <test-suite>\r\n      <xsl:attribute name=\"name\">\r\n        <xsl:value-of select=\"@name\"/>\r\n      </xsl:attribute>\r\n      <xsl:attribute name=\"success\">\r\n        <xsl:if test=\"@failed > 0\">False</xsl:if>\r\n        <xsl:if test=\"@failed = 0\">True</xsl:if>\r\n      </xsl:attribute>\r\n      <xsl:attribute name=\"time\">\r\n        <xsl:value-of select=\"@time\"/>\r\n      </xsl:attribute>\r\n      <results>\r\n        <xsl:apply-templates select=\"collection\"/>\r\n      </results>\r\n    </test-suite>\r\n  </xsl:template>\r\n\r\n  <xsl:template match=\"collection\">\r\n    <test-suite>\r\n      <xsl:attribute name=\"name\">\r\n        <xsl:value-of select=\"@name\"/>\r\n      </xsl:attribute>\r\n      <xsl:attribute name=\"success\">\r\n        <xsl:if test=\"@failed > 0\">False</xsl:if>\r\n        <xsl:if test=\"@failed = 0\">True</xsl:if>\r\n      </xsl:attribute>\r\n      <xsl:attribute name=\"time\">\r\n        <xsl:value-of select=\"@time\"/>\r\n      </xsl:attribute>\r\n      <xsl:if test=\"failure\">\r\n        <xsl:copy-of select=\"failure\"/>\r\n      </xsl:if>\r\n      <xsl:if test=\"reason\">\r\n        <reason>\r\n          <xsl:apply-templates select=\"reason\"/>\r\n        </reason>\r\n      </xsl:if>\r\n      <results>\r\n        <xsl:apply-templates select=\"test\"/>\r\n      </results>\r\n    </test-suite>\r\n  </xsl:template>\r\n\r\n  <xsl:template match=\"test\">\r\n    <test-case>\r\n      <xsl:attribute name=\"name\">\r\n        <xsl:value-of select=\"@name\"/>\r\n      </xsl:attribute>\r\n      <xsl:attribute name=\"executed\">\r\n        <xsl:if test=\"@result='Skip'\">False</xsl:if>\r\n        <xsl:if test=\"@result!='Skip'\">True</xsl:if>\r\n      </xsl:attribute>\r\n      <xsl:if test=\"@result!='Skip'\">\r\n        <xsl:attribute name=\"success\">\r\n          <xsl:if test=\"@result='Fail'\">False</xsl:if>\r\n          <xsl:if test=\"@result='Pass'\">True</xsl:if>\r\n        </xsl:attribute>\r\n      </xsl:if>\r\n      <xsl:if test=\"@time\">\r\n        <xsl:attribute name=\"time\">\r\n          <xsl:value-of select=\"@time\"/>\r\n        </xsl:attribute>\r\n      </xsl:if>\r\n      <xsl:if test=\"reason\">\r\n        <reason>\r\n          <message>\r\n            <xsl:apply-templates select=\"reason\"/>\r\n          </message>\r\n        </reason>\r\n      </xsl:if>\r\n      <xsl:apply-templates select=\"traits\"/>\r\n      <xsl:apply-templates select=\"failure\"/>\r\n    </test-case>\r\n  </xsl:template>\r\n\r\n  <xsl:template match=\"traits\">\r\n    <properties>\r\n      <xsl:apply-templates select=\"trait\"/>\r\n    </properties>\r\n  </xsl:template>\r\n\r\n  <xsl:template match=\"trait\">\r\n    <property>\r\n      <xsl:attribute name=\"name\">\r\n        <xsl:value-of select=\"@name\"/>\r\n      </xsl:attribute>\r\n      <xsl:attribute name=\"value\">\r\n        <xsl:value-of select=\"@value\"/>\r\n      </xsl:attribute>\r\n    </property>\r\n  </xsl:template>\r\n\r\n  <xsl:template match=\"failure\">\r\n    <failure>\r\n      <xsl:copy-of select=\"node()\"/>\r\n    </failure>\r\n  </xsl:template>\r\n\r\n</xsl:stylesheet>"
  },
  {
    "path": "tools/xunit/xUnit1.xslt",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n<xsl:stylesheet version=\"2.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\r\n  <xsl:output method=\"xml\" indent=\"yes\" omit-xml-declaration=\"yes\" cdata-section-elements=\"message stack-trace\"/>\r\n  <xsl:key name=\"tests-by-class\" match=\"collection/test\" use=\"@type\" />\r\n  <xsl:template match=\"/\">\r\n    <assemblies>\r\n      <xsl:for-each select=\"//assembly\">\r\n        <assembly>\r\n          <xsl:attribute name=\"name\"><xsl:value-of select=\"@name\"/></xsl:attribute>\r\n          <xsl:attribute name=\"configFile\"><xsl:value-of select=\"@config-file\"/></xsl:attribute>\r\n          <xsl:attribute name=\"run-date\"><xsl:value-of select=\"@run-date\"/></xsl:attribute>\r\n          <xsl:attribute name=\"run-time\"><xsl:value-of select=\"@run-time\"/></xsl:attribute>\r\n          <xsl:attribute name=\"time\"><xsl:value-of select=\"@time\"/></xsl:attribute>\r\n          <xsl:attribute name=\"total\"><xsl:value-of select=\"@total\"/></xsl:attribute>\r\n          <xsl:attribute name=\"passed\"><xsl:value-of select=\"@passed\"/></xsl:attribute>\r\n          <xsl:attribute name=\"failed\"><xsl:value-of select=\"@failed\"/></xsl:attribute>\r\n          <xsl:attribute name=\"skipped\"><xsl:value-of select=\"@skipped\"/></xsl:attribute>\r\n          <xsl:attribute name=\"environment\"><xsl:value-of select=\"@environment\"/></xsl:attribute>\r\n          <xsl:attribute name=\"test-framework\"><xsl:value-of select=\"@test-framework\"/></xsl:attribute>\r\n\r\n          <xsl:for-each select=\"collection/test[count(. | key('tests-by-class', @type)[1]) = 1]\">\r\n            <xsl:sort select=\"@type\" />\r\n            <class>\r\n              <xsl:attribute name=\"name\"><xsl:value-of select=\"@type\"/></xsl:attribute>\r\n              <xsl:attribute name=\"time\"><xsl:value-of select=\"format-number(sum(key('tests-by-class', @type)/@time), '0.000')\"/></xsl:attribute>\r\n              <xsl:attribute name=\"total\"><xsl:value-of select=\"count(key('tests-by-class', @type))\"/></xsl:attribute>\r\n              <xsl:attribute name=\"passed\"><xsl:value-of select=\"count(key('tests-by-class', @type)[@result='Pass'])\"/></xsl:attribute>\r\n              <xsl:attribute name=\"failed\"><xsl:value-of select=\"count(key('tests-by-class', @type)[@result='Fail'])\"/></xsl:attribute>\r\n              <xsl:attribute name=\"skipped\"><xsl:value-of select=\"count(key('tests-by-class', @type)[@result='Skip'])\"/></xsl:attribute>\r\n\r\n              <xsl:for-each select=\"key('tests-by-class', @type)\">\r\n                <xsl:sort select=\"@name\"/>\r\n                <test>\r\n                  <xsl:attribute name=\"name\"><xsl:value-of select=\"@name\"/></xsl:attribute>\r\n                  <xsl:attribute name=\"type\"><xsl:value-of select=\"@type\"/></xsl:attribute>\r\n                  <xsl:attribute name=\"method\"><xsl:value-of select=\"@method\"/></xsl:attribute>\r\n                  <xsl:attribute name=\"result\"><xsl:value-of select=\"@result\"/></xsl:attribute>\r\n                  <xsl:attribute name=\"time\"><xsl:value-of select=\"@time\"/></xsl:attribute>\r\n                  <xsl:if test=\"reason\">\r\n                    <reason>\r\n                      <message><xsl:value-of select=\"reason/text()\"/></message>\r\n                    </reason>\r\n                  </xsl:if>\r\n                  <xsl:copy-of select=\"failure\"/>\r\n                  <xsl:copy-of select=\"traits\"/>\r\n                </test>\r\n              </xsl:for-each>\r\n\r\n            </class>\r\n          </xsl:for-each>\r\n\r\n        </assembly>\r\n      </xsl:for-each>\r\n    </assemblies>\r\n  </xsl:template>\r\n</xsl:stylesheet>"
  },
  {
    "path": "tools/xunit/xunit.console.exe.config",
    "content": "<?xml version=\"1.0\"?>\r\n<configuration>\r\n  <configSections>\r\n    <section name=\"xunit\" type=\"Xunit.ConsoleClient.XunitConsoleConfigurationSection, xunit.console\"/>\r\n  </configSections>\r\n\r\n  <xunit>\r\n    <transforms>\r\n      <add commandline=\"xmlv1\" xslfile=\"xUnit1.xslt\" description=\"output results to xUnit.net v1 style XML file\"/>\r\n      <add commandline=\"nunit\" xslfile=\"NUnitXml.xslt\" description=\"output results to NUnit-style XML file\"/>\r\n      <add commandline=\"html\" xslfile=\"HTML.xslt\" description=\"output results to HTML file\"/>\r\n    </transforms>\r\n  </xunit>\r\n\r\n  <startup>\r\n    <supportedRuntime version=\"v4.0\" sku=\".NETFramework,Version=v4.5\"/>\r\n  </startup>\r\n</configuration>\r\n"
  },
  {
    "path": "tools/xunit/xunit.console.x86.exe.config",
    "content": "<?xml version=\"1.0\"?>\r\n<configuration>\r\n  <configSections>\r\n    <section name=\"xunit\" type=\"Xunit.ConsoleClient.XunitConsoleConfigurationSection, xunit.console.x86\"/>\r\n  </configSections>\r\n\r\n  <xunit>\r\n    <transforms>\r\n      <add commandline=\"xmlv1\" xslfile=\"xUnit1.xslt\" description=\"output results to xUnit.net v1 style XML file\"/>\r\n      <add commandline=\"nunit\" xslfile=\"NUnitXml.xslt\" description=\"output results to NUnit-style XML file\"/>\r\n      <add commandline=\"html\" xslfile=\"HTML.xslt\" description=\"output results to HTML file\"/>\r\n    </transforms>\r\n  </xunit>\r\n\r\n  <startup>\r\n    <supportedRuntime version=\"v4.0\" sku=\".NETFramework,Version=v4.5\"/>\r\n  </startup>\r\n</configuration>\r\n"
  },
  {
    "path": "tools/xunit/xunitmono.sh",
    "content": "#!/bin/sh\nBASEDIR=$(dirname $0)\nTESTDIR=$(dirname $1)\n\n# we need to copy xunit to the test dir so AppDomain.CurrentDomain.BaseDirectory\n# points to the test dir instead of the xunit dir when using -noappdomain\n# as Nancy relies on this to locate views.\n# -noappdomain works around https://bugzilla.xamarin.com/show_bug.cgi?id=39251\ncp ${BASEDIR}/xunit.console.x86.exe ${TESTDIR}\nmono -O=-gshared ${TESTDIR}/xunit.console.x86.exe $* -noappdomain\n"
  }
]