From ca3db8cffd060750025786f66b4506b1ee2a8871 Mon Sep 17 00:00:00 2001 From: James Humphries Date: Sun, 7 Feb 2016 14:03:49 +0000 Subject: [PATCH 01/52] added dotnet54 references to project.json file --- src/Nancy/project.json | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/Nancy/project.json b/src/Nancy/project.json index fc1d43dc2e..561512eb4f 100644 --- a/src/Nancy/project.json +++ b/src/Nancy/project.json @@ -22,6 +22,31 @@ ], "frameworks": { + "dotnet5.4": { + "dependencies": { + "Microsoft.CSharp": "4.0.1-beta-23516", + "System.Collections.Concurrent": "4.0.11-beta-23516", + "System.Collections.Specialized": "4.0.1-beta-23516", + "System.ComponentModel.TypeConverter": "4.0.1-beta-23516", + "System.Console": "4.0.0-beta-23516", + "System.Data.Common": "4.0.1-beta-23516", + "System.Diagnostics.Tools": "4.0.1-beta-23516", + "System.Dynamic.Runtime": "4.0.11-beta-23516", + "System.IO.FileSystem": "4.0.1-beta-23516", + "System.Linq": "4.0.1-beta-23516", + "System.Net.NameResolution": "4.0.0-beta-23516", + "System.Net.Primitives": "4.0.11-beta-23516", + "System.Reflection.TypeExtensions": "4.0.1-beta-23409", + "System.Reflection.Extensions" : "4.0.1-beta-23516", + "System.Runtime": "4.0.21-beta-23516", + "System.Runtime.Serialization.Primitives": "4.0.11-beta-23409", + "System.Security.Claims": "4.0.1-beta-23516", + "System.Security.Cryptography.X509Certificates": "4.0.0-beta-23516", + "System.Text.RegularExpressions": "4.0.11-beta-23516", + "System.Threading.Thread": "4.0.0-beta-23516", + "System.Xml.XmlSerializer": "4.0.11-beta-23516" + } + }, "net451": { "frameworkAssemblies": { "System.Xml": "4.0.0.0" From 3065f6364b9e9fda7a03f81cb8f150006d51026e Mon Sep 17 00:00:00 2001 From: James Humphries Date: Sun, 7 Feb 2016 14:17:24 +0000 Subject: [PATCH 02/52] replaced RNGCrytoServiceProvider with RandomNumberGenerator.Create() --- src/Nancy/Cryptography/RandomKeyGenerator.cs | 2 +- src/Nancy/Diagnostics/DiagnosticsSession.cs | 2 +- src/Nancy/Security/CsrfTokenExtensions.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Nancy/Cryptography/RandomKeyGenerator.cs b/src/Nancy/Cryptography/RandomKeyGenerator.cs index fdaf7974bc..cb38b1b907 100644 --- a/src/Nancy/Cryptography/RandomKeyGenerator.cs +++ b/src/Nancy/Cryptography/RandomKeyGenerator.cs @@ -7,7 +7,7 @@ namespace Nancy.Cryptography /// public class RandomKeyGenerator : IKeyGenerator { - private readonly RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider(); + private readonly RandomNumberGenerator provider = RandomNumberGenerator.Create(); public byte[] GetBytes(int count) { diff --git a/src/Nancy/Diagnostics/DiagnosticsSession.cs b/src/Nancy/Diagnostics/DiagnosticsSession.cs index 05925fda86..e92e5c49de 100644 --- a/src/Nancy/Diagnostics/DiagnosticsSession.cs +++ b/src/Nancy/Diagnostics/DiagnosticsSession.cs @@ -15,7 +15,7 @@ public class DiagnosticsSession public static byte[] GenerateRandomSalt() { - var provider = new RNGCryptoServiceProvider(); + var provider = RandomNumberGenerator.Create(); var buffer = new byte[32]; provider.GetBytes(buffer); diff --git a/src/Nancy/Security/CsrfTokenExtensions.cs b/src/Nancy/Security/CsrfTokenExtensions.cs index a17d7e6fef..8388f6ca57 100644 --- a/src/Nancy/Security/CsrfTokenExtensions.cs +++ b/src/Nancy/Security/CsrfTokenExtensions.cs @@ -8,7 +8,7 @@ public static class CsrfTokenExtensions { - private static readonly RandomNumberGenerator randomGenerator = new RNGCryptoServiceProvider(); + private static readonly RandomNumberGenerator randomGenerator = RandomNumberGenerator.Create(); /// /// Gets a byte array representation of the csrf token for generating From 94f6f806435675c17754455fb5f03bc9d4db7934 Mon Sep 17 00:00:00 2001 From: James Humphries Date: Sun, 7 Feb 2016 14:27:34 +0000 Subject: [PATCH 03/52] ifdefed out usages of SerializationInfo exception ctors --- .../Bootstrapper/MultipleRootPathProvidersLocatedException.cs | 2 ++ src/Nancy/ModelBinding/ModelBindingException.cs | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Nancy/Bootstrapper/MultipleRootPathProvidersLocatedException.cs b/src/Nancy/Bootstrapper/MultipleRootPathProvidersLocatedException.cs index e40fef52e3..2e120a59db 100644 --- a/src/Nancy/Bootstrapper/MultipleRootPathProvidersLocatedException.cs +++ b/src/Nancy/Bootstrapper/MultipleRootPathProvidersLocatedException.cs @@ -52,6 +52,7 @@ public MultipleRootPathProvidersLocatedException(IEnumerable providerTypes this.StoreProviderTypes(providerTypes); } +#if !DOTNET5_4 /// /// Initializes a new instance of the class. /// @@ -60,6 +61,7 @@ public MultipleRootPathProvidersLocatedException(IEnumerable providerTypes protected MultipleRootPathProvidersLocatedException(SerializationInfo info, StreamingContext context) : base(info, context) { } +#endif /// /// Gets the provider types. diff --git a/src/Nancy/ModelBinding/ModelBindingException.cs b/src/Nancy/ModelBinding/ModelBindingException.cs index c9037ed064..f08b9c5514 100644 --- a/src/Nancy/ModelBinding/ModelBindingException.cs +++ b/src/Nancy/ModelBinding/ModelBindingException.cs @@ -38,7 +38,7 @@ public ModelBindingException(Type boundType, IEnumerable(); this.BoundType = boundType; } - +#if !DOTNET5_4 /// /// Initializes a new instance of the class with serialized data. /// @@ -48,5 +48,6 @@ protected ModelBindingException(SerializationInfo info, StreamingContext context : base(info, context) { } +#endif } } \ No newline at end of file From 69f24a043b5b2f555dfc473e1c6fa1f3a86cce44 Mon Sep 17 00:00:00 2001 From: James Humphries Date: Sun, 7 Feb 2016 17:02:06 +0000 Subject: [PATCH 04/52] ifdefed out SerializableAttribute usages in nancy.xproj --- src/Nancy/Diagnostics/DiagnosticsSession.cs | 2 ++ src/Nancy/Security/CsrfToken.cs | 2 ++ 2 files changed, 4 insertions(+) diff --git a/src/Nancy/Diagnostics/DiagnosticsSession.cs b/src/Nancy/Diagnostics/DiagnosticsSession.cs index e92e5c49de..6a32cd0c28 100644 --- a/src/Nancy/Diagnostics/DiagnosticsSession.cs +++ b/src/Nancy/Diagnostics/DiagnosticsSession.cs @@ -4,7 +4,9 @@ namespace Nancy.Diagnostics using System.Security.Cryptography; using System.Text; +#if !DOTNET5_4 [Serializable] +#endif public class DiagnosticsSession { public byte[] Hash { get; set; } diff --git a/src/Nancy/Security/CsrfToken.cs b/src/Nancy/Security/CsrfToken.cs index 3c813a84a0..b48fb51115 100644 --- a/src/Nancy/Security/CsrfToken.cs +++ b/src/Nancy/Security/CsrfToken.cs @@ -6,7 +6,9 @@ /// /// Represents a Csrf protection token /// +#if !DOTNET5_4 [Serializable] +#endif public sealed class CsrfToken { /// From 73029b846812bc850d9f776486f6c231edab6564 Mon Sep 17 00:00:00 2001 From: James Humphries Date: Sun, 7 Feb 2016 14:31:41 +0000 Subject: [PATCH 05/52] ifdefed out usage of ICloneable interface in Url class --- src/Nancy/Url.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/Nancy/Url.cs b/src/Nancy/Url.cs index 7eaf840c08..8aea28ddfe 100644 --- a/src/Nancy/Url.cs +++ b/src/Nancy/Url.cs @@ -9,7 +9,11 @@ namespace Nancy /// Represents a full Url of the form scheme://hostname:port/basepath/path?query /// /// Since this is for internal use, and fragments are not passed to the server, fragments are not supported. +#if DOTNET5_4 + public sealed class Url +#else public sealed class Url : ICloneable +#endif { private string basePath; @@ -122,6 +126,7 @@ public override string ToString() .ToString(); } +#if !DOTNET5_4 /// /// Clones the url. /// @@ -130,6 +135,7 @@ object ICloneable.Clone() { return this.Clone(); } +#endif /// /// Clones the url. From e184729b45c0a60773e733ed251b5fbbc85297d9 Mon Sep 17 00:00:00 2001 From: James Humphries Date: Mon, 8 Feb 2016 13:25:18 +0000 Subject: [PATCH 06/52] YAGNI: removed ICloneable interface after discussion in #2251 --- src/Nancy/Url.cs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/Nancy/Url.cs b/src/Nancy/Url.cs index 8aea28ddfe..6ede5f87e1 100644 --- a/src/Nancy/Url.cs +++ b/src/Nancy/Url.cs @@ -9,11 +9,7 @@ namespace Nancy /// Represents a full Url of the form scheme://hostname:port/basepath/path?query /// /// Since this is for internal use, and fragments are not passed to the server, fragments are not supported. -#if DOTNET5_4 public sealed class Url -#else - public sealed class Url : ICloneable -#endif { private string basePath; From 1602865f5895a97fd98f61d6df28e504ba45d5b7 Mon Sep 17 00:00:00 2001 From: James Humphries Date: Mon, 8 Feb 2016 13:26:21 +0000 Subject: [PATCH 07/52] removed ifdefed method in Url.cs --- src/Nancy/Url.cs | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/src/Nancy/Url.cs b/src/Nancy/Url.cs index 6ede5f87e1..13b81659b7 100644 --- a/src/Nancy/Url.cs +++ b/src/Nancy/Url.cs @@ -122,17 +122,6 @@ public override string ToString() .ToString(); } -#if !DOTNET5_4 - /// - /// Clones the url. - /// - /// Returns a new cloned instance of the url. - object ICloneable.Clone() - { - return this.Clone(); - } -#endif - /// /// Clones the url. /// From f62d0eac657263800607657685ba0e85903d122f Mon Sep 17 00:00:00 2001 From: Jonathan Channon Date: Tue, 9 Feb 2016 15:57:13 +0000 Subject: [PATCH 08/52] added coreclr dotsettings file --- Nancy.Next.sln.DotSettings | 45 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Nancy.Next.sln.DotSettings diff --git a/Nancy.Next.sln.DotSettings b/Nancy.Next.sln.DotSettings new file mode 100644 index 0000000000..22caab0b2c --- /dev/null +++ b/Nancy.Next.sln.DotSettings @@ -0,0 +1,45 @@ + + True + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + <?xml version="1.0" encoding="utf-16"?><Profile name="NancyStandard"><CSUseVar><BehavourStyle>CAN_CHANGE_TO_IMPLICIT</BehavourStyle><LocalVariableStyle>ALWAYS_IMPLICIT</LocalVariableStyle><ForeachVariableStyle>ALWAYS_IMPLICIT</ForeachVariableStyle></CSUseVar><CSOptimizeUsings><OptimizeUsings>True</OptimizeUsings><EmbraceInRegion>False</EmbraceInRegion><RegionName></RegionName></CSOptimizeUsings><CSReformatCode>True</CSReformatCode><CSShortenReferences>True</CSShortenReferences><CSReorderTypeMembers>True</CSReorderTypeMembers><CSMakeFieldReadonly>True</CSMakeFieldReadonly></Profile> + All + False + NEXT_LINE + 1 + 1 + 1 + 1 + ALWAYS_ADD + ALWAYS_ADD + ALWAYS_ADD + ALWAYS_ADD + ALWAYS_ADD + ALWAYS_ADD + NEXT_LINE + 1 + 1 + True + ALWAYS_USE + False + True + False + False + True + False + True + True + <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb"><ExtraRule Prefix="" Suffix="" Style="Aa_bb" /></Policy> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /> + True + True + True + <data><IncludeFilters /><ExcludeFilters /></data> + <data /> + + From 5d22df37cd33c2c0157906773798903bec6c710f Mon Sep 17 00:00:00 2001 From: Jonathan Channon Date: Tue, 9 Feb 2016 17:04:47 +0000 Subject: [PATCH 09/52] updated all packages to 23516 build --- src/Nancy/project.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Nancy/project.json b/src/Nancy/project.json index 561512eb4f..631179f35e 100644 --- a/src/Nancy/project.json +++ b/src/Nancy/project.json @@ -36,10 +36,10 @@ "System.Linq": "4.0.1-beta-23516", "System.Net.NameResolution": "4.0.0-beta-23516", "System.Net.Primitives": "4.0.11-beta-23516", - "System.Reflection.TypeExtensions": "4.0.1-beta-23409", + "System.Reflection.TypeExtensions": "4.1.0-beta-23516", "System.Reflection.Extensions" : "4.0.1-beta-23516", "System.Runtime": "4.0.21-beta-23516", - "System.Runtime.Serialization.Primitives": "4.0.11-beta-23409", + "System.Runtime.Serialization.Primitives": "4.1.0-beta-23516", "System.Security.Claims": "4.0.1-beta-23516", "System.Security.Cryptography.X509Certificates": "4.0.0-beta-23516", "System.Text.RegularExpressions": "4.0.11-beta-23516", From 68b212339690f145f450a2ce2a36944c8e701988 Mon Sep 17 00:00:00 2001 From: Jonathan Channon Date: Tue, 9 Feb 2016 17:16:55 +0000 Subject: [PATCH 10/52] added System.IO package to resolve IOException/FileNotFound error --- src/Nancy/project.json | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Nancy/project.json b/src/Nancy/project.json index 631179f35e..bb4676c909 100644 --- a/src/Nancy/project.json +++ b/src/Nancy/project.json @@ -32,6 +32,7 @@ "System.Data.Common": "4.0.1-beta-23516", "System.Diagnostics.Tools": "4.0.1-beta-23516", "System.Dynamic.Runtime": "4.0.11-beta-23516", + "System.IO": "4.0.11-beta-23516", "System.IO.FileSystem": "4.0.1-beta-23516", "System.Linq": "4.0.1-beta-23516", "System.Net.NameResolution": "4.0.0-beta-23516", From 23ef466194d58ba8dcfa96f3253bd994c6a64281 Mon Sep 17 00:00:00 2001 From: Jonathan Channon Date: Tue, 9 Feb 2016 17:54:23 +0000 Subject: [PATCH 11/52] replaced SchemeDelimiter, UriSchemeHttp, UriSchemeHttps with string literals --- src/Nancy/Url.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Nancy/Url.cs b/src/Nancy/Url.cs index 13b81659b7..d6391b0de7 100644 --- a/src/Nancy/Url.cs +++ b/src/Nancy/Url.cs @@ -20,7 +20,7 @@ public sealed class Url /// public Url() { - this.Scheme = Uri.UriSchemeHttp; + this.Scheme = "http://"; this.HostName = string.Empty; this.Port = null; this.BasePath = string.Empty; @@ -91,7 +91,7 @@ public string SiteBase { return new StringBuilder() .Append(this.Scheme) - .Append(Uri.SchemeDelimiter) + .Append("://") .Append(GetHostName(this.HostName)) .Append(GetPort(this.Port)) .ToString(); @@ -105,7 +105,7 @@ public bool IsSecure { get { - return Uri.UriSchemeHttps.Equals(this.Scheme, StringComparison.OrdinalIgnoreCase); + return "https://".Equals(this.Scheme, StringComparison.OrdinalIgnoreCase); } } @@ -113,7 +113,7 @@ public override string ToString() { return new StringBuilder() .Append(this.Scheme) - .Append(Uri.SchemeDelimiter) + .Append("://") .Append(GetHostName(this.HostName)) .Append(GetPort(this.Port)) .Append(GetCorrectPath(this.BasePath)) From b94759329d4422def00ba50e5bfdf1c2eb37ecdd Mon Sep 17 00:00:00 2001 From: James Humphries Date: Sun, 7 Feb 2016 14:42:14 +0000 Subject: [PATCH 12/52] moved implementation of IsHex/FromHex to method inside HttpEncoder and ifdefed in implementation for dotnet54 --- src/Nancy/Helpers/HttpEncoder.cs | 40 +++++++++++++++++++++++++++++--- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/src/Nancy/Helpers/HttpEncoder.cs b/src/Nancy/Helpers/HttpEncoder.cs index 22906b32cb..f912d32078 100644 --- a/src/Nancy/Helpers/HttpEncoder.cs +++ b/src/Nancy/Helpers/HttpEncoder.cs @@ -217,7 +217,7 @@ protected internal virtual #else internal static #endif - string UrlPathEncode(string value) + string UrlPathEncode(string value) { if (string.IsNullOrEmpty(value)) return value; @@ -516,9 +516,9 @@ internal static string HtmlDecode(string s) #endif have_trailing_digits = false; } - else if (is_hex_value && Uri.IsHexDigit(c)) + else if (is_hex_value && IsHexDigit(c)) { - number = number * 16 + Uri.FromHex(c); + number = number * 16 + FromHex(c); have_trailing_digits = true; #if NET_4_0 rawEntity.Append (c); @@ -563,6 +563,40 @@ internal static string HtmlDecode(string s) return output.ToString(); } + internal static bool IsHexDigit(char character) + { +#if DOTNET5_4 + //implementation from https://github.com/dotnet/corefx/blob/ac67ffac987d0c27236c4a6cf1255c2bcbc7fe7d/src/System.Private.Uri/src/System/Uri.cs#L1366 + return ((character >= '0') && (character <= '9')) + || ((character >= 'A') && (character <= 'F')) + || ((character >= 'a') && (character <= 'f')); +#else + return Uri.IsHexDigit(character); +#endif + } + + internal static int FromHex(char digit) + { +#if DOTNET5_4 + //implementation from https://github.com/dotnet/corefx/blob/ac67ffac987d0c27236c4a6cf1255c2bcbc7fe7d/src/System.Private.Uri/src/System/Uri.cs#L1379 + if (((digit >= '0') && (digit <= '9')) + || ((digit >= 'A') && (digit <= 'F')) + || ((digit >= 'a') && (digit <= 'f'))) + { + return (digit <= '9') + ? ((int)digit - (int)'0') + : (((digit <= 'F') + ? ((int)digit - (int)'A') + : ((int)digit - (int)'a')) + + 10); + } + throw new ArgumentException("digit"); +#else + return Uri.FromHex(digit); +#endif + } + + internal static bool NotEncoded(char c) { return (c == '!' || c == '(' || c == ')' || c == '*' || c == '-' || c == '.' || c == '_' From 685ca3ce082a3a8e1d3a88acf2d01690e03ce868 Mon Sep 17 00:00:00 2001 From: James Humphries Date: Wed, 10 Feb 2016 09:32:21 +0000 Subject: [PATCH 13/52] removed unneccessary ifdeffing --- src/Nancy/Helpers/HttpEncoder.cs | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/src/Nancy/Helpers/HttpEncoder.cs b/src/Nancy/Helpers/HttpEncoder.cs index f912d32078..c1531dcb9f 100644 --- a/src/Nancy/Helpers/HttpEncoder.cs +++ b/src/Nancy/Helpers/HttpEncoder.cs @@ -1,7 +1,7 @@ // // Authors: // Patrik Torstensson (Patrik.Torstensson@labs2.com) -// Wictor Wilén (decode/encode functions) (wictor@ibizkit.se) +// Wictor Wil�n (decode/encode functions) (wictor@ibizkit.se) // Tim Coleman (tim@timcoleman.com) // Gonzalo Paniagua Javier (gonzalo@ximian.com) @@ -565,19 +565,14 @@ internal static string HtmlDecode(string s) internal static bool IsHexDigit(char character) { -#if DOTNET5_4 //implementation from https://github.com/dotnet/corefx/blob/ac67ffac987d0c27236c4a6cf1255c2bcbc7fe7d/src/System.Private.Uri/src/System/Uri.cs#L1366 return ((character >= '0') && (character <= '9')) || ((character >= 'A') && (character <= 'F')) || ((character >= 'a') && (character <= 'f')); -#else - return Uri.IsHexDigit(character); -#endif } internal static int FromHex(char digit) { -#if DOTNET5_4 //implementation from https://github.com/dotnet/corefx/blob/ac67ffac987d0c27236c4a6cf1255c2bcbc7fe7d/src/System.Private.Uri/src/System/Uri.cs#L1379 if (((digit >= '0') && (digit <= '9')) || ((digit >= 'A') && (digit <= 'F')) @@ -591,9 +586,6 @@ internal static int FromHex(char digit) + 10); } throw new ArgumentException("digit"); -#else - return Uri.FromHex(digit); -#endif } @@ -947,4 +939,4 @@ static void InitEntities() entities.Add("euro", '\u20AC'); } } -} \ No newline at end of file +} From 8d211ecfbd6dd3c05f94e9034a61842e454aa462 Mon Sep 17 00:00:00 2001 From: Jonathan Channon Date: Wed, 10 Feb 2016 09:36:48 +0000 Subject: [PATCH 14/52] removed :// in Url due to bug in portability analyzer --- src/Nancy/Url.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Nancy/Url.cs b/src/Nancy/Url.cs index d6391b0de7..141983033a 100644 --- a/src/Nancy/Url.cs +++ b/src/Nancy/Url.cs @@ -20,7 +20,7 @@ public sealed class Url /// public Url() { - this.Scheme = "http://"; + this.Scheme = "http"; this.HostName = string.Empty; this.Port = null; this.BasePath = string.Empty; @@ -105,7 +105,7 @@ public bool IsSecure { get { - return "https://".Equals(this.Scheme, StringComparison.OrdinalIgnoreCase); + return "https".Equals(this.Scheme, StringComparison.OrdinalIgnoreCase); } } From 892fd8254bd3f59894c9f9a234785fae317b0e21 Mon Sep 17 00:00:00 2001 From: James Humphries Date: Wed, 10 Feb 2016 10:14:22 +0000 Subject: [PATCH 15/52] =?UTF-8?q?fixed=20=C3=A9=20in=20comment?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Nancy/Helpers/HttpEncoder.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Nancy/Helpers/HttpEncoder.cs b/src/Nancy/Helpers/HttpEncoder.cs index c1531dcb9f..af966df152 100644 --- a/src/Nancy/Helpers/HttpEncoder.cs +++ b/src/Nancy/Helpers/HttpEncoder.cs @@ -1,7 +1,7 @@ // // Authors: // Patrik Torstensson (Patrik.Torstensson@labs2.com) -// Wictor Wil�n (decode/encode functions) (wictor@ibizkit.se) +// Wictor Wilén (decode/encode functions) (wictor@ibizkit.se) // Tim Coleman (tim@timcoleman.com) // Gonzalo Paniagua Javier (gonzalo@ximian.com) From f4e29e4a3136c5923af58a173cba722790209831 Mon Sep 17 00:00:00 2001 From: James Humphries Date: Sun, 7 Feb 2016 14:03:49 +0000 Subject: [PATCH 16/52] MemoryStream.GetBuffer -> MemoryStream.TryGetBuffer --- src/Nancy.MSBuild/Nancy.csproj | 3 ++ src/Nancy/DefaultObjectSerializer.cs | 6 ++-- .../Extensions/MemoryStreamExtensions.cs | 31 +++++++++++++++++++ src/Nancy/Helpers/HttpUtility.cs | 6 ++-- src/Nancy/project.json | 6 ++-- 5 files changed, 43 insertions(+), 9 deletions(-) create mode 100644 src/Nancy/Extensions/MemoryStreamExtensions.cs diff --git a/src/Nancy.MSBuild/Nancy.csproj b/src/Nancy.MSBuild/Nancy.csproj index 0fba880665..91e6ffb5d5 100644 --- a/src/Nancy.MSBuild/Nancy.csproj +++ b/src/Nancy.MSBuild/Nancy.csproj @@ -314,6 +314,9 @@ ErrorHandling\RouteExecutionEarlyExitException.cs + + Extensions\MemoryStreamExtensions.cs + Extensions\ModelValidationErrorExtensions.cs diff --git a/src/Nancy/DefaultObjectSerializer.cs b/src/Nancy/DefaultObjectSerializer.cs index 0c2dc92ad0..6320879389 100644 --- a/src/Nancy/DefaultObjectSerializer.cs +++ b/src/Nancy/DefaultObjectSerializer.cs @@ -1,5 +1,6 @@ namespace Nancy { + using Extensions; using System; using System.IO; using System.Runtime.Serialization; @@ -25,9 +26,8 @@ public string Serialize(object sourceObject) { formatter.Serialize(outputStream, sourceObject); - var outputBytes = outputStream.GetBuffer(); - - return Convert.ToBase64String(outputBytes, 0, (int)outputStream.Length); + var buffer = outputStream.GetBufferSegment(); + return Convert.ToBase64String(buffer.Array, buffer.Offset, buffer.Count); } } diff --git a/src/Nancy/Extensions/MemoryStreamExtensions.cs b/src/Nancy/Extensions/MemoryStreamExtensions.cs new file mode 100644 index 0000000000..950952c97c --- /dev/null +++ b/src/Nancy/Extensions/MemoryStreamExtensions.cs @@ -0,0 +1,31 @@ +namespace Nancy.Extensions +{ + using System; + using System.IO; + + internal static class MemoryStreamExtensions + { + public static ArraySegment GetBufferSegment(this MemoryStream stream) + { +#if DOTNET5_4 + ArraySegment buffer; + if (stream.TryGetBuffer(out buffer)) + { + return buffer; + } +#endif + var bytes = stream.GetBytes(); + + return new ArraySegment(bytes, 0, bytes.Length); + } + + private static byte[] GetBytes(this MemoryStream stream) + { +#if DOTNET5_4 + return stream.ToArray(); // This is all we have if TryGetBuffer fails in GetBufferSegment +#else + return stream.GetBuffer(); +#endif + } + } +} diff --git a/src/Nancy/Helpers/HttpUtility.cs b/src/Nancy/Helpers/HttpUtility.cs index b5365f393c..29c35e0621 100644 --- a/src/Nancy/Helpers/HttpUtility.cs +++ b/src/Nancy/Helpers/HttpUtility.cs @@ -31,6 +31,7 @@ namespace Nancy.Helpers { + using Extensions; using System; using System.Collections; using System.Collections.Generic; @@ -118,7 +119,8 @@ public static string UrlDecode(string str) static char[] GetChars(MemoryStream b, Encoding e) { - return e.GetChars(b.GetBuffer(), 0, (int)b.Length); + var buffer = b.GetBufferSegment(); + return e.GetChars(buffer.Array, buffer.Offset, buffer.Count); } static void WriteCharBytes(IList buf, char ch, Encoding e) @@ -750,6 +752,6 @@ private static KeyValuePair ParseQueryStringSegment(string segme return new KeyValuePair(key, value); } - #endregion // Methods +#endregion // Methods } } diff --git a/src/Nancy/project.json b/src/Nancy/project.json index bb4676c909..177421332a 100644 --- a/src/Nancy/project.json +++ b/src/Nancy/project.json @@ -1,4 +1,4 @@ -{ +{ "version": "2.0.0-*", "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.", @@ -7,7 +7,6 @@ "projectUrl": "http://nancyfx.org", "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", "iconUrl": "http://nancyfx.org/nancy-nuget.png", - "compilationOptions": { "define": [ "DNX" ] }, @@ -20,7 +19,6 @@ "Diagnostics/Resources/**/*.*", "Diagnostics/Views/**/*.*" ], - "frameworks": { "dotnet5.4": { "dependencies": { @@ -38,7 +36,7 @@ "System.Net.NameResolution": "4.0.0-beta-23516", "System.Net.Primitives": "4.0.11-beta-23516", "System.Reflection.TypeExtensions": "4.1.0-beta-23516", - "System.Reflection.Extensions" : "4.0.1-beta-23516", + "System.Reflection.Extensions": "4.0.1-beta-23516", "System.Runtime": "4.0.21-beta-23516", "System.Runtime.Serialization.Primitives": "4.1.0-beta-23516", "System.Security.Claims": "4.0.1-beta-23516", From 0fc958c2954c478a66cf107dea3ba261aea70f44 Mon Sep 17 00:00:00 2001 From: James Humphries Date: Mon, 15 Feb 2016 15:25:11 +0000 Subject: [PATCH 17/52] Swapped Rij... encryption with Aes, added ArguementException handler for a mono decryption issue --- src/Nancy.MSBuild/Nancy.csproj | 6 ++--- ...onProvider.cs => AesEncryptionProvider.cs} | 22 +++++++++++++------ .../Cryptography/CryptographyConfiguration.cs | 2 +- src/Nancy/project.json | 1 + ...FormsAuthenticationConfigurationFixture.cs | 2 +- .../FormsAuthenticationFixture.cs | 2 +- test/Nancy.Tests.MSBuild/Nancy.Tests.csproj | 10 ++++----- ...ure.cs => AesEncryptionProviderFixture.cs} | 10 ++++----- ...CookieBasedSessionsConfigurationFixture.cs | 2 +- .../Sessions/CookieBasedSessionsFixture.cs | 22 +++++++++---------- 10 files changed, 44 insertions(+), 35 deletions(-) rename src/Nancy/Cryptography/{RijndaelEncryptionProvider.cs => AesEncryptionProvider.cs} (74%) rename test/Nancy.Tests/Unit/Cryptography/{RijndaelEncryptionProviderFixture.cs => AesEncryptionProviderFixture.cs} (66%) diff --git a/src/Nancy.MSBuild/Nancy.csproj b/src/Nancy.MSBuild/Nancy.csproj index 91e6ffb5d5..e76f9231e4 100644 --- a/src/Nancy.MSBuild/Nancy.csproj +++ b/src/Nancy.MSBuild/Nancy.csproj @@ -1181,9 +1181,6 @@ Session\CookieBasedSessions.cs - - Cryptography\RijndaelEncryptionProvider.cs - DefaultObjectSerializer.cs @@ -1358,6 +1355,9 @@ + + Cryptography\AesEncryptionProvider.cs + Configuration\ConfigurationException.cs diff --git a/src/Nancy/Cryptography/RijndaelEncryptionProvider.cs b/src/Nancy/Cryptography/AesEncryptionProvider.cs similarity index 74% rename from src/Nancy/Cryptography/RijndaelEncryptionProvider.cs rename to src/Nancy/Cryptography/AesEncryptionProvider.cs index feaba06ec1..3f298876a2 100644 --- a/src/Nancy/Cryptography/RijndaelEncryptionProvider.cs +++ b/src/Nancy/Cryptography/AesEncryptionProvider.cs @@ -5,19 +5,19 @@ namespace Nancy.Cryptography using System.Text; /// - /// Default encryption provider using Rijndael + /// Default encryption provider using Aes /// - public class RijndaelEncryptionProvider : IEncryptionProvider + public class AesEncryptionProvider : IEncryptionProvider { private readonly byte[] key; private readonly byte[] iv; /// - /// Creates a new instance of the RijndaelEncryptionProvider class + /// Creates a new instance of the AesEncryptionProvider class /// /// Key generator to use to generate the key and iv - public RijndaelEncryptionProvider(IKeyGenerator keyGenerator) + public AesEncryptionProvider(IKeyGenerator keyGenerator) { this.key = keyGenerator.GetBytes(32); this.iv = keyGenerator.GetBytes(16); @@ -30,7 +30,7 @@ public RijndaelEncryptionProvider(IKeyGenerator keyGenerator) /// Encrypted string public string Encrypt(string data) { - using (var provider = new RijndaelManaged()) + using (var provider = Aes.Create()) using (var encryptor = provider.CreateEncryptor(this.key, this.iv)) { var input = Encoding.UTF8.GetBytes(data); @@ -49,7 +49,7 @@ public string Decrypt(string data) { try { - using (var provider = new RijndaelManaged()) + using (var provider = Aes.Create()) using (var decryptor = provider.CreateDecryptor(this.key, this.iv)) { var input = Convert.FromBase64String(data); @@ -66,6 +66,14 @@ public string Decrypt(string data) { return String.Empty; } + catch(ArgumentException ex) + { + if (ex.ParamName == null) + { + return String.Empty; + } + throw ex; + } } } -} \ No newline at end of file +} diff --git a/src/Nancy/Cryptography/CryptographyConfiguration.cs b/src/Nancy/Cryptography/CryptographyConfiguration.cs index a8f6d24e38..5f315f988d 100644 --- a/src/Nancy/Cryptography/CryptographyConfiguration.cs +++ b/src/Nancy/Cryptography/CryptographyConfiguration.cs @@ -9,7 +9,7 @@ public class CryptographyConfiguration { private static readonly Lazy DefaultConfiguration = new Lazy(() => new CryptographyConfiguration( - new RijndaelEncryptionProvider(new RandomKeyGenerator()), + new AesEncryptionProvider(new RandomKeyGenerator()), new DefaultHmacProvider(new RandomKeyGenerator()))); private static readonly Lazy NoEncryptionConfiguration = diff --git a/src/Nancy/project.json b/src/Nancy/project.json index 177421332a..749e449607 100644 --- a/src/Nancy/project.json +++ b/src/Nancy/project.json @@ -40,6 +40,7 @@ "System.Runtime": "4.0.21-beta-23516", "System.Runtime.Serialization.Primitives": "4.1.0-beta-23516", "System.Security.Claims": "4.0.1-beta-23516", + "System.Security.Cryptography.Algorithms": "4.0.0-beta-23516", "System.Security.Cryptography.X509Certificates": "4.0.0-beta-23516", "System.Text.RegularExpressions": "4.0.11-beta-23516", "System.Threading.Thread": "4.0.0-beta-23516", diff --git a/test/Nancy.Authentication.Forms.Tests/FormsAuthenticationConfigurationFixture.cs b/test/Nancy.Authentication.Forms.Tests/FormsAuthenticationConfigurationFixture.cs index cb9fe0bde2..9988579f74 100644 --- a/test/Nancy.Authentication.Forms.Tests/FormsAuthenticationConfigurationFixture.cs +++ b/test/Nancy.Authentication.Forms.Tests/FormsAuthenticationConfigurationFixture.cs @@ -13,7 +13,7 @@ public class FormsAuthenticationConfigurationFixture public FormsAuthenticationConfigurationFixture() { var cryptographyConfiguration = new CryptographyConfiguration( - new RijndaelEncryptionProvider(new PassphraseKeyGenerator("SuperSecretPass", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 })), + new AesEncryptionProvider(new PassphraseKeyGenerator("SuperSecretPass", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 })), new DefaultHmacProvider(new PassphraseKeyGenerator("UberSuperSecure", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }))); this.config = new FormsAuthenticationConfiguration() diff --git a/test/Nancy.Authentication.Forms.Tests/FormsAuthenticationFixture.cs b/test/Nancy.Authentication.Forms.Tests/FormsAuthenticationFixture.cs index 38a0516513..89f1d7142f 100644 --- a/test/Nancy.Authentication.Forms.Tests/FormsAuthenticationFixture.cs +++ b/test/Nancy.Authentication.Forms.Tests/FormsAuthenticationFixture.cs @@ -44,7 +44,7 @@ public class FormsAuthenticationFixture public FormsAuthenticationFixture() { this.cryptographyConfiguration = new CryptographyConfiguration( - new RijndaelEncryptionProvider(new PassphraseKeyGenerator("SuperSecretPass", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000)), + new AesEncryptionProvider(new PassphraseKeyGenerator("SuperSecretPass", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000)), new DefaultHmacProvider(new PassphraseKeyGenerator("UberSuperSecure", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000))); this.config = new FormsAuthenticationConfiguration() diff --git a/test/Nancy.Tests.MSBuild/Nancy.Tests.csproj b/test/Nancy.Tests.MSBuild/Nancy.Tests.csproj index 85ce94b4c4..14efb8618c 100644 --- a/test/Nancy.Tests.MSBuild/Nancy.Tests.csproj +++ b/test/Nancy.Tests.MSBuild/Nancy.Tests.csproj @@ -354,6 +354,9 @@ Unit\Cryptography\NoEncryptionProviderFixture.cs + + Unit\Cryptography\AesEncryptionProviderFixture.cs + Unit\DefaultNancyBootstrapperModuleCatalogFixture.cs @@ -561,9 +564,6 @@ Unit\Sessions\CookieBasedSessionsFixture.cs - - Unit\Cryptography\RijndaelEncryptionProviderFixture.cs - Unit\Sessions\DefaultSessionObjectFormatterFixture.cs @@ -733,11 +733,11 @@ - - \ No newline at end of file + diff --git a/test/Nancy.Tests/Unit/Cryptography/RijndaelEncryptionProviderFixture.cs b/test/Nancy.Tests/Unit/Cryptography/AesEncryptionProviderFixture.cs similarity index 66% rename from test/Nancy.Tests/Unit/Cryptography/RijndaelEncryptionProviderFixture.cs rename to test/Nancy.Tests/Unit/Cryptography/AesEncryptionProviderFixture.cs index daf449d545..7bf28877a8 100644 --- a/test/Nancy.Tests/Unit/Cryptography/RijndaelEncryptionProviderFixture.cs +++ b/test/Nancy.Tests/Unit/Cryptography/AesEncryptionProviderFixture.cs @@ -4,13 +4,13 @@ namespace Nancy.Tests.Unit.Cryptography using Xunit; - public class RijndaelEncryptionProviderFixture + public class AesEncryptionProviderFixture { - private RijndaelEncryptionProvider provider; + private AesEncryptionProvider provider; - public RijndaelEncryptionProviderFixture() + public AesEncryptionProviderFixture() { - this.provider = new RijndaelEncryptionProvider(new PassphraseKeyGenerator("Passphrase", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 })); + this.provider = new AesEncryptionProvider(new PassphraseKeyGenerator("Passphrase", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 })); } [Fact] @@ -40,7 +40,7 @@ public void Should_not_return_original_text_when_decrypting_with_different_keys( var inputText = "this is some text"; var encText = provider.Encrypt(inputText); - var result = new RijndaelEncryptionProvider(new PassphraseKeyGenerator("Wrong", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 })).Decrypt(encText); + var result = new AesEncryptionProvider(new PassphraseKeyGenerator("Wrong", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 })).Decrypt(encText); result.ShouldNotEqual(inputText); } diff --git a/test/Nancy.Tests/Unit/Sessions/CookieBasedSessionsConfigurationFixture.cs b/test/Nancy.Tests/Unit/Sessions/CookieBasedSessionsConfigurationFixture.cs index f5b0099f04..18860fcdd3 100644 --- a/test/Nancy.Tests/Unit/Sessions/CookieBasedSessionsConfigurationFixture.cs +++ b/test/Nancy.Tests/Unit/Sessions/CookieBasedSessionsConfigurationFixture.cs @@ -15,7 +15,7 @@ public class CookieBasesSessionsConfigurationFixture public CookieBasesSessionsConfigurationFixture() { var cryptographyConfiguration = new CryptographyConfiguration( - new RijndaelEncryptionProvider(new PassphraseKeyGenerator("SuperSecretPass", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 })), + new AesEncryptionProvider(new PassphraseKeyGenerator("SuperSecretPass", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 })), new DefaultHmacProvider(new PassphraseKeyGenerator("UberSuperSecure", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }))); this.config = new CookieBasedSessionsConfiguration() diff --git a/test/Nancy.Tests/Unit/Sessions/CookieBasedSessionsFixture.cs b/test/Nancy.Tests/Unit/Sessions/CookieBasedSessionsFixture.cs index 0fca737f57..031cd2c73d 100644 --- a/test/Nancy.Tests/Unit/Sessions/CookieBasedSessionsFixture.cs +++ b/test/Nancy.Tests/Unit/Sessions/CookieBasedSessionsFixture.cs @@ -26,7 +26,7 @@ public class CookieBasedSessionsFixture private readonly IHmacProvider fakeHmacProvider; private readonly IObjectSerializer fakeObjectSerializer; - private RijndaelEncryptionProvider rijndaelEncryptionProvider; + private AesEncryptionProvider aesEncryptionProvider; private DefaultHmacProvider defaultHmacProvider; @@ -39,7 +39,7 @@ public CookieBasedSessionsFixture() this.fakeObjectSerializer = new FakeObjectSerializer(); this.cookieStore = new CookieBasedSessions(this.fakeEncryptionProvider, this.fakeHmacProvider, this.fakeObjectSerializer); - this.rijndaelEncryptionProvider = new RijndaelEncryptionProvider(new PassphraseKeyGenerator("password", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000)); + this.aesEncryptionProvider = new AesEncryptionProvider(new PassphraseKeyGenerator("password", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000)); this.defaultHmacProvider = new DefaultHmacProvider(new PassphraseKeyGenerator("anotherpassword", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000)); this.defaultObjectSerializer = new DefaultObjectSerializer(); } @@ -128,7 +128,7 @@ public void Should_load_an_empty_session_if_session_cookie_is_invalid() //given var inputValue = ValidHmac.Substring(0, 5); //invalid Hmac inputValue = HttpUtility.UrlEncode(inputValue); - var store = new CookieBasedSessions(this.rijndaelEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer); + var store = new CookieBasedSessions(this.aesEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer); var request = new Request("GET", "/", "http"); request.Cookies.Add(store.CookieName, inputValue); @@ -284,7 +284,7 @@ public void Should_be_able_to_save_a_complex_object_to_session() var response = new Response(); var session = new Session(new Dictionary()); var payload = new DefaultSessionObjectFormatterFixture.Payload(27, true, "Test string"); - var store = new CookieBasedSessions(this.rijndaelEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer); + var store = new CookieBasedSessions(this.aesEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer); session["testObject"] = payload; store.Save(session, response); @@ -302,7 +302,7 @@ public void Should_be_able_to_load_an_object_previously_saved_to_session() var response = new Response(); var session = new Session(new Dictionary()); var payload = new DefaultSessionObjectFormatterFixture.Payload(27, true, "Test string"); - var store = new CookieBasedSessions(this.rijndaelEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer); + var store = new CookieBasedSessions(this.aesEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer); session["testObject"] = payload; store.Save(session, response); var request = new Request("GET", "/", "http"); @@ -350,7 +350,7 @@ public void Should_load_valid_test_data() { var inputValue = ValidHmac + ValidData; inputValue = HttpUtility.UrlEncode(inputValue); - var store = new CookieBasedSessions(this.rijndaelEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer); + var store = new CookieBasedSessions(this.aesEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer); var request = new Request("GET", "/", "http"); request.Cookies.Add(store.CookieName, inputValue); @@ -365,7 +365,7 @@ public void Should_return_blank_session_if_hmac_changed() { var inputValue = "b" + ValidHmac.Substring(1) + ValidData; inputValue = HttpUtility.UrlEncode(inputValue); - var store = new CookieBasedSessions(this.rijndaelEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer); + var store = new CookieBasedSessions(this.aesEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer); var request = new Request("GET", "/", "http"); request.Cookies.Add(store.CookieName, inputValue); @@ -379,7 +379,7 @@ public void Should_return_blank_session_if_hmac_missing() { var inputValue = ValidData; inputValue = HttpUtility.UrlEncode(inputValue); - var store = new CookieBasedSessions(this.rijndaelEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer); + var store = new CookieBasedSessions(this.aesEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer); var request = new Request("GET", "/", "http"); request.Cookies.Add(store.CookieName, inputValue); @@ -393,7 +393,7 @@ public void Should_return_blank_session_if_encrypted_data_modified() { var inputValue = ValidHmac + ValidData.Substring(0, ValidData.Length - 1) + "Z"; inputValue = HttpUtility.UrlEncode(inputValue); - var store = new CookieBasedSessions(this.rijndaelEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer); + var store = new CookieBasedSessions(this.aesEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer); var request = new Request("GET", "/", "http"); request.Cookies.Add(store.CookieName, inputValue); @@ -405,10 +405,10 @@ public void Should_return_blank_session_if_encrypted_data_modified() [Fact] public void Should_return_blank_session_if_encrypted_data_are_invalid_but_contain_semicolon_when_decrypted() { - var bogusEncrypted = this.rijndaelEncryptionProvider.Encrypt("foo;bar"); + var bogusEncrypted = this.aesEncryptionProvider.Encrypt("foo;bar"); var inputValue = ValidHmac + bogusEncrypted; inputValue = HttpUtility.UrlEncode(inputValue); - var store = new CookieBasedSessions(this.rijndaelEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer); + var store = new CookieBasedSessions(this.aesEncryptionProvider, this.defaultHmacProvider, this.defaultObjectSerializer); var request = new Request("GET", "/", "http"); request.Cookies.Add(store.CookieName, inputValue); From 7af79929aad13074a7ae0924f040f2c29fb7e7b4 Mon Sep 17 00:00:00 2001 From: James Humphries Date: Wed, 17 Feb 2016 09:13:05 +0000 Subject: [PATCH 18/52] Updated RandomNumberGenerator.cs comment --- src/Nancy/Cryptography/RandomKeyGenerator.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Nancy/Cryptography/RandomKeyGenerator.cs b/src/Nancy/Cryptography/RandomKeyGenerator.cs index cb38b1b907..35f3cfe6b3 100644 --- a/src/Nancy/Cryptography/RandomKeyGenerator.cs +++ b/src/Nancy/Cryptography/RandomKeyGenerator.cs @@ -3,7 +3,7 @@ namespace Nancy.Cryptography using System.Security.Cryptography; /// - /// Generates random secure keys using RNGCryptoServiceProvider + /// Generates random secure keys using RandomNumberGenerator /// public class RandomKeyGenerator : IKeyGenerator { @@ -18,4 +18,4 @@ public byte[] GetBytes(int count) return buffer; } } -} \ No newline at end of file +} From 615c6ac41808d0a8c51ee129a2994069628265a3 Mon Sep 17 00:00:00 2001 From: James Humphries Date: Wed, 17 Feb 2016 13:00:05 +0000 Subject: [PATCH 19/52] moving reflection across to dotnet54 --- .../Bootstrapper/ContainerRegistration.cs | 1 + .../Bootstrapper/FavIconApplicationStartup.cs | 5 +- .../Bootstrapper/NancyBootstrapperLocator.cs | 6 +- src/Nancy/Bootstrapper/Registrations.cs | 12 +- src/Nancy/DefaultNancyBootstrapper.cs | 9 +- .../DefaultRuntimeEnvironmentInformation.cs | 13 +- src/Nancy/DefaultSerializerFactory.cs | 5 +- src/Nancy/DefaultTypeCatalog.cs | 4 +- src/Nancy/Diagnostics/DiagnosticsHook.cs | 4 +- .../Diagnostics/DiagnosticsViewRenderer.cs | 3 +- .../Diagnostics/InteractiveDiagnostics.cs | 6 +- src/Nancy/Diagnostics/Modules/InfoModule.cs | 2 +- .../Diagnostics/Modules/InteractiveModule.cs | 4 +- src/Nancy/DynamicDictionaryValue.cs | 37 +- .../ErrorHandling/DefaultStatusCodeHandler.cs | 4 +- src/Nancy/Extensions/TypeExtensions.cs | 59 +- src/Nancy/Helpers/ReflectionUtils.cs | 207 ++--- src/Nancy/ModelBinding/DefaultBinder.cs | 10 +- src/Nancy/NegotiatorExtensions.cs | 2 +- src/Nancy/RequestHeaders.cs | 2 +- src/Nancy/ResponseExtensions.cs | 5 +- .../DefaultRouteDescriptionProvider.cs | 3 +- src/Nancy/TinyIoc/TinyIoC.cs | 715 ++++++++++++------ src/Nancy/TypeResolveStrategies.cs | 4 +- src/Nancy/ViewEngines/Extensions.cs | 7 +- src/Nancy/project.json | 1 - 26 files changed, 751 insertions(+), 379 deletions(-) diff --git a/src/Nancy/Bootstrapper/ContainerRegistration.cs b/src/Nancy/Bootstrapper/ContainerRegistration.cs index 5546bf0363..1ce894c746 100644 --- a/src/Nancy/Bootstrapper/ContainerRegistration.cs +++ b/src/Nancy/Bootstrapper/ContainerRegistration.cs @@ -2,6 +2,7 @@ namespace Nancy.Bootstrapper { using System; using System.Linq; + using System.Reflection; using Nancy.Extensions; diff --git a/src/Nancy/Bootstrapper/FavIconApplicationStartup.cs b/src/Nancy/Bootstrapper/FavIconApplicationStartup.cs index cd6004c45a..e7f14c2342 100644 --- a/src/Nancy/Bootstrapper/FavIconApplicationStartup.cs +++ b/src/Nancy/Bootstrapper/FavIconApplicationStartup.cs @@ -5,7 +5,7 @@ using System.IO; using System.Linq; using Nancy.Configuration; - + using System.Reflection; /// /// Application startup task that attempts to locate a favicon. The startup will first scan all /// folders in the path defined by the provided and if it cannot @@ -49,7 +49,8 @@ public void Initialize(IPipelines pipelines) private static byte[] ExtractDefaultIcon() { var resourceStream = - typeof(INancyEngine).Assembly.GetManifestResourceStream("Nancy.favicon.ico"); + typeof(INancyEngine).GetTypeInfo().Assembly.GetManifestResourceStream("Nancy.favicon.ico"); + if (resourceStream == null) { diff --git a/src/Nancy/Bootstrapper/NancyBootstrapperLocator.cs b/src/Nancy/Bootstrapper/NancyBootstrapperLocator.cs index e2a10d7ed4..952698a97e 100755 --- a/src/Nancy/Bootstrapper/NancyBootstrapperLocator.cs +++ b/src/Nancy/Bootstrapper/NancyBootstrapperLocator.cs @@ -5,7 +5,7 @@ using System.Linq; using System.Reflection; using Nancy.Extensions; - + using System.Reflection; /// /// Class for locating an INancyBootstrapper implementation. /// @@ -49,7 +49,7 @@ private static IReadOnlyCollection GetAvailableBootstrapperTypes() return assemblies .SelectMany(x => x.SafeGetExportedTypes()) - .Where(x => !x.IsAbstract && x.IsPublic) + .Where(x => !x.GetTypeInfo().IsAbstract && x.GetTypeInfo().IsPublic) .Where(x => typeof(INancyBootstrapper).IsAssignableFrom(x)) .ToArray(); } @@ -133,7 +133,7 @@ internal static bool TryFindMostDerivedType(IReadOnlyCollection customBoot var set = new HashSet(); bootstrapper = null; - if (customBootstrappers.All(b => set.Add(b.BaseType))) + if (customBootstrappers.All(b => set.Add(b.GetTypeInfo().BaseType))) { var except = customBootstrappers.Except(set).ToList(); bootstrapper = except.Count == 1 ? except[0] : null; diff --git a/src/Nancy/Bootstrapper/Registrations.cs b/src/Nancy/Bootstrapper/Registrations.cs index 43a3a4af1f..baf41ed444 100644 --- a/src/Nancy/Bootstrapper/Registrations.cs +++ b/src/Nancy/Bootstrapper/Registrations.cs @@ -3,6 +3,9 @@ using System; using System.Collections.Generic; using System.Linq; + using System.Reflection; + + using Nancy.Extensions; /// /// Helper class for providing application registrations @@ -126,7 +129,7 @@ public void RegisterWithDefault(Type defaultImplementation, Lifet { var implementation = this.typeCatalog .GetTypesAssignableTo() - .Where(type => type.Assembly != this.GetType().Assembly) + .Where(type => type.GetTypeInfo().Assembly != this.GetType().GetTypeInfo().Assembly) .SingleOrDefault(type => type != defaultImplementation); this.typeRegistrations.Add(new TypeRegistration(typeof(TRegistration), implementation ?? defaultImplementation, lifetime)); @@ -144,7 +147,8 @@ public void RegisterWithDefault(Func defaultImplem { var implementation = this.typeCatalog .GetTypesAssignableTo() - .SingleOrDefault(type => type.Assembly != this.GetType().Assembly); + .SingleOrDefault(type => type.GetTypeInfo().Assembly != this.GetType().GetTypeInfo().Assembly); + if (implementation != null) { @@ -171,7 +175,7 @@ public void RegisterWithDefault(IEnumerable defaultImplemen { var implementations = this.typeCatalog .GetTypesAssignableTo() - .Where(type => type.Assembly != this.GetType().Assembly) + .Where(type => type.Assembly() != this.GetType().GetTypeInfo().Assembly) .Where(type => !defaultImplementations.Contains(type)) .ToList(); @@ -198,7 +202,7 @@ public void RegisterWithUserThenDefault(IEnumerable default { var implementations = this.typeCatalog .GetTypesAssignableTo() - .Where(type => type.Assembly != this.GetType().Assembly) + .Where(type => type.Assembly() != this.GetType().GetTypeInfo().Assembly) .Where(type => !defaultImplementations.Contains(type)) .ToList(); diff --git a/src/Nancy/DefaultNancyBootstrapper.cs b/src/Nancy/DefaultNancyBootstrapper.cs index c22bb41d9b..a07b27ea91 100755 --- a/src/Nancy/DefaultNancyBootstrapper.cs +++ b/src/Nancy/DefaultNancyBootstrapper.cs @@ -279,9 +279,16 @@ protected override sealed INancyModule GetModule(TinyIoCContainer container, Typ /// Container instance private static void AutoRegister(TinyIoCContainer container, IEnumerable> ignoredAssemblies) { - var assembly = typeof(NancyEngine).Assembly; + var assembly = typeof(NancyEngine).GetTypeInfo().Assembly; +#if !DNX container.AutoRegister(AppDomain.CurrentDomain.GetAssemblies().Where(a => !ignoredAssemblies.Any(ia => ia(a))), DuplicateImplementationActions.RegisterMultiple, t => t.Assembly != assembly); +#else + var libraryManager = + Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.LibraryManager; + var thisAssemblyName = typeof(DefaultNancyBootstrapper).GetTypeInfo().Assembly.GetName().Name; + var referencing = libraryManager.GetReferencingLibraries(thisAssemblyName); +#endif } } } diff --git a/src/Nancy/DefaultRuntimeEnvironmentInformation.cs b/src/Nancy/DefaultRuntimeEnvironmentInformation.cs index 55e1f96431..f437cac1c5 100644 --- a/src/Nancy/DefaultRuntimeEnvironmentInformation.cs +++ b/src/Nancy/DefaultRuntimeEnvironmentInformation.cs @@ -3,6 +3,7 @@ namespace Nancy using System; using System.Diagnostics; using System.Linq; + using System.Reflection; /// /// Default implementation of the interface. @@ -35,10 +36,20 @@ private static bool GetDebugMode(ITypeCatalog typeCatalog) { var assembliesInDebug = typeCatalog .GetTypesAssignableTo(TypeResolveStrategies.ExcludeNancy) +#if DOTNET5_4 + .Select(x => x.GetTypeInfo().Assembly.GetCustomAttributes(typeof(DebuggableAttribute))) + .Where(x => x.Any()); + + return assembliesInDebug.Any(d => ((DebuggableAttribute)d.First()).IsJITTrackingEnabled); +#else .Select(x => x.Assembly.GetCustomAttributes(typeof(DebuggableAttribute), true)) .Where(x => x.Length != 0); + + return assembliesInDebug.Any(d => ((DebuggableAttribute)d[0]).IsJITTrackingEnabled); +#endif + + - return assembliesInDebug.Any(d => ((DebuggableAttribute)d[0]).IsJITTrackingEnabled); } catch { diff --git a/src/Nancy/DefaultSerializerFactory.cs b/src/Nancy/DefaultSerializerFactory.cs index 32a28091f6..e03d179ef5 100644 --- a/src/Nancy/DefaultSerializerFactory.cs +++ b/src/Nancy/DefaultSerializerFactory.cs @@ -3,6 +3,9 @@ namespace Nancy using System; using System.Collections.Generic; using System.Linq; + using System.Reflection; + + using Nancy.Extensions; using Nancy.Responses.Negotiation; /// @@ -53,7 +56,7 @@ private ISerializer GetDefaultSerializerForMediaRange(MediaRange mediaRange) try { return this.serializers - .Where(x => x.GetType().Assembly.Equals(typeof(INancyEngine).Assembly)) + .Where(x => x.GetType().GetTypeInfo().Assembly.Equals(typeof(INancyEngine).Assembly())) .SingleOrDefault(x => x.CanSerialize(mediaRange)); } catch diff --git a/src/Nancy/DefaultTypeCatalog.cs b/src/Nancy/DefaultTypeCatalog.cs index 7cd00be00b..ab75860246 100644 --- a/src/Nancy/DefaultTypeCatalog.cs +++ b/src/Nancy/DefaultTypeCatalog.cs @@ -4,6 +4,8 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; + using System.Reflection; + using Nancy.Extensions; /// @@ -41,7 +43,7 @@ private IReadOnlyCollection GetTypesAssignableTo(Type type) .GetAssemblies() .SelectMany(assembly => assembly.SafeGetExportedTypes()) .Where(type.IsAssignableFrom) - .Where(t => !t.IsAbstract) + .Where(t => !t.GetTypeInfo().IsAbstract) .ToArray(); } } diff --git a/src/Nancy/Diagnostics/DiagnosticsHook.cs b/src/Nancy/Diagnostics/DiagnosticsHook.cs index 797b593888..c0ecbc10c5 100644 --- a/src/Nancy/Diagnostics/DiagnosticsHook.cs +++ b/src/Nancy/Diagnostics/DiagnosticsHook.cs @@ -4,6 +4,7 @@ namespace Nancy.Diagnostics using System.Collections.Generic; using System.IO; using System.Linq; + using System.Reflection; using System.Threading; using Nancy.Bootstrapper; using Nancy.Configuration; @@ -18,7 +19,6 @@ namespace Nancy.Diagnostics using Nancy.Routing; using Nancy.Routing.Constraints; using Nancy.Routing.Trie; - /// /// Pipeline hook to handle diagnostics dashboard requests. /// @@ -95,7 +95,7 @@ public static void Enable(IPipelines pipelines, IEnumerable().DisplayErrorTraces; data.Nancy.CaseSensitivity = StaticConfiguration.CaseSensitive ? "Sensitive" : "Insensitive"; data.Nancy.RootPath = rootPathProvider.GetRootPath(); diff --git a/src/Nancy/Diagnostics/Modules/InteractiveModule.cs b/src/Nancy/Diagnostics/Modules/InteractiveModule.cs index 468d9a13ed..35a44a2687 100644 --- a/src/Nancy/Diagnostics/Modules/InteractiveModule.cs +++ b/src/Nancy/Diagnostics/Modules/InteractiveModule.cs @@ -5,7 +5,7 @@ using System.ComponentModel; using System.Linq; using Nancy.Helpers; - + using System.Reflection; public class InteractiveModule : DiagnosticModule { private readonly IInteractiveDiagnostics interactiveDiagnostics; @@ -30,7 +30,7 @@ public InteractiveModule(IInteractiveDiagnostics interactiveDiagnostics) p.Description, Type = p.GetType().Name, p.GetType().Namespace, - Assembly = p.GetType().Assembly.GetName().Name + Assembly = p.GetType().GetTypeInfo().Assembly.GetName().Name }) .ToArray(); diff --git a/src/Nancy/DynamicDictionaryValue.cs b/src/Nancy/DynamicDictionaryValue.cs index 1508d7c8a7..16376702ff 100644 --- a/src/Nancy/DynamicDictionaryValue.cs +++ b/src/Nancy/DynamicDictionaryValue.cs @@ -5,7 +5,12 @@ using System.Dynamic; using System.Globalization; using System.Linq.Expressions; + using System.Reflection; + using Microsoft.CSharp.RuntimeBinder; + using Extensions; + + using Binder = Microsoft.CSharp.RuntimeBinder.Binder; /// /// A value that is stored inside a instance. @@ -272,10 +277,10 @@ public override bool TryConvert(ConvertBinder binder, out object result) return true; } } - else if (binderType.IsEnum) + else if (binderType.GetTypeInfo().IsEnum) { // handles enum to enum assignments - if (this.value.GetType().IsEnum) + if (value.GetType().GetTypeInfo().IsEnum) { if (binderType == this.value.GetType()) { @@ -297,12 +302,12 @@ public override bool TryConvert(ConvertBinder binder, out object result) } else { - if (binderType.IsGenericType && binderType.GetGenericTypeDefinition() == typeof(Nullable<>)) + if (binderType.GetTypeInfo().IsGenericType && binderType.GetGenericTypeDefinition() == typeof(Nullable<>)) { binderType = binderType.GetGenericArguments()[0]; } - var typeCode = Type.GetTypeCode(binderType); + var typeCode = binderType.GetTypeCode(); if (typeCode == TypeCode.Object) { @@ -317,7 +322,11 @@ public override bool TryConvert(ConvertBinder binder, out object result) } } - result = Convert.ChangeType(this.value, typeCode); +#if !DOTNET5_4 + result = Convert.ChangeType(value, typeCode); +#else + result = Convert.ChangeType(value, binderType); +#endif return true; } @@ -346,7 +355,7 @@ public static implicit operator bool(DynamicDictionaryValue dynamicValue) return false; } - if (dynamicValue.value.GetType().IsValueType) + if (dynamicValue.value.GetType().GetTypeInfo().IsValueType) { return (Convert.ToBoolean(dynamicValue.value)); } @@ -384,7 +393,7 @@ public static implicit operator int(DynamicDictionaryValue dynamicValue) return default(int); } - if (dynamicValue.value.GetType().IsValueType) + if (dynamicValue.value.GetType().GetTypeInfo().IsValueType) { return Convert.ToInt32(dynamicValue.value); } @@ -484,7 +493,7 @@ public static implicit operator long(DynamicDictionaryValue dynamicValue) return default(long); } - if (dynamicValue.value.GetType().IsValueType) + if (dynamicValue.value.GetType().GetTypeInfo().IsValueType) { return Convert.ToInt64(dynamicValue.value); } @@ -509,7 +518,7 @@ public static implicit operator float(DynamicDictionaryValue dynamicValue) return default(float); } - if (dynamicValue.value.GetType().IsValueType) + if (dynamicValue.value.GetType().GetTypeInfo().IsValueType) { return Convert.ToSingle(dynamicValue.value); } @@ -534,7 +543,7 @@ public static implicit operator decimal(DynamicDictionaryValue dynamicValue) return default(decimal); } - if (dynamicValue.value.GetType().IsValueType) + if (dynamicValue.value.GetType().GetTypeInfo().IsValueType) { return Convert.ToDecimal(dynamicValue.value); } @@ -559,7 +568,7 @@ public static implicit operator double(DynamicDictionaryValue dynamicValue) return default(double); } - if (dynamicValue.value.GetType().IsValueType) + if (dynamicValue.value.GetType().GetTypeInfo().IsValueType) { return Convert.ToDouble(dynamicValue.value); } @@ -567,7 +576,7 @@ public static implicit operator double(DynamicDictionaryValue dynamicValue) return double.Parse(dynamicValue.ToString()); } - #region Implementation of IConvertible +#region Implementation of IConvertible /// /// Returns the for this instance. @@ -579,7 +588,7 @@ public static implicit operator double(DynamicDictionaryValue dynamicValue) public TypeCode GetTypeCode() { if (value == null) return TypeCode.Empty; - return Type.GetTypeCode(value.GetType()); + return value.GetType().GetTypeCode(); } /// @@ -774,6 +783,6 @@ public object ToType(Type conversionType, IFormatProvider provider) return Convert.ChangeType(value, conversionType, provider); } - #endregion +#endregion } } \ No newline at end of file diff --git a/src/Nancy/ErrorHandling/DefaultStatusCodeHandler.cs b/src/Nancy/ErrorHandling/DefaultStatusCodeHandler.cs index 8d2b500f4e..365519dfbd 100644 --- a/src/Nancy/ErrorHandling/DefaultStatusCodeHandler.cs +++ b/src/Nancy/ErrorHandling/DefaultStatusCodeHandler.cs @@ -3,6 +3,7 @@ namespace Nancy.ErrorHandling using System.Collections.Generic; using System.IO; using System.Linq; + using System.Reflection; using System.Text; using Nancy.Configuration; using Nancy.Extensions; @@ -137,7 +138,8 @@ private void ModifyResponse(HttpStatusCode statusCode, NancyContext context, Def private static string LoadResource(string filename) { - var resourceStream = typeof(INancyEngine).Assembly.GetManifestResourceStream(string.Format("Nancy.ErrorHandling.Resources.{0}", filename)); + var resourceStream = typeof(INancyEngine).GetTypeInfo().Assembly.GetManifestResourceStream(string.Format("Nancy.ErrorHandling.Resources.{0}", filename)); + if (resourceStream == null) { diff --git a/src/Nancy/Extensions/TypeExtensions.cs b/src/Nancy/Extensions/TypeExtensions.cs index 3884a7734d..52d2a4b41a 100644 --- a/src/Nancy/Extensions/TypeExtensions.cs +++ b/src/Nancy/Extensions/TypeExtensions.cs @@ -3,12 +3,13 @@ using System; using System.Collections.Generic; using System.Linq; - + using System.Reflection; /// /// Containing extensions for the object. /// public static class TypeExtensions { + /// /// Checks if a type is an array or not /// @@ -16,7 +17,8 @@ public static class TypeExtensions /// if the type is an array, otherwise . public static bool IsArray(this Type source) { - return source.BaseType == typeof(Array); + + return source.GetTypeInfo().BaseType == typeof(Array); } /// @@ -32,11 +34,10 @@ public static bool IsAssignableToGenericType(this Type givenType, Type genericTy { return false; } - return givenType == genericType || givenType.MapsToGenericTypeDefinition(genericType) || givenType.HasInterfaceThatMapsToGenericTypeDefinition(genericType) - || givenType.BaseType.IsAssignableToGenericType(genericType); + || givenType.GetTypeInfo().BaseType.IsAssignableToGenericType(genericType); } /// @@ -48,9 +49,9 @@ public static bool IsCollection(this Type source) { var collectionType = typeof(ICollection<>); - return source.IsGenericType && source + return source.GetTypeInfo().IsGenericType && source .GetInterfaces() - .Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == collectionType); + .Any(i => i.GetTypeInfo().IsGenericType && i.GetGenericTypeDefinition() == collectionType); } /// @@ -62,7 +63,7 @@ public static bool IsEnumerable(this Type source) { var enumerableType = typeof(IEnumerable<>); - return source.IsGenericType && source.GetGenericTypeDefinition() == enumerableType; + return source.GetTypeInfo().IsGenericType && source.GetGenericTypeDefinition() == enumerableType; } /// @@ -119,15 +120,53 @@ private static bool HasInterfaceThatMapsToGenericTypeDefinition(this Type givenT { return givenType .GetInterfaces() - .Where(it => it.IsGenericType) + .Where(it => it.GetTypeInfo().IsGenericType) .Any(it => it.GetGenericTypeDefinition() == genericType); } private static bool MapsToGenericTypeDefinition(this Type givenType, Type genericType) { - return genericType.IsGenericTypeDefinition - && givenType.IsGenericType + return genericType.GetTypeInfo().IsGenericTypeDefinition + && givenType.GetTypeInfo().IsGenericType && givenType.GetGenericTypeDefinition() == genericType; } + + public static TypeCode GetTypeCode(this Type type) + { + if (type == typeof(bool)) + return TypeCode.Boolean; + else if (type == typeof(char)) + return TypeCode.Char; + else if (type == typeof(sbyte)) + return TypeCode.SByte; + else if (type == typeof(byte)) + return TypeCode.Byte; + else if (type == typeof(short)) + return TypeCode.Int16; + else if (type == typeof(ushort)) + return TypeCode.UInt16; + else if (type == typeof(int)) + return TypeCode.Int32; + else if (type == typeof(uint)) + return TypeCode.UInt32; + else if (type == typeof(long)) + return TypeCode.Int64; + else if (type == typeof(ulong)) + return TypeCode.UInt64; + else if (type == typeof(float)) + return TypeCode.Single; + else if (type == typeof(double)) + return TypeCode.Double; + else if (type == typeof(decimal)) + return TypeCode.Decimal; + else if (type == typeof(DateTime)) + return TypeCode.DateTime; + else if (type == typeof(string)) + return TypeCode.String; + else if (type.GetTypeInfo().IsEnum) + return GetTypeCode(Enum.GetUnderlyingType(type)); + else + return TypeCode.Object; + } } } \ No newline at end of file diff --git a/src/Nancy/Helpers/ReflectionUtils.cs b/src/Nancy/Helpers/ReflectionUtils.cs index 3f7d4b8499..3906075b58 100644 --- a/src/Nancy/Helpers/ReflectionUtils.cs +++ b/src/Nancy/Helpers/ReflectionUtils.cs @@ -37,7 +37,8 @@ public static bool IsInstantiatableType(Type t) if (t == null) throw new ArgumentNullException("t"); - if (t.IsAbstract || t.IsInterface || t.IsArray) + + if (t.GetTypeInfo().IsAbstract || t.GetTypeInfo().IsInterface || t.IsArray) return false; if (!HasDefaultConstructor(t)) @@ -49,9 +50,13 @@ public static bool IsInstantiatableType(Type t) public static bool HasDefaultConstructor(Type t) { if (t == null) - throw new ArgumentNullException("t"); - + throw new ArgumentNullException("t"); +#if DOTNET5_4 + return (t.GetConstructor(Type.EmptyTypes) != null); +#else return (t.GetConstructor(BindingFlags.Instance, null, Type.EmptyTypes, null) != null); +#endif + } public static bool IsAssignable(Type to, Type from) @@ -62,7 +67,7 @@ public static bool IsAssignable(Type to, Type from) if (to.IsAssignableFrom(from)) return true; - if (to.IsGenericType && from.IsGenericTypeDefinition) + if (to.GetTypeInfo().IsGenericType && from.GetTypeInfo().IsGenericTypeDefinition) return to.IsAssignableFrom(from.MakeGenericType(to.GetGenericArguments())); return false; @@ -76,19 +81,19 @@ public static bool IsSubClass(Type type, Type check) if (type == check) return true; - if (check.IsInterface) + if (check.GetTypeInfo().IsInterface) { foreach (Type t in type.GetInterfaces()) { if (IsSubClass(t, check)) return true; } } - if (type.IsGenericType && !type.IsGenericTypeDefinition) + if (type.GetTypeInfo().IsGenericType && !type.GetTypeInfo().IsGenericTypeDefinition) { if (IsSubClass(type.GetGenericTypeDefinition(), check)) return true; } - return IsSubClass(type.BaseType, check); + return IsSubClass(type.GetTypeInfo().BaseType, check); } /// @@ -102,8 +107,8 @@ public static Type GetTypedListItemType(Type type) throw new ArgumentNullException("type"); if (type.IsArray) - return type.GetElementType (); - else if (type.IsGenericType && typeof(List<>).IsAssignableFrom(type.GetGenericTypeDefinition())) + return type.GetElementType(); + else if (type.GetTypeInfo().IsGenericType && typeof(List<>).IsAssignableFrom(type.GetGenericTypeDefinition())) return type.GetGenericArguments()[0]; else throw new Exception("Bad type"); @@ -117,7 +122,7 @@ public static Type GetTypedDictionaryValueType(Type type) Type genDictType = GetGenericDictionary(type); if (genDictType != null) - return genDictType.GetGenericArguments () [1]; + return genDictType.GetGenericArguments()[1]; else if (typeof(IDictionary).IsAssignableFrom(type)) return null; else @@ -127,14 +132,14 @@ public static Type GetTypedDictionaryValueType(Type type) static readonly Type GenericDictionaryType = typeof(IDictionary<,>); public static Type GetGenericDictionary(Type type) { - if (type.IsGenericType && GenericDictionaryType.IsAssignableFrom (type.GetGenericTypeDefinition())) + if (type.GetTypeInfo().IsGenericType && GenericDictionaryType.IsAssignableFrom(type.GetGenericTypeDefinition())) return type; Type[] ifaces = type.GetInterfaces(); if (ifaces != null) for (int i = 0; i < ifaces.Length; i++) { - Type current = GetGenericDictionary (ifaces[i]); + Type current = GetGenericDictionary(ifaces[i]); if (current != null) return current; } @@ -144,19 +149,25 @@ public static Type GetGenericDictionary(Type type) public static Type GetMemberUnderlyingType(MemberInfo member) { - switch (member.MemberType) - { - case MemberTypes.Field: - return ((FieldInfo)member).FieldType; - case MemberTypes.Property: - return ((PropertyInfo)member).PropertyType; - case MemberTypes.Event: - return ((EventInfo)member).EventHandlerType; - default: - throw new ArgumentException("MemberInfo must be if type FieldInfo, PropertyInfo or EventInfo", "member"); + if (member is FieldInfo) + { + return ((FieldInfo)member).FieldType; + } + else if (member is PropertyInfo) + { + return ((PropertyInfo)member).PropertyType; + } + else if (member is EventInfo) + { + return ((EventInfo)member).EventHandlerType; + } + else + { + throw new ArgumentException("MemberInfo must be if type FieldInfo, PropertyInfo or EventInfo", "member"); } - } - + } + + /// /// Determines whether the member is an indexed property. /// @@ -164,19 +175,19 @@ public static Type GetMemberUnderlyingType(MemberInfo member) /// /// true if the member is an indexed property; otherwise, false. /// - public static bool IsIndexedProperty(MemberInfo member) - { - if (member == null) - throw new ArgumentNullException("member"); - - PropertyInfo propertyInfo = member as PropertyInfo; - - if (propertyInfo != null) - return IsIndexedProperty(propertyInfo); - else - return false; - } - + public static bool IsIndexedProperty(MemberInfo member) + { + if (member == null) + throw new ArgumentNullException("member"); + + PropertyInfo propertyInfo = member as PropertyInfo; + + if (propertyInfo != null) + return IsIndexedProperty(propertyInfo); + else + return false; + } + /// /// Determines whether the property is an indexed property. /// @@ -184,59 +195,59 @@ public static bool IsIndexedProperty(MemberInfo member) /// /// true if the property is an indexed property; otherwise, false. /// - public static bool IsIndexedProperty(PropertyInfo property) - { - if (property == null) - throw new ArgumentNullException("property"); - - return (property.GetIndexParameters().Length > 0); - } - + public static bool IsIndexedProperty(PropertyInfo property) + { + if (property == null) + throw new ArgumentNullException("property"); + + return (property.GetIndexParameters().Length > 0); + } + /// /// Gets the member's value on the object. /// /// The member. /// The target object. /// The member's value on the object. - public static object GetMemberValue(MemberInfo member, object target) - { - switch (member.MemberType) - { - case MemberTypes.Field: - return ((FieldInfo)member).GetValue(target); - case MemberTypes.Property: - try - { - return ((PropertyInfo)member).GetValue(target, null); - } - catch (TargetParameterCountException e) - { - throw new ArgumentException("MemberInfo has index parameters", "member", e); - } - default: - throw new ArgumentException("MemberInfo is not of type FieldInfo or PropertyInfo", "member"); - } - } - + public static object GetMemberValue(MemberInfo member, object target) + { + if (member is FieldInfo) + { + return ((FieldInfo)member).GetValue(target); + } + else if (member is PropertyInfo) + { + try + { + return ((PropertyInfo)member).GetValue(target, null); + } + catch (TargetParameterCountException e) + { + throw new ArgumentException("MemberInfo has index parameters", "member", e); + } + } + throw new ArgumentException("MemberInfo is not of type FieldInfo or PropertyInfo", "member"); + } + /// /// Sets the member's value on the target object. /// /// The member. /// The target. /// The value. - public static void SetMemberValue(MemberInfo member, object target, object value) - { - switch (member.MemberType) - { - case MemberTypes.Field: - ((FieldInfo)member).SetValue(target, value); - break; - case MemberTypes.Property: - ((PropertyInfo)member).SetValue(target, value, null); - break; - default: - throw new ArgumentException("MemberInfo must be if type FieldInfo or PropertyInfo", "member"); - } + public static void SetMemberValue(MemberInfo member, object target, object value) + { + if (member is FieldInfo) + { + ((FieldInfo)member).SetValue(target, value); + return; + } + else if (member is PropertyInfo) + { + ((PropertyInfo)member).SetValue(target, value, null); + return; + } + throw new ArgumentException("MemberInfo must be of type FieldInfo or PropertyInfo", "member"); } /// @@ -248,17 +259,17 @@ public static void SetMemberValue(MemberInfo member, object target, object value /// public static bool CanReadMemberValue(MemberInfo member) { - switch (member.MemberType) + if(member is FieldInfo) { - case MemberTypes.Field: - return true; - case MemberTypes.Property: - return ((PropertyInfo) member).CanRead; - default: - return false; + return true; } - } - + else if (member is PropertyInfo) + { + return ((PropertyInfo)member).CanRead; + } + return false; + } + /// /// Determines whether the specified MemberInfo can be set. /// @@ -266,17 +277,17 @@ public static bool CanReadMemberValue(MemberInfo member) /// /// true if the specified MemberInfo can be set; otherwise, false. /// - public static bool CanSetMemberValue(MemberInfo member) - { - switch (member.MemberType) - { - case MemberTypes.Field: - return true; - case MemberTypes.Property: - return ((PropertyInfo)member).CanWrite; - default: - return false; - } + public static bool CanSetMemberValue(MemberInfo member) + { + if (member is FieldInfo) + { + return true; + } + else if (member is PropertyInfo) + { + return ((PropertyInfo)member).CanWrite; + } + return false; } public static IEnumerable GetFieldsAndProperties(Type type, BindingFlags bindingAttr) diff --git a/src/Nancy/ModelBinding/DefaultBinder.cs b/src/Nancy/ModelBinding/DefaultBinder.cs index c24772ace5..befc71b5c1 100644 --- a/src/Nancy/ModelBinding/DefaultBinder.cs +++ b/src/Nancy/ModelBinding/DefaultBinder.cs @@ -71,14 +71,14 @@ public object Bind(NancyContext context, Type modelType, object instance, Bindin if (modelType.IsArray() || modelType.IsCollection() || modelType.IsEnumerable()) { //make sure it has a generic type - if (modelType.IsGenericType()) + if (modelType.GetTypeInfo().IsGenericType) { genericType = modelType.GetGenericArguments().FirstOrDefault(); } else { var ienumerable = - modelType.GetInterfaces().Where(i => i.IsGenericType()).FirstOrDefault( + modelType.GetInterfaces().Where(i => i.GetTypeInfo().IsGenericType).FirstOrDefault( i => i.GetGenericTypeDefinition() == typeof(IEnumerable<>)); genericType = ienumerable == null ? null : ienumerable.GetGenericArguments().FirstOrDefault(); } @@ -240,7 +240,7 @@ private static void UpdateModelWithDeserializedModel(object bodyDeserializedMode { var bodyDeserializedModelType = bodyDeserializedModel.GetType(); - if (bodyDeserializedModelType.IsValueType) + if (bodyDeserializedModelType.GetTypeInfo().IsValueType) { bindingContext.Model = bodyDeserializedModel; return; @@ -255,7 +255,7 @@ private static void UpdateModelWithDeserializedModel(object bodyDeserializedMode { var model = (IList)bindingContext.Model; - if (o.GetType().IsValueType || o is string) + if (o.GetType().GetTypeInfo().IsValueType || o is string) { HandleValueTypeCollectionElement(model, count, o); } @@ -327,7 +327,7 @@ private static void CopyValue(BindingMemberInfo modelProperty, object source, ob private static bool IsDefaultValue(object existingValue, Type propertyType) { - return propertyType.IsValueType + return propertyType.GetTypeInfo().IsValueType ? Equals(existingValue, Activator.CreateInstance(propertyType)) : existingValue == null; } diff --git a/src/Nancy/NegotiatorExtensions.cs b/src/Nancy/NegotiatorExtensions.cs index 21bfe5946c..4e38f8da6c 100644 --- a/src/Nancy/NegotiatorExtensions.cs +++ b/src/Nancy/NegotiatorExtensions.cs @@ -6,7 +6,7 @@ using Nancy.Cookies; using Nancy.Responses.Negotiation; - + using System.Reflection; public static class NegotiatorExtensions { /// diff --git a/src/Nancy/RequestHeaders.cs b/src/Nancy/RequestHeaders.cs index 32cb0124d0..a4727d1433 100644 --- a/src/Nancy/RequestHeaders.cs +++ b/src/Nancy/RequestHeaders.cs @@ -8,7 +8,7 @@ namespace Nancy using System.Linq; using Nancy.Cookies; - + using System.Reflection; /// /// Provides strongly-typed access to HTTP request headers. /// diff --git a/src/Nancy/ResponseExtensions.cs b/src/Nancy/ResponseExtensions.cs index 9dd1c4184a..e61b98384b 100644 --- a/src/Nancy/ResponseExtensions.cs +++ b/src/Nancy/ResponseExtensions.cs @@ -6,7 +6,7 @@ namespace Nancy using Nancy.Cookies; using Nancy.Responses; - + using System.Reflection; /// /// Containing extensions for the object. /// @@ -182,7 +182,8 @@ public static Response WithStatusCode(this Response response, int statusCode) private static Tuple GetTuple(object header) { var properties = header.GetType() - .GetProperties() + .GetTypeInfo() + .DeclaredProperties .Where(prop => prop.CanRead && prop.PropertyType == typeof(string)) .ToArray(); diff --git a/src/Nancy/Routing/DefaultRouteDescriptionProvider.cs b/src/Nancy/Routing/DefaultRouteDescriptionProvider.cs index 9eff6b7111..0687de5a65 100644 --- a/src/Nancy/Routing/DefaultRouteDescriptionProvider.cs +++ b/src/Nancy/Routing/DefaultRouteDescriptionProvider.cs @@ -2,6 +2,7 @@ namespace Nancy.Routing { using System; using System.Linq; + using System.Reflection; using System.Resources; /// @@ -20,7 +21,7 @@ public class DefaultRouteDescriptionProvider : IRouteDescriptionProvider public string GetDescription(INancyModule module, string path) { var assembly = - module.GetType().Assembly; + module.GetType().GetTypeInfo().Assembly; if (assembly.IsDynamic) { diff --git a/src/Nancy/TinyIoc/TinyIoC.cs b/src/Nancy/TinyIoc/TinyIoC.cs index 6b357e4416..1cfdb1df68 100755 --- a/src/Nancy/TinyIoc/TinyIoC.cs +++ b/src/Nancy/TinyIoc/TinyIoC.cs @@ -18,20 +18,31 @@ // register the TinyMessenger messenger/event aggregator //#define TINYMESSENGER +// Uncomment this line if you want to internalize this library +//#define TINYIOC_INTERNAL + +// Uncomment this line if you want to target PCL. +//#define PORTABLE + // Preprocessor directives for enabling/disabling functionality // depending on platform features. If the platform has an appropriate // #DEFINE then these should be set automatically below. -#define EXPRESSIONS // Platform supports System.Linq.Expressions +#define EXPRESSIONS + +// Platform supports System.Linq.Expressions #define COMPILED_EXPRESSIONS // Platform supports compiling expressions #define APPDOMAIN_GETASSEMBLIES // Platform supports getting all assemblies from the AppDomain object #define UNBOUND_GENERICS_GETCONSTRUCTORS // Platform supports GetConstructors on unbound generic types #define GETPARAMETERS_OPEN_GENERICS // Platform supports GetParameters on open generics #define RESOLVE_OPEN_GENERICS // Platform supports resolving open generics #define READER_WRITER_LOCK_SLIM // Platform supports ReaderWriterLockSlim +#define SERIALIZABLE // Platform supports SerializableAttribute/SerializationInfo/StreamingContext -//// NETFX_CORE -//#if NETFX_CORE -//#endif +#if PORTABLE +#undef APPDOMAIN_GETASSEMBLIES +#undef COMPILED_EXPRESSIONS +#undef READER_WRITER_LOCK_SLIM +#endif // CompactFramework / Windows Phone 7 // By default does not support System.Linq.Expressions. @@ -64,14 +75,25 @@ #define USE_OBJECT_CONSTRUCTOR #endif + +#if DOTNET5_4 +#undef SERIALIZABLE +#undef APPDOMAIN_GETASSEMBLIES +#endif + #endregion +#if SERIALIZABLE +using System.Runtime.Serialization; +#endif + namespace Nancy.TinyIoc { using System; using System.Collections.Generic; - using System.IO; + using System.Collections.ObjectModel; using System.Linq; using System.Reflection; + #if EXPRESSIONS using System.Linq.Expressions; using System.Threading; @@ -87,7 +109,12 @@ namespace Nancy.TinyIoc #region SafeDictionary #if READER_WRITER_LOCK_SLIM - public class SafeDictionary : IDisposable +#if TINYIOC_INTERNAL + internal +#else + public +#endif + class SafeDictionary : IDisposable { private readonly ReaderWriterLockSlim _padlock = new ReaderWriterLockSlim(); private readonly Dictionary _Dictionary = new Dictionary(); @@ -201,7 +228,12 @@ where item is IDisposable #endregion } #else - public class SafeDictionary : IDisposable +#if TINYIOC_INTERNAL + internal +#else + public +#endif + class SafeDictionary : IDisposable { private readonly object _Padlock = new object(); private readonly Dictionary _Dictionary = new Dictionary(); @@ -257,7 +289,7 @@ public IEnumerable Keys return _Dictionary.Keys; } } - #region IDisposable Members + #region IDisposable Members public void Dispose() { @@ -276,13 +308,18 @@ where item is IDisposable GC.SuppressFinalize(this); } - #endregion + #endregion } #endif #endregion #region Extensions - public static class AssemblyExtensions +#if TINYIOC_INTERNAL + internal +#else + public +#endif + static class AssemblyExtensions { public static Type[] SafeGetTypes(this Assembly assembly) { @@ -290,9 +327,9 @@ public static Type[] SafeGetTypes(this Assembly assembly) try { - assemblies = assembly.GetTypes(); + assemblies = assembly.GetTypes(); } - catch (FileNotFoundException) + catch (System.IO.FileNotFoundException) { assemblies = ArrayCache.Empty(); } @@ -310,7 +347,12 @@ public static Type[] SafeGetTypes(this Assembly assembly) } } - public static class TypeExtensions +#if TINYIOC_INTERNAL + internal +#else + public +#endif + static class TypeExtensions { private static SafeDictionary _genericMethodCache; @@ -319,34 +361,34 @@ static TypeExtensions() _genericMethodCache = new SafeDictionary(); } -//#if NETFX_CORE -// /// -// /// Gets a generic method from a type given the method name, generic types and parameter types -// /// -// /// Source type -// /// Name of the method -// /// Generic types to use to make the method generic -// /// Method parameters -// /// MethodInfo or null if no matches found -// /// -// /// -// public static MethodInfo GetGenericMethod(this Type sourceType, string methodName, Type[] genericTypes, Type[] parameterTypes) -// { -// MethodInfo method; -// var cacheKey = new GenericMethodCacheKey(sourceType, methodName, genericTypes, parameterTypes); - -// // Shouldn't need any additional locking -// // we don't care if we do the method info generation -// // more than once before it gets cached. -// if (!_genericMethodCache.TryGetValue(cacheKey, out method)) -// { -// method = GetMethod(sourceType, methodName, genericTypes, parameterTypes); -// _genericMethodCache[cacheKey] = method; -// } - -// return method; -// } -//#else + //#if NETFX_CORE + // /// + // /// Gets a generic method from a type given the method name, generic types and parameter types + // /// + // /// Source type + // /// Name of the method + // /// Generic types to use to make the method generic + // /// Method parameters + // /// MethodInfo or null if no matches found + // /// + // /// + // public static MethodInfo GetGenericMethod(this Type sourceType, string methodName, Type[] genericTypes, Type[] parameterTypes) + // { + // MethodInfo method; + // var cacheKey = new GenericMethodCacheKey(sourceType, methodName, genericTypes, parameterTypes); + + // // Shouldn't need any additional locking + // // we don't care if we do the method info generation + // // more than once before it gets cached. + // if (!_genericMethodCache.TryGetValue(cacheKey, out method)) + // { + // method = GetMethod(sourceType, methodName, genericTypes, parameterTypes); + // _genericMethodCache[cacheKey] = method; + // } + + // return method; + // } + //#else /// /// Gets a generic method from a type given the method name, binding flags, generic types and parameter types /// @@ -374,7 +416,7 @@ public static MethodInfo GetGenericMethod(this Type sourceType, BindingFlags bin return method; } -//#endif + //#endif #if NETFX_CORE private static MethodInfo GetMethod(Type sourceType, BindingFlags flags, string methodName, Type[] genericTypes, Type[] parameterTypes) @@ -508,9 +550,9 @@ private int GenerateHashCode() } } - } + } - // @mbrit - 2012-05-22 - shim for ForEach call on List... + // @mbrit - 2012-05-22 - shim for ForEach call on List... #if NETFX_CORE internal static class ListExtender { @@ -525,7 +567,15 @@ internal static void ForEach(this List list, Action callback) #endregion #region TinyIoC Exception Types - public class TinyIoCResolutionException : Exception +#if SERIALIZABLE + [Serializable] +#endif +#if TINYIOC_INTERNAL + internal +#else + public +#endif + class TinyIoCResolutionException : Exception { private const string ERROR_TEXT = "Unable to resolve type: {0}"; @@ -538,9 +588,22 @@ public TinyIoCResolutionException(Type type, Exception innerException) : base(String.Format(ERROR_TEXT, type.FullName), innerException) { } +#if SERIALIZABLE + protected TinyIoCResolutionException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif } - - public class TinyIoCRegistrationTypeException : Exception +#if SERIALIZABLE + [Serializable] +#endif +#if TINYIOC_INTERNAL + internal +#else + public +#endif + class TinyIoCRegistrationTypeException : Exception { private const string REGISTER_ERROR_TEXT = "Cannot register type {0} - abstract classes or interfaces are not valid implementation types for {1}."; @@ -553,9 +616,22 @@ public TinyIoCRegistrationTypeException(Type type, string factory, Exception inn : base(String.Format(REGISTER_ERROR_TEXT, type.FullName, factory), innerException) { } +#if SERIALIZABLE + protected TinyIoCRegistrationTypeException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif } - - public class TinyIoCRegistrationException : Exception +#if SERIALIZABLE + [Serializable] +#endif +#if TINYIOC_INTERNAL + internal +#else + public +#endif + class TinyIoCRegistrationException : Exception { private const string CONVERT_ERROR_TEXT = "Cannot convert current registration of {0} to {1}"; private const string GENERIC_CONSTRAINT_ERROR_TEXT = "Type {1} is not valid for a registration of type {0}"; @@ -579,9 +655,22 @@ public TinyIoCRegistrationException(Type registerType, Type implementationType, : base(String.Format(GENERIC_CONSTRAINT_ERROR_TEXT, registerType.FullName, implementationType.FullName), innerException) { } +#if SERIALIZABLE + protected TinyIoCRegistrationException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif } - - public class TinyIoCWeakReferenceException : Exception +#if SERIALIZABLE + [Serializable] +#endif +#if TINYIOC_INTERNAL + internal +#else + public +#endif + class TinyIoCWeakReferenceException : Exception { private const string ERROR_TEXT = "Unable to instantiate {0} - referenced object has been reclaimed"; @@ -594,9 +683,22 @@ public TinyIoCWeakReferenceException(Type type, Exception innerException) : base(String.Format(ERROR_TEXT, type.FullName), innerException) { } +#if SERIALIZABLE + protected TinyIoCWeakReferenceException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif } - - public class TinyIoCConstructorResolutionException : Exception +#if SERIALIZABLE + [Serializable] +#endif +#if TINYIOC_INTERNAL + internal +#else + public +#endif + class TinyIoCConstructorResolutionException : Exception { private const string ERROR_TEXT = "Unable to resolve constructor for {0} using provided Expression."; @@ -619,9 +721,22 @@ public TinyIoCConstructorResolutionException(string message) : base(message) { } +#if SERIALIZABLE + protected TinyIoCConstructorResolutionException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif } - - public class TinyIoCAutoRegistrationException : Exception +#if SERIALIZABLE + [Serializable] +#endif +#if TINYIOC_INTERNAL + internal +#else + public +#endif + class TinyIoCAutoRegistrationException : Exception { private const string ERROR_TEXT = "Duplicate implementation of type {0} found ({1})."; @@ -634,6 +749,12 @@ public TinyIoCAutoRegistrationException(Type registerType, IEnumerable typ : base(String.Format(ERROR_TEXT, registerType, GetTypesString(types)), innerException) { } +#if SERIALIZABLE + protected TinyIoCAutoRegistrationException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif private static string GetTypesString(IEnumerable types) { @@ -649,7 +770,12 @@ private static string GetTypesString(IEnumerable types) /// /// Name/Value pairs for specifying "user" parameters when resolving /// - public sealed class NamedParameterOverloads : Dictionary +#if TINYIOC_INTERNAL + internal +#else + public +#endif + sealed class NamedParameterOverloads : Dictionary { public static NamedParameterOverloads FromIDictionary(IDictionary data) { @@ -676,7 +802,12 @@ public static NamedParameterOverloads Default } } - public enum UnregisteredResolutionActions +#if TINYIOC_INTERNAL + internal +#else + public +#endif + enum UnregisteredResolutionActions { /// /// Attempt to resolve type, even if the type isn't registered. @@ -699,13 +830,23 @@ public enum UnregisteredResolutionActions GenericsOnly } - public enum NamedResolutionFailureActions +#if TINYIOC_INTERNAL + internal +#else + public +#endif + enum NamedResolutionFailureActions { AttemptUnnamedResolution, Fail } - public enum DuplicateImplementationActions +#if TINYIOC_INTERNAL + internal +#else + public +#endif + enum DuplicateImplementationActions { RegisterSingle, RegisterMultiple, @@ -715,7 +856,12 @@ public enum DuplicateImplementationActions /// /// Resolution settings /// - public sealed class ResolveOptions +#if TINYIOC_INTERNAL + internal +#else + public +#endif + sealed class ResolveOptions { private static readonly ResolveOptions _Default = new ResolveOptions(); private static readonly ResolveOptions _FailUnregisteredAndNameNotFound = new ResolveOptions() { NamedResolutionFailureAction = NamedResolutionFailureActions.Fail, UnregisteredResolutionAction = UnregisteredResolutionActions.Fail }; @@ -782,7 +928,12 @@ public static ResolveOptions FailUnregisteredOnly } #endregion - public sealed partial class TinyIoCContainer : IDisposable +#if TINYIOC_INTERNAL + internal +#else + public +#endif + sealed partial class TinyIoCContainer : IDisposable { #region Fake NETFX_CORE Classes #if NETFX_CORE @@ -1059,7 +1210,7 @@ public void AutoRegister() #if APPDOMAIN_GETASSEMBLIES AutoRegisterInternal(AppDomain.CurrentDomain.GetAssemblies().Where(a => !IsIgnoredAssembly(a)), DuplicateImplementationActions.RegisterSingle, null); #else - AutoRegisterInternal(new Assembly[] {this.GetType().Assembly()}, true, null); + AutoRegisterInternal(new Assembly[] { this.GetType().Assembly() }, DuplicateImplementationActions.RegisterSingle, null); #endif } @@ -1076,7 +1227,7 @@ public void AutoRegister(Func registrationPredicate) #if APPDOMAIN_GETASSEMBLIES AutoRegisterInternal(AppDomain.CurrentDomain.GetAssemblies().Where(a => !IsIgnoredAssembly(a)), DuplicateImplementationActions.RegisterSingle, registrationPredicate); #else - AutoRegisterInternal(new Assembly[] { this.GetType().Assembly()}, true, registrationPredicate); + AutoRegisterInternal(new Assembly[] { this.GetType().Assembly() }, DuplicateImplementationActions.RegisterSingle, registrationPredicate); #endif } @@ -1090,7 +1241,7 @@ public void AutoRegister(DuplicateImplementationActions duplicateAction) #if APPDOMAIN_GETASSEMBLIES AutoRegisterInternal(AppDomain.CurrentDomain.GetAssemblies().Where(a => !IsIgnoredAssembly(a)), duplicateAction, null); #else - AutoRegisterInternal(new Assembly[] { this.GetType().Assembly() }, ignoreDuplicateImplementations, null); + AutoRegisterInternal(new Assembly[] { this.GetType().Assembly() }, duplicateAction, null); #endif } @@ -1106,11 +1257,11 @@ public void AutoRegister(DuplicateImplementationActions duplicateAction, Func !IsIgnoredAssembly(a)), duplicateAction, registrationPredicate); #else - AutoRegisterInternal(new Assembly[] { this.GetType().Assembly() }, ignoreDuplicateImplementations, registrationPredicate); + AutoRegisterInternal(new Assembly[] { this.GetType().Assembly() }, duplicateAction, registrationPredicate); #endif } - /// + /// /// Attempt to automatically register all non-generic classes and interfaces in the specified assemblies /// /// If more than one class implements an interface then only one implementation will be registered @@ -1442,20 +1593,20 @@ public MultiRegisterOptions RegisterMultiple(Type registrationType, IEnumerable< throw new ArgumentNullException("types", "types is null."); foreach (var type in implementationTypes) -//#if NETFX_CORE -// if (!registrationType.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())) -//#else + //#if NETFX_CORE + // if (!registrationType.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())) + //#else if (!registrationType.IsAssignableFrom(type)) -//#endif - throw new ArgumentException(String.Format("types: The type {0} is not assignable from {1}", registrationType.FullName, type.FullName)); + //#endif + throw new ArgumentException(String.Format("types: The type {0} is not assignable from {1}", registrationType.FullName, type.FullName)); if (implementationTypes.Count() != implementationTypes.Distinct().Count()) { var queryForDuplicatedTypes = from i in implementationTypes group i by i into j - where j.Count() > 1 - select j.Key.FullName; + where j.Count() > 1 + select j.Key.FullName; var fullNamesOfDuplicatedTypes = string.Join(",\n", queryForDuplicatedTypes.ToArray()); var multipleRegMessage = string.Format("types: The same implementation type cannot be specified multiple times for {0}\n\n{1}", registrationType.FullName, fullNamesOfDuplicatedTypes); @@ -1473,6 +1624,54 @@ where j.Count() > 1 } #endregion + #region Unregistration + + /// + /// Remove a container class registration. + /// + /// Type to unregister + /// true if the registration is successfully found and removed; otherwise, false. + public bool Unregister() + { + return Unregister(typeof(RegisterType), string.Empty); + } + + /// + /// Remove a named container class registration. + /// + /// Type to unregister + /// Name of registration + /// true if the registration is successfully found and removed; otherwise, false. + public bool Unregister(string name) + { + return Unregister(typeof(RegisterType), name); + } + + /// + /// Remove a container class registration. + /// + /// Type to unregister + /// true if the registration is successfully found and removed; otherwise, false. + public bool Unregister(Type registerType) + { + return Unregister(registerType, string.Empty); + } + + /// + /// Remove a named container class registration. + /// + /// Type to unregister + /// Name of registration + /// true if the registration is successfully found and removed; otherwise, false. + public bool Unregister(Type registerType, string name) + { + var typeRegistration = new TypeRegistration(registerType, name); + + return RemoveRegistration(typeRegistration); + } + + #endregion + #region Resolution /// /// Attempts to resolve a type using default options. @@ -1724,7 +1923,6 @@ public ResolveType Resolve(string name, NamedParameterOverloads par /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// /// Type to resolve - /// Name of registration /// Bool indicating whether the type can be resolved public bool CanResolve(Type resolveType) { @@ -1737,6 +1935,7 @@ public bool CanResolve(Type resolveType) /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// /// Type to resolve + /// Name of registration /// Bool indicating whether the type can be resolved private bool CanResolve(Type resolveType, string name) { @@ -1746,10 +1945,9 @@ private bool CanResolve(Type resolveType, string name) /// /// Attempts to predict whether a given type can be resolved with the specified options. /// - /// Note: Resolution may still fail if user defined factory registrations fail to construct objects when called. + /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// /// Type to resolve - /// Name of registration /// Resolution options /// Bool indicating whether the type can be resolved public bool CanResolve(Type resolveType, ResolveOptions options) @@ -1760,7 +1958,7 @@ public bool CanResolve(Type resolveType, ResolveOptions options) /// /// Attempts to predict whether a given named type can be resolved with the specified options. /// - /// Note: Resolution may still fail if user defined factory registrations fail to construct objects when called. + /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// /// Type to resolve /// Name of registration @@ -1845,7 +2043,6 @@ public bool CanResolve(Type resolveType, string name, NamedParameterOverloads pa /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// /// Type to resolve - /// Name of registration /// Bool indicating whether the type can be resolved public bool CanResolve() where ResolveType : class @@ -1872,7 +2069,6 @@ public bool CanResolve(string name) /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// /// Type to resolve - /// Name of registration /// Resolution options /// Bool indicating whether the type can be resolved public bool CanResolve(ResolveOptions options) @@ -1937,7 +2133,7 @@ public bool CanResolve(string name, NamedParameterOverloads paramet /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. /// - /// Note: Resolution may still fail if user defined factory registrations fail to construct objects when called. + /// Note: Resolution may still fail if user defined factory registations fail to construct objects when called. /// /// Type to resolve /// User supplied named parameter overloads @@ -1971,7 +2167,7 @@ public bool CanResolve(string name, NamedParameterOverloads paramet /// /// Attemps to resolve a type using the default options /// - /// Type to resolve + /// Type to resolve /// Resolved type or default if resolve fails /// True if resolved sucessfully, false otherwise public bool TryResolve(Type resolveType, out object resolvedType) @@ -1991,7 +2187,7 @@ public bool TryResolve(Type resolveType, out object resolvedType) /// /// Attemps to resolve a type using the given options /// - /// Type to resolve + /// Type to resolve /// Resolution options /// Resolved type or default if resolve fails /// True if resolved sucessfully, false otherwise @@ -2012,10 +2208,10 @@ public bool TryResolve(Type resolveType, ResolveOptions options, out object reso /// /// Attemps to resolve a type using the default options and given name /// - /// Type to resolve + /// Type to resolve /// Name of registration /// Resolved type or default if resolve fails - /// True if resolved successfully, false otherwise + /// True if resolved sucessfully, false otherwise public bool TryResolve(Type resolveType, string name, out object resolvedType) { try @@ -2033,7 +2229,7 @@ public bool TryResolve(Type resolveType, string name, out object resolvedType) /// /// Attemps to resolve a type using the given options and name /// - /// Type to resolve + /// Type to resolve /// Name of registration /// Resolution options /// Resolved type or default if resolve fails @@ -2055,7 +2251,7 @@ public bool TryResolve(Type resolveType, string name, ResolveOptions options, ou /// /// Attemps to resolve a type using the default options and supplied constructor parameters /// - /// Type to resolve + /// Type to resolve /// User specified constructor parameters /// Resolved type or default if resolve fails /// True if resolved sucessfully, false otherwise @@ -2076,11 +2272,11 @@ public bool TryResolve(Type resolveType, NamedParameterOverloads parameters, out /// /// Attemps to resolve a type using the default options and supplied name and constructor parameters /// - /// Type to resolve + /// Type to resolve /// Name of registration /// User specified constructor parameters /// Resolved type or default if resolve fails - /// True if resolved successfully, false otherwise + /// True if resolved sucessfully, false otherwise public bool TryResolve(Type resolveType, string name, NamedParameterOverloads parameters, out object resolvedType) { try @@ -2098,12 +2294,11 @@ public bool TryResolve(Type resolveType, string name, NamedParameterOverloads pa /// /// Attemps to resolve a type using the supplied options and constructor parameters /// - /// Type to resolve - /// Name of registration + /// Type to resolve /// User specified constructor parameters /// Resolution options /// Resolved type or default if resolve fails - /// True if resolved successfully, false otherwise + /// True if resolved sucessfully, false otherwise public bool TryResolve(Type resolveType, NamedParameterOverloads parameters, ResolveOptions options, out object resolvedType) { try @@ -2121,12 +2316,12 @@ public bool TryResolve(Type resolveType, NamedParameterOverloads parameters, Res /// /// Attemps to resolve a type using the supplied name, options and constructor parameters /// - /// Type to resolve + /// Type to resolve /// Name of registration /// User specified constructor parameters /// Resolution options /// Resolved type or default if resolve fails - /// True if resolved successfully, false otherwise + /// True if resolved sucessfully, false otherwise public bool TryResolve(Type resolveType, string name, NamedParameterOverloads parameters, ResolveOptions options, out object resolvedType) { try @@ -2146,7 +2341,7 @@ public bool TryResolve(Type resolveType, string name, NamedParameterOverloads pa /// /// Type to resolve /// Resolved type or default if resolve fails - /// True if resolved successfully, false otherwise + /// True if resolved sucessfully, false otherwise public bool TryResolve(out ResolveType resolvedType) where ResolveType : class { @@ -2168,7 +2363,7 @@ public bool TryResolve(out ResolveType resolvedType) /// Type to resolve /// Resolution options /// Resolved type or default if resolve fails - /// True if resolved successfully, false otherwise + /// True if resolved sucessfully, false otherwise public bool TryResolve(ResolveOptions options, out ResolveType resolvedType) where ResolveType : class { @@ -2190,7 +2385,7 @@ public bool TryResolve(ResolveOptions options, out ResolveType reso /// Type to resolve /// Name of registration /// Resolved type or default if resolve fails - /// True if resolved successfully, false otherwise + /// True if resolved sucessfully, false otherwise public bool TryResolve(string name, out ResolveType resolvedType) where ResolveType : class { @@ -2213,7 +2408,7 @@ public bool TryResolve(string name, out ResolveType resolvedType) /// Name of registration /// Resolution options /// Resolved type or default if resolve fails - /// True if resolved successfully, false otherwise + /// True if resolved sucessfully, false otherwise public bool TryResolve(string name, ResolveOptions options, out ResolveType resolvedType) where ResolveType : class { @@ -2235,7 +2430,7 @@ public bool TryResolve(string name, ResolveOptions options, out Res /// Type to resolve /// User specified constructor parameters /// Resolved type or default if resolve fails - /// True if resolved successfully, false otherwise + /// True if resolved sucessfully, false otherwise public bool TryResolve(NamedParameterOverloads parameters, out ResolveType resolvedType) where ResolveType : class { @@ -2258,7 +2453,7 @@ public bool TryResolve(NamedParameterOverloads parameters, out Reso /// Name of registration /// User specified constructor parameters /// Resolved type or default if resolve fails - /// True if resolved successfully, false otherwise + /// True if resolved sucessfully, false otherwise public bool TryResolve(string name, NamedParameterOverloads parameters, out ResolveType resolvedType) where ResolveType : class { @@ -2278,11 +2473,10 @@ public bool TryResolve(string name, NamedParameterOverloads paramet /// Attemps to resolve a type using the supplied options and constructor parameters /// /// Type to resolve - /// Name of registration /// User specified constructor parameters /// Resolution options /// Resolved type or default if resolve fails - /// True if resolved successfully, false otherwise + /// True if resolved sucessfully, false otherwise public bool TryResolve(NamedParameterOverloads parameters, ResolveOptions options, out ResolveType resolvedType) where ResolveType : class { @@ -2306,7 +2500,7 @@ public bool TryResolve(NamedParameterOverloads parameters, ResolveO /// User specified constructor parameters /// Resolution options /// Resolved type or default if resolve fails - /// True if resolved successfully, false otherwise + /// True if resolved sucessfully, false otherwise public bool TryResolve(string name, NamedParameterOverloads parameters, ResolveOptions options, out ResolveType resolvedType) where ResolveType : class { @@ -2325,7 +2519,7 @@ public bool TryResolve(string name, NamedParameterOverloads paramet /// /// Returns all registrations of a type /// - /// Type to resolveAll + /// Type to resolveAll /// Whether to include un-named (default) registrations /// IEnumerable public IEnumerable ResolveAll(Type resolveType, bool includeUnnamed) @@ -2336,7 +2530,7 @@ public IEnumerable ResolveAll(Type resolveType, bool includeUnnamed) /// /// Returns all registrations of a type, both named and unnamed /// - /// Type to resolveAll + /// Type to resolveAll /// IEnumerable public IEnumerable ResolveAll(Type resolveType) { @@ -2359,7 +2553,6 @@ public IEnumerable ResolveAll(bool includeUnnamed) /// Returns all registrations of a type, both named and unnamed /// /// Type to resolveAll - /// Whether to include un-named (default) registrations /// IEnumerable public IEnumerable ResolveAll() where ResolveType : class @@ -2415,7 +2608,7 @@ public interface ITinyIoCObjectLifetimeProvider private abstract class ObjectFactoryBase { /// - /// Whether to assume this factory successfully constructs its objects + /// Whether to assume this factory sucessfully constructs its objects /// /// Generally set to true for delegate style factories as CanResolve cannot delve /// into the delegates they contain. @@ -2501,13 +2694,13 @@ private class MultiInstanceFactory : ObjectFactoryBase public MultiInstanceFactory(Type registerType, Type registerImplementation) { -//#if NETFX_CORE -// if (registerImplementation.GetTypeInfo().IsAbstract() || registerImplementation.GetTypeInfo().IsInterface()) -// throw new TinyIoCRegistrationTypeException(registerImplementation, "MultiInstanceFactory"); -//#else + //#if NETFX_CORE + // if (registerImplementation.GetTypeInfo().IsAbstract() || registerImplementation.GetTypeInfo().IsInterface()) + // throw new TinyIoCRegistrationTypeException(registerImplementation, "MultiInstanceFactory"); + //#else if (registerImplementation.IsAbstract() || registerImplementation.IsInterface()) throw new TinyIoCRegistrationTypeException(registerImplementation, "MultiInstanceFactory"); -//#endif + //#endif if (!IsValidAssignment(registerType, registerImplementation)) throw new TinyIoCRegistrationTypeException(registerImplementation, "MultiInstanceFactory"); @@ -2574,7 +2767,7 @@ public override object GetObject(Type requestedType, TinyIoCContainer container, } } - public DelegateFactory( Type registerType, Func factory) + public DelegateFactory(Type registerType, Func factory) { if (factory == null) throw new ArgumentNullException("factory"); @@ -2831,11 +3024,11 @@ private class SingletonFactory : ObjectFactoryBase, IDisposable public SingletonFactory(Type registerType, Type registerImplementation) { -//#if NETFX_CORE -// if (registerImplementation.GetTypeInfo().IsAbstract() || registerImplementation.GetTypeInfo().IsInterface()) -//#else + //#if NETFX_CORE + // if (registerImplementation.GetTypeInfo().IsAbstract() || registerImplementation.GetTypeInfo().IsInterface()) + //#else if (registerImplementation.IsAbstract() || registerImplementation.IsInterface()) -//#endif + //#endif throw new TinyIoCRegistrationTypeException(registerImplementation, "SingletonFactory"); if (!IsValidAssignment(registerType, registerImplementation)) @@ -2894,7 +3087,7 @@ public override ObjectFactoryBase GetFactoryForChildContainer(Type type, TinyIoC public void Dispose() { - if (this._Current == null) + if (this._Current == null) return; var disposable = this._Current as IDisposable; @@ -2922,11 +3115,11 @@ public CustomObjectLifetimeFactory(Type registerType, Type registerImplementatio if (!IsValidAssignment(registerType, registerImplementation)) throw new TinyIoCRegistrationTypeException(registerImplementation, "SingletonFactory"); -//#if NETFX_CORE -// if (registerImplementation.GetTypeInfo().IsAbstract() || registerImplementation.GetTypeInfo().IsInterface()) -//#else + //#if NETFX_CORE + // if (registerImplementation.GetTypeInfo().IsAbstract() || registerImplementation.GetTypeInfo().IsInterface()) + //#else if (registerImplementation.IsAbstract() || registerImplementation.IsInterface()) -//#endif + //#endif throw new TinyIoCRegistrationTypeException(registerImplementation, errorMessage); this.registerType = registerType; @@ -3058,7 +3251,7 @@ public override int GetHashCode() } } private readonly SafeDictionary _RegisteredTypes; -#if USE_OBJECT_CONSTRUCTOR +#if USE_OBJECT_CONSTRUCTOR private delegate object ObjectConstructor(params object[] parameters); private static readonly SafeDictionary _ObjectConstructorCache = new SafeDictionary(); #endif @@ -3088,9 +3281,9 @@ private void AutoRegisterInternal(IEnumerable assemblies, DuplicateImp { var types = assemblies.SelectMany(a => a.SafeGetTypes()).Where(t => !IsIgnoredType(t, registrationPredicate)).ToList(); - var concreteTypes = from type in types - where type.IsClass() && (type.IsAbstract() == false) && (type != this.GetType() && (type.DeclaringType != this.GetType()) && (!type.IsGenericTypeDefinition())) - select type; + var concreteTypes = types + .Where(type => type.IsClass() && (type.IsAbstract() == false) && (type != this.GetType() && (type.DeclaringType != this.GetType()) && (!type.IsGenericTypeDefinition()))) + .ToList(); foreach (var type in concreteTypes) { @@ -3098,7 +3291,11 @@ where type.IsClass() && (type.IsAbstract() == false) && (type != this.GetType() { RegisterInternal(type, string.Empty, GetDefaultObjectFactory(type, type)); } +#if PORTABLE + catch (MemberAccessException) +#else catch (MethodAccessException) +#endif { // Ignore methods we can't access - added for Silverlight } @@ -3115,7 +3312,7 @@ where type.IsClass() && (type.IsAbstract() == false) && (type != this.GetType() where localType.IsAssignableFrom(implementationType) select implementationType; - if (implementations.Count() > 1) + if (implementations.Skip(1).Any()) { if (duplicateAction == DuplicateImplementationActions.Fail) throw new TinyIoCAutoRegistrationException(type, implementations); @@ -3124,7 +3321,7 @@ where localType.IsAssignableFrom(implementationType) { RegisterMultiple(type, implementations); } - } + } var firstImplementation = implementations.FirstOrDefault(); if (firstImplementation != null) @@ -3133,7 +3330,11 @@ where localType.IsAssignableFrom(implementationType) { RegisterInternal(type, string.Empty, GetDefaultObjectFactory(type, firstImplementation)); } +#if PORTABLE + catch (MemberAccessException) +#else catch (MethodAccessException) +#endif { // Ignore methods we can't access - added for Silverlight } @@ -3182,7 +3383,7 @@ private bool IsIgnoredType(Type type, Func registrationPredicate) if (registrationPredicate != null) { - ignoreChecks.Add(t => !registrationPredicate(t)); + ignoreChecks.Add(t => !registrationPredicate(t)); } foreach (var check in ignoreChecks) @@ -3228,18 +3429,18 @@ private RegisterOptions AddUpdateRegistration(TypeRegistration typeRegistration, return new RegisterOptions(this, typeRegistration); } - private void RemoveRegistration(TypeRegistration typeRegistration) + private bool RemoveRegistration(TypeRegistration typeRegistration) { - _RegisteredTypes.Remove(typeRegistration); + return _RegisteredTypes.Remove(typeRegistration); } private ObjectFactoryBase GetDefaultObjectFactory(Type registerType, Type registerImplementation) { -//#if NETFX_CORE -// if (registerType.GetTypeInfo().IsInterface() || registerType.GetTypeInfo().IsAbstract()) -//#else + //#if NETFX_CORE + // if (registerType.GetTypeInfo().IsInterface() || registerType.GetTypeInfo().IsAbstract()) + //#else if (registerType.IsInterface() || registerType.IsAbstract()) -//#endif + //#endif return new SingletonFactory(registerType, registerImplementation); return new MultiInstanceFactory(registerType, registerImplementation); @@ -3265,6 +3466,23 @@ private bool CanResolveInternal(TypeRegistration registration, NamedParameterOve return CanConstruct(factory.Constructor, parameters, options); } +#if RESOLVE_OPEN_GENERICS + if (checkType.IsInterface() && checkType.IsGenericType()) + { + // if the type is registered as an open generic, then see if the open generic is registered + if (_RegisteredTypes.TryGetValue(new TypeRegistration(checkType.GetGenericTypeDefinition(), name), out factory)) + { + if (factory.AssumeConstruction) + return true; + + if (factory.Constructor == null) + return (GetBestConstructor(factory.CreatesType, parameters, options) != null) ? true : false; + else + return CanConstruct(factory.Constructor, parameters, options); + } + } +#endif + // Fail if requesting named resolution and settings set to fail if unresolved // Or bubble up if we have a parent if (!string.IsNullOrEmpty(name) && options.NamedResolutionFailureAction == NamedResolutionFailureActions.Fail) @@ -3327,19 +3545,19 @@ private bool IsAutomaticLazyFactoryRequest(Type type) return true; // 2 parameter func with string as first parameter (name) -//#if NETFX_CORE -// if ((genericType == typeof(Func<,>) && type.GetTypeInfo().GenericTypeArguments[0] == typeof(string))) -//#else + //#if NETFX_CORE + // if ((genericType == typeof(Func<,>) && type.GetTypeInfo().GenericTypeArguments[0] == typeof(string))) + //#else if ((genericType == typeof(Func<,>) && type.GetGenericArguments()[0] == typeof(string))) -//#endif + //#endif return true; // 3 parameter func with string as first parameter (name) and IDictionary as second (parameters) -//#if NETFX_CORE -// if ((genericType == typeof(Func<,,>) && type.GetTypeInfo().GenericTypeArguments[0] == typeof(string) && type.GetTypeInfo().GenericTypeArguments[1] == typeof(IDictionary))) -//#else + //#if NETFX_CORE + // if ((genericType == typeof(Func<,,>) && type.GetTypeInfo().GenericTypeArguments[0] == typeof(string) && type.GetTypeInfo().GenericTypeArguments[1] == typeof(IDictionary))) + //#else if ((genericType == typeof(Func<,,>) && type.GetGenericArguments()[0] == typeof(string) && type.GetGenericArguments()[1] == typeof(IDictionary))) -//#endif + //#endif return true; return false; @@ -3473,22 +3691,22 @@ private object GetLazyAutomaticFactoryRequest(Type type) return null; Type genericType = type.GetGenericTypeDefinition(); -//#if NETFX_CORE -// Type[] genericArguments = type.GetTypeInfo().GenericTypeArguments.ToArray(); -//#else + //#if NETFX_CORE + // Type[] genericArguments = type.GetTypeInfo().GenericTypeArguments.ToArray(); + //#else Type[] genericArguments = type.GetGenericArguments(); -//#endif + //#endif // Just a func if (genericType == typeof(Func<>)) { Type returnType = genericArguments[0]; -//#if NETFX_CORE -// MethodInfo resolveMethod = typeof(TinyIoCContainer).GetTypeInfo().GetDeclaredMethods("Resolve").First(mi => !mi.GetParameters().Any()); -//#else + //#if NETFX_CORE + // MethodInfo resolveMethod = typeof(TinyIoCContainer).GetTypeInfo().GetDeclaredMethods("Resolve").First(mi => !mi.GetParameters().Any()); + //#else MethodInfo resolveMethod = typeof(TinyIoCContainer).GetMethod("Resolve", ArrayCache.Empty()); -//#endif + //#endif resolveMethod = resolveMethod.MakeGenericMethod(returnType); var resolveCall = Expression.Call(Expression.Constant(this), resolveMethod); @@ -3503,11 +3721,11 @@ private object GetLazyAutomaticFactoryRequest(Type type) { Type returnType = genericArguments[1]; -//#if NETFX_CORE -// MethodInfo resolveMethod = typeof(TinyIoCContainer).GetTypeInfo().GetDeclaredMethods("Resolve").First(mi => mi.GetParameters().Length == 1 && mi.GetParameters()[0].GetType() == typeof(String)); -//#else + //#if NETFX_CORE + // MethodInfo resolveMethod = typeof(TinyIoCContainer).GetTypeInfo().GetDeclaredMethods("Resolve").First(mi => mi.GetParameters().Length == 1 && mi.GetParameters()[0].GetType() == typeof(String)); + //#else MethodInfo resolveMethod = typeof(TinyIoCContainer).GetMethod("Resolve", new Type[] { typeof(String) }); -//#endif + //#endif resolveMethod = resolveMethod.MakeGenericMethod(returnType); ParameterExpression[] resolveParameters = new ParameterExpression[] { Expression.Parameter(typeof(String), "name") }; @@ -3519,22 +3737,22 @@ private object GetLazyAutomaticFactoryRequest(Type type) } // 3 parameter func with string as first parameter (name) and IDictionary as second (parameters) -//#if NETFX_CORE -// if ((genericType == typeof(Func<,,>) && type.GenericTypeArguments[0] == typeof(string) && type.GenericTypeArguments[1] == typeof(IDictionary))) -//#else + //#if NETFX_CORE + // if ((genericType == typeof(Func<,,>) && type.GenericTypeArguments[0] == typeof(string) && type.GenericTypeArguments[1] == typeof(IDictionary))) + //#else if ((genericType == typeof(Func<,,>) && type.GetGenericArguments()[0] == typeof(string) && type.GetGenericArguments()[1] == typeof(IDictionary))) -//#endif + //#endif { Type returnType = genericArguments[2]; var name = Expression.Parameter(typeof(string), "name"); var parameters = Expression.Parameter(typeof(IDictionary), "parameters"); -//#if NETFX_CORE -// MethodInfo resolveMethod = typeof(TinyIoCContainer).GetTypeInfo().GetDeclaredMethods("Resolve").First(mi => mi.GetParameters().Length == 2 && mi.GetParameters()[0].GetType() == typeof(String) && mi.GetParameters()[1].GetType() == typeof(NamedParameterOverloads)); -//#else + //#if NETFX_CORE + // MethodInfo resolveMethod = typeof(TinyIoCContainer).GetTypeInfo().GetDeclaredMethods("Resolve").First(mi => mi.GetParameters().Length == 2 && mi.GetParameters()[0].GetType() == typeof(String) && mi.GetParameters()[1].GetType() == typeof(NamedParameterOverloads)); + //#else MethodInfo resolveMethod = typeof(TinyIoCContainer).GetMethod("Resolve", new Type[] { typeof(String), typeof(NamedParameterOverloads) }); -//#endif + //#endif resolveMethod = resolveMethod.MakeGenericMethod(returnType); var resolveCall = Expression.Call(Expression.Constant(this), resolveMethod, name, Expression.Call(typeof(NamedParameterOverloads), "FromIDictionary", null, parameters)); @@ -3549,11 +3767,11 @@ private object GetLazyAutomaticFactoryRequest(Type type) #endif private object GetIEnumerableRequest(Type type) { -//#if NETFX_CORE -// var genericResolveAllMethod = this.GetType().GetGenericMethod("ResolveAll", type.GenericTypeArguments, new[] { typeof(bool) }); -//#else + //#if NETFX_CORE + // var genericResolveAllMethod = this.GetType().GetGenericMethod("ResolveAll", type.GenericTypeArguments, new[] { typeof(bool) }); + //#else var genericResolveAllMethod = this.GetType().GetGenericMethod(BindingFlags.Public | BindingFlags.Instance, "ResolveAll", type.GetGenericArguments(), new[] { typeof(bool) }); -//#endif + //#endif return genericResolveAllMethod.Invoke(this, new object[] { false }); } @@ -3570,11 +3788,11 @@ private bool CanConstruct(ConstructorInfo ctor, NamedParameterOverloads paramete var isParameterOverload = parameters.ContainsKey(parameter.Name); -//#if NETFX_CORE -// if (parameter.ParameterType.GetTypeInfo().IsPrimitive && !isParameterOverload) -//#else + //#if NETFX_CORE + // if (parameter.ParameterType.GetTypeInfo().IsPrimitive && !isParameterOverload) + //#else if (parameter.ParameterType.IsPrimitive() && !isParameterOverload) -//#endif + //#endif return false; if (!isParameterOverload && !CanResolveInternal(new TypeRegistration(parameter.ParameterType), NamedParameterOverloads.Default, options)) @@ -3589,11 +3807,11 @@ private ConstructorInfo GetBestConstructor(Type type, NamedParameterOverloads pa if (parameters == null) throw new ArgumentNullException("parameters"); -//#if NETFX_CORE -// if (type.GetTypeInfo().IsValueType) -//#else + //#if NETFX_CORE + // if (type.GetTypeInfo().IsValueType) + //#else if (type.IsValueType()) -//#endif + //#endif return null; // Get constructors in reverse order based on the number of parameters @@ -3611,11 +3829,11 @@ private ConstructorInfo GetBestConstructor(Type type, NamedParameterOverloads pa private IEnumerable GetTypeConstructors(Type type) { -//#if NETFX_CORE -// return type.GetTypeInfo().DeclaredConstructors.OrderByDescending(ctor => ctor.GetParameters().Count()); -//#else + //#if NETFX_CORE + // return type.GetTypeInfo().DeclaredConstructors.OrderByDescending(ctor => ctor.GetParameters().Count()); + //#else return type.GetConstructors().OrderByDescending(ctor => ctor.GetParameters().Count()); -//#endif + //#endif } private object ConstructType(Type requestedType, Type implementationType, ResolveOptions options) @@ -3642,7 +3860,7 @@ private object ConstructType(Type requestedType, Type implementationType, Constr { if (requestedType == null || !requestedType.IsGenericType() || !requestedType.GetGenericArguments().Any()) throw new TinyIoCResolutionException(typeToConstruct); - + typeToConstruct = typeToConstruct.MakeGenericType(requestedType.GetGenericArguments()); } #endif @@ -3667,11 +3885,11 @@ private object ConstructType(Type requestedType, Type implementationType, Constr try { - args[parameterIndex] = parameters.ContainsKey(currentParam.Name) ? - parameters[currentParam.Name] : + args[parameterIndex] = parameters.ContainsKey(currentParam.Name) ? + parameters[currentParam.Name] : ResolveInternal( - new TypeRegistration(currentParam.ParameterType), - NamedParameterOverloads.Default, + new TypeRegistration(currentParam.ParameterType), + NamedParameterOverloads.Default, options); } catch (TinyIoCResolutionException ex) @@ -3702,7 +3920,7 @@ private object ConstructType(Type requestedType, Type implementationType, Constr } } -#if USE_OBJECT_CONSTRUCTOR +#if USE_OBJECT_CONSTRUCTOR private static ObjectConstructor CreateObjectConstructionDelegateWithCache(ConstructorInfo constructor) { ObjectConstructor objectConstructor; @@ -3737,15 +3955,15 @@ private static ObjectConstructor CreateObjectConstructionDelegateWithCache(Const private void BuildUpInternal(object input, ResolveOptions resolveOptions) { -//#if NETFX_CORE -// var properties = from property in input.GetType().GetTypeInfo().DeclaredProperties -// where (property.GetMethod != null) && (property.SetMethod != null) && !property.PropertyType.GetTypeInfo().IsValueType -// select property; -//#else + //#if NETFX_CORE + // var properties = from property in input.GetType().GetTypeInfo().DeclaredProperties + // where (property.GetMethod != null) && (property.SetMethod != null) && !property.PropertyType.GetTypeInfo().IsValueType + // select property; + //#else var properties = from property in input.GetType().GetProperties() where (property.GetGetMethod() != null) && (property.GetSetMethod() != null) && !property.PropertyType.IsValueType() select property; -//#endif + //#endif foreach (var property in properties) { @@ -3775,7 +3993,7 @@ private IEnumerable GetParentRegistrationsForType(Type resolve private IEnumerable ResolveAllInternal(Type resolveType, bool includeUnnamed) { - var registrations = _RegisteredTypes.Keys.Where(tr => tr.Type == resolveType).Concat(GetParentRegistrationsForType(resolveType)); + var registrations = _RegisteredTypes.Keys.Where(tr => tr.Type == resolveType).Concat(GetParentRegistrationsForType(resolveType)).Distinct(); if (!includeUnnamed) registrations = registrations.Where(tr => tr.Name != string.Empty); @@ -3785,28 +4003,28 @@ private IEnumerable ResolveAllInternal(Type resolveType, bool includeUnn private static bool IsValidAssignment(Type registerType, Type registerImplementation) { -//#if NETFX_CORE -// var registerTypeDef = registerType.GetTypeInfo(); -// var registerImplementationDef = registerImplementation.GetTypeInfo(); - -// if (!registerTypeDef.IsGenericTypeDefinition) -// { -// if (!registerTypeDef.IsAssignableFrom(registerImplementationDef)) -// return false; -// } -// else -// { -// if (registerTypeDef.IsInterface()) -// { -// if (!registerImplementationDef.ImplementedInterfaces.Any(t => t.GetTypeInfo().Name == registerTypeDef.Name)) -// return false; -// } -// else if (registerTypeDef.IsAbstract() && registerImplementationDef.BaseType() != registerType) -// { -// return false; -// } -// } -//#else + //#if NETFX_CORE + // var registerTypeDef = registerType.GetTypeInfo(); + // var registerImplementationDef = registerImplementation.GetTypeInfo(); + + // if (!registerTypeDef.IsGenericTypeDefinition) + // { + // if (!registerTypeDef.IsAssignableFrom(registerImplementationDef)) + // return false; + // } + // else + // { + // if (registerTypeDef.IsInterface()) + // { + // if (!registerImplementationDef.ImplementedInterfaces.Any(t => t.GetTypeInfo().Name == registerTypeDef.Name)) + // return false; + // } + // else if (registerTypeDef.IsAbstract() && registerImplementationDef.BaseType() != registerType) + // { + // return false; + // } + // } + //#else if (!registerType.IsGenericTypeDefinition()) { if (!registerType.IsAssignableFrom(registerImplementation)) @@ -3816,15 +4034,20 @@ private static bool IsValidAssignment(Type registerType, Type registerImplementa { if (registerType.IsInterface()) { +#if (PORTABLE || DOTNET5_4) + if (!registerImplementation.GetInterfaces().Any(t => t.Name == registerType.Name)) + return false; +#else if (!registerImplementation.FindInterfaces((t, o) => t.Name == registerType.Name, null).Any()) return false; +#endif } else if (registerType.IsAbstract() && registerImplementation.BaseType() != registerType) { return false; } } -//#endif + //#endif return true; } @@ -3847,13 +4070,63 @@ public void Dispose() #endregion } -} +#if DOTNET5_4 + static class ReverseTypeExtender + { + public static bool IsClass(this Type type) + { + return type.GetTypeInfo().IsClass; + } -// reverse shim for WinRT SR changes... -#if !NETFX_CORE -namespace System.Reflection -{ - public static class ReverseTypeExtender + public static bool IsAbstract(this Type type) + { + return type.GetTypeInfo().IsAbstract; + } + + public static bool IsInterface(this Type type) + { + return type.GetTypeInfo().IsInterface; + } + + public static bool IsPrimitive(this Type type) + { + return type.GetTypeInfo().IsPrimitive; + } + + public static bool IsValueType(this Type type) + { + return type.GetTypeInfo().IsValueType; + } + + public static bool IsGenericType(this Type type) + { + return type.GetTypeInfo().IsGenericType; + } + + public static bool IsGenericParameter(this Type type) + { + return type.IsGenericParameter; + } + + public static bool IsGenericTypeDefinition(this Type type) + { + return type.GetTypeInfo().IsGenericTypeDefinition; + } + + public static Type BaseType(this Type type) + { + return type.GetTypeInfo().BaseType; + } + + public static Assembly Assembly(this Type type) + { + return type.GetTypeInfo().Assembly; + } + } +#endif + // reverse shim for WinRT SR changes... +#if (!NETFX_CORE && !DOTNET5_4) + static class ReverseTypeExtender { public static bool IsClass(this Type type) { @@ -3905,5 +4178,5 @@ public static Assembly Assembly(this Type type) return type.Assembly; } } +#endif } -#endif \ No newline at end of file diff --git a/src/Nancy/TypeResolveStrategies.cs b/src/Nancy/TypeResolveStrategies.cs index 373cd93c45..be9c46f350 100644 --- a/src/Nancy/TypeResolveStrategies.cs +++ b/src/Nancy/TypeResolveStrategies.cs @@ -1,7 +1,9 @@ namespace Nancy { using System; + using System.Reflection; + using Nancy.Extensions; /// /// Default implementations. /// @@ -36,7 +38,7 @@ public class TypeResolveStrategies /// public static readonly TypeResolveStrategy OnlyNancy = type => { - return type.Assembly.Equals(typeof(INancyEngine).Assembly); + return type.Assembly().Equals(typeof(INancyEngine).GetTypeInfo().Assembly); }; /// diff --git a/src/Nancy/ViewEngines/Extensions.cs b/src/Nancy/ViewEngines/Extensions.cs index 6c8d884480..26f3b60427 100644 --- a/src/Nancy/ViewEngines/Extensions.cs +++ b/src/Nancy/ViewEngines/Extensions.cs @@ -1,6 +1,7 @@ namespace Nancy.ViewEngines { using System; + using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; @@ -26,11 +27,11 @@ public static bool IsAnonymousType(this Type type) return false; } - return type.IsGenericType - && (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic + return type.GetTypeInfo().IsGenericType + && (type.GetTypeInfo().Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic && (type.Name.StartsWith("<>", StringComparison.OrdinalIgnoreCase) || type.Name.StartsWith("VB$", StringComparison.OrdinalIgnoreCase)) && (type.Name.Contains("AnonymousType") || type.Name.Contains("AnonType")) - && Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false); + && type.GetTypeInfo().GetCustomAttributes(typeof(CompilerGeneratedAttribute)).Any(); } } } \ No newline at end of file diff --git a/src/Nancy/project.json b/src/Nancy/project.json index 749e449607..ce47bdebd2 100644 --- a/src/Nancy/project.json +++ b/src/Nancy/project.json @@ -14,7 +14,6 @@ "dependencies": { "Microsoft.Extensions.PlatformAbstractions": "1.0.0-rc1-final" }, - "resource": [ "Diagnostics/Resources/**/*.*", "Diagnostics/Views/**/*.*" From 4e38bc2225ef4e3fc8a1384905cca06c35aff897 Mon Sep 17 00:00:00 2001 From: James Humphries Date: Thu, 18 Feb 2016 09:08:47 +0000 Subject: [PATCH 20/52] organised usings after comments from @thecodejunkie --- src/Nancy/Bootstrapper/ContainerRegistration.cs | 3 +-- src/Nancy/Bootstrapper/FavIconApplicationStartup.cs | 1 + src/Nancy/Bootstrapper/NancyBootstrapperLocator.cs | 2 +- src/Nancy/Bootstrapper/Registrations.cs | 1 - src/Nancy/DefaultSerializerFactory.cs | 3 +-- src/Nancy/DefaultTypeCatalog.cs | 1 - src/Nancy/Diagnostics/DiagnosticsHook.cs | 1 + src/Nancy/Diagnostics/Modules/InteractiveModule.cs | 5 +++-- src/Nancy/Extensions/TypeExtensions.cs | 3 ++- src/Nancy/NegotiatorExtensions.cs | 8 ++++---- src/Nancy/RequestHeaders.cs | 5 +++-- src/Nancy/ResponseExtensions.cs | 10 +++++----- src/Nancy/TypeResolveStrategies.cs | 2 +- 13 files changed, 23 insertions(+), 22 deletions(-) diff --git a/src/Nancy/Bootstrapper/ContainerRegistration.cs b/src/Nancy/Bootstrapper/ContainerRegistration.cs index 1ce894c746..6c18180828 100644 --- a/src/Nancy/Bootstrapper/ContainerRegistration.cs +++ b/src/Nancy/Bootstrapper/ContainerRegistration.cs @@ -3,7 +3,6 @@ namespace Nancy.Bootstrapper using System; using System.Linq; using System.Reflection; - using Nancy.Extensions; /// @@ -49,4 +48,4 @@ protected void ValidateTypeCompatibility(params Type[] types) } } } -} \ No newline at end of file +} diff --git a/src/Nancy/Bootstrapper/FavIconApplicationStartup.cs b/src/Nancy/Bootstrapper/FavIconApplicationStartup.cs index e7f14c2342..0792f59d86 100644 --- a/src/Nancy/Bootstrapper/FavIconApplicationStartup.cs +++ b/src/Nancy/Bootstrapper/FavIconApplicationStartup.cs @@ -6,6 +6,7 @@ using System.Linq; using Nancy.Configuration; using System.Reflection; + /// /// Application startup task that attempts to locate a favicon. The startup will first scan all /// folders in the path defined by the provided and if it cannot diff --git a/src/Nancy/Bootstrapper/NancyBootstrapperLocator.cs b/src/Nancy/Bootstrapper/NancyBootstrapperLocator.cs index 952698a97e..78298507a6 100755 --- a/src/Nancy/Bootstrapper/NancyBootstrapperLocator.cs +++ b/src/Nancy/Bootstrapper/NancyBootstrapperLocator.cs @@ -5,7 +5,7 @@ using System.Linq; using System.Reflection; using Nancy.Extensions; - using System.Reflection; + /// /// Class for locating an INancyBootstrapper implementation. /// diff --git a/src/Nancy/Bootstrapper/Registrations.cs b/src/Nancy/Bootstrapper/Registrations.cs index baf41ed444..219c5d43a3 100644 --- a/src/Nancy/Bootstrapper/Registrations.cs +++ b/src/Nancy/Bootstrapper/Registrations.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; - using Nancy.Extensions; /// diff --git a/src/Nancy/DefaultSerializerFactory.cs b/src/Nancy/DefaultSerializerFactory.cs index e03d179ef5..87c1715109 100644 --- a/src/Nancy/DefaultSerializerFactory.cs +++ b/src/Nancy/DefaultSerializerFactory.cs @@ -4,7 +4,6 @@ namespace Nancy using System.Collections.Generic; using System.Linq; using System.Reflection; - using Nancy.Extensions; using Nancy.Responses.Negotiation; @@ -85,4 +84,4 @@ private static bool SafeCanSerialize(ISerializer serializer, MediaRange mediaRan } } } -} \ No newline at end of file +} diff --git a/src/Nancy/DefaultTypeCatalog.cs b/src/Nancy/DefaultTypeCatalog.cs index ab75860246..b7a94b73ba 100644 --- a/src/Nancy/DefaultTypeCatalog.cs +++ b/src/Nancy/DefaultTypeCatalog.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; - using Nancy.Extensions; /// diff --git a/src/Nancy/Diagnostics/DiagnosticsHook.cs b/src/Nancy/Diagnostics/DiagnosticsHook.cs index c0ecbc10c5..a55c305325 100644 --- a/src/Nancy/Diagnostics/DiagnosticsHook.cs +++ b/src/Nancy/Diagnostics/DiagnosticsHook.cs @@ -19,6 +19,7 @@ namespace Nancy.Diagnostics using Nancy.Routing; using Nancy.Routing.Constraints; using Nancy.Routing.Trie; + /// /// Pipeline hook to handle diagnostics dashboard requests. /// diff --git a/src/Nancy/Diagnostics/Modules/InteractiveModule.cs b/src/Nancy/Diagnostics/Modules/InteractiveModule.cs index 35a44a2687..7fe807fa26 100644 --- a/src/Nancy/Diagnostics/Modules/InteractiveModule.cs +++ b/src/Nancy/Diagnostics/Modules/InteractiveModule.cs @@ -4,8 +4,9 @@ using System.Collections.Generic; using System.ComponentModel; using System.Linq; - using Nancy.Helpers; using System.Reflection; + using Nancy.Helpers; + public class InteractiveModule : DiagnosticModule { private readonly IInteractiveDiagnostics interactiveDiagnostics; @@ -149,4 +150,4 @@ private static object ConvertArgument(string value, Type destinationType) } } } -} \ No newline at end of file +} diff --git a/src/Nancy/Extensions/TypeExtensions.cs b/src/Nancy/Extensions/TypeExtensions.cs index 52d2a4b41a..e8c298d92f 100644 --- a/src/Nancy/Extensions/TypeExtensions.cs +++ b/src/Nancy/Extensions/TypeExtensions.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; + /// /// Containing extensions for the object. /// @@ -169,4 +170,4 @@ public static TypeCode GetTypeCode(this Type type) return TypeCode.Object; } } -} \ No newline at end of file +} diff --git a/src/Nancy/NegotiatorExtensions.cs b/src/Nancy/NegotiatorExtensions.cs index 4e38f8da6c..c973da9268 100644 --- a/src/Nancy/NegotiatorExtensions.cs +++ b/src/Nancy/NegotiatorExtensions.cs @@ -3,10 +3,10 @@ using System; using System.Collections.Generic; using System.Linq; - + using System.Reflection; using Nancy.Cookies; using Nancy.Responses.Negotiation; - using System.Reflection; + public static class NegotiatorExtensions { /// @@ -78,7 +78,7 @@ public static Negotiator WithHeaders(this Negotiator negotiator, params object[] /// /// Negotiator object /// - /// Array of headers - each header should be a Tuple with two string elements + /// Array of headers - each header should be a Tuple with two string elements /// for header name and header value /// /// Modified negotiator @@ -270,4 +270,4 @@ private static Tuple GetTuple(object header) (string)valueProperty.GetValue(header, null)); } } -} \ No newline at end of file +} diff --git a/src/Nancy/RequestHeaders.cs b/src/Nancy/RequestHeaders.cs index a4727d1433..409fbfa0a0 100644 --- a/src/Nancy/RequestHeaders.cs +++ b/src/Nancy/RequestHeaders.cs @@ -6,9 +6,10 @@ namespace Nancy using System.Collections.Generic; using System.Globalization; using System.Linq; - - using Nancy.Cookies; using System.Reflection; + using Nancy.Cookies; + + /// /// Provides strongly-typed access to HTTP request headers. /// diff --git a/src/Nancy/ResponseExtensions.cs b/src/Nancy/ResponseExtensions.cs index e61b98384b..1fa8bb6346 100644 --- a/src/Nancy/ResponseExtensions.cs +++ b/src/Nancy/ResponseExtensions.cs @@ -3,10 +3,10 @@ namespace Nancy using System; using System.Collections.Generic; using System.Linq; - + using System.Reflection; using Nancy.Cookies; using Nancy.Responses; - using System.Reflection; + /// /// Containing extensions for the object. /// @@ -110,7 +110,7 @@ public static Response WithHeader(this Response response, string header, string /// /// Response object /// - /// Array of headers - each header should be an anonymous type with two string properties + /// Array of headers - each header should be an anonymous type with two string properties /// 'Header' and 'Value' to represent the header name and its value. /// /// Modified response @@ -124,7 +124,7 @@ public static Response WithHeaders(this Response response, params object[] heade /// /// Response object /// - /// Array of headers - each header should be a Tuple with two string elements + /// Array of headers - each header should be a Tuple with two string elements /// for header name and header value /// /// Modified response @@ -205,4 +205,4 @@ private static Tuple GetTuple(object header) (string)valueProperty.GetValue(header, null)); } } -} \ No newline at end of file +} diff --git a/src/Nancy/TypeResolveStrategies.cs b/src/Nancy/TypeResolveStrategies.cs index be9c46f350..e5056c2b19 100644 --- a/src/Nancy/TypeResolveStrategies.cs +++ b/src/Nancy/TypeResolveStrategies.cs @@ -2,8 +2,8 @@ namespace Nancy { using System; using System.Reflection; - using Nancy.Extensions; + /// /// Default implementations. /// From 28297b2bf15fe10c4b7d769d16f9a29b4600b818 Mon Sep 17 00:00:00 2001 From: James Humphries Date: Thu, 18 Feb 2016 09:31:25 +0000 Subject: [PATCH 21/52] clean up of code after @thecodejunkie's comments --- src/Nancy/Bootstrapper/Registrations.cs | 4 +- src/Nancy/DefaultSerializerFactory.cs | 2 +- .../Diagnostics/InteractiveDiagnostics.cs | 4 - src/Nancy/Extensions/TypeExtensions.cs | 9 +++ src/Nancy/Helpers/ReflectionUtils.cs | 79 +++++++++++++++---- src/Nancy/ResponseExtensions.cs | 16 ++-- src/Nancy/TypeResolveStrategies.cs | 2 +- src/Nancy/project.json | 8 +- 8 files changed, 88 insertions(+), 36 deletions(-) diff --git a/src/Nancy/Bootstrapper/Registrations.cs b/src/Nancy/Bootstrapper/Registrations.cs index 219c5d43a3..0f30e8d7d1 100644 --- a/src/Nancy/Bootstrapper/Registrations.cs +++ b/src/Nancy/Bootstrapper/Registrations.cs @@ -174,7 +174,7 @@ public void RegisterWithDefault(IEnumerable defaultImplemen { var implementations = this.typeCatalog .GetTypesAssignableTo() - .Where(type => type.Assembly() != this.GetType().GetTypeInfo().Assembly) + .Where(type => type.GetAssembly() != this.GetType().GetTypeInfo().Assembly) .Where(type => !defaultImplementations.Contains(type)) .ToList(); @@ -201,7 +201,7 @@ public void RegisterWithUserThenDefault(IEnumerable default { var implementations = this.typeCatalog .GetTypesAssignableTo() - .Where(type => type.Assembly() != this.GetType().GetTypeInfo().Assembly) + .Where(type => type.GetAssembly() != this.GetType().GetTypeInfo().Assembly) .Where(type => !defaultImplementations.Contains(type)) .ToList(); diff --git a/src/Nancy/DefaultSerializerFactory.cs b/src/Nancy/DefaultSerializerFactory.cs index 87c1715109..041a6bdb2c 100644 --- a/src/Nancy/DefaultSerializerFactory.cs +++ b/src/Nancy/DefaultSerializerFactory.cs @@ -55,7 +55,7 @@ private ISerializer GetDefaultSerializerForMediaRange(MediaRange mediaRange) try { return this.serializers - .Where(x => x.GetType().GetTypeInfo().Assembly.Equals(typeof(INancyEngine).Assembly())) + .Where(x => x.GetType().GetTypeInfo().Assembly.Equals(typeof(INancyEngine).GetAssembly())) .SingleOrDefault(x => x.CanSerialize(mediaRange)); } catch diff --git a/src/Nancy/Diagnostics/InteractiveDiagnostics.cs b/src/Nancy/Diagnostics/InteractiveDiagnostics.cs index 2a06863441..d97351352d 100644 --- a/src/Nancy/Diagnostics/InteractiveDiagnostics.cs +++ b/src/Nancy/Diagnostics/InteractiveDiagnostics.cs @@ -175,11 +175,7 @@ private static string GetDescriptionFromProperty(IDiagnosticsProvider diagnostic private static string GetDescriptionFromAttribute(IDiagnosticsProvider diagnosticsProvider, MethodInfo methodInfo) { -#if DOTNET5_4 var attribute = (DescriptionAttribute)methodInfo.GetCustomAttribute(typeof(DescriptionAttribute)); -#else - var attribute = (DescriptionAttribute)Attribute.GetCustomAttribute(methodInfo, typeof(DescriptionAttribute)); -#endif return attribute != null ? attribute.Description : null; } diff --git a/src/Nancy/Extensions/TypeExtensions.cs b/src/Nancy/Extensions/TypeExtensions.cs index e8c298d92f..2f53ad830b 100644 --- a/src/Nancy/Extensions/TypeExtensions.cs +++ b/src/Nancy/Extensions/TypeExtensions.cs @@ -10,6 +10,15 @@ /// public static class TypeExtensions { + /// + /// returns the assembly that the type belongs to + /// + /// + /// The assembly that contains the type + public static Assembly GetAssembly(this Type source) + { + return source.GetTypeInfo().Assembly; + } /// /// Checks if a type is an array or not diff --git a/src/Nancy/Helpers/ReflectionUtils.cs b/src/Nancy/Helpers/ReflectionUtils.cs index 3906075b58..fb2562d025 100644 --- a/src/Nancy/Helpers/ReflectionUtils.cs +++ b/src/Nancy/Helpers/ReflectionUtils.cs @@ -49,8 +49,10 @@ public static bool IsInstantiatableType(Type t) public static bool HasDefaultConstructor(Type t) { - if (t == null) + if (t == null) + { throw new ArgumentNullException("t"); + } #if DOTNET5_4 return (t.GetConstructor(Type.EmptyTypes) != null); #else @@ -62,24 +64,34 @@ public static bool HasDefaultConstructor(Type t) public static bool IsAssignable(Type to, Type from) { if (to == null) + { throw new ArgumentNullException("to"); + } if (to.IsAssignableFrom(from)) + { return true; + } if (to.GetTypeInfo().IsGenericType && from.GetTypeInfo().IsGenericTypeDefinition) + { return to.IsAssignableFrom(from.MakeGenericType(to.GetGenericArguments())); + } return false; } public static bool IsSubClass(Type type, Type check) { - if (type == null || check == null) - return false; + if (type == null || check == null) + { + return false; + } - if (type == check) - return true; + if (type == check) + { + return true; + } if (check.GetTypeInfo().IsInterface) { @@ -94,7 +106,9 @@ public static bool IsSubClass(Type type, Type check) return true; } return IsSubClass(type.GetTypeInfo().BaseType, check); - } + } + + static readonly Type GenericListType = typeof(List<>); /// /// Gets the type of the typed list's items. @@ -108,41 +122,60 @@ public static Type GetTypedListItemType(Type type) if (type.IsArray) return type.GetElementType(); - else if (type.GetTypeInfo().IsGenericType && typeof(List<>).IsAssignableFrom(type.GetGenericTypeDefinition())) + else if (type.GetTypeInfo().IsGenericType + && GenericListType.IsAssignableFrom(type.GetGenericTypeDefinition())) + { return type.GetGenericArguments()[0]; + } else + { throw new Exception("Bad type"); + } } public static Type GetTypedDictionaryValueType(Type type) { - if (type == null) + if (type == null) + { throw new ArgumentNullException("type"); + } - Type genDictType = GetGenericDictionary(type); + var genDictType = GetGenericDictionary(type); if (genDictType != null) + { return genDictType.GetGenericArguments()[1]; - else if (typeof(IDictionary).IsAssignableFrom(type)) - return null; - else - throw new Exception("Bad type"); + } + else if (typeof(IDictionary).IsAssignableFrom(type)) + { + return null; + } + else + { + throw new Exception("Bad type"); + } } static readonly Type GenericDictionaryType = typeof(IDictionary<,>); + public static Type GetGenericDictionary(Type type) { - if (type.GetTypeInfo().IsGenericType && GenericDictionaryType.IsAssignableFrom(type.GetGenericTypeDefinition())) + if (type.GetTypeInfo().IsGenericType + && GenericDictionaryType.IsAssignableFrom(type.GetGenericTypeDefinition())) + { return type; + } - Type[] ifaces = type.GetInterfaces(); + var ifaces = type.GetInterfaces(); if (ifaces != null) + { for (int i = 0; i < ifaces.Length; i++) { Type current = GetGenericDictionary(ifaces[i]); if (current != null) return current; } + } return null; } @@ -178,14 +211,20 @@ public static Type GetMemberUnderlyingType(MemberInfo member) public static bool IsIndexedProperty(MemberInfo member) { if (member == null) + { throw new ArgumentNullException("member"); + } - PropertyInfo propertyInfo = member as PropertyInfo; + var propertyInfo = member as PropertyInfo; if (propertyInfo != null) + { return IsIndexedProperty(propertyInfo); + } else + { return false; + } } /// @@ -198,7 +237,9 @@ public static bool IsIndexedProperty(MemberInfo member) public static bool IsIndexedProperty(PropertyInfo property) { if (property == null) + { throw new ArgumentNullException("property"); + } return (property.GetIndexParameters().Length > 0); } @@ -259,7 +300,7 @@ public static void SetMemberValue(MemberInfo member, object target, object value /// public static bool CanReadMemberValue(MemberInfo member) { - if(member is FieldInfo) + if (member is FieldInfo) { return true; } @@ -295,10 +336,14 @@ public static IEnumerable GetFieldsAndProperties(Type type, BindingF MemberInfo[] members = type.GetFields(bindingAttr); for (int i = 0; i < members.Length; i++) + { yield return members[i]; + } members = type.GetProperties(bindingAttr); for (int i = 0; i < members.Length; i++) + { yield return members[i]; + } } } } diff --git a/src/Nancy/ResponseExtensions.cs b/src/Nancy/ResponseExtensions.cs index 1fa8bb6346..ec0ed4eca6 100644 --- a/src/Nancy/ResponseExtensions.cs +++ b/src/Nancy/ResponseExtensions.cs @@ -182,18 +182,18 @@ public static Response WithStatusCode(this Response response, int statusCode) private static Tuple GetTuple(object header) { var properties = header.GetType() - .GetTypeInfo() - .DeclaredProperties - .Where(prop => prop.CanRead && prop.PropertyType == typeof(string)) - .ToArray(); + .GetTypeInfo() + .DeclaredProperties + .Where(prop => prop.CanRead && prop.PropertyType == typeof(string)) + .ToArray(); var headerProperty = properties - .Where(p => string.Equals(p.Name, "Header", StringComparison.OrdinalIgnoreCase)) - .FirstOrDefault(); + .Where(p => string.Equals(p.Name, "Header", StringComparison.OrdinalIgnoreCase)) + .FirstOrDefault(); var valueProperty = properties - .Where(p => string.Equals(p.Name, "Value", StringComparison.OrdinalIgnoreCase)) - .FirstOrDefault(); + .Where(p => string.Equals(p.Name, "Value", StringComparison.OrdinalIgnoreCase)) + .FirstOrDefault(); if (headerProperty == null || valueProperty == null) { diff --git a/src/Nancy/TypeResolveStrategies.cs b/src/Nancy/TypeResolveStrategies.cs index e5056c2b19..75cb002bd2 100644 --- a/src/Nancy/TypeResolveStrategies.cs +++ b/src/Nancy/TypeResolveStrategies.cs @@ -38,7 +38,7 @@ public class TypeResolveStrategies /// public static readonly TypeResolveStrategy OnlyNancy = type => { - return type.Assembly().Equals(typeof(INancyEngine).GetTypeInfo().Assembly); + return type.GetAssembly().Equals(typeof(INancyEngine).GetTypeInfo().Assembly); }; /// diff --git a/src/Nancy/project.json b/src/Nancy/project.json index ce47bdebd2..a4443ce07e 100644 --- a/src/Nancy/project.json +++ b/src/Nancy/project.json @@ -12,12 +12,14 @@ }, "dependencies": { - "Microsoft.Extensions.PlatformAbstractions": "1.0.0-rc1-final" + "Microsoft.Extensions.PlatformAbstractions": "1.0.0-rc1-final" }, + "resource": [ - "Diagnostics/Resources/**/*.*", - "Diagnostics/Views/**/*.*" + "Diagnostics/Resources/**/*.*", + "Diagnostics/Views/**/*.*" ], + "frameworks": { "dotnet5.4": { "dependencies": { From ab9965ed347d35038e974fe4253d85629f53c434 Mon Sep 17 00:00:00 2001 From: James Humphries Date: Thu, 18 Feb 2016 09:42:52 +0000 Subject: [PATCH 22/52] moved auto-registration to non-static method, switched it to use assemblycatalog --- src/Nancy/DefaultNancyBootstrapper.cs | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/src/Nancy/DefaultNancyBootstrapper.cs b/src/Nancy/DefaultNancyBootstrapper.cs index a07b27ea91..53e742cb03 100755 --- a/src/Nancy/DefaultNancyBootstrapper.cs +++ b/src/Nancy/DefaultNancyBootstrapper.cs @@ -8,7 +8,7 @@ namespace Nancy using Nancy.Configuration; using Nancy.Diagnostics; using Nancy.TinyIoc; - + using Extensions; /// /// TinyIoC bootstrapper - registers default route resolver and registers itself as /// INancyModuleCatalog for resolving modules but behavior can be overridden if required. @@ -277,18 +277,11 @@ protected override sealed INancyModule GetModule(TinyIoCContainer container, Typ /// Executes auto registration with the given container. /// /// Container instance - private static void AutoRegister(TinyIoCContainer container, IEnumerable> ignoredAssemblies) + private void AutoRegister(TinyIoCContainer container, IEnumerable> ignoredAssemblies) { var assembly = typeof(NancyEngine).GetTypeInfo().Assembly; -#if !DNX - container.AutoRegister(AppDomain.CurrentDomain.GetAssemblies().Where(a => !ignoredAssemblies.Any(ia => ia(a))), DuplicateImplementationActions.RegisterMultiple, t => t.Assembly != assembly); -#else - var libraryManager = - Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.LibraryManager; - var thisAssemblyName = typeof(DefaultNancyBootstrapper).GetTypeInfo().Assembly.GetName().Name; - var referencing = libraryManager.GetReferencingLibraries(thisAssemblyName); -#endif + container.AutoRegister(this.AssemblyCatalog.GetAssemblies().Where(a => !ignoredAssemblies.Any(ia => ia(a))), DuplicateImplementationActions.RegisterMultiple, t => t.GetAssembly() != assembly); } } } From 25009d8b8510cce759088250216cc89912a7f5a4 Mon Sep 17 00:00:00 2001 From: James Humphries Date: Thu, 18 Feb 2016 10:41:43 +0000 Subject: [PATCH 23/52] ifdefed out old async stream overrides, replaced close -> dispose in dotnet54, removed unused StreamExtensions.cs --- src/Nancy.MSBuild/Nancy.csproj | 3 - src/Nancy/Extensions/StreamExtensions.cs | 73 ------------------------ src/Nancy/HeadResponse.cs | 2 + src/Nancy/IO/RequestStream.cs | 17 +++++- src/Nancy/IO/UnclosableStreamWrapper.cs | 7 ++- 5 files changed, 22 insertions(+), 80 deletions(-) delete mode 100644 src/Nancy/Extensions/StreamExtensions.cs diff --git a/src/Nancy.MSBuild/Nancy.csproj b/src/Nancy.MSBuild/Nancy.csproj index e76f9231e4..94b089d9be 100644 --- a/src/Nancy.MSBuild/Nancy.csproj +++ b/src/Nancy.MSBuild/Nancy.csproj @@ -323,9 +323,6 @@ Extensions\RequestStreamExtensions.cs - - Extensions\StreamExtensions.cs - Extensions\TypeExtensions.cs diff --git a/src/Nancy/Extensions/StreamExtensions.cs b/src/Nancy/Extensions/StreamExtensions.cs deleted file mode 100644 index 1a75f489e2..0000000000 --- a/src/Nancy/Extensions/StreamExtensions.cs +++ /dev/null @@ -1,73 +0,0 @@ -namespace Nancy.Extensions -{ - using System; - using System.IO; - - /// - /// Containing extensions for the object. - /// - public static class StreamExtensions - { - /// - /// Buffer size for copy operations - /// - internal const int BufferSize = 4096; - - /// - /// Copies the contents between two instances in an async fashion. - /// - /// The source stream to copy from. - /// The destination stream to copy to. - /// Delegate that should be invoked when the operation has completed. Will pass the source, destination and exception (if one was thrown) to the function. Can pass in . - public static void CopyTo(this Stream source, Stream destination, Action onComplete) - { - var buffer = - new byte[BufferSize]; - - Action done = e => - { - if (onComplete != null) - { - onComplete.Invoke(source, destination, e); - } - }; - - AsyncCallback rc = null; - - rc = readResult => - { - try - { - var read = - source.EndRead(readResult); - - if (read <= 0) - { - done.Invoke(null); - return; - } - - destination.BeginWrite(buffer, 0, read, writeResult => - { - try - { - destination.EndWrite(writeResult); - source.BeginRead(buffer, 0, buffer.Length, rc, null); - } - catch (Exception ex) - { - done.Invoke(ex); - } - - }, null); - } - catch (Exception ex) - { - done.Invoke(ex); - } - }; - - source.BeginRead(buffer, 0, buffer.Length, rc, null); - } - } -} \ No newline at end of file diff --git a/src/Nancy/HeadResponse.cs b/src/Nancy/HeadResponse.cs index 701a9238ad..7595a78e34 100644 --- a/src/Nancy/HeadResponse.cs +++ b/src/Nancy/HeadResponse.cs @@ -62,6 +62,7 @@ public override void Flush() { } +#if !DOTNET5_4 public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { throw new NotSupportedException(); @@ -71,6 +72,7 @@ public override int EndRead(IAsyncResult asyncResult) { throw new NotSupportedException(); } +#endif public override long Seek(long offset, SeekOrigin origin) { diff --git a/src/Nancy/IO/RequestStream.cs b/src/Nancy/IO/RequestStream.cs index 428bb837bf..c23052c69f 100644 --- a/src/Nancy/IO/RequestStream.cs +++ b/src/Nancy/IO/RequestStream.cs @@ -11,6 +11,8 @@ /// public class RequestStream : Stream { + internal const int BufferSize = 4096; + public static long DEFAULT_SWITCHOVER_THRESHOLD = 81920; private bool disableStreamSwitching; @@ -94,7 +96,7 @@ public RequestStream(Stream stream, long expectedLength, long thresholdLength, b private Task MoveToWritableStream() { var sourceStream = this.stream; - this.stream = new MemoryStream(StreamExtensions.BufferSize); + this.stream = new MemoryStream(BufferSize); return sourceStream.CopyToAsync(this); } @@ -173,6 +175,7 @@ public override long Position } } +#if !DOTNET5_4 /// /// Begins an asynchronous read operation. /// @@ -200,6 +203,7 @@ public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, As { return this.stream.BeginWrite(buffer, offset, count, callback, state); } +#endif protected override void Dispose(bool disposing) { @@ -219,7 +223,7 @@ protected override void Dispose(bool disposing) base.Dispose(disposing); } - +#if !DOTNET5_4 /// /// Waits for the pending asynchronous read to complete. /// @@ -242,6 +246,7 @@ public override void EndWrite(IAsyncResult asyncResult) this.ShiftStreamToFileStreamIfNecessary(); } +#endif /// /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device. @@ -346,7 +351,11 @@ private void ShiftStreamToFileStreamIfNecessary() // in NancyWcfGenericService - webRequest.UriTemplateMatch var old = this.stream; this.MoveStreamContentsToFileStream(); +#if DOTNET5_4 + old.Dispose(); +#else old.Close(); +#endif } } @@ -435,7 +444,11 @@ private void MoveStreamContentsToFileStream() if (this.stream.CanSeek && this.stream.Length == 0) { +#if DOTNET5_4 + this.stream.Dispose(); +#else this.stream.Close(); +#endif this.stream = targetStream; return; } diff --git a/src/Nancy/IO/UnclosableStreamWrapper.cs b/src/Nancy/IO/UnclosableStreamWrapper.cs index 84fbe4a7bc..e860ce1052 100644 --- a/src/Nancy/IO/UnclosableStreamWrapper.cs +++ b/src/Nancy/IO/UnclosableStreamWrapper.cs @@ -175,7 +175,7 @@ public override int WriteTimeout this.baseStream.WriteTimeout = value; } } - +#if !DOTNET5_4 /// /// Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. /// @@ -183,6 +183,7 @@ public override int WriteTimeout public override void Close() { } +#endif /// /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. @@ -243,6 +244,7 @@ public override void Write(byte[] buffer, int offset, int count) this.baseStream.Write(buffer, offset, count); } +#if !DOTNET5_4 /// /// Begins an asynchronous read operation. /// @@ -267,6 +269,7 @@ public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, As return this.baseStream.BeginWrite(buffer, offset, count, callback, state); } + /// /// Waits for the pending asynchronous read to complete. /// @@ -287,7 +290,7 @@ public override void EndWrite(IAsyncResult asyncResult) { this.baseStream.EndWrite(asyncResult); } - +#endif /// /// 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. /// From 003f5bbf56c4d50d20dd468764b7eb8643e6f489 Mon Sep 17 00:00:00 2001 From: Jonathan Channon Date: Thu, 18 Feb 2016 11:01:56 +0000 Subject: [PATCH 24/52] replaced binaryformatter with simplejson --- .../DemoBootstrapper.cs | 2 +- src/Nancy.MSBuild/Nancy.csproj | 6 + src/Nancy/DefaultObjectSerializer.cs | 73 +- src/Nancy/Diagnostics/DefaultDiagnostics.cs | 10 +- src/Nancy/Diagnostics/DiagnosticsHook.cs | 4 +- src/Nancy/Extensions/ObjectExtensions.cs | 29 + src/Nancy/Json/SimpleJson.cs | 2127 +++++++++++++++++ src/Nancy/Session/CookieBasedSessions.cs | 10 +- src/Nancy/project.json | 4 +- test/Nancy.Testing.Tests/BrowserFixture.cs | 3 +- .../CustomInteractiveDiagnosticsFixture.cs | 19 +- .../Diagnostics/DiagnosticsHookFixture.cs | 11 +- test/Nancy.Tests/Unit/Security/CsrfFixture.cs | 7 +- .../Sessions/CookieBasedSessionsFixture.cs | 20 +- .../DefaultSessionObjectFormatterFixture.cs | 19 +- 15 files changed, 2298 insertions(+), 46 deletions(-) create mode 100644 src/Nancy/Extensions/ObjectExtensions.cs create mode 100644 src/Nancy/Json/SimpleJson.cs diff --git a/samples/Nancy.Demo.Hosting.Aspnet/DemoBootstrapper.cs b/samples/Nancy.Demo.Hosting.Aspnet/DemoBootstrapper.cs index 45f2f63dd5..20177e0525 100644 --- a/samples/Nancy.Demo.Hosting.Aspnet/DemoBootstrapper.cs +++ b/samples/Nancy.Demo.Hosting.Aspnet/DemoBootstrapper.cs @@ -67,7 +67,7 @@ protected override void ApplicationStartup(TinyIoCContainer container, IPipeline this.Conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("moo", "Content")); - CookieBasedSessions.Enable(pipelines); + CookieBasedSessions.Enable(pipelines, this.AssemblyCatalog); pipelines.AfterRequest += (ctx) => { diff --git a/src/Nancy.MSBuild/Nancy.csproj b/src/Nancy.MSBuild/Nancy.csproj index 94b089d9be..5b12efe086 100644 --- a/src/Nancy.MSBuild/Nancy.csproj +++ b/src/Nancy.MSBuild/Nancy.csproj @@ -1355,6 +1355,12 @@ Cryptography\AesEncryptionProvider.cs + + Json\SimpleJson.cs + + + Extensions\ObjectExtensions.cs + Configuration\ConfigurationException.cs diff --git a/src/Nancy/DefaultObjectSerializer.cs b/src/Nancy/DefaultObjectSerializer.cs index 6320879389..9dc7a28bba 100644 --- a/src/Nancy/DefaultObjectSerializer.cs +++ b/src/Nancy/DefaultObjectSerializer.cs @@ -3,11 +3,28 @@ namespace Nancy using Extensions; using System; using System.IO; + using System.Linq; + using System.Reflection; using System.Runtime.Serialization; - using System.Runtime.Serialization.Formatters.Binary; + using System.Text; + using Nancy.Extensions; + /// + /// Serializes/Deserializes objects for sessions + /// public class DefaultObjectSerializer : IObjectSerializer { + private readonly IAssemblyCatalog assemblyCatalog; + + /// + /// Initializes a new instance of the class. + /// + /// + public DefaultObjectSerializer(IAssemblyCatalog assemblyCatalog) + { + this.assemblyCatalog = assemblyCatalog; + } + /// /// Serialize an object /// @@ -17,18 +34,35 @@ public string Serialize(object sourceObject) { if (sourceObject == null) { - return String.Empty; + return string.Empty; } - var formatter = new BinaryFormatter(); + dynamic serializedObject = (sourceObject is string) + ? sourceObject + : this.AddTypeInformation(sourceObject); + + var json = SimpleJson.SerializeObject(serializedObject); + return Convert.ToBase64String(Encoding.UTF8.GetBytes(json)); + } - using (var outputStream = new MemoryStream()) + private dynamic AddTypeInformation(object sourceObject) + { + var sourceType = this.assemblyCatalog.GetAssemblies().Select(assembly => assembly.GetType(sourceObject.GetType().FullName)).FirstOrDefault(type => type != null); + if (sourceType == null) { - formatter.Serialize(outputStream, sourceObject); + throw new SerializationException("Unable to find type " + sourceObject.GetType() + " in its assembly to serialize"); + } - var buffer = outputStream.GetBufferSegment(); - return Convert.ToBase64String(buffer.Array, buffer.Offset, buffer.Count); + dynamic serializedObject = null; + + var assemblyQualifiedName = sourceType.GetTypeInfo().AssemblyQualifiedName; + if (!string.IsNullOrWhiteSpace(assemblyQualifiedName)) + { + serializedObject = sourceObject.ToDynamic(); + serializedObject.TypeObject = assemblyQualifiedName; } + + return serializedObject; } /// @@ -46,13 +80,15 @@ public object Deserialize(string sourceString) try { var inputBytes = Convert.FromBase64String(sourceString); + var json = Encoding.UTF8.GetString(inputBytes); - var formatter = new BinaryFormatter(); - - using (var inputStream = new MemoryStream(inputBytes, false)) + if (ContainsTypeDescription(json)) { - return formatter.Deserialize(inputStream); + dynamic serializedObject = SimpleJson.DeserializeObject(json); + var actual = SimpleJson.DeserializeObject(json, Type.GetType(serializedObject.TypeObject)); + return actual; } + return SimpleJson.DeserializeObject(json); } catch (FormatException) { @@ -62,10 +98,15 @@ public object Deserialize(string sourceString) { return null; } - catch (IOException) - { - return null; - } + catch (IOException) + { + return null; + } + } + + private static bool ContainsTypeDescription(string json) + { + return json.Contains("TypeObject"); } } -} +} \ No newline at end of file diff --git a/src/Nancy/Diagnostics/DefaultDiagnostics.cs b/src/Nancy/Diagnostics/DefaultDiagnostics.cs index 61ef520c37..551fcaaad9 100644 --- a/src/Nancy/Diagnostics/DefaultDiagnostics.cs +++ b/src/Nancy/Diagnostics/DefaultDiagnostics.cs @@ -30,6 +30,8 @@ public class DefaultDiagnostics : IDiagnostics private readonly INancyEnvironment environment; private readonly ITypeCatalog typeCatalog; + private readonly IAssemblyCatalog assemblyCatalog; + /// /// Creates a new instance of the class. /// @@ -46,6 +48,7 @@ public class DefaultDiagnostics : IDiagnostics /// /// /// + /// public DefaultDiagnostics( IEnumerable diagnosticProviders, IRootPathProvider rootPathProvider, @@ -59,7 +62,8 @@ public DefaultDiagnostics( IEnumerable routeMetadataProviders, ITextResource textResource, INancyEnvironment environment, - ITypeCatalog typeCatalog) + ITypeCatalog typeCatalog, + IAssemblyCatalog assemblyCatalog) { this.diagnosticProviders = diagnosticProviders; this.rootPathProvider = rootPathProvider; @@ -74,6 +78,7 @@ public DefaultDiagnostics( this.textResource = textResource; this.environment = environment; this.typeCatalog = typeCatalog; + this.assemblyCatalog = assemblyCatalog; } /// @@ -96,7 +101,8 @@ public void Initialize(IPipelines pipelines) this.routeMetadataProviders, this.textResource, this.environment, - this.typeCatalog); + this.typeCatalog, + this.assemblyCatalog); } } } \ No newline at end of file diff --git a/src/Nancy/Diagnostics/DiagnosticsHook.cs b/src/Nancy/Diagnostics/DiagnosticsHook.cs index a55c305325..d8524b796b 100644 --- a/src/Nancy/Diagnostics/DiagnosticsHook.cs +++ b/src/Nancy/Diagnostics/DiagnosticsHook.cs @@ -33,7 +33,7 @@ public static class DiagnosticsHook /// Enables the diagnostics dashboard and will intercept all requests that are passed to /// the condigured paths. /// - public static void Enable(IPipelines pipelines, IEnumerable providers, IRootPathProvider rootPathProvider, IRequestTracing requestTracing, NancyInternalConfiguration configuration, IModelBinderLocator modelBinderLocator, IEnumerable responseProcessors, IEnumerable routeSegmentConstraints, ICultureService cultureService, IRequestTraceFactory requestTraceFactory, IEnumerable routeMetadataProviders, ITextResource textResource, INancyEnvironment environment, ITypeCatalog typeCatalog) + public static void Enable(IPipelines pipelines, IEnumerable providers, IRootPathProvider rootPathProvider, IRequestTracing requestTracing, NancyInternalConfiguration configuration, IModelBinderLocator modelBinderLocator, IEnumerable responseProcessors, IEnumerable routeSegmentConstraints, ICultureService cultureService, IRequestTraceFactory requestTraceFactory, IEnumerable routeMetadataProviders, ITextResource textResource, INancyEnvironment environment, ITypeCatalog typeCatalog, IAssemblyCatalog assemblyCatalog) { var diagnosticsConfiguration = environment.GetValue(); @@ -58,7 +58,7 @@ public static void Enable(IPipelines pipelines, IEnumerable>( diff --git a/src/Nancy/Extensions/ObjectExtensions.cs b/src/Nancy/Extensions/ObjectExtensions.cs new file mode 100644 index 0000000000..767d9576ca --- /dev/null +++ b/src/Nancy/Extensions/ObjectExtensions.cs @@ -0,0 +1,29 @@ +namespace Nancy.Extensions +{ + using System.Collections.Generic; + using System.Dynamic; + using System.Reflection; + + /// + /// Contains extensions to class. + /// + public static class ObjectExtensions + { + /// + /// Convert an object to a dynamic type + /// + /// An object to convert to dynamic + /// Returns a dynamic version of the specified type + public static dynamic ToDynamic(this object value) + { + var expando = new ExpandoObject() as IDictionary; + + foreach (var property in value.GetType().GetTypeInfo().DeclaredProperties) + { + expando.Add(property.Name, property.GetValue(value)); + } + + return (ExpandoObject)expando; + } + } +} \ No newline at end of file diff --git a/src/Nancy/Json/SimpleJson.cs b/src/Nancy/Json/SimpleJson.cs new file mode 100644 index 0000000000..a6014190a3 --- /dev/null +++ b/src/Nancy/Json/SimpleJson.cs @@ -0,0 +1,2127 @@ +//----------------------------------------------------------------------- +// +// Copyright (c) 2011, The Outercurve Foundation. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.opensource.org/licenses/mit-license.php +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Nathan Totten (ntotten.com), Jim Zimmerman (jimzimmerman.com) and Prabir Shrestha (prabir.me) +// https://github.com/facebook-csharp-sdk/simple-json +//----------------------------------------------------------------------- + +// VERSION: 0.38.0 + +// NOTE: uncomment the following line to make SimpleJson class internal. +#define SIMPLE_JSON_INTERNAL + +// NOTE: uncomment the following line to make JsonArray and JsonObject class internal. +#define SIMPLE_JSON_OBJARRAYINTERNAL + +// NOTE: uncomment the following line to enable dynamic support. +#define SIMPLE_JSON_DYNAMIC + +// NOTE: uncomment the following line to enable DataContract support. +//#define SIMPLE_JSON_DATACONTRACT + +// NOTE: uncomment the following line to enable IReadOnlyCollection and IReadOnlyList support. +//#define SIMPLE_JSON_READONLY_COLLECTIONS + +// NOTE: uncomment the following line to disable linq expressions/compiled lambda (better performance) instead of method.invoke(). +// define if you are using .net framework <= 3.0 or < WP7.5 +//#define SIMPLE_JSON_NO_LINQ_EXPRESSION + +// NOTE: uncomment the following line if you are compiling under Window Metro style application/library. +// usually already defined in properties +//#define NETFX_CORE; + +// If you are targetting WinStore, WP8 and NET4.5+ PCL make sure to #define SIMPLE_JSON_TYPEINFO; + +// 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 + +#if NETFX_CORE +#define SIMPLE_JSON_TYPEINFO +#endif + +using System; +using System.CodeDom.Compiler; +using System.Collections; +using System.Collections.Generic; +#if !SIMPLE_JSON_NO_LINQ_EXPRESSION +using System.Linq.Expressions; +#endif +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +#if SIMPLE_JSON_DYNAMIC +using System.Dynamic; +#endif +using System.Globalization; +using System.Reflection; +using System.Runtime.Serialization; +using System.Text; +using Nancy.Reflection; + +// ReSharper disable LoopCanBeConvertedToQuery +// ReSharper disable RedundantExplicitArrayCreation +// ReSharper disable SuggestUseVarKeywordEvident +namespace Nancy +{ + /// + /// Represents the json array. + /// + [GeneratedCode("simple-json", "1.0.0")] + [EditorBrowsable(EditorBrowsableState.Never)] + [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] +#if SIMPLE_JSON_OBJARRAYINTERNAL + internal +#else + public +#endif + class JsonArray : List + { + /// + /// Initializes a new instance of the class. + /// + public JsonArray() { } + + /// + /// Initializes a new instance of the class. + /// + /// The capacity of the json array. + public JsonArray(int capacity) : base(capacity) { } + + /// + /// The json representation of the array. + /// + /// The json representation of the array. + public override string ToString() + { + return SimpleJson.SerializeObject(this) ?? string.Empty; + } + } + + /// + /// Represents the json object. + /// + [GeneratedCode("simple-json", "1.0.0")] + [EditorBrowsable(EditorBrowsableState.Never)] + [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] +#if SIMPLE_JSON_OBJARRAYINTERNAL + internal +#else + public +#endif + class JsonObject : +#if SIMPLE_JSON_DYNAMIC + DynamicObject, +#endif + IDictionary + { + /// + /// The internal member dictionary. + /// + private readonly Dictionary _members; + + /// + /// Initializes a new instance of . + /// + public JsonObject() + { + _members = new Dictionary(); + } + + /// + /// Initializes a new instance of . + /// + /// The implementation to use when comparing keys, or null to use the default for the type of the key. + public JsonObject(IEqualityComparer comparer) + { + _members = new Dictionary(comparer); + } + + /// + /// Gets the at the specified index. + /// + /// + public object this[int index] + { + get { return GetAtIndex(_members, index); } + } + + internal static object GetAtIndex(IDictionary obj, int index) + { + if (obj == null) + throw new ArgumentNullException("obj"); + if (index >= obj.Count) + throw new ArgumentOutOfRangeException("index"); + int i = 0; + foreach (KeyValuePair o in obj) + if (i++ == index) return o.Value; + return null; + } + + /// + /// Adds the specified key. + /// + /// The key. + /// The value. + public void Add(string key, object value) + { + _members.Add(key, value); + } + + /// + /// Determines whether the specified key contains key. + /// + /// The key. + /// + /// true if the specified key contains key; otherwise, false. + /// + public bool ContainsKey(string key) + { + return _members.ContainsKey(key); + } + + /// + /// Gets the keys. + /// + /// The keys. + public ICollection Keys + { + get { return _members.Keys; } + } + + /// + /// Removes the specified key. + /// + /// The key. + /// + public bool Remove(string key) + { + return _members.Remove(key); + } + + /// + /// Tries the get value. + /// + /// The key. + /// The value. + /// + public bool TryGetValue(string key, out object value) + { + return _members.TryGetValue(key, out value); + } + + /// + /// Gets the values. + /// + /// The values. + public ICollection Values + { + get { return _members.Values; } + } + + /// + /// Gets or sets the with the specified key. + /// + /// + public object this[string key] + { + get { return _members[key]; } + set { _members[key] = value; } + } + + /// + /// Adds the specified item. + /// + /// The item. + public void Add(KeyValuePair item) + { + _members.Add(item.Key, item.Value); + } + + /// + /// Clears this instance. + /// + public void Clear() + { + _members.Clear(); + } + + /// + /// Determines whether [contains] [the specified item]. + /// + /// The item. + /// + /// true if [contains] [the specified item]; otherwise, false. + /// + public bool Contains(KeyValuePair item) + { + return _members.ContainsKey(item.Key) && _members[item.Key] == item.Value; + } + + /// + /// Copies to. + /// + /// The array. + /// Index of the array. + public void CopyTo(KeyValuePair[] array, int arrayIndex) + { + if (array == null) throw new ArgumentNullException("array"); + int num = Count; + foreach (KeyValuePair kvp in this) + { + array[arrayIndex++] = kvp; + if (--num <= 0) + return; + } + } + + /// + /// Gets the count. + /// + /// The count. + public int Count + { + get { return _members.Count; } + } + + /// + /// Gets a value indicating whether this instance is read only. + /// + /// + /// true if this instance is read only; otherwise, false. + /// + public bool IsReadOnly + { + get { return false; } + } + + /// + /// Removes the specified item. + /// + /// The item. + /// + public bool Remove(KeyValuePair item) + { + return _members.Remove(item.Key); + } + + /// + /// Gets the enumerator. + /// + /// + public IEnumerator> GetEnumerator() + { + return _members.GetEnumerator(); + } + + /// + /// Returns an enumerator that iterates through a collection. + /// + /// + /// An object that can be used to iterate through the collection. + /// + IEnumerator IEnumerable.GetEnumerator() + { + return _members.GetEnumerator(); + } + + /// + /// Returns a json that represents the current . + /// + /// + /// A json that represents the current . + /// + public override string ToString() + { + return SimpleJson.SerializeObject(this); + } + +#if SIMPLE_JSON_DYNAMIC + /// + /// Provides implementation for type conversion operations. Classes derived from the class can override this method to specify dynamic behavior for operations that convert an object from one type to another. + /// + /// 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 class, binder.Type returns the 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. + /// The result of the type conversion operation. + /// + /// Alwasy returns true. + /// + public override bool TryConvert(ConvertBinder binder, out object result) + { + // + if (binder == null) + throw new ArgumentNullException("binder"); + // + Type targetType = binder.Type; + + if ((targetType == typeof(IEnumerable)) || + (targetType == typeof(IEnumerable>)) || + (targetType == typeof(IDictionary)) || + (targetType == typeof(IDictionary))) + { + result = this; + return true; + } + + return base.TryConvert(binder, out result); + } + + /// + /// Provides the implementation for operations that delete an object member. This method is not intended for use in C# or Visual Basic. + /// + /// Provides information about the deletion. + /// + /// Alwasy returns true. + /// + public override bool TryDeleteMember(DeleteMemberBinder binder) + { + // + if (binder == null) + throw new ArgumentNullException("binder"); + // + return _members.Remove(binder.Name); + } + + /// + /// Provides the implementation for operations that get a value by index. Classes derived from the class can override this method to specify dynamic behavior for indexing operations. + /// + /// Provides information about the operation. + /// 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, is equal to 3. + /// The result of the index operation. + /// + /// Alwasy returns true. + /// + public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) + { + if (indexes == null) throw new ArgumentNullException("indexes"); + if (indexes.Length == 1) + { + result = ((IDictionary)this)[(string)indexes[0]]; + return true; + } + result = null; + return true; + } + + /// + /// Provides the implementation for operations that get member values. Classes derived from the class can override this method to specify dynamic behavior for operations such as getting a value for a property. + /// + /// 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 class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive. + /// The result of the get operation. For example, if the method is called for a property, you can assign the property value to . + /// + /// Alwasy returns true. + /// + public override bool TryGetMember(GetMemberBinder binder, out object result) + { + object value; + if (_members.TryGetValue(binder.Name, out value)) + { + result = value; + return true; + } + result = null; + return true; + } + + /// + /// Provides the implementation for operations that set a value by index. Classes derived from the class can override this method to specify dynamic behavior for operations that access objects by a specified index. + /// + /// Provides information about the operation. + /// 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 class, is equal to 3. + /// 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 class, is equal to 10. + /// + /// 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. + /// + public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value) + { + if (indexes == null) throw new ArgumentNullException("indexes"); + if (indexes.Length == 1) + { + ((IDictionary)this)[(string)indexes[0]] = value; + return true; + } + return base.TrySetIndex(binder, indexes, value); + } + + /// + /// Provides the implementation for operations that set member values. Classes derived from the class can override this method to specify dynamic behavior for operations such as setting a value for a property. + /// + /// 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 class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive. + /// The value to set to the member. For example, for sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the class, the is "Test". + /// + /// 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.) + /// + public override bool TrySetMember(SetMemberBinder binder, object value) + { + // + if (binder == null) + throw new ArgumentNullException("binder"); + // + _members[binder.Name] = value; + return true; + } + + /// + /// Returns the enumeration of all dynamic member names. + /// + /// + /// A sequence that contains dynamic member names. + /// + public override IEnumerable GetDynamicMemberNames() + { + foreach (var key in Keys) + yield return key; + } +#endif + } +} + +namespace Nancy +{ + /// + /// This class encodes and decodes JSON strings. + /// Spec. details, see http://www.json.org/ + /// + /// JSON uses Arrays and Objects. These correspond here to the datatypes JsonArray(IList<object>) and JsonObject(IDictionary<string,object>). + /// All numbers are parsed to doubles. + /// + [GeneratedCode("simple-json", "1.0.0")] +#if SIMPLE_JSON_INTERNAL + internal +#else + public +#endif + static class SimpleJson + { + private const int TOKEN_NONE = 0; + private const int TOKEN_CURLY_OPEN = 1; + private const int TOKEN_CURLY_CLOSE = 2; + private const int TOKEN_SQUARED_OPEN = 3; + private const int TOKEN_SQUARED_CLOSE = 4; + private const int TOKEN_COLON = 5; + private const int TOKEN_COMMA = 6; + private const int TOKEN_STRING = 7; + private const int TOKEN_NUMBER = 8; + private const int TOKEN_TRUE = 9; + private const int TOKEN_FALSE = 10; + private const int TOKEN_NULL = 11; + private const int BUILDER_CAPACITY = 2000; + + private static readonly char[] EscapeTable; + private static readonly char[] EscapeCharacters = new char[] { '"', '\\', '\b', '\f', '\n', '\r', '\t' }; + private static readonly string EscapeCharactersString = new string(EscapeCharacters); + + static SimpleJson() + { + EscapeTable = new char[93]; + EscapeTable['"'] = '"'; + EscapeTable['\\'] = '\\'; + EscapeTable['\b'] = 'b'; + EscapeTable['\f'] = 'f'; + EscapeTable['\n'] = 'n'; + EscapeTable['\r'] = 'r'; + EscapeTable['\t'] = 't'; + } + + /// + /// Parses the string json into a value + /// + /// A JSON string. + /// An IList<object>, a IDictionary<string,object>, a double, a string, null, true, or false + public static object DeserializeObject(string json) + { + object obj; + if (TryDeserializeObject(json, out obj)) + return obj; + throw new SerializationException("Invalid JSON string"); + } + + /// + /// Try parsing the json string into a value. + /// + /// + /// A JSON string. + /// + /// + /// The object. + /// + /// + /// Returns true if successfull otherwise false. + /// + [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification="Need to support .NET 2")] + public static bool TryDeserializeObject(string json, out object obj) + { + bool success = true; + if (json != null) + { + char[] charArray = json.ToCharArray(); + int index = 0; + obj = ParseValue(charArray, ref index, ref success); + } + else + obj = null; + + return success; + } + + public static object DeserializeObject(string json, Type type, IJsonSerializerStrategy jsonSerializerStrategy) + { + object jsonObject = DeserializeObject(json); + return type == null || jsonObject != null && ReflectionUtils.IsAssignableFrom(jsonObject.GetType(), type) + ? jsonObject + : (jsonSerializerStrategy ?? CurrentJsonSerializerStrategy).DeserializeObject(jsonObject, type); + } + + public static object DeserializeObject(string json, Type type) + { + return DeserializeObject(json, type, null); + } + + public static T DeserializeObject(string json, IJsonSerializerStrategy jsonSerializerStrategy) + { + return (T)DeserializeObject(json, typeof(T), jsonSerializerStrategy); + } + + public static T DeserializeObject(string json) + { + return (T)DeserializeObject(json, typeof(T), null); + } + + /// + /// Converts a IDictionary<string,object> / IList<object> object into a JSON string + /// + /// A IDictionary<string,object> / IList<object> + /// Serializer strategy to use + /// A JSON encoded string, or null if object 'json' is not serializable + public static string SerializeObject(object json, IJsonSerializerStrategy jsonSerializerStrategy) + { + StringBuilder builder = new StringBuilder(BUILDER_CAPACITY); + bool success = SerializeValue(jsonSerializerStrategy, json, builder); + return (success ? builder.ToString() : null); + } + + public static string SerializeObject(object json) + { + return SerializeObject(json, CurrentJsonSerializerStrategy); + } + + public static string EscapeToJavascriptString(string jsonString) + { + if (string.IsNullOrEmpty(jsonString)) + return jsonString; + + StringBuilder sb = new StringBuilder(); + char c; + + for (int i = 0; i < jsonString.Length; ) + { + c = jsonString[i++]; + + if (c == '\\') + { + int remainingLength = jsonString.Length - i; + if (remainingLength >= 2) + { + char lookahead = jsonString[i]; + if (lookahead == '\\') + { + sb.Append('\\'); + ++i; + } + else if (lookahead == '"') + { + sb.Append("\""); + ++i; + } + else if (lookahead == 't') + { + sb.Append('\t'); + ++i; + } + else if (lookahead == 'b') + { + sb.Append('\b'); + ++i; + } + else if (lookahead == 'n') + { + sb.Append('\n'); + ++i; + } + else if (lookahead == 'r') + { + sb.Append('\r'); + ++i; + } + } + } + else + { + sb.Append(c); + } + } + return sb.ToString(); + } + + static IDictionary ParseObject(char[] json, ref int index, ref bool success) + { + IDictionary table = new JsonObject(); + int token; + + // { + NextToken(json, ref index); + + bool done = false; + while (!done) + { + token = LookAhead(json, index); + if (token == TOKEN_NONE) + { + success = false; + return null; + } + else if (token == TOKEN_COMMA) + NextToken(json, ref index); + else if (token == TOKEN_CURLY_CLOSE) + { + NextToken(json, ref index); + return table; + } + else + { + // name + string name = ParseString(json, ref index, ref success); + if (!success) + { + success = false; + return null; + } + // : + token = NextToken(json, ref index); + if (token != TOKEN_COLON) + { + success = false; + return null; + } + // value + object value = ParseValue(json, ref index, ref success); + if (!success) + { + success = false; + return null; + } + table[name] = value; + } + } + return table; + } + + static JsonArray ParseArray(char[] json, ref int index, ref bool success) + { + JsonArray array = new JsonArray(); + + // [ + NextToken(json, ref index); + + bool done = false; + while (!done) + { + int token = LookAhead(json, index); + if (token == TOKEN_NONE) + { + success = false; + return null; + } + else if (token == TOKEN_COMMA) + NextToken(json, ref index); + else if (token == TOKEN_SQUARED_CLOSE) + { + NextToken(json, ref index); + break; + } + else + { + object value = ParseValue(json, ref index, ref success); + if (!success) + return null; + array.Add(value); + } + } + return array; + } + + static object ParseValue(char[] json, ref int index, ref bool success) + { + switch (LookAhead(json, index)) + { + case TOKEN_STRING: + return ParseString(json, ref index, ref success); + case TOKEN_NUMBER: + return ParseNumber(json, ref index, ref success); + case TOKEN_CURLY_OPEN: + return ParseObject(json, ref index, ref success); + case TOKEN_SQUARED_OPEN: + return ParseArray(json, ref index, ref success); + case TOKEN_TRUE: + NextToken(json, ref index); + return true; + case TOKEN_FALSE: + NextToken(json, ref index); + return false; + case TOKEN_NULL: + NextToken(json, ref index); + return null; + case TOKEN_NONE: + break; + } + success = false; + return null; + } + + static string ParseString(char[] json, ref int index, ref bool success) + { + StringBuilder s = new StringBuilder(BUILDER_CAPACITY); + char c; + + EatWhitespace(json, ref index); + + // " + c = json[index++]; + bool complete = false; + while (!complete) + { + if (index == json.Length) + break; + + c = json[index++]; + if (c == '"') + { + complete = true; + break; + } + else if (c == '\\') + { + if (index == json.Length) + break; + c = json[index++]; + if (c == '"') + s.Append('"'); + else if (c == '\\') + s.Append('\\'); + else if (c == '/') + s.Append('/'); + else if (c == 'b') + s.Append('\b'); + else if (c == 'f') + s.Append('\f'); + else if (c == 'n') + s.Append('\n'); + else if (c == 'r') + s.Append('\r'); + else if (c == 't') + s.Append('\t'); + else if (c == 'u') + { + int remainingLength = json.Length - index; + if (remainingLength >= 4) + { + // parse the 32 bit hex into an integer codepoint + uint codePoint; + if (!(success = UInt32.TryParse(new string(json, index, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out codePoint))) + return ""; + + // convert the integer codepoint to a unicode char and add to string + if (0xD800 <= codePoint && codePoint <= 0xDBFF) // if high surrogate + { + index += 4; // skip 4 chars + remainingLength = json.Length - index; + if (remainingLength >= 6) + { + uint lowCodePoint; + if (new string(json, index, 2) == "\\u" && UInt32.TryParse(new string(json, index + 2, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out lowCodePoint)) + { + if (0xDC00 <= lowCodePoint && lowCodePoint <= 0xDFFF) // if low surrogate + { + s.Append((char)codePoint); + s.Append((char)lowCodePoint); + index += 6; // skip 6 chars + continue; + } + } + } + success = false; // invalid surrogate pair + return ""; + } + s.Append(ConvertFromUtf32((int)codePoint)); + // skip 4 chars + index += 4; + } + else + break; + } + } + else + s.Append(c); + } + if (!complete) + { + success = false; + return null; + } + return s.ToString(); + } + + private static string ConvertFromUtf32(int utf32) + { + // http://www.java2s.com/Open-Source/CSharp/2.6.4-mono-.net-core/System/System/Char.cs.htm + if (utf32 < 0 || utf32 > 0x10FFFF) + throw new ArgumentOutOfRangeException("utf32", "The argument must be from 0 to 0x10FFFF."); + if (0xD800 <= utf32 && utf32 <= 0xDFFF) + throw new ArgumentOutOfRangeException("utf32", "The argument must not be in surrogate pair range."); + if (utf32 < 0x10000) + return new string((char)utf32, 1); + utf32 -= 0x10000; + return new string(new char[] { (char)((utf32 >> 10) + 0xD800), (char)(utf32 % 0x0400 + 0xDC00) }); + } + + static object ParseNumber(char[] json, ref int index, ref bool success) + { + EatWhitespace(json, ref index); + int lastIndex = GetLastIndexOfNumber(json, index); + int charLength = (lastIndex - index) + 1; + object returnNumber; + string str = new string(json, index, charLength); + if (str.IndexOf(".", StringComparison.OrdinalIgnoreCase) != -1 || str.IndexOf("e", StringComparison.OrdinalIgnoreCase) != -1) + { + double number; + success = double.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number); + returnNumber = number; + } + else + { + long number; + success = long.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number); + returnNumber = number; + } + index = lastIndex + 1; + return returnNumber; + } + + static int GetLastIndexOfNumber(char[] json, int index) + { + int lastIndex; + for (lastIndex = index; lastIndex < json.Length; lastIndex++) + if ("0123456789+-.eE".IndexOf(json[lastIndex]) == -1) break; + return lastIndex - 1; + } + + static void EatWhitespace(char[] json, ref int index) + { + for (; index < json.Length; index++) + if (" \t\n\r\b\f".IndexOf(json[index]) == -1) break; + } + + static int LookAhead(char[] json, int index) + { + int saveIndex = index; + return NextToken(json, ref saveIndex); + } + + [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] + static int NextToken(char[] json, ref int index) + { + EatWhitespace(json, ref index); + if (index == json.Length) + return TOKEN_NONE; + char c = json[index]; + index++; + switch (c) + { + case '{': + return TOKEN_CURLY_OPEN; + case '}': + return TOKEN_CURLY_CLOSE; + case '[': + return TOKEN_SQUARED_OPEN; + case ']': + return TOKEN_SQUARED_CLOSE; + case ',': + return TOKEN_COMMA; + case '"': + return TOKEN_STRING; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '-': + return TOKEN_NUMBER; + case ':': + return TOKEN_COLON; + } + index--; + int remainingLength = json.Length - index; + // false + if (remainingLength >= 5) + { + if (json[index] == 'f' && json[index + 1] == 'a' && json[index + 2] == 'l' && json[index + 3] == 's' && json[index + 4] == 'e') + { + index += 5; + return TOKEN_FALSE; + } + } + // true + if (remainingLength >= 4) + { + if (json[index] == 't' && json[index + 1] == 'r' && json[index + 2] == 'u' && json[index + 3] == 'e') + { + index += 4; + return TOKEN_TRUE; + } + } + // null + if (remainingLength >= 4) + { + if (json[index] == 'n' && json[index + 1] == 'u' && json[index + 2] == 'l' && json[index + 3] == 'l') + { + index += 4; + return TOKEN_NULL; + } + } + return TOKEN_NONE; + } + + static bool SerializeValue(IJsonSerializerStrategy jsonSerializerStrategy, object value, StringBuilder builder) + { + bool success = true; + string stringValue = value as string; + if (stringValue != null) + success = SerializeString(stringValue, builder); + else + { + IDictionary dict = value as IDictionary; + if (dict != null) + { + success = SerializeObject(jsonSerializerStrategy, dict.Keys, dict.Values, builder); + } + else + { + IDictionary stringDictionary = value as IDictionary; + if (stringDictionary != null) + { + success = SerializeObject(jsonSerializerStrategy, stringDictionary.Keys, stringDictionary.Values, builder); + } + else + { + IEnumerable enumerableValue = value as IEnumerable; + if (enumerableValue != null) + success = SerializeArray(jsonSerializerStrategy, enumerableValue, builder); + else if (IsNumeric(value)) + success = SerializeNumber(value, builder); + else if (value is bool) + builder.Append((bool)value ? "true" : "false"); + else if (value == null) + builder.Append("null"); + else + { + object serializedObject; + success = jsonSerializerStrategy.TrySerializeNonPrimitiveObject(value, out serializedObject); + if (success) + SerializeValue(jsonSerializerStrategy, serializedObject, builder); + } + } + } + } + return success; + } + + static bool SerializeObject(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable keys, IEnumerable values, StringBuilder builder) + { + builder.Append("{"); + IEnumerator ke = keys.GetEnumerator(); + IEnumerator ve = values.GetEnumerator(); + bool first = true; + while (ke.MoveNext() && ve.MoveNext()) + { + object key = ke.Current; + object value = ve.Current; + if (!first) + builder.Append(","); + string stringKey = key as string; + if (stringKey != null) + SerializeString(stringKey, builder); + else + if (!SerializeValue(jsonSerializerStrategy, value, builder)) return false; + builder.Append(":"); + if (!SerializeValue(jsonSerializerStrategy, value, builder)) + return false; + first = false; + } + builder.Append("}"); + return true; + } + + static bool SerializeArray(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable anArray, StringBuilder builder) + { + builder.Append("["); + bool first = true; + foreach (object value in anArray) + { + if (!first) + builder.Append(","); + if (!SerializeValue(jsonSerializerStrategy, value, builder)) + return false; + first = false; + } + builder.Append("]"); + return true; + } + + static bool SerializeString(string aString, StringBuilder builder) + { + // Happy path if there's nothing to be escaped. IndexOfAny is highly optimized (and unmanaged) + if (aString.IndexOfAny(EscapeCharacters) == -1) + { + builder.Append('"'); + builder.Append(aString); + builder.Append('"'); + + return true; + } + + builder.Append('"'); + int safeCharacterCount = 0; + char[] charArray = aString.ToCharArray(); + + for (int i = 0; i < charArray.Length; i++) + { + char c = charArray[i]; + + // Non ascii characters are fine, buffer them up and send them to the builder + // in larger chunks if possible. The escape table is a 1:1 translation table + // with \0 [default(char)] denoting a safe character. + if (c >= EscapeTable.Length || EscapeTable[c] == default(char)) + { + safeCharacterCount++; + } + else + { + if (safeCharacterCount > 0) + { + builder.Append(charArray, i - safeCharacterCount, safeCharacterCount); + safeCharacterCount = 0; + } + + builder.Append('\\'); + builder.Append(EscapeTable[c]); + } + } + + if (safeCharacterCount > 0) + { + builder.Append(charArray, charArray.Length - safeCharacterCount, safeCharacterCount); + } + + builder.Append('"'); + return true; + } + + static bool SerializeNumber(object number, StringBuilder builder) + { + if (number is long) + builder.Append(((long)number).ToString(CultureInfo.InvariantCulture)); + else if (number is ulong) + builder.Append(((ulong)number).ToString(CultureInfo.InvariantCulture)); + else if (number is int) + builder.Append(((int)number).ToString(CultureInfo.InvariantCulture)); + else if (number is uint) + builder.Append(((uint)number).ToString(CultureInfo.InvariantCulture)); + else if (number is decimal) + builder.Append(((decimal)number).ToString(CultureInfo.InvariantCulture)); + else if (number is float) + builder.Append(((float)number).ToString(CultureInfo.InvariantCulture)); + else + builder.Append(Convert.ToDouble(number, CultureInfo.InvariantCulture).ToString("r", CultureInfo.InvariantCulture)); + return true; + } + + /// + /// Determines if a given object is numeric in any way + /// (can be integer, double, null, etc). + /// + static bool IsNumeric(object value) + { + if (value is sbyte) return true; + if (value is byte) return true; + if (value is short) return true; + if (value is ushort) return true; + if (value is int) return true; + if (value is uint) return true; + if (value is long) return true; + if (value is ulong) return true; + if (value is float) return true; + if (value is double) return true; + if (value is decimal) return true; + return false; + } + + private static IJsonSerializerStrategy _currentJsonSerializerStrategy; + public static IJsonSerializerStrategy CurrentJsonSerializerStrategy + { + get + { + return _currentJsonSerializerStrategy ?? + (_currentJsonSerializerStrategy = +#if SIMPLE_JSON_DATACONTRACT + DataContractJsonSerializerStrategy +#else + PocoJsonSerializerStrategy +#endif +); + } + set + { + _currentJsonSerializerStrategy = value; + } + } + + private static PocoJsonSerializerStrategy _pocoJsonSerializerStrategy; + [EditorBrowsable(EditorBrowsableState.Advanced)] + public static PocoJsonSerializerStrategy PocoJsonSerializerStrategy + { + get + { + return _pocoJsonSerializerStrategy ?? (_pocoJsonSerializerStrategy = new PocoJsonSerializerStrategy()); + } + } + +#if SIMPLE_JSON_DATACONTRACT + + private static DataContractJsonSerializerStrategy _dataContractJsonSerializerStrategy; + [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Advanced)] + public static DataContractJsonSerializerStrategy DataContractJsonSerializerStrategy + { + get + { + return _dataContractJsonSerializerStrategy ?? (_dataContractJsonSerializerStrategy = new DataContractJsonSerializerStrategy()); + } + } + +#endif + } + + [GeneratedCode("simple-json", "1.0.0")] +#if SIMPLE_JSON_INTERNAL + internal +#else + public +#endif + interface IJsonSerializerStrategy + { + [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification="Need to support .NET 2")] + bool TrySerializeNonPrimitiveObject(object input, out object output); + object DeserializeObject(object value, Type type); + } + + [GeneratedCode("simple-json", "1.0.0")] +#if SIMPLE_JSON_INTERNAL + internal +#else + public +#endif + class PocoJsonSerializerStrategy : IJsonSerializerStrategy + { + internal IDictionary ConstructorCache; + internal IDictionary> GetCache; + internal IDictionary>> SetCache; + + internal static readonly Type[] EmptyTypes = new Type[0]; + internal static readonly Type[] ArrayConstructorParameterTypes = new Type[] { typeof(int) }; + + private static readonly string[] Iso8601Format = new string[] + { + @"yyyy-MM-dd\THH:mm:ss.FFFFFFF\Z", + @"yyyy-MM-dd\THH:mm:ss\Z", + @"yyyy-MM-dd\THH:mm:ssK" + }; + + public PocoJsonSerializerStrategy() + { + ConstructorCache = new ReflectionUtils.ThreadSafeDictionary(ContructorDelegateFactory); + GetCache = new ReflectionUtils.ThreadSafeDictionary>(GetterValueFactory); + SetCache = new ReflectionUtils.ThreadSafeDictionary>>(SetterValueFactory); + } + + protected virtual string MapClrMemberNameToJsonFieldName(string clrPropertyName) + { + return clrPropertyName; + } + + internal virtual ReflectionUtils.ConstructorDelegate ContructorDelegateFactory(Type key) + { + return ReflectionUtils.GetContructor(key, key.IsArray ? ArrayConstructorParameterTypes : EmptyTypes); + } + + internal virtual IDictionary GetterValueFactory(Type type) + { + IDictionary result = new Dictionary(); + foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type)) + { + if (propertyInfo.CanRead) + { + MethodInfo getMethod = ReflectionUtils.GetGetterMethodInfo(propertyInfo); + if (getMethod.IsStatic || !getMethod.IsPublic) + continue; + result[MapClrMemberNameToJsonFieldName(propertyInfo.Name)] = ReflectionUtils.GetGetMethod(propertyInfo); + } + } + foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type)) + { + if (fieldInfo.IsStatic || !fieldInfo.IsPublic) + continue; + result[MapClrMemberNameToJsonFieldName(fieldInfo.Name)] = ReflectionUtils.GetGetMethod(fieldInfo); + } + return result; + } + + internal virtual IDictionary> SetterValueFactory(Type type) + { + IDictionary> result = new Dictionary>(); + foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type)) + { + if (propertyInfo.CanWrite) + { + MethodInfo setMethod = ReflectionUtils.GetSetterMethodInfo(propertyInfo); + if (setMethod.IsStatic || !setMethod.IsPublic) + continue; + result[MapClrMemberNameToJsonFieldName(propertyInfo.Name)] = new KeyValuePair(propertyInfo.PropertyType, ReflectionUtils.GetSetMethod(propertyInfo)); + } + } + foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type)) + { + if (fieldInfo.IsInitOnly || fieldInfo.IsStatic || !fieldInfo.IsPublic) + continue; + result[MapClrMemberNameToJsonFieldName(fieldInfo.Name)] = new KeyValuePair(fieldInfo.FieldType, ReflectionUtils.GetSetMethod(fieldInfo)); + } + return result; + } + + public virtual bool TrySerializeNonPrimitiveObject(object input, out object output) + { + return TrySerializeKnownTypes(input, out output) || TrySerializeUnknownTypes(input, out output); + } + + [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] + public virtual object DeserializeObject(object value, Type type) + { + if (type == null) throw new ArgumentNullException("type"); + string str = value as string; + + if (type == typeof (Guid) && string.IsNullOrEmpty(str)) + return default(Guid); + + if (value == null) + return null; + + object obj = null; + + if (str != null) + { + if (str.Length != 0) // We know it can't be null now. + { + if (type == typeof(DateTime) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(DateTime))) + return DateTime.ParseExact(str, Iso8601Format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); + if (type == typeof(DateTimeOffset) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(DateTimeOffset))) + return DateTimeOffset.ParseExact(str, Iso8601Format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); + if (type == typeof(Guid) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid))) + return new Guid(str); + if (type == typeof(Uri)) + { + bool isValid = Uri.IsWellFormedUriString(str, UriKind.RelativeOrAbsolute); + + Uri result; + if (isValid && Uri.TryCreate(str, UriKind.RelativeOrAbsolute, out result)) + return result; + + return null; + } + + if (type == typeof(string)) + return str; + + return Convert.ChangeType(str, type, CultureInfo.InvariantCulture); + } + else + { + if (type == typeof(Guid)) + obj = default(Guid); + else if (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid)) + obj = null; + else + obj = str; + } + // Empty string case + if (!ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(Guid)) + return str; + } + else if (value is bool) + return value; + + bool valueIsLong = value is long; + bool valueIsDouble = value is double; + if ((valueIsLong && type == typeof(long)) || (valueIsDouble && type == typeof(double))) + return value; + if ((valueIsDouble && type != typeof(double)) || (valueIsLong && type != typeof(long))) + { + 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) + ? Convert.ChangeType(value, type, CultureInfo.InvariantCulture) + : value; + } + else + { + IDictionary objects = value as IDictionary; + if (objects != null) + { + IDictionary jsonObject = objects; + + if (ReflectionUtils.IsTypeDictionary(type)) + { + // if dictionary then + Type[] types = ReflectionUtils.GetGenericTypeArguments(type); + Type keyType = types[0]; + Type valueType = types[1]; + + Type genericType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType); + + IDictionary dict = (IDictionary)ConstructorCache[genericType](); + + foreach (KeyValuePair kvp in jsonObject) + dict.Add(kvp.Key, DeserializeObject(kvp.Value, valueType)); + + obj = dict; + } + else + { + if (type == typeof(object)) + obj = value; + else + { + obj = ConstructorCache[type](); + foreach (KeyValuePair> setter in SetCache[type]) + { + object jsonValue; + if (jsonObject.TryGetValue(setter.Key, out jsonValue)) + { + jsonValue = DeserializeObject(jsonValue, setter.Value.Key); + setter.Value.Value(obj, jsonValue); + } + } + } + } + } + else + { + IList valueAsList = value as IList; + if (valueAsList != null) + { + IList jsonObject = valueAsList; + IList list = null; + + if (type.IsArray) + { + list = (IList)ConstructorCache[type](jsonObject.Count); + int i = 0; + foreach (object o in jsonObject) + list[i++] = DeserializeObject(o, type.GetElementType()); + } + else if (ReflectionUtils.IsTypeGenericeCollectionInterface(type) || ReflectionUtils.IsAssignableFrom(typeof(IList), type)) + { + Type innerType = ReflectionUtils.GetGenericListElementType(type); + list = (IList)(ConstructorCache[type] ?? ConstructorCache[typeof(List<>).MakeGenericType(innerType)])(jsonObject.Count); + foreach (object o in jsonObject) + list.Add(DeserializeObject(o, innerType)); + } + obj = list; + } + } + return obj; + } + if (ReflectionUtils.IsNullableType(type)) + return ReflectionUtils.ToNullableType(obj, type); + return obj; + } + + protected virtual object SerializeEnum(Enum p) + { + return Convert.ToDouble(p, CultureInfo.InvariantCulture); + } + + [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification="Need to support .NET 2")] + protected virtual bool TrySerializeKnownTypes(object input, out object output) + { + bool returnValue = true; + if (input is DateTime) + output = ((DateTime)input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture); + else if (input is DateTimeOffset) + output = ((DateTimeOffset)input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture); + else if (input is Guid) + output = ((Guid)input).ToString("D"); + else if (input is Uri) + output = input.ToString(); + else + { + Enum inputEnum = input as Enum; + if (inputEnum != null) + output = SerializeEnum(inputEnum); + else + { + returnValue = false; + output = null; + } + } + return returnValue; + } + [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification="Need to support .NET 2")] + protected virtual bool TrySerializeUnknownTypes(object input, out object output) + { + if (input == null) throw new ArgumentNullException("input"); + output = null; + Type type = input.GetType(); + if (type.FullName == null) + return false; + IDictionary obj = new JsonObject(); + IDictionary getters = GetCache[type]; + foreach (KeyValuePair getter in getters) + { + if (getter.Value != null) + obj.Add(MapClrMemberNameToJsonFieldName(getter.Key), getter.Value(input)); + } + output = obj; + return true; + } + } + +#if SIMPLE_JSON_DATACONTRACT + [GeneratedCode("simple-json", "1.0.0")] +#if SIMPLE_JSON_INTERNAL + internal +#else + public +#endif + class DataContractJsonSerializerStrategy : PocoJsonSerializerStrategy + { + public DataContractJsonSerializerStrategy() + { + GetCache = new ReflectionUtils.ThreadSafeDictionary>(GetterValueFactory); + SetCache = new ReflectionUtils.ThreadSafeDictionary>>(SetterValueFactory); + } + + internal override IDictionary GetterValueFactory(Type type) + { + bool hasDataContract = ReflectionUtils.GetAttribute(type, typeof(DataContractAttribute)) != null; + if (!hasDataContract) + return base.GetterValueFactory(type); + string jsonKey; + IDictionary result = new Dictionary(); + foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type)) + { + if (propertyInfo.CanRead) + { + MethodInfo getMethod = ReflectionUtils.GetGetterMethodInfo(propertyInfo); + if (!getMethod.IsStatic && CanAdd(propertyInfo, out jsonKey)) + result[jsonKey] = ReflectionUtils.GetGetMethod(propertyInfo); + } + } + foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type)) + { + if (!fieldInfo.IsStatic && CanAdd(fieldInfo, out jsonKey)) + result[jsonKey] = ReflectionUtils.GetGetMethod(fieldInfo); + } + return result; + } + + internal override IDictionary> SetterValueFactory(Type type) + { + bool hasDataContract = ReflectionUtils.GetAttribute(type, typeof(DataContractAttribute)) != null; + if (!hasDataContract) + return base.SetterValueFactory(type); + string jsonKey; + IDictionary> result = new Dictionary>(); + foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type)) + { + if (propertyInfo.CanWrite) + { + MethodInfo setMethod = ReflectionUtils.GetSetterMethodInfo(propertyInfo); + if (!setMethod.IsStatic && CanAdd(propertyInfo, out jsonKey)) + result[jsonKey] = new KeyValuePair(propertyInfo.PropertyType, ReflectionUtils.GetSetMethod(propertyInfo)); + } + } + foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type)) + { + if (!fieldInfo.IsInitOnly && !fieldInfo.IsStatic && CanAdd(fieldInfo, out jsonKey)) + result[jsonKey] = new KeyValuePair(fieldInfo.FieldType, ReflectionUtils.GetSetMethod(fieldInfo)); + } + // todo implement sorting for DATACONTRACT. + return result; + } + + private static bool CanAdd(MemberInfo info, out string jsonKey) + { + jsonKey = null; + if (ReflectionUtils.GetAttribute(info, typeof(IgnoreDataMemberAttribute)) != null) + return false; + DataMemberAttribute dataMemberAttribute = (DataMemberAttribute)ReflectionUtils.GetAttribute(info, typeof(DataMemberAttribute)); + if (dataMemberAttribute == null) + return false; + jsonKey = string.IsNullOrEmpty(dataMemberAttribute.Name) ? info.Name : dataMemberAttribute.Name; + return true; + } + } + +#endif + + namespace Reflection + { + // This class is meant to be copied into other libraries. So we want to exclude it from Code Analysis rules + // that might be in place in the target project. + [GeneratedCode("reflection-utils", "1.0.0")] +#if SIMPLE_JSON_REFLECTION_UTILS_PUBLIC + public +#else + internal +#endif + class ReflectionUtils + { + private static readonly object[] EmptyObjects = new object[] { }; + + public delegate object GetDelegate(object source); + public delegate void SetDelegate(object source, object value); + public delegate object ConstructorDelegate(params object[] args); + + public delegate TValue ThreadSafeDictionaryValueFactory(TKey key); + +#if SIMPLE_JSON_TYPEINFO + public static TypeInfo GetTypeInfo(Type type) + { + return type.GetTypeInfo(); + } +#else + public static Type GetTypeInfo(Type type) + { + return type; + } +#endif + + public static Attribute GetAttribute(MemberInfo info, Type type) + { +#if SIMPLE_JSON_TYPEINFO + if (info == null || type == null || !info.IsDefined(type)) + return null; + return info.GetCustomAttribute(type); +#else + if (info == null || type == null || !Attribute.IsDefined(info, type)) + return null; + return Attribute.GetCustomAttribute(info, type); +#endif + } + + public static Type GetGenericListElementType(Type type) + { + IEnumerable interfaces; +#if SIMPLE_JSON_TYPEINFO + interfaces = type.GetTypeInfo().ImplementedInterfaces; +#else + interfaces = type.GetInterfaces(); +#endif + foreach (Type implementedInterface in interfaces) + { + if (IsTypeGeneric(implementedInterface) && + implementedInterface.GetGenericTypeDefinition() == typeof (IList<>)) + { + return GetGenericTypeArguments(implementedInterface)[0]; + } + } + return GetGenericTypeArguments(type)[0]; + } + + public static Attribute GetAttribute(Type objectType, Type attributeType) + { + +#if SIMPLE_JSON_TYPEINFO + if (objectType == null || attributeType == null || !objectType.GetTypeInfo().IsDefined(attributeType)) + return null; + return objectType.GetTypeInfo().GetCustomAttribute(attributeType); +#else + if (objectType == null || attributeType == null || !Attribute.IsDefined(objectType, attributeType)) + return null; + return Attribute.GetCustomAttribute(objectType, attributeType); +#endif + } + + public static Type[] GetGenericTypeArguments(Type type) + { +#if SIMPLE_JSON_TYPEINFO + return type.GetTypeInfo().GenericTypeArguments; +#else + return type.GetGenericArguments(); +#endif + } + + public static bool IsTypeGeneric(Type type) + { + return GetTypeInfo(type).IsGenericType; + } + + public static bool IsTypeGenericeCollectionInterface(Type type) + { + if (!IsTypeGeneric(type)) + return false; + + Type genericDefinition = type.GetGenericTypeDefinition(); + + return (genericDefinition == typeof(IList<>) + || genericDefinition == typeof(ICollection<>) + || genericDefinition == typeof(IEnumerable<>) +#if SIMPLE_JSON_READONLY_COLLECTIONS + || genericDefinition == typeof(IReadOnlyCollection<>) + || genericDefinition == typeof(IReadOnlyList<>) +#endif + ); + } + + public static bool IsAssignableFrom(Type type1, Type type2) + { + return GetTypeInfo(type1).IsAssignableFrom(GetTypeInfo(type2)); + } + + public static bool IsTypeDictionary(Type type) + { +#if SIMPLE_JSON_TYPEINFO + if (typeof(IDictionary<,>).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())) + return true; +#else + if (typeof(System.Collections.IDictionary).IsAssignableFrom(type)) + return true; +#endif + if (!GetTypeInfo(type).IsGenericType) + return false; + + Type genericDefinition = type.GetGenericTypeDefinition(); + return genericDefinition == typeof(IDictionary<,>); + } + + public static bool IsNullableType(Type type) + { + return GetTypeInfo(type).IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); + } + + public static object ToNullableType(object obj, Type nullableType) + { + return obj == null ? null : Convert.ChangeType(obj, Nullable.GetUnderlyingType(nullableType), CultureInfo.InvariantCulture); + } + + public static bool IsValueType(Type type) + { + return GetTypeInfo(type).IsValueType; + } + + public static IEnumerable GetConstructors(Type type) + { +#if SIMPLE_JSON_TYPEINFO + return type.GetTypeInfo().DeclaredConstructors; +#else + return type.GetConstructors(); +#endif + } + + public static ConstructorInfo GetConstructorInfo(Type type, params Type[] argsType) + { + IEnumerable constructorInfos = GetConstructors(type); + int i; + bool matches; + foreach (ConstructorInfo constructorInfo in constructorInfos) + { + ParameterInfo[] parameters = constructorInfo.GetParameters(); + if (argsType.Length != parameters.Length) + continue; + + i = 0; + matches = true; + foreach (ParameterInfo parameterInfo in constructorInfo.GetParameters()) + { + if (parameterInfo.ParameterType != argsType[i]) + { + matches = false; + break; + } + } + + if (matches) + return constructorInfo; + } + + return null; + } + + public static IEnumerable GetProperties(Type type) + { +#if SIMPLE_JSON_TYPEINFO + return type.GetRuntimeProperties(); +#else + return type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); +#endif + } + + public static IEnumerable GetFields(Type type) + { +#if SIMPLE_JSON_TYPEINFO + return type.GetRuntimeFields(); +#else + return type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); +#endif + } + + public static MethodInfo GetGetterMethodInfo(PropertyInfo propertyInfo) + { +#if SIMPLE_JSON_TYPEINFO + return propertyInfo.GetMethod; +#else + return propertyInfo.GetGetMethod(true); +#endif + } + + public static MethodInfo GetSetterMethodInfo(PropertyInfo propertyInfo) + { +#if SIMPLE_JSON_TYPEINFO + return propertyInfo.SetMethod; +#else + return propertyInfo.GetSetMethod(true); +#endif + } + + public static ConstructorDelegate GetContructor(ConstructorInfo constructorInfo) + { +#if SIMPLE_JSON_NO_LINQ_EXPRESSION + return GetConstructorByReflection(constructorInfo); +#else + return GetConstructorByExpression(constructorInfo); +#endif + } + + public static ConstructorDelegate GetContructor(Type type, params Type[] argsType) + { +#if SIMPLE_JSON_NO_LINQ_EXPRESSION + return GetConstructorByReflection(type, argsType); +#else + return GetConstructorByExpression(type, argsType); +#endif + } + + public static ConstructorDelegate GetConstructorByReflection(ConstructorInfo constructorInfo) + { + return delegate(object[] args) { return constructorInfo.Invoke(args); }; + } + + public static ConstructorDelegate GetConstructorByReflection(Type type, params Type[] argsType) + { + ConstructorInfo constructorInfo = GetConstructorInfo(type, argsType); + return constructorInfo == null ? null : GetConstructorByReflection(constructorInfo); + } + +#if !SIMPLE_JSON_NO_LINQ_EXPRESSION + + public static ConstructorDelegate GetConstructorByExpression(ConstructorInfo constructorInfo) + { + ParameterInfo[] paramsInfo = constructorInfo.GetParameters(); + ParameterExpression param = Expression.Parameter(typeof(object[]), "args"); + Expression[] argsExp = new Expression[paramsInfo.Length]; + for (int i = 0; i < paramsInfo.Length; i++) + { + Expression index = Expression.Constant(i); + Type paramType = paramsInfo[i].ParameterType; + Expression paramAccessorExp = Expression.ArrayIndex(param, index); + Expression paramCastExp = Expression.Convert(paramAccessorExp, paramType); + argsExp[i] = paramCastExp; + } + NewExpression newExp = Expression.New(constructorInfo, argsExp); + Expression> lambda = Expression.Lambda>(newExp, param); + Func compiledLambda = lambda.Compile(); + return delegate(object[] args) { return compiledLambda(args); }; + } + + public static ConstructorDelegate GetConstructorByExpression(Type type, params Type[] argsType) + { + ConstructorInfo constructorInfo = GetConstructorInfo(type, argsType); + return constructorInfo == null ? null : GetConstructorByExpression(constructorInfo); + } + +#endif + + public static GetDelegate GetGetMethod(PropertyInfo propertyInfo) + { +#if SIMPLE_JSON_NO_LINQ_EXPRESSION + return GetGetMethodByReflection(propertyInfo); +#else + return GetGetMethodByExpression(propertyInfo); +#endif + } + + public static GetDelegate GetGetMethod(FieldInfo fieldInfo) + { +#if SIMPLE_JSON_NO_LINQ_EXPRESSION + return GetGetMethodByReflection(fieldInfo); +#else + return GetGetMethodByExpression(fieldInfo); +#endif + } + + public static GetDelegate GetGetMethodByReflection(PropertyInfo propertyInfo) + { + MethodInfo methodInfo = GetGetterMethodInfo(propertyInfo); + return delegate(object source) { return methodInfo.Invoke(source, EmptyObjects); }; + } + + public static GetDelegate GetGetMethodByReflection(FieldInfo fieldInfo) + { + return delegate(object source) { return fieldInfo.GetValue(source); }; + } + +#if !SIMPLE_JSON_NO_LINQ_EXPRESSION + + public static GetDelegate GetGetMethodByExpression(PropertyInfo propertyInfo) + { + MethodInfo getMethodInfo = GetGetterMethodInfo(propertyInfo); + ParameterExpression instance = Expression.Parameter(typeof(object), "instance"); + UnaryExpression instanceCast = (!IsValueType(propertyInfo.DeclaringType)) ? Expression.TypeAs(instance, propertyInfo.DeclaringType) : Expression.Convert(instance, propertyInfo.DeclaringType); + Func compiled = Expression.Lambda>(Expression.TypeAs(Expression.Call(instanceCast, getMethodInfo), typeof(object)), instance).Compile(); + return delegate(object source) { return compiled(source); }; + } + + public static GetDelegate GetGetMethodByExpression(FieldInfo fieldInfo) + { + ParameterExpression instance = Expression.Parameter(typeof(object), "instance"); + MemberExpression member = Expression.Field(Expression.Convert(instance, fieldInfo.DeclaringType), fieldInfo); + GetDelegate compiled = Expression.Lambda(Expression.Convert(member, typeof(object)), instance).Compile(); + return delegate(object source) { return compiled(source); }; + } + +#endif + + public static SetDelegate GetSetMethod(PropertyInfo propertyInfo) + { +#if SIMPLE_JSON_NO_LINQ_EXPRESSION + return GetSetMethodByReflection(propertyInfo); +#else + return GetSetMethodByExpression(propertyInfo); +#endif + } + + public static SetDelegate GetSetMethod(FieldInfo fieldInfo) + { +#if SIMPLE_JSON_NO_LINQ_EXPRESSION + return GetSetMethodByReflection(fieldInfo); +#else + return GetSetMethodByExpression(fieldInfo); +#endif + } + + public static SetDelegate GetSetMethodByReflection(PropertyInfo propertyInfo) + { + MethodInfo methodInfo = GetSetterMethodInfo(propertyInfo); + return delegate(object source, object value) { methodInfo.Invoke(source, new object[] { value }); }; + } + + public static SetDelegate GetSetMethodByReflection(FieldInfo fieldInfo) + { + return delegate(object source, object value) { fieldInfo.SetValue(source, value); }; + } + +#if !SIMPLE_JSON_NO_LINQ_EXPRESSION + + public static SetDelegate GetSetMethodByExpression(PropertyInfo propertyInfo) + { + MethodInfo setMethodInfo = GetSetterMethodInfo(propertyInfo); + ParameterExpression instance = Expression.Parameter(typeof(object), "instance"); + ParameterExpression value = Expression.Parameter(typeof(object), "value"); + UnaryExpression instanceCast = (!IsValueType(propertyInfo.DeclaringType)) ? Expression.TypeAs(instance, propertyInfo.DeclaringType) : Expression.Convert(instance, propertyInfo.DeclaringType); + UnaryExpression valueCast = (!IsValueType(propertyInfo.PropertyType)) ? Expression.TypeAs(value, propertyInfo.PropertyType) : Expression.Convert(value, propertyInfo.PropertyType); + Action compiled = Expression.Lambda>(Expression.Call(instanceCast, setMethodInfo, valueCast), new ParameterExpression[] { instance, value }).Compile(); + return delegate(object source, object val) { compiled(source, val); }; + } + + public static SetDelegate GetSetMethodByExpression(FieldInfo fieldInfo) + { + ParameterExpression instance = Expression.Parameter(typeof(object), "instance"); + ParameterExpression value = Expression.Parameter(typeof(object), "value"); + Action compiled = Expression.Lambda>( + Assign(Expression.Field(Expression.Convert(instance, fieldInfo.DeclaringType), fieldInfo), Expression.Convert(value, fieldInfo.FieldType)), instance, value).Compile(); + return delegate(object source, object val) { compiled(source, val); }; + } + + public static BinaryExpression Assign(Expression left, Expression right) + { +#if SIMPLE_JSON_TYPEINFO + return Expression.Assign(left, right); +#else + MethodInfo assign = typeof(Assigner<>).MakeGenericType(left.Type).GetMethod("Assign"); + BinaryExpression assignExpr = Expression.Add(left, right, assign); + return assignExpr; +#endif + } + + private static class Assigner + { + public static T Assign(ref T left, T right) + { + return (left = right); + } + } + +#endif + + public sealed class ThreadSafeDictionary : IDictionary + { + private readonly object _lock = new object(); + private readonly ThreadSafeDictionaryValueFactory _valueFactory; + private Dictionary _dictionary; + + public ThreadSafeDictionary(ThreadSafeDictionaryValueFactory valueFactory) + { + _valueFactory = valueFactory; + } + + private TValue Get(TKey key) + { + if (_dictionary == null) + return AddValue(key); + TValue value; + if (!_dictionary.TryGetValue(key, out value)) + return AddValue(key); + return value; + } + + private TValue AddValue(TKey key) + { + TValue value = _valueFactory(key); + lock (_lock) + { + if (_dictionary == null) + { + _dictionary = new Dictionary(); + _dictionary[key] = value; + } + else + { + TValue val; + if (_dictionary.TryGetValue(key, out val)) + return val; + Dictionary dict = new Dictionary(_dictionary); + dict[key] = value; + _dictionary = dict; + } + } + return value; + } + + public void Add(TKey key, TValue value) + { + throw new NotImplementedException(); + } + + public bool ContainsKey(TKey key) + { + return _dictionary.ContainsKey(key); + } + + public ICollection Keys + { + get { return _dictionary.Keys; } + } + + public bool Remove(TKey key) + { + throw new NotImplementedException(); + } + + public bool TryGetValue(TKey key, out TValue value) + { + value = this[key]; + return true; + } + + public ICollection Values + { + get { return _dictionary.Values; } + } + + public TValue this[TKey key] + { + get { return Get(key); } + set { throw new NotImplementedException(); } + } + + public void Add(KeyValuePair item) + { + throw new NotImplementedException(); + } + + public void Clear() + { + throw new NotImplementedException(); + } + + public bool Contains(KeyValuePair item) + { + throw new NotImplementedException(); + } + + public void CopyTo(KeyValuePair[] array, int arrayIndex) + { + throw new NotImplementedException(); + } + + public int Count + { + get { return _dictionary.Count; } + } + + public bool IsReadOnly + { + get { throw new NotImplementedException(); } + } + + public bool Remove(KeyValuePair item) + { + throw new NotImplementedException(); + } + + public IEnumerator> GetEnumerator() + { + return _dictionary.GetEnumerator(); + } + + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() + { + return _dictionary.GetEnumerator(); + } + } + + } + } +} +// ReSharper restore LoopCanBeConvertedToQuery +// ReSharper restore RedundantExplicitArrayCreation +// ReSharper restore SuggestUseVarKeywordEvident diff --git a/src/Nancy/Session/CookieBasedSessions.cs b/src/Nancy/Session/CookieBasedSessions.cs index 06d3046021..b8dc3cef8b 100644 --- a/src/Nancy/Session/CookieBasedSessions.cs +++ b/src/Nancy/Session/CookieBasedSessions.cs @@ -90,12 +90,13 @@ public static IObjectSerializerSelector Enable(IPipelines pipelines, CookieBased /// /// Application pipelines /// Cryptography configuration + /// Assembly catalog /// Formatter selector for choosing a non-default serializer - public static IObjectSerializerSelector Enable(IPipelines pipelines, CryptographyConfiguration cryptographyConfiguration) + public static IObjectSerializerSelector Enable(IPipelines pipelines, CryptographyConfiguration cryptographyConfiguration, IAssemblyCatalog assemblyCatalog) { var cookieBasedSessionsConfiguration = new CookieBasedSessionsConfiguration(cryptographyConfiguration) { - Serializer = new DefaultObjectSerializer() + Serializer = new DefaultObjectSerializer(assemblyCatalog) }; return Enable(pipelines, cookieBasedSessionsConfiguration); } @@ -104,12 +105,13 @@ public static IObjectSerializerSelector Enable(IPipelines pipelines, Cryptograph /// Initialise and add cookie based session hooks to the application pipeline with the default encryption provider. /// /// Application pipelines + /// Assembly catalog /// Formatter selector for choosing a non-default serializer - public static IObjectSerializerSelector Enable(IPipelines pipelines) + public static IObjectSerializerSelector Enable(IPipelines pipelines, IAssemblyCatalog assemblyCatalog) { return Enable(pipelines, new CookieBasedSessionsConfiguration { - Serializer = new DefaultObjectSerializer() + Serializer = new DefaultObjectSerializer(assemblyCatalog) }); } diff --git a/src/Nancy/project.json b/src/Nancy/project.json index a4443ce07e..641e2554cf 100644 --- a/src/Nancy/project.json +++ b/src/Nancy/project.json @@ -1,4 +1,4 @@ -{ +{ "version": "2.0.0-*", "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.", @@ -36,8 +36,8 @@ "System.Linq": "4.0.1-beta-23516", "System.Net.NameResolution": "4.0.0-beta-23516", "System.Net.Primitives": "4.0.11-beta-23516", - "System.Reflection.TypeExtensions": "4.1.0-beta-23516", "System.Reflection.Extensions": "4.0.1-beta-23516", + "System.Reflection.TypeExtensions": "4.1.0-beta-23516", "System.Runtime": "4.0.21-beta-23516", "System.Runtime.Serialization.Primitives": "4.1.0-beta-23516", "System.Security.Claims": "4.0.1-beta-23516", diff --git a/test/Nancy.Testing.Tests/BrowserFixture.cs b/test/Nancy.Testing.Tests/BrowserFixture.cs index fcb0a59ae0..dbbe7abb9b 100644 --- a/test/Nancy.Testing.Tests/BrowserFixture.cs +++ b/test/Nancy.Testing.Tests/BrowserFixture.cs @@ -13,6 +13,7 @@ namespace Nancy.Testing.Tests using Nancy.Session; using Nancy.Tests; using Nancy.Authentication.Forms; + using Nancy.Bootstrapper; using Nancy.Configuration; using Nancy.Tests.xUnitExtensions; using Xunit; @@ -27,7 +28,7 @@ public BrowserFixture() var bootstrapper = new ConfigurableBootstrapper(config => config.Modules(typeof(EchoModule))); - CookieBasedSessions.Enable(bootstrapper); + CookieBasedSessions.Enable(bootstrapper, A.Fake()); this.browser = new Browser(bootstrapper); } diff --git a/test/Nancy.Tests/Unit/Diagnostics/CustomInteractiveDiagnosticsFixture.cs b/test/Nancy.Tests/Unit/Diagnostics/CustomInteractiveDiagnosticsFixture.cs index ca9d642a36..da2775dcc8 100644 --- a/test/Nancy.Tests/Unit/Diagnostics/CustomInteractiveDiagnosticsFixture.cs +++ b/test/Nancy.Tests/Unit/Diagnostics/CustomInteractiveDiagnosticsFixture.cs @@ -3,7 +3,9 @@ using System; using System.Collections.Generic; using System.Linq; + using System.Reflection; using System.Threading.Tasks; + using FakeItEasy; using Nancy.Bootstrapper; using Nancy.Configuration; using Nancy.Cryptography; @@ -26,7 +28,14 @@ public class CustomInteractiveDiagnosticsHookFixture public CustomInteractiveDiagnosticsHookFixture() { this.cryptoConfig = CryptographyConfiguration.Default; - this.objectSerializer = new DefaultObjectSerializer(); + var fakeAssemblyCatalog = A.Fake(); + A.CallTo(() => fakeAssemblyCatalog.GetAssemblies(AssemblyResolveStrategies.All)) + .Returns(new[] + { + typeof(CustomInteractiveDiagnosticsHookFixture).GetTypeInfo().Assembly, + typeof(DiagnosticsSession).GetTypeInfo().Assembly + }); + this.objectSerializer = new DefaultObjectSerializer(fakeAssemblyCatalog); } private class FakeDiagnostics : IDiagnostics @@ -44,6 +53,7 @@ private class FakeDiagnostics : IDiagnostics private readonly ITextResource textResource; private readonly INancyEnvironment environment; private readonly ITypeCatalog typeCatalog; + private readonly IAssemblyCatalog assemblyCatalog; public FakeDiagnostics( IRootPathProvider rootPathProvider, @@ -57,7 +67,8 @@ public FakeDiagnostics( IEnumerable routeMetadataProviders, ITextResource textResource, INancyEnvironment environment, - ITypeCatalog typeCatalog) + ITypeCatalog typeCatalog, + IAssemblyCatalog assemblyCatalog) { this.diagnosticProviders = (new IDiagnosticsProvider[] { new FakeDiagnosticsProvider() }).ToArray(); this.rootPathProvider = rootPathProvider; @@ -72,6 +83,7 @@ public FakeDiagnostics( this.textResource = textResource; this.environment = environment; this.typeCatalog = typeCatalog; + this.assemblyCatalog = assemblyCatalog; } public void Initialize(IPipelines pipelines) @@ -90,7 +102,8 @@ public void Initialize(IPipelines pipelines) this.routeMetadataProviders, this.textResource, this.environment, - this.typeCatalog); + this.typeCatalog, + this.assemblyCatalog); } } diff --git a/test/Nancy.Tests/Unit/Diagnostics/DiagnosticsHookFixture.cs b/test/Nancy.Tests/Unit/Diagnostics/DiagnosticsHookFixture.cs index 235b144829..4381cacb91 100644 --- a/test/Nancy.Tests/Unit/Diagnostics/DiagnosticsHookFixture.cs +++ b/test/Nancy.Tests/Unit/Diagnostics/DiagnosticsHookFixture.cs @@ -2,7 +2,9 @@ { using System; using System.Linq; + using System.Reflection; using System.Threading.Tasks; + using FakeItEasy; using Nancy.Cookies; using Nancy.Cryptography; using Nancy.Diagnostics; @@ -21,7 +23,14 @@ public class DiagnosticsHookFixture public DiagnosticsHookFixture() { this.cryptoConfig = CryptographyConfiguration.Default; - this.objectSerializer = new DefaultObjectSerializer(); + var fakeAssemblyCatalog = A.Fake(); + A.CallTo(() => fakeAssemblyCatalog.GetAssemblies(AssemblyResolveStrategies.All)) + .Returns(new[] + { + typeof(DiagnosticsHookFixture).GetTypeInfo().Assembly, + typeof(DiagnosticsSession).GetTypeInfo().Assembly + }); + this.objectSerializer = new DefaultObjectSerializer(fakeAssemblyCatalog); } #if DEBUG diff --git a/test/Nancy.Tests/Unit/Security/CsrfFixture.cs b/test/Nancy.Tests/Unit/Security/CsrfFixture.cs index 04c1f106ae..cc29e51863 100644 --- a/test/Nancy.Tests/Unit/Security/CsrfFixture.cs +++ b/test/Nancy.Tests/Unit/Security/CsrfFixture.cs @@ -2,6 +2,7 @@ { using System.Collections.Generic; using System.Linq; + using System.Reflection; using System.Threading; using FakeItEasy; @@ -34,8 +35,10 @@ public CsrfFixture() this.pipelines = new MockPipelines(); this.cryptographyConfiguration = CryptographyConfiguration.Default; - - this.objectSerializer = new DefaultObjectSerializer(); + var fakeAssemblyCatalog = A.Fake(); + A.CallTo(() => fakeAssemblyCatalog.GetAssemblies(AssemblyResolveStrategies.All)) + .Returns(new[] { typeof(CsrfFixture).GetTypeInfo().Assembly, typeof(CsrfToken).GetTypeInfo().Assembly }); + this.objectSerializer = new DefaultObjectSerializer(fakeAssemblyCatalog); var csrfStartup = new CsrfApplicationStartup( this.cryptographyConfiguration, this.objectSerializer, diff --git a/test/Nancy.Tests/Unit/Sessions/CookieBasedSessionsFixture.cs b/test/Nancy.Tests/Unit/Sessions/CookieBasedSessionsFixture.cs index 031cd2c73d..eb1fc2bfe6 100644 --- a/test/Nancy.Tests/Unit/Sessions/CookieBasedSessionsFixture.cs +++ b/test/Nancy.Tests/Unit/Sessions/CookieBasedSessionsFixture.cs @@ -3,6 +3,7 @@ namespace Nancy.Tests.Unit.Sessions using System.Collections.Generic; using System.IO; using System.Linq; + using System.Reflection; using System.Threading; using System.Web; @@ -18,8 +19,8 @@ namespace Nancy.Tests.Unit.Sessions public class CookieBasedSessionsFixture { - private const string ValidData = "VgPJvXYwcXkn0gxDvg84tsfV9F5he1ZxhjsTZK1UZHVqWk7izPd9XsWnuFMrtQNRJEfyiqU2J7tAZDQvdKjQij9wUO6mOTCyZ7HPHK/pEnkgDFMXbHDctGQZSbb2WZZxola+Q3nP2tlQ+Tx//N6YyK7BwpsNPrvyHAvU1z5YzHfPT6HEowIl8mz/uUL6o+FME/Goi7RN2getMeYaPCs0fJkiMCAomnnagAy4aXN0Ak/p7Y3K/kpNAS6PvNu4aok0zVpfo1utP84GyyLomfr4urmDNFIe8PBVoKhuomxjsUOddaarHqqmN3PXOp15SPXPDxEKfpuLzhmqXnStiB8nH9qMBYI/AuLHMckDzkeESH5rQ2q2+1RgCN82PujzGhhVnBMk95ZS9k9zKCvKQa2yzVkaHqwSESyOFboU89kLAEQ0h48dtoJ2FTBs9GjsL3Z4fGogeLwjIvP8I8JF39HI+9U3PC2KnicA/bgUL/Z1paDzZYTrqQS4QSyFgy4DOxYz"; - private const string ValidHmac = "un/5uJOoOAyn4AX8VU0HsGYYtr79A40TFF1wVqd/jDQ="; + 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="; + private const string ValidHmac = "QWc9gRZbQ6pK5ECs2Zp4E5WenpQ/XXgYUDPY46WihPY="; private readonly IEncryptionProvider fakeEncryptionProvider; private readonly CookieBasedSessions cookieStore; @@ -32,6 +33,8 @@ public class CookieBasedSessionsFixture private IObjectSerializer defaultObjectSerializer; + private IAssemblyCatalog assemblyCatalog; + public CookieBasedSessionsFixture() { this.fakeEncryptionProvider = A.Fake(); @@ -41,7 +44,10 @@ public CookieBasedSessionsFixture() this.aesEncryptionProvider = new AesEncryptionProvider(new PassphraseKeyGenerator("password", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000)); this.defaultHmacProvider = new DefaultHmacProvider(new PassphraseKeyGenerator("anotherpassword", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000)); - this.defaultObjectSerializer = new DefaultObjectSerializer(); + this.assemblyCatalog = A.Fake(); + A.CallTo(() => this.assemblyCatalog.GetAssemblies(AssemblyResolveStrategies.All)) + .Returns(new[] { typeof(CookieBasedSessionsFixture).GetTypeInfo().Assembly }); + this.defaultObjectSerializer = new DefaultObjectSerializer(this.assemblyCatalog); } [Fact] @@ -185,7 +191,7 @@ public void Should_add_pre_and_post_hooks_when_enabled() A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline); A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline); - CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider)); + CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider), this.assemblyCatalog); beforePipeline.PipelineDelegates.Count().ShouldEqual(1); afterPipeline.PipelineItems.Count().ShouldEqual(1); @@ -199,7 +205,7 @@ public void Should_only_not_add_response_cookie_if_it_has_not_changed() var hooks = A.Fake(); A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline); A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline); - CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider)).WithSerializer(this.fakeObjectSerializer); + CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider), this.assemblyCatalog).WithSerializer(this.fakeObjectSerializer); var request = CreateRequest("encryptedkey1=value1"); A.CallTo(() => this.fakeEncryptionProvider.Decrypt("encryptedkey1=value1")).Returns("key1=value1;"); var response = A.Fake(); @@ -219,7 +225,7 @@ public void Should_add_response_cookie_if_it_has_changed() var hooks = A.Fake(); A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline); A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline); - CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider)).WithSerializer(this.fakeObjectSerializer); + CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider), this.assemblyCatalog).WithSerializer(this.fakeObjectSerializer); var request = CreateRequest("encryptedkey1=value1"); A.CallTo(() => this.fakeEncryptionProvider.Decrypt("encryptedkey1=value1")).Returns("key1=value1;"); var response = A.Fake(); @@ -269,7 +275,7 @@ public void Should_set_formatter_when_using_formatter_selector() A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline); var fakeFormatter = A.Fake(); A.CallTo(() => this.fakeEncryptionProvider.Decrypt("encryptedkey1=value1")).Returns("key1=value1;"); - CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider)).WithSerializer(fakeFormatter); + CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider), this.assemblyCatalog).WithSerializer(fakeFormatter); var request = CreateRequest("encryptedkey1=value1"); var nancyContext = new NancyContext() { Request = request }; diff --git a/test/Nancy.Tests/Unit/Sessions/DefaultSessionObjectFormatterFixture.cs b/test/Nancy.Tests/Unit/Sessions/DefaultSessionObjectFormatterFixture.cs index cf353f6006..e5f13e1390 100644 --- a/test/Nancy.Tests/Unit/Sessions/DefaultSessionObjectFormatterFixture.cs +++ b/test/Nancy.Tests/Unit/Sessions/DefaultSessionObjectFormatterFixture.cs @@ -1,7 +1,8 @@ namespace Nancy.Tests.Unit.Sessions { using System; - + using System.Reflection; + using FakeItEasy; using Xunit; public class DefaultSessionObjectFormatterFixture @@ -10,7 +11,10 @@ public class DefaultSessionObjectFormatterFixture public DefaultSessionObjectFormatterFixture() { - this.serializer = new DefaultObjectSerializer(); + var fakeAssemblyCatalog = A.Fake(); + A.CallTo(() => fakeAssemblyCatalog.GetAssemblies(AssemblyResolveStrategies.All)) + .Returns(new[] { typeof(DefaultSessionObjectFormatterFixture).GetTypeInfo().Assembly }); + this.serializer = new DefaultObjectSerializer(fakeAssemblyCatalog); } [Fact] @@ -68,11 +72,16 @@ public void Should_return_null_when_deserializing_empty_string() [Serializable] public class Payload : IEquatable { - public int IntValue { get; private set; } + public int IntValue { get; set; } + + public bool BoolValue { get; set; } - public bool BoolValue { get; private set; } + public string StringValue { get; set; } - public string StringValue { get; private set; } + public Payload() + { + + } /// /// Initializes a new instance of the class. From f4e1e91cea3a2390c5b9510256ce2305d0ed4b38 Mon Sep 17 00:00:00 2001 From: James Humphries Date: Thu, 18 Feb 2016 22:02:14 +0000 Subject: [PATCH 25/52] added ifdef for dotnet54 in simplejson --- src/Nancy/Json/SimpleJson.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Nancy/Json/SimpleJson.cs b/src/Nancy/Json/SimpleJson.cs index a6014190a3..7caf436e8a 100644 --- a/src/Nancy/Json/SimpleJson.cs +++ b/src/Nancy/Json/SimpleJson.cs @@ -46,7 +46,7 @@ // 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 -#if NETFX_CORE +#if NETFX_CORE || DOTNET5_4 #define SIMPLE_JSON_TYPEINFO #endif From b692e4613b264508dcc6c0cdcc1dc917372c0b09 Mon Sep 17 00:00:00 2001 From: James Humphries Date: Fri, 19 Feb 2016 14:55:55 +0000 Subject: [PATCH 26/52] changed isjittrackingenabled -> debugger.isattached, ifdefed out bootstrapper exception ctor, swapped crypto classes --- src/Nancy/Bootstrapper/BootstrapperException.cs | 4 +++- src/Nancy/Bootstrapper/NancyBootstrapperBase.cs | 2 +- .../DefaultRuntimeEnvironmentInformation.cs | 17 +---------------- src/Nancy/Diagnostics/DiagnosticsSession.cs | 2 +- src/Nancy/Responses/EmbeddedFileResponse.cs | 2 +- 5 files changed, 7 insertions(+), 20 deletions(-) diff --git a/src/Nancy/Bootstrapper/BootstrapperException.cs b/src/Nancy/Bootstrapper/BootstrapperException.cs index 8a9c11f292..26100086f9 100644 --- a/src/Nancy/Bootstrapper/BootstrapperException.cs +++ b/src/Nancy/Bootstrapper/BootstrapperException.cs @@ -28,6 +28,7 @@ public BootstrapperException(string message, Exception innerException) : base(me { } +#if !DOTNET5_4 /// /// Initializes a new instance of the class. /// @@ -37,5 +38,6 @@ protected BootstrapperException(SerializationInfo info, StreamingContext context : base(info, context) { } +#endif } -} \ No newline at end of file +} diff --git a/src/Nancy/Bootstrapper/NancyBootstrapperBase.cs b/src/Nancy/Bootstrapper/NancyBootstrapperBase.cs index a99d6c034c..72e0a7ee85 100755 --- a/src/Nancy/Bootstrapper/NancyBootstrapperBase.cs +++ b/src/Nancy/Bootstrapper/NancyBootstrapperBase.cs @@ -307,7 +307,7 @@ public void Initialise() return null; } - if (String.Equals(ctx.Request.Path, "/favicon.ico", StringComparison.InvariantCultureIgnoreCase)) + if (String.Equals(ctx.Request.Path, "/favicon.ico", StringComparison.OrdinalIgnoreCase)) { var response = new Response { diff --git a/src/Nancy/DefaultRuntimeEnvironmentInformation.cs b/src/Nancy/DefaultRuntimeEnvironmentInformation.cs index f437cac1c5..aadaa2f812 100644 --- a/src/Nancy/DefaultRuntimeEnvironmentInformation.cs +++ b/src/Nancy/DefaultRuntimeEnvironmentInformation.cs @@ -34,22 +34,7 @@ private static bool GetDebugMode(ITypeCatalog typeCatalog) { try { - var assembliesInDebug = typeCatalog - .GetTypesAssignableTo(TypeResolveStrategies.ExcludeNancy) -#if DOTNET5_4 - .Select(x => x.GetTypeInfo().Assembly.GetCustomAttributes(typeof(DebuggableAttribute))) - .Where(x => x.Any()); - - return assembliesInDebug.Any(d => ((DebuggableAttribute)d.First()).IsJITTrackingEnabled); -#else - .Select(x => x.Assembly.GetCustomAttributes(typeof(DebuggableAttribute), true)) - .Where(x => x.Length != 0); - - return assembliesInDebug.Any(d => ((DebuggableAttribute)d[0]).IsJITTrackingEnabled); -#endif - - - + return Debugger.IsAttached; } catch { diff --git a/src/Nancy/Diagnostics/DiagnosticsSession.cs b/src/Nancy/Diagnostics/DiagnosticsSession.cs index 6a32cd0c28..efe3547683 100644 --- a/src/Nancy/Diagnostics/DiagnosticsSession.cs +++ b/src/Nancy/Diagnostics/DiagnosticsSession.cs @@ -27,7 +27,7 @@ public static byte[] GenerateRandomSalt() public static byte[] GenerateSaltedHash(byte[] plainText, byte[] salt) { - var algorithm = new SHA256Managed(); + var algorithm = SHA256.Create(); var plainTextWithSaltBytes = new byte[plainText.Length + salt.Length]; diff --git a/src/Nancy/Responses/EmbeddedFileResponse.cs b/src/Nancy/Responses/EmbeddedFileResponse.cs index 367360687f..59689fb08d 100644 --- a/src/Nancy/Responses/EmbeddedFileResponse.cs +++ b/src/Nancy/Responses/EmbeddedFileResponse.cs @@ -63,7 +63,7 @@ private static string GetFileNameFromResourceName(string resourcePath, string re private static string GenerateETag(Stream stream) { - using (var sha1 = new SHA1CryptoServiceProvider()) + using (var sha1 = SHA1.Create()) { var hash = sha1.ComputeHash(stream); return string.Concat("\"", ByteArrayToString(hash), "\""); From 01f0db7dc787cebec93e5e3ab79775625677a498 Mon Sep 17 00:00:00 2001 From: James Humphries Date: Fri, 19 Feb 2016 15:13:03 +0000 Subject: [PATCH 27/52] added IAssemblyCatalog to DiagnosticsModuleCatalog, updated infomodule to use assembly catalog instead of AppDomain --- src/Nancy/Diagnostics/DiagnosticsModuleCatalog.cs | 8 +++++--- src/Nancy/Diagnostics/Modules/InfoModule.cs | 12 +++++++----- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/src/Nancy/Diagnostics/DiagnosticsModuleCatalog.cs b/src/Nancy/Diagnostics/DiagnosticsModuleCatalog.cs index 479ac3aa82..83225e67fd 100644 --- a/src/Nancy/Diagnostics/DiagnosticsModuleCatalog.cs +++ b/src/Nancy/Diagnostics/DiagnosticsModuleCatalog.cs @@ -14,9 +14,9 @@ internal class DiagnosticsModuleCatalog : INancyModuleCatalog { private readonly TinyIoCContainer container; - public DiagnosticsModuleCatalog(IEnumerable providers, IRootPathProvider rootPathProvider, IRequestTracing requestTracing, NancyInternalConfiguration configuration, INancyEnvironment diagnosticsEnvironment, ITypeCatalog typeCatalog) + public DiagnosticsModuleCatalog(IEnumerable providers, IRootPathProvider rootPathProvider, IRequestTracing requestTracing, NancyInternalConfiguration configuration, INancyEnvironment diagnosticsEnvironment, ITypeCatalog typeCatalog, IAssemblyCatalog assemblyCatalog) { - this.container = ConfigureContainer(providers, rootPathProvider, requestTracing, configuration, diagnosticsEnvironment, typeCatalog); + this.container = ConfigureContainer(providers, rootPathProvider, requestTracing, configuration, diagnosticsEnvironment, typeCatalog, assemblyCatalog); } /// @@ -40,7 +40,7 @@ public INancyModule GetModule(Type moduleType, NancyContext context) return this.container.Resolve(moduleType.FullName); } - private static TinyIoCContainer ConfigureContainer(IEnumerable providers, IRootPathProvider rootPathProvider, IRequestTracing requestTracing, NancyInternalConfiguration configuration, INancyEnvironment diagnosticsEnvironment, ITypeCatalog typeCatalog) + private static TinyIoCContainer ConfigureContainer(IEnumerable providers, IRootPathProvider rootPathProvider, IRequestTracing requestTracing, NancyInternalConfiguration configuration, INancyEnvironment diagnosticsEnvironment, ITypeCatalog typeCatalog, IAssemblyCatalog assemblyCatalog) { var diagContainer = new TinyIoCContainer(); @@ -55,6 +55,8 @@ private static TinyIoCContainer ConfigureContainer(IEnumerable(diagnosticsEnvironment); diagContainer.Register(new DefaultJsonSerializer(diagnosticsEnvironment)); diagContainer.Register(typeCatalog); + diagContainer.Register(assemblyCatalog); + foreach (var diagnosticsProvider in providers) { diff --git a/src/Nancy/Diagnostics/Modules/InfoModule.cs b/src/Nancy/Diagnostics/Modules/InfoModule.cs index b717028532..4cb4ed4553 100644 --- a/src/Nancy/Diagnostics/Modules/InfoModule.cs +++ b/src/Nancy/Diagnostics/Modules/InfoModule.cs @@ -13,11 +13,13 @@ public class InfoModule : DiagnosticModule { private readonly ITypeCatalog typeCatalog; + private readonly IAssemblyCatalog assemblyCatalog; - public InfoModule(IRootPathProvider rootPathProvider, NancyInternalConfiguration configuration, INancyEnvironment environment, ITypeCatalog typeCatalog) + public InfoModule(IRootPathProvider rootPathProvider, NancyInternalConfiguration configuration, INancyEnvironment environment, ITypeCatalog typeCatalog, IAssemblyCatalog assemblyCatalog) : base("/info") { this.typeCatalog = typeCatalog; + this.assemblyCatalog = assemblyCatalog; Get("/", _ => { @@ -62,9 +64,9 @@ private string[] GetViewEngines() .ToArray(); } - private static string GetBootstrapperContainer() + private string GetBootstrapperContainer() { - var name = AppDomain.CurrentDomain + var name = this.assemblyCatalog .GetAssemblies() .Select(asm => asm.GetName()) .FirstOrDefault(asmName => asmName.Name != null && asmName.Name.StartsWith("Nancy.Bootstrappers.")); @@ -74,9 +76,9 @@ private static string GetBootstrapperContainer() string.Format("{0} (v{1})", name.Name.Split('.').Last(), name.Version); } - private static string GetHosting() + private string GetHosting() { - var name = AppDomain.CurrentDomain + var name = this.assemblyCatalog .GetAssemblies() .Select(asm => asm.GetName()) .FirstOrDefault(asmName => asmName.Name != null && asmName.Name.StartsWith("Nancy.Hosting.")); From c3408bd159db9c373bf53dce051d0a4bcf05654f Mon Sep 17 00:00:00 2001 From: Jonathan Channon Date: Fri, 19 Feb 2016 21:22:41 +0000 Subject: [PATCH 28/52] removed GetRawCertData error by passing X509Certificate2 directly through instead of byte[] --- src/Nancy.Hosting.Aspnet/NancyHandler.cs | 3 ++- src/Nancy.Hosting.Self/NancyHost.cs | 5 +++-- src/Nancy.Testing/Browser.cs | 4 +--- src/Nancy/Owin/NancyMiddleware.cs | 6 +++--- src/Nancy/Request.cs | 6 +++--- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/Nancy.Hosting.Aspnet/NancyHandler.cs b/src/Nancy.Hosting.Aspnet/NancyHandler.cs index c5ef11b318..14a1819639 100644 --- a/src/Nancy.Hosting.Aspnet/NancyHandler.cs +++ b/src/Nancy.Hosting.Aspnet/NancyHandler.cs @@ -4,6 +4,7 @@ namespace Nancy.Hosting.Aspnet using System.Configuration; using System.Globalization; using System.Linq; + using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using System.Web; @@ -84,7 +85,7 @@ private static Request CreateNancyRequest(HttpContextBase context) body, incomingHeaders, context.Request.UserHostAddress, - certificate, + new X509Certificate2(certificate), protocolVersion); } diff --git a/src/Nancy.Hosting.Self/NancyHost.cs b/src/Nancy.Hosting.Self/NancyHost.cs index d04601f16b..30fa48b75a 100644 --- a/src/Nancy.Hosting.Self/NancyHost.cs +++ b/src/Nancy.Hosting.Self/NancyHost.cs @@ -6,6 +6,7 @@ using System.IO; using System.Linq; using System.Net; + using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.Threading.Tasks; using Nancy.Bootstrapper; @@ -264,7 +265,7 @@ private Request ConvertRequestToNancyRequest(HttpListenerRequest request) Query = request.Url.Query, }; - byte[] certificate = null; + X509Certificate2 certificate = null; if (this.configuration.EnableClientCertificates) { @@ -272,7 +273,7 @@ private Request ConvertRequestToNancyRequest(HttpListenerRequest request) if (x509Certificate != null) { - certificate = x509Certificate.RawData; + certificate = x509Certificate; } } diff --git a/src/Nancy.Testing/Browser.cs b/src/Nancy.Testing/Browser.cs index 0fbf6cd89d..5ca9fdad9a 100644 --- a/src/Nancy.Testing/Browser.cs +++ b/src/Nancy.Testing/Browser.cs @@ -326,9 +326,7 @@ private static Request CreateRequest(string method, Url url, IBrowserContextValu var requestStream = RequestStream.FromStream(contextValues.Body, 0, true); - var certBytes = (contextValues.ClientCertificate == null) - ? ArrayCache.Empty() - : contextValues.ClientCertificate.GetRawCertData(); + var certBytes = contextValues.ClientCertificate ?? null; var requestUrl = url; requestUrl.Scheme = string.IsNullOrWhiteSpace(contextValues.Protocol) ? requestUrl.Scheme : contextValues.Protocol; diff --git a/src/Nancy/Owin/NancyMiddleware.cs b/src/Nancy/Owin/NancyMiddleware.cs index 9944e47311..c5dde06999 100644 --- a/src/Nancy/Owin/NancyMiddleware.cs +++ b/src/Nancy/Owin/NancyMiddleware.cs @@ -70,11 +70,11 @@ public static MidFunc UseNancy(NancyOptions options = null) var owinRequestHost = GetHeader(owinRequestHeaders, "Host") ?? Dns.GetHostName(); var owinUser = GetUser(environment); - byte[] certificate = null; + X509Certificate2 certificate = null; if (options.EnableClientCertificates) { - var clientCertificate = Get(environment, "ssl.ClientCertificate"); - certificate = (clientCertificate == null) ? null : clientCertificate.GetRawCertData(); + var clientCertificate = Get(environment, "ssl.ClientCertificate"); + certificate = clientCertificate ?? null; } var serverClientIp = Get(environment, "server.RemoteIpAddress"); diff --git a/src/Nancy/Request.cs b/src/Nancy/Request.cs index 32eb004251..6d16f518eb 100644 --- a/src/Nancy/Request.cs +++ b/src/Nancy/Request.cs @@ -50,7 +50,7 @@ public Request(string method, RequestStream body = null, IDictionary> headers = null, string ip = null, - byte[] certificate = null, + X509Certificate certificate = null, string protocolVersion = null) { if (string.IsNullOrEmpty(method)) @@ -87,9 +87,9 @@ public Request(string method, this.Session = new NullSessionProvider(); - if (certificate != null && certificate.Length != 0) + if (certificate != null) { - this.ClientCertificate = new X509Certificate2(certificate); + this.ClientCertificate = certificate; } this.ProtocolVersion = protocolVersion ?? string.Empty; From 436ec4a3d6236ee9f655a8eb063d483ad2fcba3f Mon Sep 17 00:00:00 2001 From: James Humphries Date: Mon, 22 Feb 2016 08:02:15 +0000 Subject: [PATCH 29/52] added IAssemblyCatalog to the ctor calld in DiagnosticsHook --- src/Nancy/Diagnostics/DiagnosticsHook.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Nancy/Diagnostics/DiagnosticsHook.cs b/src/Nancy/Diagnostics/DiagnosticsHook.cs index d8524b796b..9d7ed3ec8a 100644 --- a/src/Nancy/Diagnostics/DiagnosticsHook.cs +++ b/src/Nancy/Diagnostics/DiagnosticsHook.cs @@ -19,7 +19,7 @@ namespace Nancy.Diagnostics using Nancy.Routing; using Nancy.Routing.Constraints; using Nancy.Routing.Trie; - + /// /// Pipeline hook to handle diagnostics dashboard requests. /// @@ -41,7 +41,7 @@ public static void Enable(IPipelines pipelines, IEnumerable Date: Mon, 22 Feb 2016 12:39:13 +0000 Subject: [PATCH 30/52] added owin test to verify ssl certificate creation from environment --- src/Nancy/Owin/NancyMiddleware.cs | 8 +-- .../AppBuilderExtensionsFixture.cs | 66 ++++++++++++++++++- 2 files changed, 67 insertions(+), 7 deletions(-) diff --git a/src/Nancy/Owin/NancyMiddleware.cs b/src/Nancy/Owin/NancyMiddleware.cs index c5dde06999..d166faf1c2 100644 --- a/src/Nancy/Owin/NancyMiddleware.cs +++ b/src/Nancy/Owin/NancyMiddleware.cs @@ -68,12 +68,12 @@ public static MidFunc UseNancy(NancyOptions options = null) var owinRequestProtocol = Get(environment, "owin.RequestProtocol"); var owinCallCancelled = Get(environment, "owin.CallCancelled"); var owinRequestHost = GetHeader(owinRequestHeaders, "Host") ?? Dns.GetHostName(); - var owinUser = GetUser(environment); + var owinUser = GetUser(environment); X509Certificate2 certificate = null; if (options.EnableClientCertificates) { - var clientCertificate = Get(environment, "ssl.ClientCertificate"); + var clientCertificate = new X509Certificate2(Get(environment, "ssl.ClientCertificate").Export(X509ContentType.Cert)); certificate = clientCertificate ?? null; } @@ -133,12 +133,12 @@ private static Task RequestComplete( foreach (var responseHeader in nancyResponse.Headers) { - owinResponseHeaders[responseHeader.Key] = new[] {responseHeader.Value}; + owinResponseHeaders[responseHeader.Key] = new[] { responseHeader.Value }; } if (!string.IsNullOrWhiteSpace(nancyResponse.ContentType)) { - owinResponseHeaders["Content-Type"] = new[] {nancyResponse.ContentType}; + owinResponseHeaders["Content-Type"] = new[] { nancyResponse.ContentType }; } if (nancyResponse.Cookies != null && nancyResponse.Cookies.Count != 0) diff --git a/test/Nancy.Owin.Tests/AppBuilderExtensionsFixture.cs b/test/Nancy.Owin.Tests/AppBuilderExtensionsFixture.cs index aa3ca3762f..d22a90a5f1 100644 --- a/test/Nancy.Owin.Tests/AppBuilderExtensionsFixture.cs +++ b/test/Nancy.Owin.Tests/AppBuilderExtensionsFixture.cs @@ -1,7 +1,11 @@ namespace Nancy.Owin.Tests { using System; - + using System.Collections.Generic; + using System.IO; + using System.Reflection; + using System.Security.Cryptography.X509Certificates; + using System.Text; using global::Owin; using Microsoft.Owin.Testing; @@ -21,7 +25,7 @@ public void When_host_Nancy_via_IAppBuilder_then_should_handle_requests() // Given var bootstrapper = new ConfigurableBootstrapper(config => config.Module()); - using(var server = TestServer.Create(app => app.UseNancy(opts => opts.Bootstrapper = bootstrapper))) + using (var server = TestServer.Create(app => app.UseNancy(opts => opts.Bootstrapper = bootstrapper))) { // When var response = server.HttpClient.GetAsync(new Uri("http://localhost/")).Result; @@ -30,13 +34,69 @@ public void When_host_Nancy_via_IAppBuilder_then_should_handle_requests() Assert.Equal(response.StatusCode, System.Net.HttpStatusCode.OK); } } + + [Fact] + public void When_host_Nancy_via_IAppBuilder_should_read_X509Certificate2() + { + // Given + var bootstrapper = new ConfigurableBootstrapper(config => config.Module()); + + + using (var server = TestServer.Create(app => app.UseNancy(opts => + { + opts.Bootstrapper = bootstrapper; + opts.EnableClientCertificates = true; + }))) + { + // When + var cert = @"-----BEGIN CERTIFICATE----- + MIICNTCCAZ4CCQC21XwOAYG32zANBgkqhkiG9w0BAQUFADBfMQswCQYDVQQGEwJH + QjETMBEGA1UECBMKU29tZS1TdGF0ZTEOMAwGA1UEChMFTmFuY3kxDjAMBgNVBAsT + BU5hbmN5MRswGQYDVQQDExJodHRwOi8vbmFuY3lmeC5vcmcwHhcNMTYwMjIyMTE1 + NzQ3WhcNMTcwMjIxMTE1NzQ3WjBfMQswCQYDVQQGEwJHQjETMBEGA1UECBMKU29t + ZS1TdGF0ZTEOMAwGA1UEChMFTmFuY3kxDjAMBgNVBAsTBU5hbmN5MRswGQYDVQQD + ExJodHRwOi8vbmFuY3lmeC5vcmcwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGB + AMT4vOtIH9Fzad+8KCGjMPkkVpCtn+L5H97bnI3x+y3x5lY0WRsK8FyxVshY/7fv + TDeeVKUWanmbMkQjgFRYffA3ep3/AIguswYdANiNVHrx0L7DXNDcgsjRwaa6JVgQ + 9iavlli0a80AF67FN1wfidlHCX53u3/fAjiSTwf7D+NBAgMBAAEwDQYJKoZIhvcN + AQEFBQADgYEAh12A4NntHHdVMGaw+2umXkWqCOyAPuNhyBGUHK5vGON+VG0HPFaf + 8P8eMtdF4deBHkrfoWxRuGGn2tJzNpZLiEf23BAivEf36IqwfkVP7/zDwI+bjVXC + k64Un2uN8ALR/wLwfJzHfOLPtsca7ySWhlv8oZo2nk0vR34asQiGJDQ= + -----END CERTIFICATE----- + "; + + byte[] embeddedCert = Encoding.UTF8.GetBytes(cert); + + var env = new Dictionary() + { + { "owin.RequestPath", "/ssl" }, + { "owin.RequestScheme", "http" }, + { "owin.RequestHeaders", new Dictionary() { { "Host", new[] { "localhost" } } } }, + { "owin.RequestMethod", "GET" }, + {"ssl.ClientCertificate", new X509Certificate(embeddedCert) } + }; + server.Invoke(env); + + + // Then + Assert.Equal(env["owin.ResponseStatusCode"], 200); + } + } #endif public class TestModule : NancyModule { public TestModule() { - Get("/", args => HttpStatusCode.OK); + Get["/"] = _ => + { + return HttpStatusCode.OK; + }; + + Get("/ssl", args => + { + return this.Request.ClientCertificate != null ? 200 : 500; + }); } } } From 0200e76847eec000a01f3ae44592380e3ed86a8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20H=C3=A5kansson?= Date: Tue, 23 Feb 2016 08:35:46 +0100 Subject: [PATCH 31/52] Changed TypeConverter.IsValid to TypeConvert.CanConvertFrom --- src/Nancy/DynamicDictionaryValue.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Nancy/DynamicDictionaryValue.cs b/src/Nancy/DynamicDictionaryValue.cs index 16376702ff..00f50c99bf 100644 --- a/src/Nancy/DynamicDictionaryValue.cs +++ b/src/Nancy/DynamicDictionaryValue.cs @@ -122,7 +122,7 @@ public object Value { var converter = TypeDescriptor.GetConverter(parseType); - if (converter.IsValid(stringValue)) + if (converter.CanConvertFrom(typeof(string))) { return (T) converter.ConvertFromInvariantString(stringValue); } From d7922f08bf7041878f521ad9229ec29967d118ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20H=C3=A5kansson?= Date: Tue, 23 Feb 2016 09:13:45 +0100 Subject: [PATCH 32/52] Fixed GetProperties with System.Reflection.TypeExtensions --- src/Nancy/ViewEngines/DefaultViewFactory.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Nancy/ViewEngines/DefaultViewFactory.cs b/src/Nancy/ViewEngines/DefaultViewFactory.cs index f3f81c0e7c..887dd17e6a 100644 --- a/src/Nancy/ViewEngines/DefaultViewFactory.cs +++ b/src/Nancy/ViewEngines/DefaultViewFactory.cs @@ -5,8 +5,8 @@ using System.Dynamic; using System.IO; using System.Linq; + using System.Reflection; using System.Text.RegularExpressions; - using Nancy.Conventions; /// @@ -101,7 +101,7 @@ private string[] GetInspectedLocations(string viewName, dynamic model, ViewLocat { var inspectedLocations = new List(); - foreach (var convention in conventions) + foreach (var convention in this.conventions) { try { @@ -115,6 +115,7 @@ private string[] GetInspectedLocations(string viewName, dynamic model, ViewLocat } catch { + // ignored } } From 5580ab3dd8e9a54cfe430306528547c19ace1c7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20H=C3=A5kansson?= Date: Tue, 23 Feb 2016 14:57:23 +0100 Subject: [PATCH 33/52] Changed DiagnosticsSession to use DateTimeOffset --- src/Nancy/Diagnostics/DiagnosticsHook.cs | 2 +- src/Nancy/Diagnostics/DiagnosticsSession.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Nancy/Diagnostics/DiagnosticsHook.cs b/src/Nancy/Diagnostics/DiagnosticsHook.cs index 9d7ed3ec8a..69b39bf940 100644 --- a/src/Nancy/Diagnostics/DiagnosticsHook.cs +++ b/src/Nancy/Diagnostics/DiagnosticsHook.cs @@ -244,7 +244,7 @@ private static DiagnosticsSession GetSession(NancyContext context, DiagnosticsCo var decryptedValue = diagnosticsConfiguration.CryptographyConfiguration.EncryptionProvider.Decrypt(encryptedSession); var session = serializer.Deserialize(decryptedValue) as DiagnosticsSession; - if (session == null || session.Expiry < DateTime.Now || !SessionPasswordValid(session, diagnosticsConfiguration.Password)) + if (session == null || session.Expiry < DateTimeOffset.Now || !SessionPasswordValid(session, diagnosticsConfiguration.Password)) { return null; } diff --git a/src/Nancy/Diagnostics/DiagnosticsSession.cs b/src/Nancy/Diagnostics/DiagnosticsSession.cs index efe3547683..612c0e6c9c 100644 --- a/src/Nancy/Diagnostics/DiagnosticsSession.cs +++ b/src/Nancy/Diagnostics/DiagnosticsSession.cs @@ -13,7 +13,7 @@ public class DiagnosticsSession public byte[] Salt { get; set; } - public DateTime Expiry { get; set; } + public DateTimeOffset Expiry { get; set; } public static byte[] GenerateRandomSalt() { From 853275db2e35ad9fd9e18cbf3973f787b43718e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20H=C3=A5kansson?= Date: Tue, 23 Feb 2016 16:07:18 +0100 Subject: [PATCH 34/52] Changed Csrf token validation to use DateTimeOffset --- src/Nancy/Security/Csrf.cs | 3 ++- src/Nancy/Security/CsrfToken.cs | 2 +- src/Nancy/Security/CsrfTokenExtensions.cs | 2 +- src/Nancy/Security/DefaultCsrfTokenValidator.cs | 2 +- test/Nancy.Tests/Unit/Security/CsrfFixture.cs | 12 ++++++------ 5 files changed, 11 insertions(+), 10 deletions(-) diff --git a/src/Nancy/Security/Csrf.cs b/src/Nancy/Security/Csrf.cs index 8faf6cac68..88b3f0d2da 100644 --- a/src/Nancy/Security/Csrf.cs +++ b/src/Nancy/Security/Csrf.cs @@ -93,8 +93,9 @@ internal static string GenerateTokenString(CryptographyConfiguration cryptograph cryptographyConfiguration = cryptographyConfiguration ?? CsrfApplicationStartup.CryptographyConfiguration; var token = new CsrfToken { - CreatedDate = DateTime.Now, + CreatedDate = DateTimeOffset.Now, }; + token.CreateRandomBytes(); token.CreateHmac(cryptographyConfiguration.HmacProvider); var tokenString = CsrfApplicationStartup.ObjectSerializer.Serialize(token); diff --git a/src/Nancy/Security/CsrfToken.cs b/src/Nancy/Security/CsrfToken.cs index b48fb51115..5c6333939c 100644 --- a/src/Nancy/Security/CsrfToken.cs +++ b/src/Nancy/Security/CsrfToken.cs @@ -24,7 +24,7 @@ public sealed class CsrfToken /// /// Date and time the token was created /// - public DateTime CreatedDate { get; set; } + public DateTimeOffset CreatedDate { get; set; } /// /// Tamper prevention hmac diff --git a/src/Nancy/Security/CsrfTokenExtensions.cs b/src/Nancy/Security/CsrfTokenExtensions.cs index 8388f6ca57..cb5be887d0 100644 --- a/src/Nancy/Security/CsrfTokenExtensions.cs +++ b/src/Nancy/Security/CsrfTokenExtensions.cs @@ -19,7 +19,7 @@ public static class CsrfTokenExtensions public static byte[] GetCsrfTokenBytes(this CsrfToken token) { return token.RandomBytes - .Concat(BitConverter.GetBytes(token.CreatedDate.Ticks)) + .Concat(BitConverter.GetBytes(token.CreatedDate.UtcTicks)) .ToArray(); } diff --git a/src/Nancy/Security/DefaultCsrfTokenValidator.cs b/src/Nancy/Security/DefaultCsrfTokenValidator.cs index 473e1af7f8..e982ae81b9 100644 --- a/src/Nancy/Security/DefaultCsrfTokenValidator.cs +++ b/src/Nancy/Security/DefaultCsrfTokenValidator.cs @@ -61,7 +61,7 @@ public DefaultCsrfTokenValidator(CryptographyConfiguration cryptoConfig) { var expiryDate = tokenOne.CreatedDate.Add(validityPeriod.Value); - if (DateTime.Now > expiryDate) + if (DateTimeOffset.Now > expiryDate) { return CsrfTokenValidationResult.TokenExpired; } diff --git a/test/Nancy.Tests/Unit/Security/CsrfFixture.cs b/test/Nancy.Tests/Unit/Security/CsrfFixture.cs index cc29e51863..c167d8079c 100644 --- a/test/Nancy.Tests/Unit/Security/CsrfFixture.cs +++ b/test/Nancy.Tests/Unit/Security/CsrfFixture.cs @@ -18,17 +18,17 @@ public class CsrfFixture { private readonly IPipelines pipelines; - + private readonly Request request; private readonly FakeRequest optionsRequest; - + private readonly Response response; private readonly CryptographyConfiguration cryptographyConfiguration; private readonly DefaultObjectSerializer objectSerializer; - + public CsrfFixture() { @@ -90,7 +90,7 @@ public void Should_copy_request_cookie_to_context_but_not_response_if_it_exists_ public void Should_not_generate_a_new_token_on_an_options_request_and_not_add_a_cookie() { this.optionsRequest.Cookies.Add(CsrfToken.DEFAULT_CSRF_KEY, "ValidToken"); - + var fakeValidator = A.Fake(); A.CallTo(() => fakeValidator.CookieTokenStillValid(A.Ignored)).Returns(true); var csrfStartup = new CsrfApplicationStartup( @@ -182,7 +182,7 @@ public void ValidateCsrfToken_gets_provided_token_from_form_data() var token = Csrf.GenerateTokenString(); var context = new NancyContext { Request = this.request }; var module = new FakeNancyModule { Context = context }; - + // When context.Request.Form[CsrfToken.DEFAULT_CSRF_KEY] = token; context.Request.Cookies.Add(CsrfToken.DEFAULT_CSRF_KEY, token); @@ -198,7 +198,7 @@ public void ValidateCsrfToken_gets_provided_token_from_request_header_if_not_pre var token = Csrf.GenerateTokenString(); var context = new NancyContext(); var module = new FakeNancyModule { Context = context }; - + // When context.Request = RequestWithHeader(CsrfToken.DEFAULT_CSRF_KEY, token); context.Request.Cookies.Add(CsrfToken.DEFAULT_CSRF_KEY, token); From d7d220e39207a3c25f78ad1cc675307b054861d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20H=C3=A5kansson?= Date: Tue, 23 Feb 2016 23:58:16 +0100 Subject: [PATCH 35/52] Removed use of IAssemblyCatalog in DefaultObjectSerializer --- .../DemoBootstrapper.cs | 2 +- src/Nancy/DefaultObjectSerializer.cs | 46 +++++-------------- src/Nancy/Diagnostics/DiagnosticsHook.cs | 2 +- src/Nancy/Session/CookieBasedSessions.cs | 17 ++----- test/Nancy.Testing.Tests/BrowserFixture.cs | 3 +- .../CustomInteractiveDiagnosticsFixture.cs | 11 +---- .../Diagnostics/DiagnosticsHookFixture.cs | 11 +---- test/Nancy.Tests/Unit/Security/CsrfFixture.cs | 15 +----- .../Sessions/CookieBasedSessionsFixture.cs | 34 ++++++-------- .../DefaultSessionObjectFormatterFixture.cs | 13 ++---- 10 files changed, 40 insertions(+), 114 deletions(-) diff --git a/samples/Nancy.Demo.Hosting.Aspnet/DemoBootstrapper.cs b/samples/Nancy.Demo.Hosting.Aspnet/DemoBootstrapper.cs index 20177e0525..45f2f63dd5 100644 --- a/samples/Nancy.Demo.Hosting.Aspnet/DemoBootstrapper.cs +++ b/samples/Nancy.Demo.Hosting.Aspnet/DemoBootstrapper.cs @@ -67,7 +67,7 @@ protected override void ApplicationStartup(TinyIoCContainer container, IPipeline this.Conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("moo", "Content")); - CookieBasedSessions.Enable(pipelines, this.AssemblyCatalog); + CookieBasedSessions.Enable(pipelines); pipelines.AfterRequest += (ctx) => { diff --git a/src/Nancy/DefaultObjectSerializer.cs b/src/Nancy/DefaultObjectSerializer.cs index 9dc7a28bba..31ef70daac 100644 --- a/src/Nancy/DefaultObjectSerializer.cs +++ b/src/Nancy/DefaultObjectSerializer.cs @@ -3,28 +3,15 @@ namespace Nancy using Extensions; using System; using System.IO; - using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Text; - using Nancy.Extensions; /// /// Serializes/Deserializes objects for sessions /// public class DefaultObjectSerializer : IObjectSerializer { - private readonly IAssemblyCatalog assemblyCatalog; - - /// - /// Initializes a new instance of the class. - /// - /// - public DefaultObjectSerializer(IAssemblyCatalog assemblyCatalog) - { - this.assemblyCatalog = assemblyCatalog; - } - /// /// Serialize an object /// @@ -39,28 +26,18 @@ public string Serialize(object sourceObject) dynamic serializedObject = (sourceObject is string) ? sourceObject - : this.AddTypeInformation(sourceObject); + : AddTypeInformation(sourceObject); var json = SimpleJson.SerializeObject(serializedObject); return Convert.ToBase64String(Encoding.UTF8.GetBytes(json)); } - private dynamic AddTypeInformation(object sourceObject) + private static dynamic AddTypeInformation(object sourceObject) { - var sourceType = this.assemblyCatalog.GetAssemblies().Select(assembly => assembly.GetType(sourceObject.GetType().FullName)).FirstOrDefault(type => type != null); - if (sourceType == null) - { - throw new SerializationException("Unable to find type " + sourceObject.GetType() + " in its assembly to serialize"); - } - - dynamic serializedObject = null; + var assemblyQualifiedName = sourceObject.GetType().GetTypeInfo().AssemblyQualifiedName; - var assemblyQualifiedName = sourceType.GetTypeInfo().AssemblyQualifiedName; - if (!string.IsNullOrWhiteSpace(assemblyQualifiedName)) - { - serializedObject = sourceObject.ToDynamic(); - serializedObject.TypeObject = assemblyQualifiedName; - } + dynamic serializedObject = sourceObject.ToDynamic(); + serializedObject.TypeObject = assemblyQualifiedName; return serializedObject; } @@ -82,13 +59,14 @@ public object Deserialize(string sourceString) var inputBytes = Convert.FromBase64String(sourceString); var json = Encoding.UTF8.GetString(inputBytes); - if (ContainsTypeDescription(json)) + if (!ContainsTypeDescription(json)) { - dynamic serializedObject = SimpleJson.DeserializeObject(json); - var actual = SimpleJson.DeserializeObject(json, Type.GetType(serializedObject.TypeObject)); - return actual; + return SimpleJson.DeserializeObject(json); } - return SimpleJson.DeserializeObject(json); + + dynamic serializedObject = SimpleJson.DeserializeObject(json); + + return SimpleJson.DeserializeObject(json, Type.GetType(serializedObject.TypeObject)); } catch (FormatException) { @@ -109,4 +87,4 @@ private static bool ContainsTypeDescription(string json) return json.Contains("TypeObject"); } } -} \ No newline at end of file +} diff --git a/src/Nancy/Diagnostics/DiagnosticsHook.cs b/src/Nancy/Diagnostics/DiagnosticsHook.cs index 69b39bf940..5ce308a7fb 100644 --- a/src/Nancy/Diagnostics/DiagnosticsHook.cs +++ b/src/Nancy/Diagnostics/DiagnosticsHook.cs @@ -58,7 +58,7 @@ public static void Enable(IPipelines pipelines, IEnumerable>( diff --git a/src/Nancy/Session/CookieBasedSessions.cs b/src/Nancy/Session/CookieBasedSessions.cs index b8dc3cef8b..46be9ffda1 100644 --- a/src/Nancy/Session/CookieBasedSessions.cs +++ b/src/Nancy/Session/CookieBasedSessions.cs @@ -23,10 +23,7 @@ public class CookieBasedSessions : IObjectSerializerSelector /// Cookie name public string CookieName { - get - { - return this.currentConfiguration.CookieName; - } + get { return this.currentConfiguration.CookieName; } } /// @@ -62,8 +59,6 @@ public CookieBasedSessions(CookieBasedSessionsConfiguration configuration) this.currentConfiguration = configuration; } - - /// /// Initialise and add cookie based session hooks to the application pipeline /// @@ -90,13 +85,12 @@ public static IObjectSerializerSelector Enable(IPipelines pipelines, CookieBased /// /// Application pipelines /// Cryptography configuration - /// Assembly catalog /// Formatter selector for choosing a non-default serializer - public static IObjectSerializerSelector Enable(IPipelines pipelines, CryptographyConfiguration cryptographyConfiguration, IAssemblyCatalog assemblyCatalog) + public static IObjectSerializerSelector Enable(IPipelines pipelines, CryptographyConfiguration cryptographyConfiguration) { var cookieBasedSessionsConfiguration = new CookieBasedSessionsConfiguration(cryptographyConfiguration) { - Serializer = new DefaultObjectSerializer(assemblyCatalog) + Serializer = new DefaultObjectSerializer() }; return Enable(pipelines, cookieBasedSessionsConfiguration); } @@ -105,13 +99,12 @@ public static IObjectSerializerSelector Enable(IPipelines pipelines, Cryptograph /// Initialise and add cookie based session hooks to the application pipeline with the default encryption provider. /// /// Application pipelines - /// Assembly catalog /// Formatter selector for choosing a non-default serializer - public static IObjectSerializerSelector Enable(IPipelines pipelines, IAssemblyCatalog assemblyCatalog) + public static IObjectSerializerSelector Enable(IPipelines pipelines) { return Enable(pipelines, new CookieBasedSessionsConfiguration { - Serializer = new DefaultObjectSerializer(assemblyCatalog) + Serializer = new DefaultObjectSerializer() }); } diff --git a/test/Nancy.Testing.Tests/BrowserFixture.cs b/test/Nancy.Testing.Tests/BrowserFixture.cs index dbbe7abb9b..fcb0a59ae0 100644 --- a/test/Nancy.Testing.Tests/BrowserFixture.cs +++ b/test/Nancy.Testing.Tests/BrowserFixture.cs @@ -13,7 +13,6 @@ namespace Nancy.Testing.Tests using Nancy.Session; using Nancy.Tests; using Nancy.Authentication.Forms; - using Nancy.Bootstrapper; using Nancy.Configuration; using Nancy.Tests.xUnitExtensions; using Xunit; @@ -28,7 +27,7 @@ public BrowserFixture() var bootstrapper = new ConfigurableBootstrapper(config => config.Modules(typeof(EchoModule))); - CookieBasedSessions.Enable(bootstrapper, A.Fake()); + CookieBasedSessions.Enable(bootstrapper); this.browser = new Browser(bootstrapper); } diff --git a/test/Nancy.Tests/Unit/Diagnostics/CustomInteractiveDiagnosticsFixture.cs b/test/Nancy.Tests/Unit/Diagnostics/CustomInteractiveDiagnosticsFixture.cs index da2775dcc8..41fa173af7 100644 --- a/test/Nancy.Tests/Unit/Diagnostics/CustomInteractiveDiagnosticsFixture.cs +++ b/test/Nancy.Tests/Unit/Diagnostics/CustomInteractiveDiagnosticsFixture.cs @@ -3,9 +3,7 @@ using System; using System.Collections.Generic; using System.Linq; - using System.Reflection; using System.Threading.Tasks; - using FakeItEasy; using Nancy.Bootstrapper; using Nancy.Configuration; using Nancy.Cryptography; @@ -28,14 +26,7 @@ public class CustomInteractiveDiagnosticsHookFixture public CustomInteractiveDiagnosticsHookFixture() { this.cryptoConfig = CryptographyConfiguration.Default; - var fakeAssemblyCatalog = A.Fake(); - A.CallTo(() => fakeAssemblyCatalog.GetAssemblies(AssemblyResolveStrategies.All)) - .Returns(new[] - { - typeof(CustomInteractiveDiagnosticsHookFixture).GetTypeInfo().Assembly, - typeof(DiagnosticsSession).GetTypeInfo().Assembly - }); - this.objectSerializer = new DefaultObjectSerializer(fakeAssemblyCatalog); + this.objectSerializer = new DefaultObjectSerializer(); } private class FakeDiagnostics : IDiagnostics diff --git a/test/Nancy.Tests/Unit/Diagnostics/DiagnosticsHookFixture.cs b/test/Nancy.Tests/Unit/Diagnostics/DiagnosticsHookFixture.cs index 4381cacb91..8729b7b3b5 100644 --- a/test/Nancy.Tests/Unit/Diagnostics/DiagnosticsHookFixture.cs +++ b/test/Nancy.Tests/Unit/Diagnostics/DiagnosticsHookFixture.cs @@ -15,22 +15,13 @@ public class DiagnosticsHookFixture { private const string DiagsCookieName = "__ncd"; - private readonly CryptographyConfiguration cryptoConfig; - private readonly IObjectSerializer objectSerializer; public DiagnosticsHookFixture() { this.cryptoConfig = CryptographyConfiguration.Default; - var fakeAssemblyCatalog = A.Fake(); - A.CallTo(() => fakeAssemblyCatalog.GetAssemblies(AssemblyResolveStrategies.All)) - .Returns(new[] - { - typeof(DiagnosticsHookFixture).GetTypeInfo().Assembly, - typeof(DiagnosticsSession).GetTypeInfo().Assembly - }); - this.objectSerializer = new DefaultObjectSerializer(fakeAssemblyCatalog); + this.objectSerializer = new DefaultObjectSerializer(); } #if DEBUG diff --git a/test/Nancy.Tests/Unit/Security/CsrfFixture.cs b/test/Nancy.Tests/Unit/Security/CsrfFixture.cs index c167d8079c..a41218623a 100644 --- a/test/Nancy.Tests/Unit/Security/CsrfFixture.cs +++ b/test/Nancy.Tests/Unit/Security/CsrfFixture.cs @@ -2,14 +2,10 @@ { using System.Collections.Generic; using System.Linq; - using System.Reflection; using System.Threading; - using FakeItEasy; - using Nancy.Bootstrapper; using Nancy.Cryptography; - using Nancy.Helpers; using Nancy.Security; using Nancy.Tests.Fakes; @@ -18,27 +14,18 @@ public class CsrfFixture { private readonly IPipelines pipelines; - private readonly Request request; - private readonly FakeRequest optionsRequest; - private readonly Response response; - private readonly CryptographyConfiguration cryptographyConfiguration; - private readonly DefaultObjectSerializer objectSerializer; - public CsrfFixture() { this.pipelines = new MockPipelines(); this.cryptographyConfiguration = CryptographyConfiguration.Default; - var fakeAssemblyCatalog = A.Fake(); - A.CallTo(() => fakeAssemblyCatalog.GetAssemblies(AssemblyResolveStrategies.All)) - .Returns(new[] { typeof(CsrfFixture).GetTypeInfo().Assembly, typeof(CsrfToken).GetTypeInfo().Assembly }); - this.objectSerializer = new DefaultObjectSerializer(fakeAssemblyCatalog); + this.objectSerializer = new DefaultObjectSerializer(); var csrfStartup = new CsrfApplicationStartup( this.cryptographyConfiguration, this.objectSerializer, diff --git a/test/Nancy.Tests/Unit/Sessions/CookieBasedSessionsFixture.cs b/test/Nancy.Tests/Unit/Sessions/CookieBasedSessionsFixture.cs index eb1fc2bfe6..cd513cbd2d 100644 --- a/test/Nancy.Tests/Unit/Sessions/CookieBasedSessionsFixture.cs +++ b/test/Nancy.Tests/Unit/Sessions/CookieBasedSessionsFixture.cs @@ -26,14 +26,9 @@ public class CookieBasedSessionsFixture private readonly CookieBasedSessions cookieStore; private readonly IHmacProvider fakeHmacProvider; private readonly IObjectSerializer fakeObjectSerializer; - - private AesEncryptionProvider aesEncryptionProvider; - - private DefaultHmacProvider defaultHmacProvider; - - private IObjectSerializer defaultObjectSerializer; - - private IAssemblyCatalog assemblyCatalog; + private readonly AesEncryptionProvider aesEncryptionProvider; + private readonly DefaultHmacProvider defaultHmacProvider; + private readonly IObjectSerializer defaultObjectSerializer; public CookieBasedSessionsFixture() { @@ -44,10 +39,7 @@ public CookieBasedSessionsFixture() this.aesEncryptionProvider = new AesEncryptionProvider(new PassphraseKeyGenerator("password", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000)); this.defaultHmacProvider = new DefaultHmacProvider(new PassphraseKeyGenerator("anotherpassword", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000)); - this.assemblyCatalog = A.Fake(); - A.CallTo(() => this.assemblyCatalog.GetAssemblies(AssemblyResolveStrategies.All)) - .Returns(new[] { typeof(CookieBasedSessionsFixture).GetTypeInfo().Assembly }); - this.defaultObjectSerializer = new DefaultObjectSerializer(this.assemblyCatalog); + this.defaultObjectSerializer = new DefaultObjectSerializer(); } [Fact] @@ -56,7 +48,7 @@ public void Should_save_nothing_if_the_session_is_null() var response = new Response(); cookieStore.Save(null, response); - + response.Cookies.Count.ShouldEqual(0); } @@ -76,7 +68,7 @@ public void Should_save_the_session_cookie() var response = new Response(); var session = new Session(new Dictionary { - {"key1", "val1"}, + {"key1", "val1"}, }); session["key2"] = "val2"; A.CallTo(() => this.fakeEncryptionProvider.Encrypt("key1=val1;key2=val2;")).Returns("encrypted=key1=val1;key2=val2;"); @@ -124,7 +116,7 @@ public void Should_load_an_empty_session_if_no_session_cookie_exists() var request = CreateRequest(null); var result = cookieStore.Load(request); - + result.Count.ShouldEqual(0); } @@ -191,7 +183,7 @@ public void Should_add_pre_and_post_hooks_when_enabled() A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline); A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline); - CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider), this.assemblyCatalog); + CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider)); beforePipeline.PipelineDelegates.Count().ShouldEqual(1); afterPipeline.PipelineItems.Count().ShouldEqual(1); @@ -205,7 +197,7 @@ public void Should_only_not_add_response_cookie_if_it_has_not_changed() var hooks = A.Fake(); A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline); A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline); - CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider), this.assemblyCatalog).WithSerializer(this.fakeObjectSerializer); + CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider)).WithSerializer(this.fakeObjectSerializer); var request = CreateRequest("encryptedkey1=value1"); A.CallTo(() => this.fakeEncryptionProvider.Decrypt("encryptedkey1=value1")).Returns("key1=value1;"); var response = A.Fake(); @@ -225,7 +217,7 @@ public void Should_add_response_cookie_if_it_has_changed() var hooks = A.Fake(); A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline); A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline); - CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider), this.assemblyCatalog).WithSerializer(this.fakeObjectSerializer); + CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider)).WithSerializer(this.fakeObjectSerializer); var request = CreateRequest("encryptedkey1=value1"); A.CallTo(() => this.fakeEncryptionProvider.Decrypt("encryptedkey1=value1")).Returns("key1=value1;"); var response = A.Fake(); @@ -275,7 +267,7 @@ public void Should_set_formatter_when_using_formatter_selector() A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline); var fakeFormatter = A.Fake(); A.CallTo(() => this.fakeEncryptionProvider.Decrypt("encryptedkey1=value1")).Returns("key1=value1;"); - CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider), this.assemblyCatalog).WithSerializer(fakeFormatter); + CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider)).WithSerializer(fakeFormatter); var request = CreateRequest("encryptedkey1=value1"); var nancyContext = new NancyContext() { Request = request }; @@ -325,7 +317,7 @@ public void Should_encrypt_data() var response = new Response(); var session = new Session(new Dictionary { - {"key1", "val1"}, + {"key1", "val1"}, }); session["key2"] = "val2"; @@ -341,7 +333,7 @@ public void Should_generate_hmac() var response = new Response(); var session = new Session(new Dictionary { - {"key1", "val1"}, + {"key1", "val1"}, }); session["key2"] = "val2"; diff --git a/test/Nancy.Tests/Unit/Sessions/DefaultSessionObjectFormatterFixture.cs b/test/Nancy.Tests/Unit/Sessions/DefaultSessionObjectFormatterFixture.cs index e5f13e1390..4df5c7f98f 100644 --- a/test/Nancy.Tests/Unit/Sessions/DefaultSessionObjectFormatterFixture.cs +++ b/test/Nancy.Tests/Unit/Sessions/DefaultSessionObjectFormatterFixture.cs @@ -1,20 +1,15 @@ namespace Nancy.Tests.Unit.Sessions { using System; - using System.Reflection; - using FakeItEasy; using Xunit; public class DefaultSessionObjectFormatterFixture { - private DefaultObjectSerializer serializer; + private readonly DefaultObjectSerializer serializer; public DefaultSessionObjectFormatterFixture() { - var fakeAssemblyCatalog = A.Fake(); - A.CallTo(() => fakeAssemblyCatalog.GetAssemblies(AssemblyResolveStrategies.All)) - .Returns(new[] { typeof(DefaultSessionObjectFormatterFixture).GetTypeInfo().Assembly }); - this.serializer = new DefaultObjectSerializer(fakeAssemblyCatalog); + this.serializer = new DefaultObjectSerializer(); } [Fact] @@ -43,7 +38,7 @@ public void Should_serialize_and_deserialize_serializable_object() public void Should_return_empty_string_when_serializing_null() { object input = null; - + var output = this.serializer.Serialize(input); output.ShouldEqual(string.Empty); @@ -80,7 +75,7 @@ public class Payload : IEquatable public Payload() { - + } /// From 5d071d9a142838b7f6508d1ba75700ccb1dd3129 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20H=C3=A5kansson?= Date: Thu, 25 Feb 2016 11:11:13 +0100 Subject: [PATCH 36/52] Fixed build errors on dotnet5_4 --- src/Nancy/Bootstrapper/NancyBootstrapperLocator.cs | 6 +++--- src/Nancy/Extensions/TypeExtensions.cs | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Nancy/Bootstrapper/NancyBootstrapperLocator.cs b/src/Nancy/Bootstrapper/NancyBootstrapperLocator.cs index 78298507a6..d46a3a12e1 100755 --- a/src/Nancy/Bootstrapper/NancyBootstrapperLocator.cs +++ b/src/Nancy/Bootstrapper/NancyBootstrapperLocator.cs @@ -44,7 +44,7 @@ private static INancyBootstrapper LocateBootstrapper() private static IReadOnlyCollection GetAvailableBootstrapperTypes() { var assemblies = GetNancyReferencingAssemblies() - .Where(x => !x.IsDynamic && !x.ReflectionOnly) + .Where(x => !x.IsDynamic) .ToArray(); return assemblies @@ -61,7 +61,7 @@ private static IEnumerable GetNancyReferencingAssemblies() var results = new HashSet { - typeof (INancyEngine).Assembly + typeof (INancyEngine).GetAssembly() }; var referencingLibraries = libraryManager.GetReferencingLibraries(NancyAssemblyName.Name); @@ -79,7 +79,7 @@ private static IEnumerable GetNancyReferencingAssemblies() return results.ToArray(); #else - return AppDomain.CurrentDomain.GetAssemblies().Where(IsNancyReferencing); + return AppDomain.CurrentDomain.GetAssemblies().Where(IsNancyReferencing).Where(assembly => !assembly.ReflectionOnly); #endif } diff --git a/src/Nancy/Extensions/TypeExtensions.cs b/src/Nancy/Extensions/TypeExtensions.cs index 2f53ad830b..88b29632b8 100644 --- a/src/Nancy/Extensions/TypeExtensions.cs +++ b/src/Nancy/Extensions/TypeExtensions.cs @@ -91,12 +91,12 @@ public static bool IsNumeric(this Type source) var underlyingType = Nullable.GetUnderlyingType(source) ?? source; - if (underlyingType.IsEnum) + if (underlyingType.GetTypeInfo().IsEnum) { return false; } - switch (Type.GetTypeCode(underlyingType)) + switch (underlyingType.GetTypeCode()) { case TypeCode.Byte: case TypeCode.Decimal: From 99cc7504f0ae9194a2fb318861676bfbe7e09903 Mon Sep 17 00:00:00 2001 From: Jonathan Channon Date: Thu, 25 Feb 2016 13:28:33 +0000 Subject: [PATCH 37/52] added kestrel demo project --- Nancy.Next.sln | 9 ++++++++ .../Nancy.Demo.Hosting.Kestrel/HomeModule.cs | 14 ++++++++++++ .../Nancy.Demo.Hosting.Kestrel.xproj | 20 +++++++++++++++++ samples/Nancy.Demo.Hosting.Kestrel/Person.cs | 7 ++++++ samples/Nancy.Demo.Hosting.Kestrel/Startup.cs | 16 ++++++++++++++ .../Nancy.Demo.Hosting.Kestrel/project.json | 22 +++++++++++++++++++ 6 files changed, 88 insertions(+) create mode 100644 samples/Nancy.Demo.Hosting.Kestrel/HomeModule.cs create mode 100644 samples/Nancy.Demo.Hosting.Kestrel/Nancy.Demo.Hosting.Kestrel.xproj create mode 100644 samples/Nancy.Demo.Hosting.Kestrel/Person.cs create mode 100644 samples/Nancy.Demo.Hosting.Kestrel/Startup.cs create mode 100644 samples/Nancy.Demo.Hosting.Kestrel/project.json diff --git a/Nancy.Next.sln b/Nancy.Next.sln index 3497d16d0e..aa2b1e6ec4 100644 --- a/Nancy.Next.sln +++ b/Nancy.Next.sln @@ -82,6 +82,10 @@ Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Nancy.ViewEngines.Razor.Tes EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Nancy.ViewEngines.Razor.Tests.Models", "test\Nancy.ViewEngines.Razor.Tests.Models\Nancy.ViewEngines.Razor.Tests.Models.xproj", "{31FA18D3-24AD-4AB0-B297-5A2FD871989E}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{AA791E28-7914-439A-B59A-580B8D8FE95D}" +EndProject +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Nancy.Demo.Hosting.Kestrel", "samples\Nancy.Demo.Hosting.Kestrel\Nancy.Demo.Hosting.Kestrel.xproj", "{9921E059-612B-4011-9AB6-FD30E69850A1}" +EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Nancy.Tests.Functional", "test\Nancy.Tests.Functional\Nancy.Tests.Functional.xproj", "{742AC687-FC9A-4534-BB50-3D91738563A7}" EndProject Global @@ -230,6 +234,10 @@ Global {31FA18D3-24AD-4AB0-B297-5A2FD871989E}.Debug|Any CPU.Build.0 = Debug|Any CPU {31FA18D3-24AD-4AB0-B297-5A2FD871989E}.Release|Any CPU.ActiveCfg = Release|Any CPU {31FA18D3-24AD-4AB0-B297-5A2FD871989E}.Release|Any CPU.Build.0 = Release|Any CPU + {9921E059-612B-4011-9AB6-FD30E69850A1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9921E059-612B-4011-9AB6-FD30E69850A1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9921E059-612B-4011-9AB6-FD30E69850A1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9921E059-612B-4011-9AB6-FD30E69850A1}.Release|Any CPU.Build.0 = Release|Any CPU {742AC687-FC9A-4534-BB50-3D91738563A7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {742AC687-FC9A-4534-BB50-3D91738563A7}.Debug|Any CPU.Build.0 = Debug|Any CPU {742AC687-FC9A-4534-BB50-3D91738563A7}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -274,6 +282,7 @@ Global {C46BFAA7-F471-45A6-A5AC-FCF9390408EE} = {F44224E5-8E58-4D52-A0F0-BCBA2ADC0A0B} {A24271FA-E058-42E0-BB7D-3C8C43DF4B04} = {F44224E5-8E58-4D52-A0F0-BCBA2ADC0A0B} {31FA18D3-24AD-4AB0-B297-5A2FD871989E} = {F44224E5-8E58-4D52-A0F0-BCBA2ADC0A0B} + {9921E059-612B-4011-9AB6-FD30E69850A1} = {AA791E28-7914-439A-B59A-580B8D8FE95D} {742AC687-FC9A-4534-BB50-3D91738563A7} = {F44224E5-8E58-4D52-A0F0-BCBA2ADC0A0B} EndGlobalSection EndGlobal diff --git a/samples/Nancy.Demo.Hosting.Kestrel/HomeModule.cs b/samples/Nancy.Demo.Hosting.Kestrel/HomeModule.cs new file mode 100644 index 0000000000..05dc19cd48 --- /dev/null +++ b/samples/Nancy.Demo.Hosting.Kestrel/HomeModule.cs @@ -0,0 +1,14 @@ +namespace Nancy.Demo.Hosting.Kestrel +{ + using System.Threading.Tasks; + + public class HomeModule : NancyModule + { + public HomeModule() + { + Get["/"] = (o, token) => Task.FromResult("Hello from Nancy running on CoreCLR"); + + Get["/conneg/{name}"] = (parameters, token) => Task.FromResult(new Person() { Name = parameters.name }); + } + } +} diff --git a/samples/Nancy.Demo.Hosting.Kestrel/Nancy.Demo.Hosting.Kestrel.xproj b/samples/Nancy.Demo.Hosting.Kestrel/Nancy.Demo.Hosting.Kestrel.xproj new file mode 100644 index 0000000000..fee5ed11a8 --- /dev/null +++ b/samples/Nancy.Demo.Hosting.Kestrel/Nancy.Demo.Hosting.Kestrel.xproj @@ -0,0 +1,20 @@ + + + + 14.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + + 9921e059-612b-4011-9ab6-fd30e69850a1 + Nancy.Demo.Hosting.Kestrel + ..\..\artifacts\obj\$(MSBuildProjectName) + ..\..\artifacts\bin\$(MSBuildProjectName)\ + + + + 2.0 + + + diff --git a/samples/Nancy.Demo.Hosting.Kestrel/Person.cs b/samples/Nancy.Demo.Hosting.Kestrel/Person.cs new file mode 100644 index 0000000000..47fc4603f8 --- /dev/null +++ b/samples/Nancy.Demo.Hosting.Kestrel/Person.cs @@ -0,0 +1,7 @@ +namespace Nancy.Demo.Hosting.Kestrel +{ + public class Person + { + public string Name { get; set; } + } +} \ No newline at end of file diff --git a/samples/Nancy.Demo.Hosting.Kestrel/Startup.cs b/samples/Nancy.Demo.Hosting.Kestrel/Startup.cs new file mode 100644 index 0000000000..c2206326c7 --- /dev/null +++ b/samples/Nancy.Demo.Hosting.Kestrel/Startup.cs @@ -0,0 +1,16 @@ +namespace Nancy.Demo.Hosting.Kestrel +{ + using Microsoft.AspNet.Builder; + using Microsoft.AspNet.Hosting; + using Nancy.Owin; + + public class Startup + { + public void Configure(IApplicationBuilder app) + { + app.UseOwin(x => x.UseNancy()); + } + + public static void Main(string[] args) => WebApplication.Run(args); + } +} diff --git a/samples/Nancy.Demo.Hosting.Kestrel/project.json b/samples/Nancy.Demo.Hosting.Kestrel/project.json new file mode 100644 index 0000000000..9cc598ccc0 --- /dev/null +++ b/samples/Nancy.Demo.Hosting.Kestrel/project.json @@ -0,0 +1,22 @@ +{ + "compilationOptions": { + "emitEntryPoint": true + }, + + "dependencies": { + "Nancy": { "target": "project" } + }, + + "commands": { + "Nancy.Demo.Hosting.Kestrel": "Nancy.Demo.Hosting.Kestrel --server Microsoft.AspNet.Server.Kestrel --server.urls http://127.0.0.1:5001" + }, + + "frameworks": { + "dnxcore50": { + "dependencies": { + "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final", + "Microsoft.AspNet.Owin": "1.0.0-rc1-final" + } + } + } +} \ No newline at end of file From 2abbbded5a7db4695a050e43139765c0b8dcaa8a Mon Sep 17 00:00:00 2001 From: Jonathan Channon Date: Fri, 26 Feb 2016 12:22:20 +0000 Subject: [PATCH 38/52] nancy forms auth on coreclr --- src/Nancy.Authentication.Forms/project.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Nancy.Authentication.Forms/project.json b/src/Nancy.Authentication.Forms/project.json index c16231feea..b49f966ab8 100644 --- a/src/Nancy.Authentication.Forms/project.json +++ b/src/Nancy.Authentication.Forms/project.json @@ -13,6 +13,7 @@ }, "frameworks": { - "net451": { } + "net451": { }, + "dotnet5.4": { } } } From ab7d4b61a8c42a491b5343a3e3ca9f2ea3c82847 Mon Sep 17 00:00:00 2001 From: Jonathan Channon Date: Fri, 26 Feb 2016 12:33:06 +0000 Subject: [PATCH 39/52] made nancy.auth.basic coreclr compatible --- src/Nancy.Authentication.Basic/project.json | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Nancy.Authentication.Basic/project.json b/src/Nancy.Authentication.Basic/project.json index fafeeec9bf..a59e428162 100644 --- a/src/Nancy.Authentication.Basic/project.json +++ b/src/Nancy.Authentication.Basic/project.json @@ -13,6 +13,7 @@ }, "frameworks": { + "dotnet5.4": { }, "net451": { } } } From 17481ccb22ed4ee50358568b91dab4103d0bb884 Mon Sep 17 00:00:00 2001 From: Jonathan Channon Date: Fri, 26 Feb 2016 12:36:45 +0000 Subject: [PATCH 40/52] made nancy.auth.statless coreclr compatible --- src/Nancy.Authentication.Stateless/project.json | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Nancy.Authentication.Stateless/project.json b/src/Nancy.Authentication.Stateless/project.json index 44d4fca147..558f6a8964 100644 --- a/src/Nancy.Authentication.Stateless/project.json +++ b/src/Nancy.Authentication.Stateless/project.json @@ -13,6 +13,7 @@ }, "frameworks": { + "dotnet5.4": { }, "net451": { } } } From 93389f2ef80b54e1640e6430a83b5be2a8dab6a0 Mon Sep 17 00:00:00 2001 From: Jonathan Channon Date: Fri, 26 Feb 2016 12:40:48 +0000 Subject: [PATCH 41/52] nancy embedded coreclr ready --- src/Nancy.Embedded/project.json | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Nancy.Embedded/project.json b/src/Nancy.Embedded/project.json index 3d00f3e2af..07eb1c44dc 100644 --- a/src/Nancy.Embedded/project.json +++ b/src/Nancy.Embedded/project.json @@ -13,6 +13,7 @@ }, "frameworks": { + "dotnet5.4": { }, "net451": { } } } From 102881aa684ba5e797dd27c9dd5e4f2c407a99a1 Mon Sep 17 00:00:00 2001 From: Jonathan Channon Date: Fri, 26 Feb 2016 12:44:06 +0000 Subject: [PATCH 42/52] made nancy metadata modules coreclr compatible --- src/Nancy.Metadata.Modules/project.json | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Nancy.Metadata.Modules/project.json b/src/Nancy.Metadata.Modules/project.json index 6aae3dc89f..e708e6140b 100644 --- a/src/Nancy.Metadata.Modules/project.json +++ b/src/Nancy.Metadata.Modules/project.json @@ -13,6 +13,7 @@ }, "frameworks": { + "dotnet5.4": { }, "net451": { } } } From 1183a24a4b167cb172511f357dca3ae3d2145268 Mon Sep 17 00:00:00 2001 From: Jonathan Channon Date: Mon, 29 Feb 2016 19:14:18 +0000 Subject: [PATCH 43/52] added coreclr apis for nancy testing --- src/Nancy.Testing/AssertEqualityComparer.cs | 5 +++-- src/Nancy.Testing/AssertException.cs | 2 ++ src/Nancy.Testing/BrowserContext.cs | 2 +- src/Nancy.Testing/ConfigurableBootstrapper.cs | 8 ++++---- src/Nancy.Testing/NancyContextExtensions.cs | 8 ++++---- src/Nancy.Testing/Properties/Resources.Designer.cs | 8 +++++--- src/Nancy.Testing/project.json | 7 +++++++ src/Nancy/Extensions/MemoryStreamExtensions.cs | 2 +- 8 files changed, 27 insertions(+), 15 deletions(-) diff --git a/src/Nancy.Testing/AssertEqualityComparer.cs b/src/Nancy.Testing/AssertEqualityComparer.cs index ae41afd191..f4b3cb5fb2 100644 --- a/src/Nancy.Testing/AssertEqualityComparer.cs +++ b/src/Nancy.Testing/AssertEqualityComparer.cs @@ -2,12 +2,13 @@ { using System; using System.Collections.Generic; + using System.Reflection; public class AssertEqualityComparer : IEqualityComparer { private static bool IsTypeNullable(Type type) { - return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); + return type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); } public bool Equals(T expected, T actual) @@ -15,7 +16,7 @@ public bool Equals(T expected, T actual) var type = typeof(T); - if (!type.IsValueType || IsTypeNullable(type)) + if (!type.GetTypeInfo().IsValueType || IsTypeNullable(type)) { var actualIsNull = (Object.Equals(actual, default(T))); diff --git a/src/Nancy.Testing/AssertException.cs b/src/Nancy.Testing/AssertException.cs index d0123cae04..00b98b3c41 100644 --- a/src/Nancy.Testing/AssertException.cs +++ b/src/Nancy.Testing/AssertException.cs @@ -32,6 +32,7 @@ public AssertException(string message, Exception innerException) : base(message, { } +#if !DOTNET5_4 /// /// Initializes a new instance of the class. /// @@ -42,5 +43,6 @@ public AssertException(string message, Exception innerException) : base(message, protected AssertException(SerializationInfo info, StreamingContext context) : base(info, context) { } +#endif } } \ No newline at end of file diff --git a/src/Nancy.Testing/BrowserContext.cs b/src/Nancy.Testing/BrowserContext.cs index 7fe435466c..068186f29b 100644 --- a/src/Nancy.Testing/BrowserContext.cs +++ b/src/Nancy.Testing/BrowserContext.cs @@ -206,7 +206,7 @@ public void Certificate() using ( var pkcs12 = - Assembly.GetAssembly(typeof (BrowserContext)) + typeof (BrowserContext).GetTypeInfo().Assembly .GetManifestResourceStream("Nancy.Testing.Resources.NancyTestingCert.pfx")) { using (var br = new BinaryReader(pkcs12)) diff --git a/src/Nancy.Testing/ConfigurableBootstrapper.cs b/src/Nancy.Testing/ConfigurableBootstrapper.cs index d96849ff73..c5bb2b4c76 100644 --- a/src/Nancy.Testing/ConfigurableBootstrapper.cs +++ b/src/Nancy.Testing/ConfigurableBootstrapper.cs @@ -34,7 +34,7 @@ public class ConfigurableBootstrapper : NancyBootstrapperWithRequestContainerBas private bool enableAutoRegistration; private readonly List> applicationStartupActions; private readonly List> requestStartupActions; - private readonly Assembly nancyAssembly = typeof(NancyEngine).Assembly; + private readonly Assembly nancyAssembly = typeof(NancyEngine).GetTypeInfo().Assembly; private Action configure; private readonly IList> configurationOverrides; @@ -290,7 +290,7 @@ protected override IEnumerable ApplicationStartupTasks if (this.disableAutoApplicationStartupRegistration || user.Any()) { - tasks = tasks.Where(x => x.Assembly.GetName().Name.StartsWith("Nancy", StringComparison.OrdinalIgnoreCase)); + tasks = tasks.Where(x => x.GetTypeInfo().Assembly.GetName().Name.StartsWith("Nancy", StringComparison.OrdinalIgnoreCase)); } return tasks.Union(user); @@ -310,7 +310,7 @@ protected override IEnumerable RequestStartupTasks if (this.disableAutoRequestStartupRegistration || user.Any()) { - tasks = tasks.Where(x => x.Assembly.GetName().Name.StartsWith("Nancy", StringComparison.OrdinalIgnoreCase)); + tasks = tasks.Where(x => x.GetTypeInfo().Assembly.GetName().Name.StartsWith("Nancy", StringComparison.OrdinalIgnoreCase)); } return tasks.Union(user); @@ -432,7 +432,7 @@ protected override IEnumerable GetRegistrationTasks() } return this.ApplicationContainer.ResolveAll(false) - .Where(x => x.GetType().Assembly == nancyAssembly); + .Where(x => x.GetType().GetTypeInfo().Assembly == nancyAssembly); } /// diff --git a/src/Nancy.Testing/NancyContextExtensions.cs b/src/Nancy.Testing/NancyContextExtensions.cs index cda9e9f8c6..a0007730b1 100644 --- a/src/Nancy.Testing/NancyContextExtensions.cs +++ b/src/Nancy.Testing/NancyContextExtensions.cs @@ -3,7 +3,7 @@ namespace Nancy.Testing using System; using System.IO; using System.Xml.Serialization; - + using Nancy.Extensions; using Nancy.Json; /// @@ -43,7 +43,7 @@ public static DocumentWrapper DocumentBody(this NancyContext context) { context.Response.Contents.Invoke(contentsStream); contentsStream.Position = 0; - return new DocumentWrapper(contentsStream.GetBuffer()); + return new DocumentWrapper(contentsStream.GetBufferSegment()); } }); } @@ -78,9 +78,9 @@ public static TModel XmlBody(this NancyContext context) { context.Response.Contents.Invoke(contentsStream); contentsStream.Position = 0; - var serializer = new XmlSerializer(typeof (TModel)); + var serializer = new XmlSerializer(typeof(TModel)); var model = serializer.Deserialize(contentsStream); - return (TModel) model; + return (TModel)model; } }); } diff --git a/src/Nancy.Testing/Properties/Resources.Designer.cs b/src/Nancy.Testing/Properties/Resources.Designer.cs index 1d9c2467ff..f6063262db 100644 --- a/src/Nancy.Testing/Properties/Resources.Designer.cs +++ b/src/Nancy.Testing/Properties/Resources.Designer.cs @@ -14,8 +14,10 @@ namespace Nancy.Testing.Properties { using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; + using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; + using System.Text; /// /// A strongly-typed resource class, for looking up localized strings, etc. @@ -44,7 +46,7 @@ internal Resources() { internal static ResourceManager ResourceManager { get { if (ReferenceEquals(resourceMan, null)) { - ResourceManager temp = new ResourceManager("Nancy.Testing.Properties.Resources", typeof(Resources).Assembly); + ResourceManager temp = new ResourceManager("Nancy.Testing.Properties.Resources", typeof(Resources).GetTypeInfo().Assembly); resourceMan = temp; } return resourceMan; @@ -70,8 +72,8 @@ internal static CultureInfo Culture { /// internal static byte[] NancyTestingCert { get { - object obj = ResourceManager.GetObject("NancyTestingCert", resourceCulture); - return ((byte[])(obj)); + var cert = ResourceManager.GetString("NancyCert"); + return Encoding.UTF8.GetBytes(cert); } } } diff --git a/src/Nancy.Testing/project.json b/src/Nancy.Testing/project.json index 09fe21006c..1a795ec122 100644 --- a/src/Nancy.Testing/project.json +++ b/src/Nancy.Testing/project.json @@ -10,6 +10,7 @@ "dependencies": { "AngleSharp": "0.9.5", + "Nancy": { "target": "project" }, "Nancy.Authentication.Forms": { "target": "project" } }, @@ -18,6 +19,12 @@ ], "frameworks": { + "dotnet5.4": { + "dependencies": { + "System.Xml.XmlDocument": "4.0.1-beta-23516", + "System.Xml.XDocument": "4.0.11-beta-23516" + } + }, "net451": { "frameworkAssemblies": { "System.IO": "4.0.0.0", diff --git a/src/Nancy/Extensions/MemoryStreamExtensions.cs b/src/Nancy/Extensions/MemoryStreamExtensions.cs index 950952c97c..eab3b3746b 100644 --- a/src/Nancy/Extensions/MemoryStreamExtensions.cs +++ b/src/Nancy/Extensions/MemoryStreamExtensions.cs @@ -3,7 +3,7 @@ using System; using System.IO; - internal static class MemoryStreamExtensions + public static class MemoryStreamExtensions { public static ArraySegment GetBufferSegment(this MemoryStream stream) { From 77b4085b050197232b4c22b1d021045b346fb3d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20H=C3=A5kansson?= Date: Wed, 2 Mar 2016 13:07:19 +0100 Subject: [PATCH 44/52] Made Nancy.Tests.Functional run on the coreclr --- src/Nancy/Helpers/ReflectionUtils.cs | 252 +++++++++--------- src/Nancy/ModelBinding/DefaultBinder.cs | 4 +- .../Tests/PartialViewTests.cs | 5 +- .../Tests/RouteConstraintTests.cs | 1 - .../Tests/TracingSmokeTests.cs | 5 +- .../Tests/ViewBagTests.cs | 9 +- test/Nancy.Tests.Functional/project.json | 11 +- 7 files changed, 150 insertions(+), 137 deletions(-) diff --git a/src/Nancy/Helpers/ReflectionUtils.cs b/src/Nancy/Helpers/ReflectionUtils.cs index fb2562d025..6587599e88 100644 --- a/src/Nancy/Helpers/ReflectionUtils.cs +++ b/src/Nancy/Helpers/ReflectionUtils.cs @@ -1,64 +1,66 @@ -#region License -// Copyright (c) 2007 James Newton-King -// -// Permission is hereby granted, free of charge, to any person -// obtaining a copy of this software and associated documentation -// files (the "Software"), to deal in the Software without -// restriction, including without limitation the rights to use, -// copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following -// conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -// OTHER DEALINGS IN THE SOFTWARE. +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. #endregion -namespace Nancy.Helpers +namespace Nancy.Helpers { using System; using System.Collections; using System.Collections.Generic; + using System.Linq; using System.Reflection; - internal static class ReflectionUtils - { - public static bool IsInstantiatableType(Type t) - { - if (t == null) - throw new ArgumentNullException("t"); - - - if (t.GetTypeInfo().IsAbstract || t.GetTypeInfo().IsInterface || t.IsArray) - return false; - - if (!HasDefaultConstructor(t)) - return false; - - return true; - } - - public static bool HasDefaultConstructor(Type t) - { + internal static class ReflectionUtils + { + public static bool IsInstantiatableType(Type t) + { if (t == null) - { + throw new ArgumentNullException("t"); + + if (t.GetTypeInfo().IsAbstract || t.GetTypeInfo().IsInterface || t.IsArray) + return false; + + if (t.GetTypeInfo().IsGenericType) + return false; + + if (!HasDefaultConstructor(t)) + return false; + + return true; + } + + public static bool HasDefaultConstructor(Type t) + { + if (t == null) + { throw new ArgumentNullException("t"); } -#if DOTNET5_4 - return (t.GetConstructor(Type.EmptyTypes) != null); -#else - return (t.GetConstructor(BindingFlags.Instance, null, Type.EmptyTypes, null) != null); -#endif + var hasDefaultConstructor = + t.GetTypeInfo().DeclaredConstructors.Any(ctor => !ctor.GetParameters().Any()); + + return hasDefaultConstructor; } public static bool IsAssignable(Type to, Type from) @@ -79,44 +81,44 @@ public static bool IsAssignable(Type to, Type from) } return false; - } - - public static bool IsSubClass(Type type, Type check) - { + } + + public static bool IsSubClass(Type type, Type check) + { if (type == null || check == null) { return false; - } - + } + if (type == check) - { + { return true; - } - - if (check.GetTypeInfo().IsInterface) - { - foreach (Type t in type.GetInterfaces()) - { - if (IsSubClass(t, check)) return true; - } - } - if (type.GetTypeInfo().IsGenericType && !type.GetTypeInfo().IsGenericTypeDefinition) - { - if (IsSubClass(type.GetGenericTypeDefinition(), check)) - return true; - } - return IsSubClass(type.GetTypeInfo().BaseType, check); + } + + if (check.GetTypeInfo().IsInterface) + { + foreach (Type t in type.GetInterfaces()) + { + if (IsSubClass(t, check)) return true; + } + } + if (type.GetTypeInfo().IsGenericType && !type.GetTypeInfo().IsGenericTypeDefinition) + { + if (IsSubClass(type.GetGenericTypeDefinition(), check)) + return true; + } + return IsSubClass(type.GetTypeInfo().BaseType, check); } - static readonly Type GenericListType = typeof(List<>); - - /// - /// Gets the type of the typed list's items. - /// - /// The type. - /// The type of the typed list's items. - public static Type GetTypedListItemType(Type type) - { + static readonly Type GenericListType = typeof(List<>); + + /// + /// Gets the type of the typed list's items. + /// + /// The type. + /// The type of the typed list's items. + public static Type GetTypedListItemType(Type type) + { if (type == null) throw new ArgumentNullException("type"); @@ -131,10 +133,10 @@ public static Type GetTypedListItemType(Type type) { throw new Exception("Bad type"); } - } - - public static Type GetTypedDictionaryValueType(Type type) - { + } + + public static Type GetTypedDictionaryValueType(Type type) + { if (type == null) { throw new ArgumentNullException("type"); @@ -149,11 +151,11 @@ public static Type GetTypedDictionaryValueType(Type type) else if (typeof(IDictionary).IsAssignableFrom(type)) { return null; - } + } else { throw new Exception("Bad type"); - } + } } static readonly Type GenericDictionaryType = typeof(IDictionary<,>); @@ -178,10 +180,10 @@ public static Type GetGenericDictionary(Type type) } return null; - } - - public static Type GetMemberUnderlyingType(MemberInfo member) - { + } + + public static Type GetMemberUnderlyingType(MemberInfo member) + { if (member is FieldInfo) { return ((FieldInfo)member).FieldType; @@ -197,17 +199,17 @@ public static Type GetMemberUnderlyingType(MemberInfo member) else { throw new ArgumentException("MemberInfo must be if type FieldInfo, PropertyInfo or EventInfo", "member"); - } + } } - /// - /// Determines whether the member is an indexed property. - /// - /// The member. - /// - /// true if the member is an indexed property; otherwise, false. - /// + /// + /// Determines whether the member is an indexed property. + /// + /// The member. + /// + /// true if the member is an indexed property; otherwise, false. + /// public static bool IsIndexedProperty(MemberInfo member) { if (member == null) @@ -227,13 +229,13 @@ public static bool IsIndexedProperty(MemberInfo member) } } - /// - /// Determines whether the property is an indexed property. - /// - /// The property. - /// - /// true if the property is an indexed property; otherwise, false. - /// + /// + /// Determines whether the property is an indexed property. + /// + /// The property. + /// + /// true if the property is an indexed property; otherwise, false. + /// public static bool IsIndexedProperty(PropertyInfo property) { if (property == null) @@ -244,12 +246,12 @@ public static bool IsIndexedProperty(PropertyInfo property) return (property.GetIndexParameters().Length > 0); } - /// - /// Gets the member's value on the object. - /// - /// The member. - /// The target object. - /// The member's value on the object. + /// + /// Gets the member's value on the object. + /// + /// The member. + /// The target object. + /// The member's value on the object. public static object GetMemberValue(MemberInfo member, object target) { if (member is FieldInfo) @@ -270,12 +272,12 @@ public static object GetMemberValue(MemberInfo member, object target) throw new ArgumentException("MemberInfo is not of type FieldInfo or PropertyInfo", "member"); } - /// - /// Sets the member's value on the target object. - /// - /// The member. - /// The target. - /// The value. + /// + /// Sets the member's value on the target object. + /// + /// The member. + /// The target. + /// The value. public static void SetMemberValue(MemberInfo member, object target, object value) { if (member is FieldInfo) @@ -311,13 +313,13 @@ public static bool CanReadMemberValue(MemberInfo member) return false; } - /// - /// Determines whether the specified MemberInfo can be set. - /// - /// The MemberInfo to determine whether can be set. - /// - /// true if the specified MemberInfo can be set; otherwise, false. - /// + /// + /// Determines whether the specified MemberInfo can be set. + /// + /// The MemberInfo to determine whether can be set. + /// + /// true if the specified MemberInfo can be set; otherwise, false. + /// public static bool CanSetMemberValue(MemberInfo member) { if (member is FieldInfo) @@ -346,4 +348,4 @@ public static IEnumerable GetFieldsAndProperties(Type type, BindingF } } } -} +} diff --git a/src/Nancy/ModelBinding/DefaultBinder.cs b/src/Nancy/ModelBinding/DefaultBinder.cs index befc71b5c1..f9425eb3e7 100644 --- a/src/Nancy/ModelBinding/DefaultBinder.cs +++ b/src/Nancy/ModelBinding/DefaultBinder.cs @@ -437,11 +437,11 @@ private static object CreateModel(Type modelType, Type genericType, object insta if (instance == null) { - return Activator.CreateInstance(modelType, true); + return Activator.CreateInstance(modelType); } return !modelType.IsInstanceOfType(instance) ? - Activator.CreateInstance(modelType, true) : + Activator.CreateInstance(modelType) : instance; } diff --git a/test/Nancy.Tests.Functional/Tests/PartialViewTests.cs b/test/Nancy.Tests.Functional/Tests/PartialViewTests.cs index bca0bf2f7a..cd5db69879 100644 --- a/test/Nancy.Tests.Functional/Tests/PartialViewTests.cs +++ b/test/Nancy.Tests.Functional/Tests/PartialViewTests.cs @@ -1,4 +1,5 @@ -namespace Nancy.Tests.Functional.Tests +#if !DNXCORE50 +namespace Nancy.Tests.Functional.Tests { using System; using System.Threading.Tasks; @@ -59,3 +60,5 @@ public async Task When_Partial_View_Could_Not_Be_Found_An_Meaningful_Exception_S } } } + +#endif diff --git a/test/Nancy.Tests.Functional/Tests/RouteConstraintTests.cs b/test/Nancy.Tests.Functional/Tests/RouteConstraintTests.cs index 12a8f76b83..951bc9eb04 100644 --- a/test/Nancy.Tests.Functional/Tests/RouteConstraintTests.cs +++ b/test/Nancy.Tests.Functional/Tests/RouteConstraintTests.cs @@ -1,7 +1,6 @@ namespace Nancy.Tests.Functional.Tests { using System; - using System.Runtime.Remoting.Messaging; using System.Threading.Tasks; using Nancy.Bootstrapper; using Nancy.Routing.Constraints; diff --git a/test/Nancy.Tests.Functional/Tests/TracingSmokeTests.cs b/test/Nancy.Tests.Functional/Tests/TracingSmokeTests.cs index 0abb106f81..2641b023c1 100644 --- a/test/Nancy.Tests.Functional/Tests/TracingSmokeTests.cs +++ b/test/Nancy.Tests.Functional/Tests/TracingSmokeTests.cs @@ -1,4 +1,5 @@ -namespace Nancy.Tests.Functional.Tests +#if !DNXCORE50 +namespace Nancy.Tests.Functional.Tests { using System; using System.Threading.Tasks; @@ -39,3 +40,5 @@ public async Task Should_render_content_from_viewbag() } } } + +#endif diff --git a/test/Nancy.Tests.Functional/Tests/ViewBagTests.cs b/test/Nancy.Tests.Functional/Tests/ViewBagTests.cs index 2be7ae4b7f..af62c8d16f 100644 --- a/test/Nancy.Tests.Functional/Tests/ViewBagTests.cs +++ b/test/Nancy.Tests.Functional/Tests/ViewBagTests.cs @@ -1,11 +1,10 @@ -namespace Nancy.Tests.Functional.Tests +#if !DNXCORE50 +namespace Nancy.Tests.Functional.Tests { - using System; using System.Threading.Tasks; using Nancy.Bootstrapper; using Nancy.Testing; using Nancy.Tests.Functional.Modules; - using Xunit; public class ViewBagTests @@ -13,7 +12,7 @@ public class ViewBagTests private readonly INancyBootstrapper bootstrapper; private readonly Browser browser; - + public ViewBagTests() { this.bootstrapper = new ConfigurableBootstrapper( @@ -90,3 +89,5 @@ public class ViewBagModel } } } + +#endif diff --git a/test/Nancy.Tests.Functional/project.json b/test/Nancy.Tests.Functional/project.json index 1e49fefdbb..ce68ab2c6b 100644 --- a/test/Nancy.Tests.Functional/project.json +++ b/test/Nancy.Tests.Functional/project.json @@ -2,13 +2,13 @@ "dependencies": { "Nancy": { "target": "project" }, "Nancy.Testing": { "target": "project" }, - "Nancy.ViewEngines.Razor": { "target": "project" }, "xunit": "2.1.0", "xunit.runner.dnx": "2.1.0-*" }, "commands": { - "test": "xunit.runner.dnx" + "test": "xunit.runner.dnx", + "test-dnxcore50": "xunit.runner.dnx" }, "compilationOptions": { @@ -20,6 +20,11 @@ ], "frameworks": { - "dnx451": { } + "dnxcore50": { }, + "dnx451": { + "dependencies": { + "Nancy.ViewEngines.Razor": { "target": "project" } + } + } } } From 8e314a47ef4a24d2b88ef6950243d3a9deddcf21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20H=C3=A5kansson?= Date: Wed, 2 Mar 2016 13:44:19 +0100 Subject: [PATCH 45/52] Added Type extension to create an instance Extension method to allow you to create an instance of a type that does not have public default constructor. Compatible with both full-framework and coreclr --- src/Nancy/Extensions/TypeExtensions.cs | 66 +++++++++++++++++++++++++ src/Nancy/Json/JavaScriptSerializer.cs | 2 +- src/Nancy/ModelBinding/DefaultBinder.cs | 6 +-- 3 files changed, 70 insertions(+), 4 deletions(-) diff --git a/src/Nancy/Extensions/TypeExtensions.cs b/src/Nancy/Extensions/TypeExtensions.cs index 88b29632b8..63c8aa4cd9 100644 --- a/src/Nancy/Extensions/TypeExtensions.cs +++ b/src/Nancy/Extensions/TypeExtensions.cs @@ -10,6 +10,31 @@ /// public static class TypeExtensions { + /// + /// Creates an instance of and cast it to . + /// + /// The type to create an instance of. + /// if a non-public constructor can be used, otherwise . + public static T CreateInstance(this Type type, bool nonPublic = false) + { + if (!typeof(T).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())) + { + throw new InvalidOperationException("Unable to create instance of " + type.GetTypeInfo().FullName + "since it can't be cast to " + typeof(T).GetTypeInfo().FullName); + } + + return (T)CreateInstance(type, nonPublic); + } + + /// + /// Creates an instance of . + /// + /// The type to create an instance of. + /// if a non-public constructor can be used, otherwise . + public static object CreateInstance(this Type type, bool nonPublic = false) + { + return CreateInstanceInternal(type, nonPublic); + } + /// /// returns the assembly that the type belongs to /// @@ -178,5 +203,46 @@ public static TypeCode GetTypeCode(this Type type) else return TypeCode.Object; } + + private static object CreateInstanceInternal(Type type, bool nonPublic = false) + { +#if !DOTNET5_4 + return Activator.CreateInstance(type, nonPublic); + } +#else + var constructor = type.GetDefaultConstructor(nonPublic); + + if (constructor == null) + { + throw new MissingMethodException("No parameterless constructor defined for this object."); + } + + return constructor.Invoke(Array.Empty()); + } + + private static ConstructorInfo GetDefaultConstructor(this Type type, bool nonPublic = false) + { + var typeInfo = type.GetTypeInfo(); + + var constructors = typeInfo.DeclaredConstructors; + + foreach (var constructor in constructors) + { + var parameters = constructor.GetParameters(); + + if (parameters.Length > 0) + { + continue; + } + + if (!constructor.IsPrivate || nonPublic) + { + return constructor; + } + } + + return null; + } +#endif } } diff --git a/src/Nancy/Json/JavaScriptSerializer.cs b/src/Nancy/Json/JavaScriptSerializer.cs index da78d8c3b6..d777bdda59 100644 --- a/src/Nancy/Json/JavaScriptSerializer.cs +++ b/src/Nancy/Json/JavaScriptSerializer.cs @@ -33,7 +33,7 @@ namespace Nancy.Json using System.Collections.Generic; using System.IO; using Nancy.Json.Simple; - + using Nancy.Extensions; /// /// JavaScriptSerializer responsible for serializing objects /// diff --git a/src/Nancy/ModelBinding/DefaultBinder.cs b/src/Nancy/ModelBinding/DefaultBinder.cs index f9425eb3e7..9a3dbe4986 100644 --- a/src/Nancy/ModelBinding/DefaultBinder.cs +++ b/src/Nancy/ModelBinding/DefaultBinder.cs @@ -125,7 +125,7 @@ public object Bind(NancyContext context, Type modelType, object instance, Bindin } else { - genericinstance = Activator.CreateInstance(bindingContext.GenericType); + genericinstance = bindingContext.GenericType.CreateInstance(); model.Add(genericinstance); } @@ -437,11 +437,11 @@ private static object CreateModel(Type modelType, Type genericType, object insta if (instance == null) { - return Activator.CreateInstance(modelType); + return modelType.CreateInstance(true); } return !modelType.IsInstanceOfType(instance) ? - Activator.CreateInstance(modelType) : + modelType.CreateInstance(true) : instance; } From c5ed5eb6de97cb3146741957407bffb30570f3b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20H=C3=A5kansson?= Date: Fri, 8 Apr 2016 12:37:04 +0200 Subject: [PATCH 46/52] Added ASPNET CI Feed to NuGet.config (#2407) --- NuGet.config | 1 + 1 file changed, 1 insertion(+) diff --git a/NuGet.config b/NuGet.config index 600712bc45..d054066286 100644 --- a/NuGet.config +++ b/NuGet.config @@ -2,6 +2,7 @@ + From b9b62859d2f932219d25265a2f7af61e1a476eb3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20H=C3=A5kansson?= Date: Thu, 14 Apr 2016 11:26:29 +0200 Subject: [PATCH 47/52] Updated to be compatible with rc2 changes --- NuGet.config | 3 +- build.ps1 | 106 ++++----------- global.json | 5 +- samples/Nancy.Demo.Hosting.Kestrel/Program.cs | 20 +++ samples/Nancy.Demo.Hosting.Kestrel/Startup.cs | 16 --- .../Nancy.Demo.Hosting.Kestrel/project.json | 40 +++--- src/Nancy.Authentication.Basic/project.json | 20 ++- src/Nancy.Authentication.Forms/project.json | 20 ++- .../project.json | 20 ++- src/Nancy.Embedded/project.json | 20 ++- src/Nancy.Encryption.MachineKey/project.json | 18 +-- src/Nancy.Hosting.Aspnet/project.json | 18 +-- .../FileSystemRootPathProvider.cs | 13 +- src/Nancy.Hosting.Self/project.json | 23 ++-- src/Nancy.Metadata.Modules/project.json | 20 ++- src/Nancy.Owin/project.json | 14 +- .../Nancy.Testing.csproj | 18 --- src/Nancy.Testing/AssertException.cs | 2 +- .../Properties/Resources.Designer.cs | 80 ----------- src/Nancy.Testing/Properties/Resources.resx | 124 ------------------ src/Nancy.Testing/project.json | 32 +++-- .../project.json | 16 ++- .../project.json | 14 +- src/Nancy.ViewEngines.DotLiquid/project.json | 14 +- src/Nancy.ViewEngines.Markdown/project.json | 14 +- src/Nancy.ViewEngines.Nustache/project.json | 14 +- .../project.json | 4 +- .../RazorViewEngine.cs | 33 +---- src/Nancy.ViewEngines.Razor/project.json | 41 +++--- src/Nancy.ViewEngines.Spark/project.json | 16 ++- src/Nancy/AppDomainAssemblyCatalog.cs | 2 +- .../Bootstrapper/BootstrapperException.cs | 2 +- ...ltipleRootPathProvidersLocatedException.cs | 2 +- .../Bootstrapper/NancyBootstrapperBase.cs | 4 +- .../Bootstrapper/NancyBootstrapperLocator.cs | 27 +--- src/Nancy/DefaultRootPathProvider.cs | 3 +- src/Nancy/DependencyContextAssemblyCatalog.cs | 72 ++++++++++ src/Nancy/Diagnostics/DiagnosticsSession.cs | 2 +- src/Nancy/DynamicDictionaryValue.cs | 2 +- .../Extensions/MemoryStreamExtensions.cs | 4 +- src/Nancy/Extensions/TypeExtensions.cs | 2 +- src/Nancy/HeadResponse.cs | 2 +- src/Nancy/IO/RequestStream.cs | 10 +- src/Nancy/IO/UnclosableStreamWrapper.cs | 4 +- src/Nancy/Json/SimpleJson.cs | 2 +- src/Nancy/LibraryManagerAssemblyCatalog.cs | 68 ---------- .../ModelBinding/ModelBindingException.cs | 2 +- src/Nancy/Security/CsrfToken.cs | 2 +- src/Nancy/TinyIoc/TinyIoC.cs | 8 +- src/Nancy/project.json | 84 ++++++------ .../project.json | 28 ++-- .../project.json | 27 ++-- test/Nancy.Embedded.Tests/project.json | 26 ++-- .../project.json | 27 ++-- test/Nancy.Hosting.Aspnet.Tests/project.json | 29 ++-- test/Nancy.Hosting.Self.Tests/project.json | 28 ++-- .../Nancy.Metadata.Modules.Tests/project.json | 27 ++-- test/Nancy.Owin.Tests/project.json | 27 ++-- test/Nancy.Testing.Tests/project.json | 28 ++-- .../Tests/PartialViewTests.cs | 2 +- .../Tests/TracingSmokeTests.cs | 2 +- .../Tests/ViewBagTests.cs | 2 +- test/Nancy.Tests.Functional/project.json | 48 +++++-- .../NancyInternalConfigurationFixture.cs | 4 +- .../Unit/ResponseExtensionsFixture.cs | 4 +- .../Responses/GenericFileResponseFixture.cs | 4 +- test/Nancy.Tests/project.json | 36 ++--- .../project.json | 27 ++-- .../project.json | 27 ++-- .../project.json | 34 +++-- .../project.json | 34 ++--- .../project.json | 4 +- .../RazorViewEngineFixture.cs | 8 +- .../project.json | 31 +++-- 74 files changed, 694 insertions(+), 922 deletions(-) create mode 100644 samples/Nancy.Demo.Hosting.Kestrel/Program.cs delete mode 100644 samples/Nancy.Demo.Hosting.Kestrel/Startup.cs delete mode 100644 src/Nancy.Testing/Properties/Resources.Designer.cs delete mode 100644 src/Nancy.Testing/Properties/Resources.resx create mode 100644 src/Nancy/DependencyContextAssemblyCatalog.cs delete mode 100644 src/Nancy/LibraryManagerAssemblyCatalog.cs diff --git a/NuGet.config b/NuGet.config index d054066286..404f2cb17c 100644 --- a/NuGet.config +++ b/NuGet.config @@ -2,7 +2,8 @@ - + + diff --git a/build.ps1 b/build.ps1 index ad7582060f..d79d412f47 100644 --- a/build.ps1 +++ b/build.ps1 @@ -1,56 +1,30 @@ -function Install-Dnvm +function Install-Dotnet { - & where.exe dnvm 2>&1 | Out-Null - if(($LASTEXITCODE -ne 0) -Or ((Test-Path Env:\APPVEYOR) -eq $true)) - { - Write-Host "DNVM not found" - &{$Branch='dev';iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.ps1'))} + & where.exe dotnet 2>&1 | Out-Null - # Normally this happens automatically during install but AppVeyor has - # an issue where you may need to manually re-run setup from within this process. - if($env:DNX_HOME -eq $NULL) - { - Write-Host "Initial DNVM environment setup failed; running manual setup" - $tempDnvmPath = Join-Path $env:TEMP "dnvminstall" - $dnvmSetupCmdPath = Join-Path $tempDnvmPath "dnvm.ps1" - & $dnvmSetupCmdPath setup - } - } -} - -function Get-DnxVersion -{ - $globalJson = join-path $PSScriptRoot "global.json" - $jsonData = Get-Content -Path $globalJson -Raw | ConvertFrom-JSON - return $jsonData.sdk.version + if(($LASTEXITCODE -ne 0) -Or ((Test-Path Env:\APPVEYOR) -eq $true)) + { + Write-Host "Dotnet CLI not found - downloading latest version" + & { iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/dotnet/cli/rel/1.0.0/scripts/obtain/install.ps1')) } + } } function Restore-Packages { param([string] $DirectoryName) - & dnu restore --quiet ("""" + $DirectoryName + """") -} - -function Pack-Projects -{ - param([string] $DirectoryName, [string] $Configuration) - & dnu pack --quiet ("""" + $DirectoryName + """") --configuration $Configuration --out .\artifacts\packages; if($LASTEXITCODE -ne 0) { exit 2 } + & dotnet restore -v Error ("""" + $DirectoryName + """") } function Test-Projects { - & dnx test; if($LASTEXITCODE -ne 0) { exit 3 } -} + param([string] $framework) + & dotnet test; + #& dotnet test -f $framework; -function Remove-PathVariable -{ - param([string] $VariableToRemove) - $path = [Environment]::GetEnvironmentVariable("PATH", "User") - $newItems = $path.Split(';') | Where-Object { $_.ToString() -inotlike $VariableToRemove } - [Environment]::SetEnvironmentVariable("PATH", [System.String]::Join(';', $newItems), "User") - $path = [Environment]::GetEnvironmentVariable("PATH", "Process") - $newItems = $path.Split(';') | Where-Object { $_.ToString() -inotlike $VariableToRemove } - [Environment]::SetEnvironmentVariable("PATH", [System.String]::Join(';', $newItems), "Process") + if($LASTEXITCODE -ne 0) + { + exit 3 + } } ######################## @@ -59,55 +33,19 @@ function Remove-PathVariable Push-Location $PSScriptRoot -$dnxVersion = Get-DnxVersion - -if (!$env:CONFIGURATION) -{ - $env:CONFIGURATION = "Release" -} - -# Clean -if(Test-Path .\artifacts) { Remove-Item .\artifacts -Force -Recurse } - -# Remove the installed DNVM from the path and force use of -# per-user DNVM (which we can upgrade as needed without admin permissions) -Remove-PathVariable "*Program Files\Microsoft DNX\DNVM*" - -# Make sure per-user DNVM is installed -Install-Dnvm - -# Install DNX -dnvm install $dnxVersion -r CoreCLR -NoNative -dnvm install $dnxVersion -r CLR -NoNative - -# Start with regular CLR -dnvm use $dnxVersion -r CLR +# Install Dotnet CLI +Install-Dotnet # Package restore +Write-Host "Running package restore" Get-ChildItem -Path . -Filter *.xproj -Recurse | ForEach-Object { Restore-Packages $_.DirectoryName } -# Set build number -$env:DNX_BUILD_VERSION = @{ $true = $env:APPVEYOR_BUILD_NUMBER; $false = 1 }[$env:APPVEYOR_BUILD_NUMBER -ne $NULL]; -Write-Host "Build number: " $env:DNX_BUILD_VERSION - -# Package -Get-ChildItem -Path .\src -Filter *.xproj -Recurse | ForEach-Object { Pack-Projects $_.DirectoryName $env:CONFIGURATION } - -# Test +# Tests +Write-Host "Running tests" Get-ChildItem -Path .\test -Filter *.xproj -Exclude Nancy.ViewEngines.Razor.Tests.Models.xproj -Recurse | ForEach-Object { Push-Location $_.DirectoryName - Test-Projects $_.DirectoryName + Test-Projects "netcoreapp1.0" Pop-Location - } - -# Switch to Core CLR -#dnvm use $dnxVersion -r CoreCLR - -# Test again -# Get-ChildItem -Path .\test -Filter *Tests.xproj -Recurse | ForEach-Object { -# Push-Location $_.DirectoryName -# Test-Projects $_.DirectoryName -# Pop-Location -# } +} Pop-Location diff --git a/global.json b/global.json index 3fc66c1ced..e34d48985a 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,3 @@ { - "projects": [ "src", "test", "samples" ], - "sdk": { - "version": "1.0.0-rc1-update1" - } + "projects": [ "src", "test", "samples" ] } diff --git a/samples/Nancy.Demo.Hosting.Kestrel/Program.cs b/samples/Nancy.Demo.Hosting.Kestrel/Program.cs new file mode 100644 index 0000000000..ef189578a5 --- /dev/null +++ b/samples/Nancy.Demo.Hosting.Kestrel/Program.cs @@ -0,0 +1,20 @@ +namespace Nancy.Demo.Hosting.Kestrel +{ + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Hosting; + using Microsoft.AspNetCore.Http; + using Nancy.Owin; + + public class Program + { + public static void Main(string[] args) + { + var host = new WebHostBuilder() + .UseKestrel() + .Configure(app => app.UseOwin(x => x.UseNancy())) + .Build(); + + host.Run(); + } + } +} diff --git a/samples/Nancy.Demo.Hosting.Kestrel/Startup.cs b/samples/Nancy.Demo.Hosting.Kestrel/Startup.cs deleted file mode 100644 index c2206326c7..0000000000 --- a/samples/Nancy.Demo.Hosting.Kestrel/Startup.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace Nancy.Demo.Hosting.Kestrel -{ - using Microsoft.AspNet.Builder; - using Microsoft.AspNet.Hosting; - using Nancy.Owin; - - public class Startup - { - public void Configure(IApplicationBuilder app) - { - app.UseOwin(x => x.UseNancy()); - } - - public static void Main(string[] args) => WebApplication.Run(args); - } -} diff --git a/samples/Nancy.Demo.Hosting.Kestrel/project.json b/samples/Nancy.Demo.Hosting.Kestrel/project.json index 9cc598ccc0..cb2b2094e6 100644 --- a/samples/Nancy.Demo.Hosting.Kestrel/project.json +++ b/samples/Nancy.Demo.Hosting.Kestrel/project.json @@ -1,22 +1,28 @@ { - "compilationOptions": { - "emitEntryPoint": true - }, - - "dependencies": { - "Nancy": { "target": "project" } - }, + "buildOptions": { + "debugType": "portable", + "emitEntryPoint": true + }, - "commands": { - "Nancy.Demo.Hosting.Kestrel": "Nancy.Demo.Hosting.Kestrel --server Microsoft.AspNet.Server.Kestrel --server.urls http://127.0.0.1:5001" - }, + "dependencies": { + "Nancy": { "target": "project" } + }, - "frameworks": { - "dnxcore50": { - "dependencies": { - "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final", - "Microsoft.AspNet.Owin": "1.0.0-rc1-final" - } + "frameworks": { + "netcoreapp1.0": { + "dependencies": { + "Microsoft.AspNetCore.Hosting": "1.0.0-*", + "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*", + "Microsoft.AspNetCore.Owin": "1.0.0-rc2-*", + "Microsoft.NETCore.App": { + "type": "platform", + "version": "1.0.0-rc2-*" + } + }, + "imports": [ + "dotnet54", + "portable-net451+win8" + ] + } } - } } \ No newline at end of file diff --git a/src/Nancy.Authentication.Basic/project.json b/src/Nancy.Authentication.Basic/project.json index a59e428162..f8a59db831 100644 --- a/src/Nancy.Authentication.Basic/project.json +++ b/src/Nancy.Authentication.Basic/project.json @@ -1,19 +1,25 @@ { "version": "2.0.0-*", - "description": "A basic HTTP authentication provider for Nancy.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - "tags": [ "Nancy", "Authentication" ], - "projectUrl": "http://nancyfx.org", - "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", - "iconUrl": "http://nancyfx.org/nancy-nuget.png", + + "packOptions": { + "tags": [ "Nancy", "Authentication" ], + "projectUrl": "http://nancyfx.org", + "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", + "iconUrl": "http://nancyfx.org/nancy-nuget.png" + }, "dependencies": { "Nancy": { "target": "project" } }, "frameworks": { - "dotnet5.4": { }, - "net451": { } + "netstandard1.5": { + "imports": [ + "portable-net451+win8" + ] + }, + "net452": { } } } diff --git a/src/Nancy.Authentication.Forms/project.json b/src/Nancy.Authentication.Forms/project.json index b49f966ab8..a4ade82574 100644 --- a/src/Nancy.Authentication.Forms/project.json +++ b/src/Nancy.Authentication.Forms/project.json @@ -1,19 +1,25 @@ { "version": "2.0.0-*", - "description": "A forms authentication provider for Nancy.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - "tags": [ "Nancy", "Authentication" ], - "projectUrl": "http://nancyfx.org", - "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", - "iconUrl": "http://nancyfx.org/nancy-nuget.png", + + "packOptions": { + "tags": [ "Nancy", "Authentication" ], + "projectUrl": "http://nancyfx.org", + "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", + "iconUrl": "http://nancyfx.org/nancy-nuget.png" + }, "dependencies": { "Nancy": { "target": "project" } }, "frameworks": { - "net451": { }, - "dotnet5.4": { } + "netstandard1.5": { + "imports": [ + "portable-net451+win8" + ] + }, + "net452": { } } } diff --git a/src/Nancy.Authentication.Stateless/project.json b/src/Nancy.Authentication.Stateless/project.json index 558f6a8964..bf86be3c00 100644 --- a/src/Nancy.Authentication.Stateless/project.json +++ b/src/Nancy.Authentication.Stateless/project.json @@ -1,19 +1,25 @@ { "version": "2.0.0-*", - "description": "A stateless authentication provider for Nancy.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - "tags": [ "Nancy", "Authentication" ], - "projectUrl": "http://nancyfx.org", - "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", - "iconUrl": "http://nancyfx.org/nancy-nuget.png", + + "packOptions": { + "tags": [ "Nancy", "Authentication" ], + "projectUrl": "http://nancyfx.org", + "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", + "iconUrl": "http://nancyfx.org/nancy-nuget.png" + }, "dependencies": { "Nancy": { "target": "project" } }, "frameworks": { - "dotnet5.4": { }, - "net451": { } + "netstandard1.5": { + "imports": [ + "portable-net451+win8" + ] + }, + "net452": { } } } diff --git a/src/Nancy.Embedded/project.json b/src/Nancy.Embedded/project.json index 07eb1c44dc..41234ee806 100644 --- a/src/Nancy.Embedded/project.json +++ b/src/Nancy.Embedded/project.json @@ -1,19 +1,25 @@ { "version": "2.0.0-*", - "description": "Helpers for serving embedded static content with Nancy.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - "tags": [ "Nancy", "Embedded", "Static Content" ], - "projectUrl": "http://nancyfx.org", - "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", - "iconUrl": "http://nancyfx.org/nancy-nuget.png", + + "packOptions": { + "tags": [ "Nancy", "Embedded", "Static Content" ], + "projectUrl": "http://nancyfx.org", + "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", + "iconUrl": "http://nancyfx.org/nancy-nuget.png" + }, "dependencies": { "Nancy": { "target": "project" } }, "frameworks": { - "dotnet5.4": { }, - "net451": { } + "netstandard1.5": { + "imports": [ + "portable-net451+win8" + ] + }, + "net452": { } } } diff --git a/src/Nancy.Encryption.MachineKey/project.json b/src/Nancy.Encryption.MachineKey/project.json index 4b1dfd6bf2..563e60a395 100644 --- a/src/Nancy.Encryption.MachineKey/project.json +++ b/src/Nancy.Encryption.MachineKey/project.json @@ -1,22 +1,24 @@ { "version": "2.0.0-*", - "description": "System.Web MachineKey encrypton and HMAC providers for Nancy.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - "tags": [ "Nancy", "Encryption" ], - "projectUrl": "http://nancyfx.org", - "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", - "iconUrl": "http://nancyfx.org/nancy-nuget.png", + + "packOptions": { + "tags": [ "Nancy", "Encryption" ], + "projectUrl": "http://nancyfx.org", + "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", + "iconUrl": "http://nancyfx.org/nancy-nuget.png" + }, "dependencies": { "Nancy": { "target": "project" } }, "frameworks": { - "net451": { + "net452": { "frameworkAssemblies": { - "System.Configuration": "4.0.0.0", - "System.Web": "4.0.0.0" + "System.Configuration": { "type": "build" }, + "System.Web": { "type": "build" } } } } diff --git a/src/Nancy.Hosting.Aspnet/project.json b/src/Nancy.Hosting.Aspnet/project.json index 5f7606d2f0..4b316df31d 100644 --- a/src/Nancy.Hosting.Aspnet/project.json +++ b/src/Nancy.Hosting.Aspnet/project.json @@ -1,22 +1,24 @@ { "version": "2.0.0-*", - "description": "Enables hosting Nancy on ASP.NET.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - "tags": [ "Nancy", "Host" ], - "projectUrl": "http://nancyfx.org", - "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", - "iconUrl": "http://nancyfx.org/nancy-nuget.png", + + "packOptions": { + "tags": [ "Nancy", "Host" ], + "projectUrl": "http://nancyfx.org", + "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", + "iconUrl": "http://nancyfx.org/nancy-nuget.png" + }, "dependencies": { "Nancy": { "target": "project" } }, "frameworks": { - "net451": { + "net452": { "frameworkAssemblies": { - "System.Configuration": "4.0.0.0", - "System.Web": "4.0.0.0" + "System.Configuration": { "type": "build" }, + "System.Web": { "type": "build" } } } } diff --git a/src/Nancy.Hosting.Self/FileSystemRootPathProvider.cs b/src/Nancy.Hosting.Self/FileSystemRootPathProvider.cs index 2dca9a0495..006058b5c5 100644 --- a/src/Nancy.Hosting.Self/FileSystemRootPathProvider.cs +++ b/src/Nancy.Hosting.Self/FileSystemRootPathProvider.cs @@ -18,19 +18,8 @@ private static string ExtractRootPath() var assembly = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly(); - var location = string.Empty; + var location = assembly.Location; -#if DNX - var libraryManager = - Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.LibraryManager; - - var library = - libraryManager.GetLibrary(assembly.GetName().Name); - - location = library.Path; -#else - location = assembly.Location; -#endif return Path.GetDirectoryName(location); } } diff --git a/src/Nancy.Hosting.Self/project.json b/src/Nancy.Hosting.Self/project.json index c35b92084b..6a9b3df5a9 100644 --- a/src/Nancy.Hosting.Self/project.json +++ b/src/Nancy.Hosting.Self/project.json @@ -1,23 +1,26 @@ { "version": "2.0.0-*", - "description": "Enables hosting Nancy in any application.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - "tags": [ "Nancy", "Host" ], - "projectUrl": "http://nancyfx.org", - "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", - "iconUrl": "http://nancyfx.org/nancy-nuget.png", + + "packOptions": { + "tags": [ "Nancy", "Host" ], + "projectUrl": "http://nancyfx.org", + "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", + "iconUrl": "http://nancyfx.org/nancy-nuget.png" + }, - "compilationOptions": { - "define": [ "DNX" ] + "buildOptions": { + "define": [ "CORE" ] }, "dependencies": { - "Nancy": { "target": "project" }, - "Microsoft.Extensions.PlatformAbstractions": "1.0.0-rc1-final" + "Nancy": { "target": "project" } }, "frameworks": { - "net451": { } + "net452": { + + } } } diff --git a/src/Nancy.Metadata.Modules/project.json b/src/Nancy.Metadata.Modules/project.json index e708e6140b..47063cc42f 100644 --- a/src/Nancy.Metadata.Modules/project.json +++ b/src/Nancy.Metadata.Modules/project.json @@ -1,19 +1,25 @@ { "version": "2.0.0-*", - "description": "Nancy metadata modules to describe your APIs.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - "tags": [ "Nancy", "Metadata" ], - "projectUrl": "http://nancyfx.org", - "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", - "iconUrl": "http://nancyfx.org/nancy-nuget.png", + + "packOptions": { + "tags": [ "Nancy", "Metadata" ], + "projectUrl": "http://nancyfx.org", + "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", + "iconUrl": "http://nancyfx.org/nancy-nuget.png" + }, "dependencies": { "Nancy": { "target": "project" } }, "frameworks": { - "dotnet5.4": { }, - "net451": { } + "netstandard1.5": { + "imports": [ + "portable-net451+win8" + ] + }, + "net452": { } } } diff --git a/src/Nancy.Owin/project.json b/src/Nancy.Owin/project.json index 27a0918a19..3b91e23720 100644 --- a/src/Nancy.Owin/project.json +++ b/src/Nancy.Owin/project.json @@ -1,12 +1,14 @@ { "version": "2.0.0-*", - "description": "Nancy extensions for OWIN hosting.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - "tags": [ "Nancy", "OWIN" ], - "projectUrl": "http://nancyfx.org", - "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", - "iconUrl": "http://nancyfx.org/nancy-nuget.png", + + "packOptions": { + "tags": [ "Nancy", "OWIN" ], + "projectUrl": "http://nancyfx.org", + "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", + "iconUrl": "http://nancyfx.org/nancy-nuget.png" + }, "dependencies": { "Nancy": { "target": "project" }, @@ -14,6 +16,6 @@ }, "frameworks": { - "net451": { } + "net452": { } } } diff --git a/src/Nancy.Testing.MSBuild/Nancy.Testing.csproj b/src/Nancy.Testing.MSBuild/Nancy.Testing.csproj index 4ce898263b..87bae49575 100644 --- a/src/Nancy.Testing.MSBuild/Nancy.Testing.csproj +++ b/src/Nancy.Testing.MSBuild/Nancy.Testing.csproj @@ -181,12 +181,6 @@ PathHelper.cs - - True - True - Resources.resx - Properties\Resources.Designer.cs - QueryWrapper.cs @@ -209,18 +203,6 @@ Resources\NancyTestingCert.pfx - - - ResXFileCodeGenerator - Resources.Designer.cs - Properties\Resources.resx - - - - - Designer - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - - ..\Resources\NancyTestingCert.pfx;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/src/Nancy.Testing/project.json b/src/Nancy.Testing/project.json index 1a795ec122..4e2ecdd10d 100644 --- a/src/Nancy.Testing/project.json +++ b/src/Nancy.Testing/project.json @@ -1,12 +1,14 @@ { "version": "2.0.0-*", - "description": "Test harness for Nancy applications.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - "tags": [ "Nancy", "Testing" ], - "projectUrl": "http://nancyfx.org", - "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", - "iconUrl": "http://nancyfx.org/nancy-nuget.png", + + "packOptions": { + "tags": [ "Nancy", "Testing" ], + "projectUrl": "http://nancyfx.org", + "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", + "iconUrl": "http://nancyfx.org/nancy-nuget.png" + }, "dependencies": { "AngleSharp": "0.9.5", @@ -19,17 +21,21 @@ ], "frameworks": { - "dotnet5.4": { + "netstandard1.5": { "dependencies": { - "System.Xml.XmlDocument": "4.0.1-beta-23516", - "System.Xml.XDocument": "4.0.11-beta-23516" - } + "System.Xml.XmlDocument": "4.0.1-rc2-*", + "System.Xml.XDocument": "4.0.11-rc2-*" + }, + "imports": [ + "dotnet54", + "portable-net451+win8" + ] }, - "net451": { + "net452": { "frameworkAssemblies": { - "System.IO": "4.0.0.0", - "System.Runtime": "4.0.10.0", - "System.Xml.Linq": "4.0.0.0" + "System.IO": { "type": "build" }, + "System.Runtime": { "type": "build" }, + "System.Xml.Linq": { "type": "build" } } } } diff --git a/src/Nancy.Validation.DataAnnotations/project.json b/src/Nancy.Validation.DataAnnotations/project.json index e7d40b8b8d..f13b30606e 100644 --- a/src/Nancy.Validation.DataAnnotations/project.json +++ b/src/Nancy.Validation.DataAnnotations/project.json @@ -1,21 +1,23 @@ { "version": "2.0.0-*", - "description": "Adds Data Annotation validation support to Nancy.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - "tags": [ "Nancy", "Validation", "DataAnnotations" ], - "projectUrl": "http://nancyfx.org", - "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", - "iconUrl": "http://nancyfx.org/nancy-nuget.png", + + "packOptions": { + "tags": [ "Nancy", "Validation", "DataAnnotations" ], + "projectUrl": "http://nancyfx.org", + "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", + "iconUrl": "http://nancyfx.org/nancy-nuget.png" + }, "dependencies": { "Nancy": { "target": "project" } }, "frameworks": { - "net451": { + "net452": { "frameworkAssemblies": { - "System.ComponentModel.DataAnnotations": "4.0.0.0" + "System.ComponentModel.DataAnnotations": { "type": "build" } } } } diff --git a/src/Nancy.Validation.FluentValidation/project.json b/src/Nancy.Validation.FluentValidation/project.json index 4f743321d5..c64a5ccfa3 100644 --- a/src/Nancy.Validation.FluentValidation/project.json +++ b/src/Nancy.Validation.FluentValidation/project.json @@ -1,12 +1,14 @@ { "version": "2.0.0-*", - "description": "Adds Fluent Validation support to Nancy.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - "tags": [ "Nancy", "Validation", "FluentValidation" ], - "projectUrl": "http://nancyfx.org", - "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", - "iconUrl": "http://nancyfx.org/nancy-nuget.png", + + "packOptions": { + "tags": [ "Nancy", "Validation", "FluentValidation" ], + "projectUrl": "http://nancyfx.org", + "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", + "iconUrl": "http://nancyfx.org/nancy-nuget.png" + }, "dependencies": { "Nancy": { "target": "project" }, @@ -14,6 +16,6 @@ }, "frameworks": { - "net451": { } + "net452": { } } } diff --git a/src/Nancy.ViewEngines.DotLiquid/project.json b/src/Nancy.ViewEngines.DotLiquid/project.json index d0785cbd04..54186972ac 100644 --- a/src/Nancy.ViewEngines.DotLiquid/project.json +++ b/src/Nancy.ViewEngines.DotLiquid/project.json @@ -1,12 +1,14 @@ { "version": "2.0.0-*", - "description": "Enables using the DotLiquid view engine with Nancy.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - "tags": [ "Nancy", "View Engine", "DotLiquid" ], - "projectUrl": "http://nancyfx.org", - "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", - "iconUrl": "http://nancyfx.org/nancy-nuget.png", + + "packOptions": { + "tags": [ "Nancy", "View Engine", "DotLiquid" ], + "projectUrl": "http://nancyfx.org", + "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", + "iconUrl": "http://nancyfx.org/nancy-nuget.png" + }, "dependencies": { "Nancy": { "target": "project" }, @@ -14,6 +16,6 @@ }, "frameworks": { - "net451": { } + "net452": { } } } diff --git a/src/Nancy.ViewEngines.Markdown/project.json b/src/Nancy.ViewEngines.Markdown/project.json index bbe1551f6f..408d45def0 100644 --- a/src/Nancy.ViewEngines.Markdown/project.json +++ b/src/Nancy.ViewEngines.Markdown/project.json @@ -1,12 +1,14 @@ { "version": "2.0.0-*", - "description": "Enables using Markdown with Nancy.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - "tags": [ "Nancy", "View Engine", "Markdown" ], - "projectUrl": "http://nancyfx.org", - "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", - "iconUrl": "http://nancyfx.org/nancy-nuget.png", + + "packOptions": { + "tags": [ "Nancy", "View Engine", "Markdown" ], + "projectUrl": "http://nancyfx.org", + "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", + "iconUrl": "http://nancyfx.org/nancy-nuget.png" + }, "dependencies": { "Nancy": { "target": "project" }, @@ -14,6 +16,6 @@ }, "frameworks": { - "net451": { } + "net452": { } } } diff --git a/src/Nancy.ViewEngines.Nustache/project.json b/src/Nancy.ViewEngines.Nustache/project.json index e2524184ca..64cb08c8aa 100644 --- a/src/Nancy.ViewEngines.Nustache/project.json +++ b/src/Nancy.ViewEngines.Nustache/project.json @@ -1,12 +1,14 @@ { "version": "2.0.0-*", - "description": "Enables using the Nustache view engine with Nancy.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - "tags": [ "Nancy", "View Engine", "Nustache" ], - "projectUrl": "http://nancyfx.org", - "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", - "iconUrl": "http://nancyfx.org/nancy-nuget.png", + + "packOptions": { + "tags": [ "Nancy", "View Engine", "Nustache" ], + "projectUrl": "http://nancyfx.org", + "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", + "iconUrl": "http://nancyfx.org/nancy-nuget.png" + }, "dependencies": { "Nancy": { "target": "project" }, @@ -14,6 +16,6 @@ }, "frameworks": { - "net451": { } + "net452": { } } } diff --git a/src/Nancy.ViewEngines.Razor.BuildProviders/project.json b/src/Nancy.ViewEngines.Razor.BuildProviders/project.json index 9fc1811923..adc95bd0c3 100644 --- a/src/Nancy.ViewEngines.Razor.BuildProviders/project.json +++ b/src/Nancy.ViewEngines.Razor.BuildProviders/project.json @@ -7,9 +7,9 @@ }, "frameworks": { - "net451": { + "net452": { "frameworkAssemblies": { - "System.Web": "4.0.0.0" + "System.Web": { "type": "build" } } } } diff --git a/src/Nancy.ViewEngines.Razor/RazorViewEngine.cs b/src/Nancy.ViewEngines.Razor/RazorViewEngine.cs index 26bebc75bc..2e37e5b4ff 100644 --- a/src/Nancy.ViewEngines.Razor/RazorViewEngine.cs +++ b/src/Nancy.ViewEngines.Razor/RazorViewEngine.cs @@ -266,41 +266,10 @@ private Lazy> GetMetadataReferences() { return new Lazy>(() => { - var references = new List(); - - var assemblyCatalogReferences = this.razorAssemblyProvider.GetAssemblies() + return this.razorAssemblyProvider.GetAssemblies() .Where(x => !string.IsNullOrEmpty(x.Location)) .Select(x => MetadataReference.CreateFromFile(x.Location)) .ToList(); - - references.AddRange(assemblyCatalogReferences); - -#if DNX - var libraryExporter = - Microsoft.Dnx.Compilation.CompilationServices.Default.LibraryExporter; - - var services = - Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default; - - var q = libraryExporter.GetAllExports(services.Application.ApplicationName).MetadataReferences; - - var projectReferences = libraryExporter.GetAllExports(services.Application.ApplicationName).MetadataReferences - .Where(x => x is Microsoft.Dnx.Compilation.IMetadataProjectReference) - .Cast() - .Select(x => - { - using (var ms = new MemoryStream()) - { - x.EmitReferenceAssembly(ms); - return MetadataReference.CreateFromImage(ms.ToArray()); - } - }) - .ToArray(); - - references.AddRange(projectReferences); -#endif - - return references; }); } diff --git a/src/Nancy.ViewEngines.Razor/project.json b/src/Nancy.ViewEngines.Razor/project.json index 031cccd9a0..b133ecac44 100644 --- a/src/Nancy.ViewEngines.Razor/project.json +++ b/src/Nancy.ViewEngines.Razor/project.json @@ -1,12 +1,14 @@ { "version": "2.0.0-*", - "description": "Enables using the Razor view engine with Nancy.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - "tags": [ "Nancy", "View Engine", "Razor" ], - "projectUrl": "http://nancyfx.org", - "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", - "iconUrl": "http://nancyfx.org/nancy-nuget.png", + + "packOptions": { + "tags": [ "Nancy", "View Engine", "Razor" ], + "projectUrl": "http://nancyfx.org", + "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", + "iconUrl": "http://nancyfx.org/nancy-nuget.png" + }, "dependencies": { "Nancy": { "target": "project" }, @@ -14,30 +16,23 @@ "Microsoft.CodeAnalysis.CSharp": "1.1.0-rc1-20151109-01" }, - "compilationOptions": { - "define": [ "DNX" ] - }, - "resource": "Resources/**/*.*", "frameworks": { - "net451": { + "net452": { + "buildOptions": { + "define": [ "DNX" ] + }, "dependencies": { - "Microsoft.Dnx.Compilation.Abstractions": "1.0.0-rc1-final", - "Microsoft.CodeDom.Providers.DotNetCompilerPlatform": "1.0.1", - "Microsoft.Extensions.PlatformAbstractions": "1.0.0-rc1-final", - "Microsoft.Net.Compilers": { - "version": "1.1.1", - "type": "build" - } + "Microsoft.CodeDom.Providers.DotNetCompilerPlatform": "1.0.1" }, "frameworkAssemblies": { - "System.Configuration": "4.0.0.0", - "System.IO": "4.0.0.0", - "System.Reflection": "4.0.0.0", - "System.Runtime": "4.0.10.0", - "System.Text.Encoding": "4.0.0.0", - "System.Threading.Tasks": "4.0.0.0" + "System.Configuration": { "type": "build" }, + "System.IO": { "type": "build" }, + "System.Reflection": { "type": "build" }, + "System.Runtime": { "type": "build" }, + "System.Text.Encoding": { "type": "build" }, + "System.Threading.Tasks": { "type": "build" } } } } diff --git a/src/Nancy.ViewEngines.Spark/project.json b/src/Nancy.ViewEngines.Spark/project.json index 22d83a008a..bb133a5de1 100644 --- a/src/Nancy.ViewEngines.Spark/project.json +++ b/src/Nancy.ViewEngines.Spark/project.json @@ -1,12 +1,14 @@ { "version": "2.0.0-*", - "description": "Enables using the Spark view engine with Nancy.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], "tags": [ "Nancy", "View Engine", "Spark" ], - "projectUrl": "http://nancyfx.org", - "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", - "iconUrl": "http://nancyfx.org/nancy-nuget.png", + + "packOptions": { + "projectUrl": "http://nancyfx.org", + "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", + "iconUrl": "http://nancyfx.org/nancy-nuget.png" + }, "dependencies": { "Nancy": { "target": "project" }, @@ -14,10 +16,10 @@ }, "frameworks": { - "net451": { + "net452": { "frameworkAssemblies": { - "System.Configuration": "4.0.0.0", - "System.Web": "4.0.0.0" + "System.Configuration": { "type": "build" }, + "System.Web": { "type": "build" } } } } diff --git a/src/Nancy/AppDomainAssemblyCatalog.cs b/src/Nancy/AppDomainAssemblyCatalog.cs index 08a1342e82..39e5ef3fda 100644 --- a/src/Nancy/AppDomainAssemblyCatalog.cs +++ b/src/Nancy/AppDomainAssemblyCatalog.cs @@ -1,4 +1,4 @@ -#if !DNX +#if !CORE namespace Nancy { using System; diff --git a/src/Nancy/Bootstrapper/BootstrapperException.cs b/src/Nancy/Bootstrapper/BootstrapperException.cs index 26100086f9..2032aba833 100644 --- a/src/Nancy/Bootstrapper/BootstrapperException.cs +++ b/src/Nancy/Bootstrapper/BootstrapperException.cs @@ -28,7 +28,7 @@ public BootstrapperException(string message, Exception innerException) : base(me { } -#if !DOTNET5_4 +#if !NETSTANDARD1_5 /// /// Initializes a new instance of the class. /// diff --git a/src/Nancy/Bootstrapper/MultipleRootPathProvidersLocatedException.cs b/src/Nancy/Bootstrapper/MultipleRootPathProvidersLocatedException.cs index 2e120a59db..cd0ff62182 100644 --- a/src/Nancy/Bootstrapper/MultipleRootPathProvidersLocatedException.cs +++ b/src/Nancy/Bootstrapper/MultipleRootPathProvidersLocatedException.cs @@ -52,7 +52,7 @@ public MultipleRootPathProvidersLocatedException(IEnumerable providerTypes this.StoreProviderTypes(providerTypes); } -#if !DOTNET5_4 +#if !NETSTANDARD1_5 /// /// Initializes a new instance of the class. /// diff --git a/src/Nancy/Bootstrapper/NancyBootstrapperBase.cs b/src/Nancy/Bootstrapper/NancyBootstrapperBase.cs index 72e0a7ee85..83a183ba54 100755 --- a/src/Nancy/Bootstrapper/NancyBootstrapperBase.cs +++ b/src/Nancy/Bootstrapper/NancyBootstrapperBase.cs @@ -91,10 +91,10 @@ protected virtual IAssemblyCatalog AssemblyCatalog { get { return this.assemblyCatalog ?? ( -#if !DNX +#if !CORE this.assemblyCatalog = new AppDomainAssemblyCatalog() #else - this.assemblyCatalog = new LibraryManagerAssemblyCatalog() + this.assemblyCatalog = new DependencyContextAssemblyCatalog() #endif ); } diff --git a/src/Nancy/Bootstrapper/NancyBootstrapperLocator.cs b/src/Nancy/Bootstrapper/NancyBootstrapperLocator.cs index d46a3a12e1..fa2072157a 100755 --- a/src/Nancy/Bootstrapper/NancyBootstrapperLocator.cs +++ b/src/Nancy/Bootstrapper/NancyBootstrapperLocator.cs @@ -56,34 +56,17 @@ private static IReadOnlyCollection GetAvailableBootstrapperTypes() private static IEnumerable GetNancyReferencingAssemblies() { -#if DNX - var libraryManager = Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.LibraryManager; +#if CORE + var assemblyCatalog = + new DependencyContextAssemblyCatalog(); - var results = new HashSet - { - typeof (INancyEngine).GetAssembly() - }; - - var referencingLibraries = libraryManager.GetReferencingLibraries(NancyAssemblyName.Name); - - foreach (var assemblyName in referencingLibraries.SelectMany(referencingLibrary => referencingLibrary.Assemblies)) - { - try - { - results.Add(Assembly.Load(assemblyName)); - } - catch - { - } - } - - return results.ToArray(); + return assemblyCatalog.GetAssemblies(); #else return AppDomain.CurrentDomain.GetAssemblies().Where(IsNancyReferencing).Where(assembly => !assembly.ReflectionOnly); #endif } -#if !DNX +#if !CORE private static bool IsNancyReferencing(Assembly assembly) { if (AssemblyName.ReferenceMatchesDefinition(assembly.GetName(), NancyAssemblyName)) diff --git a/src/Nancy/DefaultRootPathProvider.cs b/src/Nancy/DefaultRootPathProvider.cs index 0d7a9d6c7a..d1cd50d049 100644 --- a/src/Nancy/DefaultRootPathProvider.cs +++ b/src/Nancy/DefaultRootPathProvider.cs @@ -13,7 +13,7 @@ public class DefaultRootPathProvider : IRootPathProvider /// A containing the path of the root folder. public string GetRootPath() { -#if DNX +#if CORE return Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.ApplicationBasePath; #else return AppDomain.CurrentDomain.BaseDirectory; @@ -21,3 +21,4 @@ public string GetRootPath() } } } + diff --git a/src/Nancy/DependencyContextAssemblyCatalog.cs b/src/Nancy/DependencyContextAssemblyCatalog.cs new file mode 100644 index 0000000000..2c6ca0205d --- /dev/null +++ b/src/Nancy/DependencyContextAssemblyCatalog.cs @@ -0,0 +1,72 @@ +#if CORE +namespace Nancy +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + using Microsoft.Extensions.DependencyModel; + + /// + /// Default implementation of the interface, based on + /// retrieving information from . + /// + public class DependencyContextAssemblyCatalog : IAssemblyCatalog + { + private static readonly Assembly NancyAssembly = typeof(INancyEngine).GetTypeInfo().Assembly; + private readonly DependencyContext dependencyContext; + + /// + /// Initializes a new instance of the class. + /// + public DependencyContextAssemblyCatalog() + { + var entryAssembly = Assembly.GetEntryAssembly(); + + this.dependencyContext = DependencyContext.Load(entryAssembly); + } + + /// + /// Gets all instances in the catalog. + /// + /// An of instances. + public IReadOnlyCollection GetAssemblies() + { + var results = new HashSet + { + typeof (DependencyContextAssemblyCatalog).GetTypeInfo().Assembly + }; + + foreach (var library in this.dependencyContext.RuntimeLibraries) + { + if (IsReferencingNancy(library)) + { + foreach (var assemblyName in library.GetDefaultAssemblyNames(this.dependencyContext)) + { + results.Add(SafeLoadAssembly(assemblyName)); + } + } + } + + return results.ToArray(); + } + + private static Assembly SafeLoadAssembly(AssemblyName assemblyName) + { + try + { + return Assembly.Load(assemblyName); + } + catch (Exception) + { + return null; + } + } + + private static bool IsReferencingNancy(Library library) + { + return library.Dependencies.Any(dependency => dependency.Name.Equals(NancyAssembly.GetName().Name)); + } + } +} +#endif diff --git a/src/Nancy/Diagnostics/DiagnosticsSession.cs b/src/Nancy/Diagnostics/DiagnosticsSession.cs index 612c0e6c9c..75376ee3c3 100644 --- a/src/Nancy/Diagnostics/DiagnosticsSession.cs +++ b/src/Nancy/Diagnostics/DiagnosticsSession.cs @@ -4,7 +4,7 @@ namespace Nancy.Diagnostics using System.Security.Cryptography; using System.Text; -#if !DOTNET5_4 +#if !NETSTANDARD1_5 [Serializable] #endif public class DiagnosticsSession diff --git a/src/Nancy/DynamicDictionaryValue.cs b/src/Nancy/DynamicDictionaryValue.cs index 00f50c99bf..792e0876fb 100644 --- a/src/Nancy/DynamicDictionaryValue.cs +++ b/src/Nancy/DynamicDictionaryValue.cs @@ -322,7 +322,7 @@ public override bool TryConvert(ConvertBinder binder, out object result) } } -#if !DOTNET5_4 +#if !NETSTANDARD1_5 result = Convert.ChangeType(value, typeCode); #else result = Convert.ChangeType(value, binderType); diff --git a/src/Nancy/Extensions/MemoryStreamExtensions.cs b/src/Nancy/Extensions/MemoryStreamExtensions.cs index eab3b3746b..e49b0235d6 100644 --- a/src/Nancy/Extensions/MemoryStreamExtensions.cs +++ b/src/Nancy/Extensions/MemoryStreamExtensions.cs @@ -7,7 +7,7 @@ public static class MemoryStreamExtensions { public static ArraySegment GetBufferSegment(this MemoryStream stream) { -#if DOTNET5_4 +#if NETSTANDARD1_5 ArraySegment buffer; if (stream.TryGetBuffer(out buffer)) { @@ -21,7 +21,7 @@ public static ArraySegment GetBufferSegment(this MemoryStream stream) private static byte[] GetBytes(this MemoryStream stream) { -#if DOTNET5_4 +#if NETSTANDARD1_5 return stream.ToArray(); // This is all we have if TryGetBuffer fails in GetBufferSegment #else return stream.GetBuffer(); diff --git a/src/Nancy/Extensions/TypeExtensions.cs b/src/Nancy/Extensions/TypeExtensions.cs index 63c8aa4cd9..42c2dba42d 100644 --- a/src/Nancy/Extensions/TypeExtensions.cs +++ b/src/Nancy/Extensions/TypeExtensions.cs @@ -206,7 +206,7 @@ public static TypeCode GetTypeCode(this Type type) private static object CreateInstanceInternal(Type type, bool nonPublic = false) { -#if !DOTNET5_4 +#if !NETSTANDARD1_5 return Activator.CreateInstance(type, nonPublic); } #else diff --git a/src/Nancy/HeadResponse.cs b/src/Nancy/HeadResponse.cs index 7595a78e34..5caba97459 100644 --- a/src/Nancy/HeadResponse.cs +++ b/src/Nancy/HeadResponse.cs @@ -62,7 +62,7 @@ public override void Flush() { } -#if !DOTNET5_4 +#if !NETSTANDARD1_5 public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { throw new NotSupportedException(); diff --git a/src/Nancy/IO/RequestStream.cs b/src/Nancy/IO/RequestStream.cs index c23052c69f..5d62c1c23f 100644 --- a/src/Nancy/IO/RequestStream.cs +++ b/src/Nancy/IO/RequestStream.cs @@ -175,7 +175,7 @@ public override long Position } } -#if !DOTNET5_4 +#if !NETSTANDARD1_5 /// /// Begins an asynchronous read operation. /// @@ -223,7 +223,7 @@ protected override void Dispose(bool disposing) base.Dispose(disposing); } -#if !DOTNET5_4 +#if !NETSTANDARD1_5 /// /// Waits for the pending asynchronous read to complete. /// @@ -351,7 +351,7 @@ private void ShiftStreamToFileStreamIfNecessary() // in NancyWcfGenericService - webRequest.UriTemplateMatch var old = this.stream; this.MoveStreamContentsToFileStream(); -#if DOTNET5_4 +#if NETSTANDARD1_5 old.Dispose(); #else old.Close(); @@ -375,7 +375,7 @@ private static FileStream CreateTemporaryFileStream() FileAccess.ReadWrite, FileShare.None, 8192, - StaticConfiguration.AllowFileStreamUploadAsync); + StaticConfiguration.AllowFileStreamUploadAsync); } private Stream CreateDefaultMemoryStream(long expectedLength) @@ -444,7 +444,7 @@ private void MoveStreamContentsToFileStream() if (this.stream.CanSeek && this.stream.Length == 0) { -#if DOTNET5_4 +#if NETSTANDARD1_5 this.stream.Dispose(); #else this.stream.Close(); diff --git a/src/Nancy/IO/UnclosableStreamWrapper.cs b/src/Nancy/IO/UnclosableStreamWrapper.cs index e860ce1052..eb85d9b032 100644 --- a/src/Nancy/IO/UnclosableStreamWrapper.cs +++ b/src/Nancy/IO/UnclosableStreamWrapper.cs @@ -175,7 +175,7 @@ public override int WriteTimeout this.baseStream.WriteTimeout = value; } } -#if !DOTNET5_4 +#if !NETSTANDARD1_5 /// /// Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. /// @@ -244,7 +244,7 @@ public override void Write(byte[] buffer, int offset, int count) this.baseStream.Write(buffer, offset, count); } -#if !DOTNET5_4 +#if !NETSTANDARD1_5 /// /// Begins an asynchronous read operation. /// diff --git a/src/Nancy/Json/SimpleJson.cs b/src/Nancy/Json/SimpleJson.cs index 7caf436e8a..263af4edfd 100644 --- a/src/Nancy/Json/SimpleJson.cs +++ b/src/Nancy/Json/SimpleJson.cs @@ -46,7 +46,7 @@ // 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 -#if NETFX_CORE || DOTNET5_4 +#if NETFX_CORE || NETSTANDARD1_5 #define SIMPLE_JSON_TYPEINFO #endif diff --git a/src/Nancy/LibraryManagerAssemblyCatalog.cs b/src/Nancy/LibraryManagerAssemblyCatalog.cs deleted file mode 100644 index ea803e8cbf..0000000000 --- a/src/Nancy/LibraryManagerAssemblyCatalog.cs +++ /dev/null @@ -1,68 +0,0 @@ -#if DNX -namespace Nancy -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.Reflection; - using Microsoft.Extensions.PlatformAbstractions; - - /// - /// Default implementation of the interface, based on - /// retrieving information from an . - /// - public class LibraryManagerAssemblyCatalog : IAssemblyCatalog - { - private readonly ILibraryManager libraryManager; - private readonly AssemblyName nancyAssemblyName = typeof(LibraryManagerAssemblyCatalog).GetTypeInfo().Assembly.GetName(); - private readonly Lazy> assemblies; - - /// - /// Initializes a new instance of the class. - /// - public LibraryManagerAssemblyCatalog() - { - this.libraryManager = PlatformServices.Default.LibraryManager; - this.assemblies = new Lazy>(this.LoadAllNancyReferencingAssemblies); - } - - /// - /// Gets all instances in the catalog. - /// - /// An of instances. - public IReadOnlyCollection GetAssemblies() - { - return this.assemblies.Value; - } - - private IReadOnlyCollection LoadAllNancyReferencingAssemblies() - { - var results = new HashSet - { - typeof (INancyEngine).GetTypeInfo().Assembly - }; - - var referencingLibraries = this.libraryManager.GetReferencingLibraries(this.nancyAssemblyName.Name); - - foreach (var assemblyName in referencingLibraries.SelectMany(referencingLibrary => referencingLibrary.Assemblies)) - { - results.Add(SafeLoadAssembly(assemblyName)); - } - - return results.ToArray(); - } - - private static Assembly SafeLoadAssembly(AssemblyName assemblyName) - { - try - { - return Assembly.Load(assemblyName); - } - catch (Exception) - { - return null; - } - } - } -} -#endif diff --git a/src/Nancy/ModelBinding/ModelBindingException.cs b/src/Nancy/ModelBinding/ModelBindingException.cs index f08b9c5514..ceaee62e42 100644 --- a/src/Nancy/ModelBinding/ModelBindingException.cs +++ b/src/Nancy/ModelBinding/ModelBindingException.cs @@ -38,7 +38,7 @@ public ModelBindingException(Type boundType, IEnumerable(); this.BoundType = boundType; } -#if !DOTNET5_4 +#if !NETSTANDARD1_5 /// /// Initializes a new instance of the class with serialized data. /// diff --git a/src/Nancy/Security/CsrfToken.cs b/src/Nancy/Security/CsrfToken.cs index 5c6333939c..6704b77d3e 100644 --- a/src/Nancy/Security/CsrfToken.cs +++ b/src/Nancy/Security/CsrfToken.cs @@ -6,7 +6,7 @@ /// /// Represents a Csrf protection token /// -#if !DOTNET5_4 +#if !NETSTANDARD1_5 [Serializable] #endif public sealed class CsrfToken diff --git a/src/Nancy/TinyIoc/TinyIoC.cs b/src/Nancy/TinyIoc/TinyIoC.cs index 1cfdb1df68..a1ffeb823f 100755 --- a/src/Nancy/TinyIoc/TinyIoC.cs +++ b/src/Nancy/TinyIoc/TinyIoC.cs @@ -76,7 +76,7 @@ #endif -#if DOTNET5_4 +#if NETSTANDARD1_5 #undef SERIALIZABLE #undef APPDOMAIN_GETASSEMBLIES #endif @@ -4034,7 +4034,7 @@ private static bool IsValidAssignment(Type registerType, Type registerImplementa { if (registerType.IsInterface()) { -#if (PORTABLE || DOTNET5_4) +#if (PORTABLE || NETSTANDARD1_5) if (!registerImplementation.GetInterfaces().Any(t => t.Name == registerType.Name)) return false; #else @@ -4070,7 +4070,7 @@ public void Dispose() #endregion } -#if DOTNET5_4 +#if NETSTANDARD1_5 static class ReverseTypeExtender { public static bool IsClass(this Type type) @@ -4125,7 +4125,7 @@ public static Assembly Assembly(this Type type) } #endif // reverse shim for WinRT SR changes... -#if (!NETFX_CORE && !DOTNET5_4) +#if (!NETFX_CORE && !NETSTANDARD1_5) static class ReverseTypeExtender { public static bool IsClass(this Type type) diff --git a/src/Nancy/project.json b/src/Nancy/project.json index 641e2554cf..8b7ebe227f 100644 --- a/src/Nancy/project.json +++ b/src/Nancy/project.json @@ -1,56 +1,64 @@ { "version": "2.0.0-*", - "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.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - "tags": [ "Nancy" ], - "projectUrl": "http://nancyfx.org", - "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", - "iconUrl": "http://nancyfx.org/nancy-nuget.png", - "compilationOptions": { - "define": [ "DNX" ] + + "packOptions": { + "tags": [ "Nancy" ], + "projectUrl": "http://nancyfx.org", + "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", + "iconUrl": "http://nancyfx.org/nancy-nuget.png" }, "dependencies": { - "Microsoft.Extensions.PlatformAbstractions": "1.0.0-rc1-final" + "Microsoft.Extensions.DependencyModel": "1.0.0-rc2-*" }, "resource": [ - "Diagnostics/Resources/**/*.*", - "Diagnostics/Views/**/*.*" + "Diagnostics/Resources/**/*.*", + "Diagnostics/Views/**/*.*" ], "frameworks": { - "dotnet5.4": { - "dependencies": { - "Microsoft.CSharp": "4.0.1-beta-23516", - "System.Collections.Concurrent": "4.0.11-beta-23516", - "System.Collections.Specialized": "4.0.1-beta-23516", - "System.ComponentModel.TypeConverter": "4.0.1-beta-23516", - "System.Console": "4.0.0-beta-23516", - "System.Data.Common": "4.0.1-beta-23516", - "System.Diagnostics.Tools": "4.0.1-beta-23516", - "System.Dynamic.Runtime": "4.0.11-beta-23516", - "System.IO": "4.0.11-beta-23516", - "System.IO.FileSystem": "4.0.1-beta-23516", - "System.Linq": "4.0.1-beta-23516", - "System.Net.NameResolution": "4.0.0-beta-23516", - "System.Net.Primitives": "4.0.11-beta-23516", - "System.Reflection.Extensions": "4.0.1-beta-23516", - "System.Reflection.TypeExtensions": "4.1.0-beta-23516", - "System.Runtime": "4.0.21-beta-23516", - "System.Runtime.Serialization.Primitives": "4.1.0-beta-23516", - "System.Security.Claims": "4.0.1-beta-23516", - "System.Security.Cryptography.Algorithms": "4.0.0-beta-23516", - "System.Security.Cryptography.X509Certificates": "4.0.0-beta-23516", - "System.Text.RegularExpressions": "4.0.11-beta-23516", - "System.Threading.Thread": "4.0.0-beta-23516", - "System.Xml.XmlSerializer": "4.0.11-beta-23516" - } + "netstandard1.5": { + "buildOptions": { + "define": [ "CORE" ] + }, + "dependencies": { + "Microsoft.CSharp": "4.0.1-rc2-*", + "Microsoft.Extensions.PlatformAbstractions": "1.0.0-rc2-*", + "System.Collections.Concurrent": "4.0.12-rc2-*", + "System.Collections.Specialized": "4.0.1-rc2-*", + "System.ComponentModel.TypeConverter": "4.0.1-rc2-*", + "System.Console": "4.0.0-rc2-*", + "System.Data.Common": "4.0.1-rc2-*", + "System.Diagnostics.Tools": "4.0.1-rc2-*", + "System.Dynamic.Runtime": "4.0.11-rc2-*", + "System.IO": "4.1.0-rc2-*", + "System.IO.FileSystem": "4.0.1-rc2-*", + "System.Linq": "4.1.0-rc2-*", + "System.Net.NameResolution": "4.0.0-rc2-*", + "System.Net.Primitives": "4.0.11-rc2-*", + "System.Reflection.Extensions": "4.0.1-rc2-*", + "System.Reflection.TypeExtensions": "4.1.0-rc2-*", + "System.Runtime": "4.1.0-rc2-*", + "System.Runtime.Serialization.Primitives": "4.1.1-rc2-*", + "System.Security.Claims": "4.0.1-rc2-*", + "System.Security.Cryptography.Algorithms": "4.1.0-rc2-*", + "System.Security.Cryptography.X509Certificates": "4.1.0-rc2-*", + "System.Text.RegularExpressions": "4.0.12-rc2-*", + "System.Threading": "4.0.11-rc2-*", + "System.Threading.Thread": "4.0.0-rc2-*", + "System.Xml.XmlSerializer": "4.0.11-rc2-*" + }, + "imports": [ + "dotnet54", + "portable-net451+win8" + ] }, - "net451": { + "net452": { "frameworkAssemblies": { - "System.Xml": "4.0.0.0" + "System.Xml": { "type": "build"} } } } diff --git a/test/Nancy.Authentication.Basic.Tests/project.json b/test/Nancy.Authentication.Basic.Tests/project.json index 0ed7e44308..0d6c7c68c4 100644 --- a/test/Nancy.Authentication.Basic.Tests/project.json +++ b/test/Nancy.Authentication.Basic.Tests/project.json @@ -1,18 +1,10 @@ { "dependencies": { - "FakeItEasy": "2.0.0-beta011", + "dotnet-test-xunit": "1.0.0-*", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", "Nancy": { "target": "project" }, "Nancy.Authentication.Basic": { "target": "project" }, - "xunit": "2.1.0", - "xunit.runner.dnx": "2.1.0-*" - }, - - "commands": { - "test": "xunit.runner.dnx" - }, - - "compilationOptions": { - "define": [ "DNX" ] + "xunit": "2.1.0" }, "compileFiles": [ @@ -21,6 +13,16 @@ ], "frameworks": { - "dnx451": { } - } + "net452": { + "dependencies": { + "FakeItEasy": "2.0.0-beta011" + }, + "frameworkAssemblies": { + "System.Runtime": { "type": "build" }, + "System.Threading.Tasks": { "type": "build" } + } + } + }, + + "testRunner": "xunit" } diff --git a/test/Nancy.Authentication.Forms.Tests/project.json b/test/Nancy.Authentication.Forms.Tests/project.json index 083da1e5c3..e7f416264b 100644 --- a/test/Nancy.Authentication.Forms.Tests/project.json +++ b/test/Nancy.Authentication.Forms.Tests/project.json @@ -1,14 +1,10 @@ { "dependencies": { - "FakeItEasy": "2.0.0-beta011", + "dotnet-test-xunit": "1.0.0-*", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", "Nancy": { "target": "project" }, "Nancy.Authentication.Forms": { "target": "project" }, - "xunit": "2.1.0", - "xunit.runner.dnx": "2.1.0-*" - }, - - "commands": { - "test": "xunit.runner.dnx" + "xunit": "2.1.0" }, "compileFiles": [ @@ -16,15 +12,18 @@ "../Nancy.Tests/ShouldExtensions.cs" ], - "compilationOptions": { - "define": [ "DNX" ] - }, - "frameworks": { - "dnx451": { + "net452": { + "dependencies": { + "FakeItEasy": "2.0.0-beta011" + }, "frameworkAssemblies": { - "System.Web": "" + "System.Runtime": { "type": "build" }, + "System.Threading.Tasks": { "type": "build" }, + "System.Web": { "type": "build" } } } - } + }, + + "testRunner": "xunit" } diff --git a/test/Nancy.Embedded.Tests/project.json b/test/Nancy.Embedded.Tests/project.json index ae4e38d032..0ae98022b7 100644 --- a/test/Nancy.Embedded.Tests/project.json +++ b/test/Nancy.Embedded.Tests/project.json @@ -1,31 +1,29 @@ { "dependencies": { - "FakeItEasy": "2.0.0-beta011", + "dotnet-test-xunit": "1.0.0-*", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", "Nancy": { "target": "project" }, "Nancy.Embedded": { "target": "project" }, - "xunit": "2.1.0", - "xunit.runner.dnx": "2.1.0-*" - }, - - "commands": { - "test": "xunit.runner.dnx" + "xunit": "2.1.0" }, "compileFiles": [ "../Nancy.Tests/ShouldExtensions.cs" ], - "compilationOptions": { - "define": [ "DNX" ] - }, - "resource": "Resources/**/*.*", "frameworks": { - "dnx451": { + "net452": { + "dependencies": { + "FakeItEasy": "2.0.0-beta011" + }, "frameworkAssemblies": { - "System.Web": "" + "System.Runtime": { "type": "build" }, + "System.Web": { "type": "build" } } } - } + }, + + "testRunner": "xunit" } diff --git a/test/Nancy.Encryption.MachineKey.Tests/project.json b/test/Nancy.Encryption.MachineKey.Tests/project.json index 84da076d22..9ab0ba9dc1 100644 --- a/test/Nancy.Encryption.MachineKey.Tests/project.json +++ b/test/Nancy.Encryption.MachineKey.Tests/project.json @@ -1,18 +1,10 @@ { "dependencies": { - "FakeItEasy": "2.0.0-beta011", + "dotnet-test-xunit": "1.0.0-*", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", "Nancy": { "target": "project" }, "Nancy.Encryption.MachineKey": { "target": "project" }, - "xunit": "2.1.0", - "xunit.runner.dnx": "2.1.0-*" - }, - - "commands": { - "test": "xunit.runner.dnx" - }, - - "compilationOptions": { - "define": [ "DNX" ] + "xunit": "2.1.0" }, "compileFiles": [ @@ -20,6 +12,15 @@ ], "frameworks": { - "dnx451": { } - } + "net452": { + "dependencies": { + "FakeItEasy": "2.0.0-beta011" + }, + "frameworkAssemblies": { + "System.Runtime": { "type": "build" } + } + } + }, + + "testRunner": "xunit" } diff --git a/test/Nancy.Hosting.Aspnet.Tests/project.json b/test/Nancy.Hosting.Aspnet.Tests/project.json index b2534b04a0..dac94a1a90 100644 --- a/test/Nancy.Hosting.Aspnet.Tests/project.json +++ b/test/Nancy.Hosting.Aspnet.Tests/project.json @@ -1,25 +1,26 @@ { "dependencies": { - "FakeItEasy": "2.0.0-beta011", + "dotnet-test-xunit": "1.0.0-*", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", "Nancy": { "target": "project" }, "Nancy.Hosting.Aspnet": { "target": "project" }, - "xunit": "2.1.0", - "xunit.runner.dnx": "2.1.0-*" + "xunit": "2.1.0" }, - - "commands": { - "test": "xunit.runner.dnx" - }, - - "compilationOptions": { - "define": [ "DNX" ] - }, - + "compileFiles": [ "../Nancy.Tests/ShouldExtensions.cs" ], "frameworks": { - "dnx451": { } - } + "net452": { + "dependencies": { + "FakeItEasy": "2.0.0-beta011" + }, + "frameworkAssemblies": { + "System.Runtime": { "type": "build" } + } + } + }, + + "testRunner": "xunit" } diff --git a/test/Nancy.Hosting.Self.Tests/project.json b/test/Nancy.Hosting.Self.Tests/project.json index b50cf025a2..e96f4cc44f 100644 --- a/test/Nancy.Hosting.Self.Tests/project.json +++ b/test/Nancy.Hosting.Self.Tests/project.json @@ -1,18 +1,10 @@ { "dependencies": { - "FakeItEasy": "2.0.0-beta011", + "dotnet-test-xunit": "1.0.0-*", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", "Nancy": { "target": "project" }, "Nancy.Hosting.Self": { "target": "project" }, - "xunit": "2.1.0", - "xunit.runner.dnx": "2.1.0-*" - }, - - "commands": { - "test": "xunit.runner.dnx" - }, - - "compilationOptions": { - "define": [ "DNX" ] + "xunit": "2.1.0" }, "compileFiles": [ @@ -22,6 +14,16 @@ ], "frameworks": { - "dnx451": { } - } + "net452": { + "dependencies": { + "FakeItEasy": "2.0.0-beta011" + }, + "frameworkAssemblies": { + "System.Runtime": { "type": "build" }, + "System.Threading.Tasks": { "type": "build" } + } + } + }, + + "testRunner": "xunit" } diff --git a/test/Nancy.Metadata.Modules.Tests/project.json b/test/Nancy.Metadata.Modules.Tests/project.json index 8a97b4d0f0..df09cf6ba8 100644 --- a/test/Nancy.Metadata.Modules.Tests/project.json +++ b/test/Nancy.Metadata.Modules.Tests/project.json @@ -1,18 +1,10 @@ { "dependencies": { - "FakeItEasy": "2.0.0-beta011", + "dotnet-test-xunit": "1.0.0-*", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", "Nancy": { "target": "project" }, "Nancy.Metadata.Modules": { "target": "project" }, - "xunit": "2.1.0", - "xunit.runner.dnx": "2.1.0-*" - }, - - "commands": { - "test": "xunit.runner.dnx" - }, - - "compilationOptions": { - "define": [ "DNX" ] + "xunit": "2.1.0" }, "compileFiles": [ @@ -20,6 +12,15 @@ ], "frameworks": { - "dnx451": { } - } + "net452": { + "dependencies": { + "FakeItEasy": "2.0.0-beta011" + }, + "frameworkAssemblies": { + "System.Runtime": { "type": "build" } + } + } + }, + + "testRunner": "xunit" } diff --git a/test/Nancy.Owin.Tests/project.json b/test/Nancy.Owin.Tests/project.json index 58fe3808cb..b91877cef7 100644 --- a/test/Nancy.Owin.Tests/project.json +++ b/test/Nancy.Owin.Tests/project.json @@ -1,20 +1,12 @@ { "dependencies": { - "FakeItEasy": "2.0.0-beta011", + "dotnet-test-xunit": "1.0.0-*", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", "Microsoft.Owin.Testing": "2.1.0", "Nancy": { "target": "project" }, "Nancy.Owin": { "target": "project" }, "Nancy.Testing": { "target": "project" }, - "xunit": "2.1.0", - "xunit.runner.dnx": "2.1.0-*" - }, - - "commands": { - "test": "xunit.runner.dnx" - }, - - "compilationOptions": { - "define": [ "DNX" ] + "xunit": "2.1.0" }, "compileFiles": [ @@ -23,6 +15,15 @@ ], "frameworks": { - "dnx451": { } - } + "net452": { + "dependencies": { + "FakeItEasy": "2.0.0-beta011" + }, + "frameworkAssemblies": { + "System.Runtime": { "type": "build" } + } + } + }, + + "testRunner": "xunit" } diff --git a/test/Nancy.Testing.Tests/project.json b/test/Nancy.Testing.Tests/project.json index 4e6c521796..90f23c467b 100644 --- a/test/Nancy.Testing.Tests/project.json +++ b/test/Nancy.Testing.Tests/project.json @@ -1,19 +1,11 @@ { "dependencies": { "AngleSharp": "0.9.5", - "FakeItEasy": "2.0.0-beta011", + "dotnet-test-xunit": "1.0.0-*", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", "Nancy": { "target": "project" }, "Nancy.Testing": { "target": "project" }, - "xunit": "2.1.0", - "xunit.runner.dnx": "2.1.0-*" - }, - - "commands": { - "test": "xunit.runner.dnx" - }, - - "compilationOptions": { - "define": [ "DNX" ] + "xunit": "2.1.0" }, "compileFiles": [ @@ -26,6 +18,16 @@ ], "frameworks": { - "dnx451": { } - } + "net452": { + "dependencies": { + "FakeItEasy": "2.0.0-beta011" + }, + "frameworkAssemblies": { + "System.Runtime": { "type": "build" }, + "System.Threading.Tasks": { "type": "build" } + } + } + }, + + "testRunner": "xunit" } diff --git a/test/Nancy.Tests.Functional/Tests/PartialViewTests.cs b/test/Nancy.Tests.Functional/Tests/PartialViewTests.cs index cd5db69879..0daa6d6aee 100644 --- a/test/Nancy.Tests.Functional/Tests/PartialViewTests.cs +++ b/test/Nancy.Tests.Functional/Tests/PartialViewTests.cs @@ -1,4 +1,4 @@ -#if !DNXCORE50 +#if !NETCOREAPP1_0 namespace Nancy.Tests.Functional.Tests { using System; diff --git a/test/Nancy.Tests.Functional/Tests/TracingSmokeTests.cs b/test/Nancy.Tests.Functional/Tests/TracingSmokeTests.cs index 2641b023c1..99c99fb922 100644 --- a/test/Nancy.Tests.Functional/Tests/TracingSmokeTests.cs +++ b/test/Nancy.Tests.Functional/Tests/TracingSmokeTests.cs @@ -1,4 +1,4 @@ -#if !DNXCORE50 +#if !NETCOREAPP1_0 namespace Nancy.Tests.Functional.Tests { using System; diff --git a/test/Nancy.Tests.Functional/Tests/ViewBagTests.cs b/test/Nancy.Tests.Functional/Tests/ViewBagTests.cs index af62c8d16f..c2b440b944 100644 --- a/test/Nancy.Tests.Functional/Tests/ViewBagTests.cs +++ b/test/Nancy.Tests.Functional/Tests/ViewBagTests.cs @@ -1,4 +1,4 @@ -#if !DNXCORE50 +#if !NETCOREAPP1_0 namespace Nancy.Tests.Functional.Tests { using System.Threading.Tasks; diff --git a/test/Nancy.Tests.Functional/project.json b/test/Nancy.Tests.Functional/project.json index ce68ab2c6b..3b8895cd1d 100644 --- a/test/Nancy.Tests.Functional/project.json +++ b/test/Nancy.Tests.Functional/project.json @@ -1,30 +1,50 @@ { "dependencies": { + "dotnet-test-xunit": "1.0.0-*", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", "Nancy": { "target": "project" }, "Nancy.Testing": { "target": "project" }, - "xunit": "2.1.0", - "xunit.runner.dnx": "2.1.0-*" - }, - - "commands": { - "test": "xunit.runner.dnx", - "test-dnxcore50": "xunit.runner.dnx" - }, - - "compilationOptions": { - "define": [ "DNX" ] + "xunit": "2.1.0" }, "compileFiles": [ "../Nancy.Tests/xUnitExtensions/RecordAsync.cs" ], + + "content": [ + "Content/**/*", + "Views/**/*" + ], "frameworks": { - "dnxcore50": { }, - "dnx451": { + "netcoreapp1.0": { + "buildOptions": { + "define": [ "CORE" ] + }, + "dependencies": { + "dotnet-test-xunit": "1.0.0-*", + "Microsoft.NETCore.App": { + "type": "platform", + "version": "1.0.0-rc2-*" + } + }, + + "imports": [ + "dotnet", + "portable-net451+win8" + ] + }, + + "net452": { "dependencies": { "Nancy.ViewEngines.Razor": { "target": "project" } + }, + "frameworkAssemblies": { + "System.Runtime": { "type": "build" }, + "System.Threading.Tasks": { "type": "build" } } } - } + }, + + "testRunner": "xunit" } diff --git a/test/Nancy.Tests/Unit/Bootstrapper/NancyInternalConfigurationFixture.cs b/test/Nancy.Tests/Unit/Bootstrapper/NancyInternalConfigurationFixture.cs index b40fe2f044..c2efcadc07 100644 --- a/test/Nancy.Tests/Unit/Bootstrapper/NancyInternalConfigurationFixture.cs +++ b/test/Nancy.Tests/Unit/Bootstrapper/NancyInternalConfigurationFixture.cs @@ -14,10 +14,10 @@ public NancyInternalConfigurationFixture() { IAssemblyCatalog assemblyCatalog; -#if !DNX +#if !CORE assemblyCatalog = new AppDomainAssemblyCatalog(); #else - assemblyCatalog = new LibraryManagerAssemblyCatalog(); + assemblyCatalog = new DependencyContextAssemblyCatalog(); #endif this.typeCatalog = new DefaultTypeCatalog(assemblyCatalog); diff --git a/test/Nancy.Tests/Unit/ResponseExtensionsFixture.cs b/test/Nancy.Tests/Unit/ResponseExtensionsFixture.cs index 7ee3ec4368..bfe09d92bf 100644 --- a/test/Nancy.Tests/Unit/ResponseExtensionsFixture.cs +++ b/test/Nancy.Tests/Unit/ResponseExtensionsFixture.cs @@ -177,7 +177,7 @@ public void Should_set_status_code_int() private string GetLocation() { -#if DNX +#if CORE return Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.ApplicationBasePath; #else return Path.GetDirectoryName(this.GetType().Assembly.Location); @@ -186,7 +186,7 @@ private string GetLocation() private string GetFilePath() { -#if DNX +#if CORE return Path.Combine("Resources", "test.txt"); #else return Path.GetFileName(this.GetType().Assembly.Location); diff --git a/test/Nancy.Tests/Unit/Responses/GenericFileResponseFixture.cs b/test/Nancy.Tests/Unit/Responses/GenericFileResponseFixture.cs index f0b21ea599..9acb5057d6 100644 --- a/test/Nancy.Tests/Unit/Responses/GenericFileResponseFixture.cs +++ b/test/Nancy.Tests/Unit/Responses/GenericFileResponseFixture.cs @@ -25,7 +25,7 @@ public GenericFileResponseFixture(ITestOutputHelper output) private string GetLocation() { -#if DNX +#if CORE return Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.ApplicationBasePath; #else return Path.GetDirectoryName(this.GetType().Assembly.Location); @@ -34,7 +34,7 @@ private string GetLocation() private string GetFilePath() { -#if DNX +#if CORE return Path.Combine("Resources", "test.txt"); #else return Path.GetFileName(this.GetType().Assembly.Location); diff --git a/test/Nancy.Tests/project.json b/test/Nancy.Tests/project.json index 0133e781db..1b2eda2f88 100644 --- a/test/Nancy.Tests/project.json +++ b/test/Nancy.Tests/project.json @@ -1,28 +1,32 @@ { "dependencies": { - "FakeItEasy": "2.0.0-beta011", - "Microsoft.Extensions.PlatformAbstractions": "1.0.0-rc1-final", + "dotnet-test-xunit": "1.0.0-*", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", "Nancy": { "target": "project" }, "Nancy.Testing": { "target": "project" }, - "xunit": "2.1.0", - "xunit.runner.dnx": "2.1.0-*" + "xunit": "2.1.0" }, + + "content": [ + "Resources/**/*" + ], - "commands": { - "test": "xunit.runner.dnx" - }, - - "compilationOptions": { - "define": [ "DNX" ] - }, - - "resource": "Resources/views/staticviewresource.html", + "resourceFiles": [ + "Resources/views/staticviewresource.html" + ], "frameworks": { - "dnx451": { + "net452": { + "dependencies": { + "FakeItEasy": "2.0.0-beta011" + }, "frameworkAssemblies": { - "System.Web": "" + "System.Runtime": { "type": "build" }, + "System.Threading.Tasks": { "type": "build" }, + "System.Web": { "type": "build" } } } - } + }, + + "testRunner": "xunit" } diff --git a/test/Nancy.Validation.DataAnnotatioins.Tests/project.json b/test/Nancy.Validation.DataAnnotatioins.Tests/project.json index adb60b630a..7dca3f0898 100644 --- a/test/Nancy.Validation.DataAnnotatioins.Tests/project.json +++ b/test/Nancy.Validation.DataAnnotatioins.Tests/project.json @@ -1,18 +1,10 @@ { "dependencies": { - "FakeItEasy": "2.0.0-beta011", + "dotnet-test-xunit": "1.0.0-*", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", "Nancy": { "target": "project" }, "Nancy.Validation.DataAnnotations": { "target": "project" }, - "xunit": "2.1.0", - "xunit.runner.dnx": "2.1.0-*" - }, - - "commands": { - "test": "xunit.runner.dnx" - }, - - "compilationOptions": { - "define": [ "DNX" ] + "xunit": "2.1.0" }, "compileFiles": [ @@ -20,10 +12,17 @@ ], "frameworks": { - "dnx451": { + "net452": { + "dependencies": { + "FakeItEasy": "2.0.0-beta011" + }, "frameworkAssemblies": { - "System.ComponentModel.Annotations": "" + "System.ComponentModel.Annotations": { "type": "build" }, + "System.Runtime": { "type": "build" }, + "System.Threading.Tasks": { "type": "build" } } } - } + }, + + "testRunner": "xunit" } diff --git a/test/Nancy.Validation.FluentValidation.Tests/project.json b/test/Nancy.Validation.FluentValidation.Tests/project.json index 13389defec..c80af11716 100644 --- a/test/Nancy.Validation.FluentValidation.Tests/project.json +++ b/test/Nancy.Validation.FluentValidation.Tests/project.json @@ -1,19 +1,11 @@ { "dependencies": { - "FakeItEasy": "2.0.0-beta011", + "dotnet-test-xunit": "1.0.0-*", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", "FluentValidation": "3.4.0", "Nancy": { "target": "project" }, "Nancy.Validation.FluentValidation": { "target": "project" }, - "xunit": "2.1.0", - "xunit.runner.dnx": "2.1.0-*" - }, - - "commands": { - "test": "xunit.runner.dnx" - }, - - "compilationOptions": { - "define": [ "DNX" ] + "xunit": "2.1.0" }, "compileFiles": [ @@ -21,6 +13,15 @@ ], "frameworks": { - "dnx451": { } - } + "net452": { + "dependencies": { + "FakeItEasy": "2.0.0-beta011" + }, + "frameworkAssemblies": { + "System.Runtime": { "type": "build" } + } + } + }, + + "testRunner": "xunit" } diff --git a/test/Nancy.ViewEngines.DotLiquid.Tests/project.json b/test/Nancy.ViewEngines.DotLiquid.Tests/project.json index 1a4be6df3b..d2b74a308e 100644 --- a/test/Nancy.ViewEngines.DotLiquid.Tests/project.json +++ b/test/Nancy.ViewEngines.DotLiquid.Tests/project.json @@ -1,27 +1,33 @@ { "dependencies": { "DotLiquid": "1.7.0", - "FakeItEasy": "2.0.0-beta011", + "dotnet-test-xunit": "1.0.0-*", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", "Nancy": { "target": "project" }, "Nancy.Testing": { "target": "project" }, "Nancy.ViewEngines.DotLiquid": { "target": "project" }, - "xunit": "2.1.0", - "xunit.runner.dnx": "2.1.0-*" + "xunit": "2.1.0" }, - - "commands": { - "test": "xunit.runner.dnx" - }, - - "compilationOptions": { - "define": [ "DNX" ] - }, - + "compileFiles": [ "../Nancy.Tests/ShouldExtensions.cs" ], + + "content": [ + "Views/**/*" + ], "frameworks": { - "dnx451": { } - } + "net452": { + "dependencies": { + "FakeItEasy": "2.0.0-beta011" + }, + "frameworkAssemblies": { + "System.Runtime": { "type": "build" }, + "System.Threading.Tasks": { "type": "build" } + } + } + }, + + "testRunner": "xunit" } diff --git a/test/Nancy.ViewEngines.Markdown.Tests/project.json b/test/Nancy.ViewEngines.Markdown.Tests/project.json index 5b0334047b..f49ed9515e 100644 --- a/test/Nancy.ViewEngines.Markdown.Tests/project.json +++ b/test/Nancy.ViewEngines.Markdown.Tests/project.json @@ -1,27 +1,31 @@ { "dependencies": { - "DotLiquid": "1.7.0", - "FakeItEasy": "2.0.0-beta011", + "dotnet-test-xunit": "1.0.0-*", + "MarkdownSharp": "1.13.0", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", "Nancy": { "target": "project" }, "Nancy.ViewEngines.Markdown": { "target": "project" }, - "MarkdownSharp": "1.13.0", - "xunit": "2.1.0", - "xunit.runner.dnx": "2.1.0-*" - }, - - "commands": { - "test": "xunit.runner.dnx" - }, - - "compilationOptions": { - "define": [ "DNX" ] + "xunit": "2.1.0" }, "compileFiles": [ "../Nancy.Tests/ShouldExtensions.cs" ], + + "content": [ + "Markdown/**/*" + ], "frameworks": { - "dnx451": { } - } + "net452": { + "dependencies": { + "FakeItEasy": "2.0.0-beta011" + }, + "frameworkAssemblies": { + "System.Runtime": { "type": "build" } + } + } + }, + + "testRunner": "xunit" } diff --git a/test/Nancy.ViewEngines.Razor.Tests.Models/project.json b/test/Nancy.ViewEngines.Razor.Tests.Models/project.json index 48d73a0172..183cfa69ad 100644 --- a/test/Nancy.ViewEngines.Razor.Tests.Models/project.json +++ b/test/Nancy.ViewEngines.Razor.Tests.Models/project.json @@ -1,5 +1,7 @@ { "frameworks": { - "net451": { } + "net452": { + + } } } diff --git a/test/Nancy.ViewEngines.Razor.Tests/RazorViewEngineFixture.cs b/test/Nancy.ViewEngines.Razor.Tests/RazorViewEngineFixture.cs index d933b67aeb..e9bbdeb16f 100644 --- a/test/Nancy.ViewEngines.Razor.Tests/RazorViewEngineFixture.cs +++ b/test/Nancy.ViewEngines.Razor.Tests/RazorViewEngineFixture.cs @@ -24,13 +24,7 @@ public class RazorViewEngineFixture public RazorViewEngineFixture() { - IAssemblyCatalog assemblyCatalog; - -#if !DNX - assemblyCatalog = new AppDomainAssemblyCatalog(); -#else - assemblyCatalog = new LibraryManagerAssemblyCatalog(); -#endif + var assemblyCatalog = new AppDomainAssemblyCatalog(); var environment = new DefaultNancyEnvironment(); environment.Tracing( diff --git a/test/Nancy.ViewEngines.Razor.Tests/project.json b/test/Nancy.ViewEngines.Razor.Tests/project.json index 7d023d8069..4ebd04c49f 100644 --- a/test/Nancy.ViewEngines.Razor.Tests/project.json +++ b/test/Nancy.ViewEngines.Razor.Tests/project.json @@ -1,27 +1,32 @@ { "dependencies": { - "FakeItEasy": "2.0.0-beta011", + "dotnet-test-xunit": "1.0.0-*", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", "Nancy": { "target": "project" }, "Nancy.Testing": { "target": "project" }, "Nancy.ViewEngines.Razor": { "target": "project" }, "Nancy.ViewEngines.Razor.Tests.Models": { "target": "project" }, - "xunit": "2.1.0", - "xunit.runner.dnx": "2.1.0-*" - }, - - "commands": { - "test": "xunit.runner.dnx" - }, - - "compilationOptions": { - "define": [ "DNX" ] + "xunit": "2.1.0" }, "compileFiles": [ "../Nancy.Tests/ShouldExtensions.cs" ], + + "content": [ + "TestViews/**/*" + ], "frameworks": { - "dnx451": { } - } + "net452": { + "dependencies": { + "FakeItEasy": "2.0.0-beta011" + }, + "frameworkAssemblies": { + "System.Runtime": { "type": "build" } + } + } + }, + + "testRunner": "xunit" } From 625ae5dc566339d19b568b4a8518d6c31e901de9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20H=C3=A5kansson?= Date: Wed, 18 May 2016 10:53:49 +0200 Subject: [PATCH 48/52] Updated to stable rc2 bits --- NuGet.config | 4 +- global.json | 5 +- .../Nancy.Demo.Hosting.Kestrel.xproj | 6 +- .../Nancy.Demo.Hosting.Kestrel/project.json | 10 +-- .../Nancy.Authentication.Basic.xproj | 11 ++-- src/Nancy.Authentication.Basic/project.json | 2 +- .../Nancy.Authentication.Forms.xproj | 11 ++-- src/Nancy.Authentication.Forms/project.json | 2 +- .../Nancy.Authentication.Stateless.xproj | 11 ++-- .../project.json | 2 +- src/Nancy.Embedded/Nancy.Embedded.xproj | 11 ++-- src/Nancy.Embedded/project.json | 2 +- .../Nancy.Encryption.MachineKey.xproj | 20 +++--- src/Nancy.Encryption.MachineKey/project.json | 2 +- .../Nancy.Hosting.Aspnet.xproj | 11 ++-- src/Nancy.Hosting.Aspnet/project.json | 2 +- .../Nancy.Hosting.Self.xproj | 11 ++-- src/Nancy.Hosting.Self/project.json | 6 +- .../Nancy.Metadata.Modules.xproj | 11 ++-- src/Nancy.Owin/Nancy.Owin.xproj | 11 ++-- src/Nancy.Owin/project.json | 2 +- src/Nancy.Testing/Nancy.Testing.xproj | 20 +++--- src/Nancy.Testing/project.json | 14 ++-- .../Nancy.Validation.DataAnnotations.xproj | 11 ++-- .../project.json | 2 +- .../Nancy.Validation.FluentValidation.xproj | 11 ++-- .../project.json | 2 +- .../Nancy.ViewEngines.DotLiquid.xproj | 11 ++-- src/Nancy.ViewEngines.DotLiquid/project.json | 2 +- .../Nancy.ViewEngines.Markdown.xproj | 11 ++-- .../Nancy.ViewEngines.Nustache.xproj | 11 ++-- src/Nancy.ViewEngines.Nustache/project.json | 2 +- ...ncy.ViewEngines.Razor.BuildProviders.xproj | 11 ++-- .../Nancy.ViewEngines.Razor.xproj | 11 ++-- src/Nancy.ViewEngines.Razor/project.json | 9 ++- .../Nancy.ViewEngines.Spark.xproj | 11 ++-- src/Nancy.ViewEngines.Spark/project.json | 4 +- src/Nancy/Nancy.xproj | 13 ++-- src/Nancy/project.json | 64 ++++++++++--------- .../Nancy.Authentication.Basic.Tests.xproj | 16 ++--- .../project.json | 14 ++-- .../Nancy.Authentication.Forms.Tests.xproj | 16 ++--- .../project.json | 14 ++-- .../Nancy.Embedded.Tests.xproj | 16 ++--- test/Nancy.Embedded.Tests/project.json | 15 +++-- .../Nancy.Encryption.MachineKey.Tests.xproj | 16 ++--- .../project.json | 12 ++-- .../Nancy.Hosting.Aspnet.Tests.xproj | 16 ++--- test/Nancy.Hosting.Aspnet.Tests/project.json | 14 ++-- .../Nancy.Hosting.Self.Tests.xproj | 16 ++--- test/Nancy.Hosting.Self.Tests/project.json | 16 +++-- .../Nancy.Metadata.Modules.Tests.xproj | 16 ++--- .../Nancy.Metadata.Modules.Tests/project.json | 12 ++-- test/Nancy.Owin.Tests/Nancy.Owin.Tests.xproj | 16 ++--- test/Nancy.Owin.Tests/project.json | 14 ++-- .../Nancy.Testing.Tests.xproj | 16 ++--- test/Nancy.Testing.Tests/project.json | 21 +++--- .../Nancy.Tests.Functional.xproj | 16 ++--- test/Nancy.Tests.Functional/project.json | 24 +++---- test/Nancy.Tests/Nancy.Tests.xproj | 18 +++--- test/Nancy.Tests/project.json | 19 +++--- ...cy.Validation.DataAnnotatioins.Tests.xproj | 16 ++--- .../project.json | 12 ++-- ...cy.Validation.FluentValidation.Tests.xproj | 16 ++--- .../project.json | 12 ++-- .../Nancy.ViewEngines.DotLiquid.Tests.xproj | 16 ++--- .../project.json | 21 +++--- .../Nancy.ViewEngines.Markdown.Tests.xproj | 16 ++--- .../project.json | 21 +++--- ...Nancy.ViewEngines.Razor.Tests.Models.xproj | 16 ++--- .../project.json | 4 +- .../Nancy.ViewEngines.Razor.Tests.xproj | 16 ++--- .../project.json | 19 +++--- 73 files changed, 492 insertions(+), 419 deletions(-) diff --git a/NuGet.config b/NuGet.config index 404f2cb17c..843603a7d5 100644 --- a/NuGet.config +++ b/NuGet.config @@ -3,7 +3,9 @@ - + + + diff --git a/global.json b/global.json index e34d48985a..4fcee94fc3 100644 --- a/global.json +++ b/global.json @@ -1,3 +1,6 @@ { - "projects": [ "src", "test", "samples" ] + "projects": [ "src", "test", "samples" ], + "sdk": { + "version": "1.0.0-preview1-002702" + } } diff --git a/samples/Nancy.Demo.Hosting.Kestrel/Nancy.Demo.Hosting.Kestrel.xproj b/samples/Nancy.Demo.Hosting.Kestrel/Nancy.Demo.Hosting.Kestrel.xproj index fee5ed11a8..e5d70ed642 100644 --- a/samples/Nancy.Demo.Hosting.Kestrel/Nancy.Demo.Hosting.Kestrel.xproj +++ b/samples/Nancy.Demo.Hosting.Kestrel/Nancy.Demo.Hosting.Kestrel.xproj @@ -4,17 +4,15 @@ 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 9921e059-612b-4011-9ab6-fd30e69850a1 Nancy.Demo.Hosting.Kestrel ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + .\bin\ - 2.0 - + \ No newline at end of file diff --git a/samples/Nancy.Demo.Hosting.Kestrel/project.json b/samples/Nancy.Demo.Hosting.Kestrel/project.json index cb2b2094e6..c0e76a0acc 100644 --- a/samples/Nancy.Demo.Hosting.Kestrel/project.json +++ b/samples/Nancy.Demo.Hosting.Kestrel/project.json @@ -1,6 +1,6 @@ { "buildOptions": { - "debugType": "portable", + "debugType": "portable", "emitEntryPoint": true }, @@ -11,12 +11,12 @@ "frameworks": { "netcoreapp1.0": { "dependencies": { - "Microsoft.AspNetCore.Hosting": "1.0.0-*", - "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*", - "Microsoft.AspNetCore.Owin": "1.0.0-rc2-*", + "Microsoft.AspNetCore.Hosting": "1.0.0-rc2-final", + "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final", + "Microsoft.AspNetCore.Owin": "1.0.0-rc2-final", "Microsoft.NETCore.App": { "type": "platform", - "version": "1.0.0-rc2-*" + "version": "1.0.0-rc2-3002702" } }, "imports": [ diff --git a/src/Nancy.Authentication.Basic/Nancy.Authentication.Basic.xproj b/src/Nancy.Authentication.Basic/Nancy.Authentication.Basic.xproj index 6088c2d351..6b7198ffde 100644 --- a/src/Nancy.Authentication.Basic/Nancy.Authentication.Basic.xproj +++ b/src/Nancy.Authentication.Basic/Nancy.Authentication.Basic.xproj @@ -4,14 +4,17 @@ 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 0c3b1176-a01d-4edd-a0b8-17f04c513025 - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.Authentication.Basic + .\obj + .\bin\ + + + Nancy.Authentication.Basic 2.0 - + diff --git a/src/Nancy.Authentication.Basic/project.json b/src/Nancy.Authentication.Basic/project.json index f8a59db831..070dfc89ab 100644 --- a/src/Nancy.Authentication.Basic/project.json +++ b/src/Nancy.Authentication.Basic/project.json @@ -2,7 +2,7 @@ "version": "2.0.0-*", "description": "A basic HTTP authentication provider for Nancy.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - + "packOptions": { "tags": [ "Nancy", "Authentication" ], "projectUrl": "http://nancyfx.org", diff --git a/src/Nancy.Authentication.Forms/Nancy.Authentication.Forms.xproj b/src/Nancy.Authentication.Forms/Nancy.Authentication.Forms.xproj index e99618eb7d..878efed32c 100644 --- a/src/Nancy.Authentication.Forms/Nancy.Authentication.Forms.xproj +++ b/src/Nancy.Authentication.Forms/Nancy.Authentication.Forms.xproj @@ -4,14 +4,17 @@ 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 52b05c75-46f1-4c1b-b660-edd88ba38924 - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.Authentication.Forms + .\obj + .\bin\ + + + Nancy.Authentication.Forms 2.0 - + diff --git a/src/Nancy.Authentication.Forms/project.json b/src/Nancy.Authentication.Forms/project.json index a4ade82574..6362d83dac 100644 --- a/src/Nancy.Authentication.Forms/project.json +++ b/src/Nancy.Authentication.Forms/project.json @@ -2,7 +2,7 @@ "version": "2.0.0-*", "description": "A forms authentication provider for Nancy.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - + "packOptions": { "tags": [ "Nancy", "Authentication" ], "projectUrl": "http://nancyfx.org", diff --git a/src/Nancy.Authentication.Stateless/Nancy.Authentication.Stateless.xproj b/src/Nancy.Authentication.Stateless/Nancy.Authentication.Stateless.xproj index 882837b4b3..d66524a4bb 100644 --- a/src/Nancy.Authentication.Stateless/Nancy.Authentication.Stateless.xproj +++ b/src/Nancy.Authentication.Stateless/Nancy.Authentication.Stateless.xproj @@ -4,14 +4,17 @@ 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 7c8cd644-8c3e-491d-9583-ccdd352223c8 - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.Authentication.Stateless + .\obj + .\bin\ + + + Nancy.Authentication.Stateless 2.0 - + diff --git a/src/Nancy.Authentication.Stateless/project.json b/src/Nancy.Authentication.Stateless/project.json index bf86be3c00..edc21cb0f3 100644 --- a/src/Nancy.Authentication.Stateless/project.json +++ b/src/Nancy.Authentication.Stateless/project.json @@ -2,7 +2,7 @@ "version": "2.0.0-*", "description": "A stateless authentication provider for Nancy.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - + "packOptions": { "tags": [ "Nancy", "Authentication" ], "projectUrl": "http://nancyfx.org", diff --git a/src/Nancy.Embedded/Nancy.Embedded.xproj b/src/Nancy.Embedded/Nancy.Embedded.xproj index e0de5d0d76..d04b094834 100644 --- a/src/Nancy.Embedded/Nancy.Embedded.xproj +++ b/src/Nancy.Embedded/Nancy.Embedded.xproj @@ -4,14 +4,17 @@ 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - a4dedd2f-5565-404a-b60f-98217221518d - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.Embedded + .\obj + .\bin\ + + + Nancy.Embedded 2.0 - + diff --git a/src/Nancy.Embedded/project.json b/src/Nancy.Embedded/project.json index 41234ee806..96b56fc17f 100644 --- a/src/Nancy.Embedded/project.json +++ b/src/Nancy.Embedded/project.json @@ -2,7 +2,7 @@ "version": "2.0.0-*", "description": "Helpers for serving embedded static content with Nancy.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - + "packOptions": { "tags": [ "Nancy", "Embedded", "Static Content" ], "projectUrl": "http://nancyfx.org", diff --git a/src/Nancy.Encryption.MachineKey/Nancy.Encryption.MachineKey.xproj b/src/Nancy.Encryption.MachineKey/Nancy.Encryption.MachineKey.xproj index 10c97f06a3..8d294ac725 100644 --- a/src/Nancy.Encryption.MachineKey/Nancy.Encryption.MachineKey.xproj +++ b/src/Nancy.Encryption.MachineKey/Nancy.Encryption.MachineKey.xproj @@ -1,22 +1,20 @@ - + 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 186cab00-195d-490f-873b-0b2b0fb546f2 - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.Encryption.MachineKey + .\obj + .\bin\ + + + Nancy.Encryption.MachineKey 2.0 - - - - - - - \ No newline at end of file + + diff --git a/src/Nancy.Encryption.MachineKey/project.json b/src/Nancy.Encryption.MachineKey/project.json index 563e60a395..2c6b2ed3fd 100644 --- a/src/Nancy.Encryption.MachineKey/project.json +++ b/src/Nancy.Encryption.MachineKey/project.json @@ -2,7 +2,7 @@ "version": "2.0.0-*", "description": "System.Web MachineKey encrypton and HMAC providers for Nancy.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - + "packOptions": { "tags": [ "Nancy", "Encryption" ], "projectUrl": "http://nancyfx.org", diff --git a/src/Nancy.Hosting.Aspnet/Nancy.Hosting.Aspnet.xproj b/src/Nancy.Hosting.Aspnet/Nancy.Hosting.Aspnet.xproj index fed7eaf676..9a27807436 100644 --- a/src/Nancy.Hosting.Aspnet/Nancy.Hosting.Aspnet.xproj +++ b/src/Nancy.Hosting.Aspnet/Nancy.Hosting.Aspnet.xproj @@ -4,14 +4,17 @@ 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 4262ab60-e51d-43d1-ae63-d60ed24cf04f - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.Hosting.Aspnet + .\obj + .\bin\ + + + Nancy.Hosting.Aspnet 2.0 - + diff --git a/src/Nancy.Hosting.Aspnet/project.json b/src/Nancy.Hosting.Aspnet/project.json index 4b316df31d..da22057f70 100644 --- a/src/Nancy.Hosting.Aspnet/project.json +++ b/src/Nancy.Hosting.Aspnet/project.json @@ -2,7 +2,7 @@ "version": "2.0.0-*", "description": "Enables hosting Nancy on ASP.NET.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - + "packOptions": { "tags": [ "Nancy", "Host" ], "projectUrl": "http://nancyfx.org", diff --git a/src/Nancy.Hosting.Self/Nancy.Hosting.Self.xproj b/src/Nancy.Hosting.Self/Nancy.Hosting.Self.xproj index 6ec74d5fe9..5220e7cc34 100644 --- a/src/Nancy.Hosting.Self/Nancy.Hosting.Self.xproj +++ b/src/Nancy.Hosting.Self/Nancy.Hosting.Self.xproj @@ -4,14 +4,17 @@ 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - a3a80c91-557a-44de-bd0f-ac3e96903424 - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.Hosting.Self + .\obj + .\bin\ + + + Nancy.Hosting.Self 2.0 - + diff --git a/src/Nancy.Hosting.Self/project.json b/src/Nancy.Hosting.Self/project.json index 6a9b3df5a9..fd3374aa95 100644 --- a/src/Nancy.Hosting.Self/project.json +++ b/src/Nancy.Hosting.Self/project.json @@ -2,7 +2,7 @@ "version": "2.0.0-*", "description": "Enables hosting Nancy in any application.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - + "packOptions": { "tags": [ "Nancy", "Host" ], "projectUrl": "http://nancyfx.org", @@ -19,8 +19,6 @@ }, "frameworks": { - "net452": { - - } + "net452": { } } } diff --git a/src/Nancy.Metadata.Modules/Nancy.Metadata.Modules.xproj b/src/Nancy.Metadata.Modules/Nancy.Metadata.Modules.xproj index 70b9078f99..617aec4451 100644 --- a/src/Nancy.Metadata.Modules/Nancy.Metadata.Modules.xproj +++ b/src/Nancy.Metadata.Modules/Nancy.Metadata.Modules.xproj @@ -4,14 +4,17 @@ 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - ad0737d9-12d7-449f-9b2d-a3045731c946 - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.Metadata.Modules + .\obj + .\bin\ + + + Nancy.Metadata.Modules 2.0 - + diff --git a/src/Nancy.Owin/Nancy.Owin.xproj b/src/Nancy.Owin/Nancy.Owin.xproj index c8053ea706..8410c28488 100644 --- a/src/Nancy.Owin/Nancy.Owin.xproj +++ b/src/Nancy.Owin/Nancy.Owin.xproj @@ -4,14 +4,17 @@ 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - baa9cbdf-f6b7-4c85-8a22-6a316a4acc46 - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.Owin + .\obj + .\bin\ + + + Nancy.Owin 2.0 - + diff --git a/src/Nancy.Owin/project.json b/src/Nancy.Owin/project.json index 3b91e23720..3775e0e06d 100644 --- a/src/Nancy.Owin/project.json +++ b/src/Nancy.Owin/project.json @@ -2,7 +2,7 @@ "version": "2.0.0-*", "description": "Nancy extensions for OWIN hosting.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - + "packOptions": { "tags": [ "Nancy", "OWIN" ], "projectUrl": "http://nancyfx.org", diff --git a/src/Nancy.Testing/Nancy.Testing.xproj b/src/Nancy.Testing/Nancy.Testing.xproj index f7b5996832..da22f6abde 100644 --- a/src/Nancy.Testing/Nancy.Testing.xproj +++ b/src/Nancy.Testing/Nancy.Testing.xproj @@ -1,22 +1,20 @@ - + 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - e948f38f-4f8b-41fe-8f49-4792f4ec2531 - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.Testing + .\obj + .\bin\ + + + Nancy.Testing 2.0 - - - - - - - \ No newline at end of file + + diff --git a/src/Nancy.Testing/project.json b/src/Nancy.Testing/project.json index 4e2ecdd10d..08ae0462d9 100644 --- a/src/Nancy.Testing/project.json +++ b/src/Nancy.Testing/project.json @@ -2,7 +2,7 @@ "version": "2.0.0-*", "description": "Test harness for Nancy applications.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - + "packOptions": { "tags": [ "Nancy", "Testing" ], "projectUrl": "http://nancyfx.org", @@ -16,15 +16,17 @@ "Nancy.Authentication.Forms": { "target": "project" } }, - "resource": [ - "Resources/NancyTestingCert.pfx" - ], + "buildOptions": { + "embed": [ + "Resources/NancyTestingCert.pfx" + ] + }, "frameworks": { "netstandard1.5": { "dependencies": { - "System.Xml.XmlDocument": "4.0.1-rc2-*", - "System.Xml.XDocument": "4.0.11-rc2-*" + "System.Xml.XmlDocument": "4.0.1-rc2-24027", + "System.Xml.XDocument": "4.0.11-rc2-24027" }, "imports": [ "dotnet54", diff --git a/src/Nancy.Validation.DataAnnotations/Nancy.Validation.DataAnnotations.xproj b/src/Nancy.Validation.DataAnnotations/Nancy.Validation.DataAnnotations.xproj index 328d9a1427..1f215535f6 100644 --- a/src/Nancy.Validation.DataAnnotations/Nancy.Validation.DataAnnotations.xproj +++ b/src/Nancy.Validation.DataAnnotations/Nancy.Validation.DataAnnotations.xproj @@ -4,14 +4,17 @@ 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 21fb2d6b-2525-4a24-bf66-d34941c7fa88 - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.Validation.DataAnnotations + .\obj + .\bin\ + + + Nancy.Validation.DataAnnotations 2.0 - + diff --git a/src/Nancy.Validation.DataAnnotations/project.json b/src/Nancy.Validation.DataAnnotations/project.json index f13b30606e..d1ffe9dc36 100644 --- a/src/Nancy.Validation.DataAnnotations/project.json +++ b/src/Nancy.Validation.DataAnnotations/project.json @@ -2,7 +2,7 @@ "version": "2.0.0-*", "description": "Adds Data Annotation validation support to Nancy.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - + "packOptions": { "tags": [ "Nancy", "Validation", "DataAnnotations" ], "projectUrl": "http://nancyfx.org", diff --git a/src/Nancy.Validation.FluentValidation/Nancy.Validation.FluentValidation.xproj b/src/Nancy.Validation.FluentValidation/Nancy.Validation.FluentValidation.xproj index cf617bf54b..37dfa3744a 100644 --- a/src/Nancy.Validation.FluentValidation/Nancy.Validation.FluentValidation.xproj +++ b/src/Nancy.Validation.FluentValidation/Nancy.Validation.FluentValidation.xproj @@ -4,14 +4,17 @@ 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 35b9dd79-d65a-423c-9dc0-59dcf3bf2e98 - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.Validation.FluentValidation + .\obj + .\bin\ + + + Nancy.Validation.FluentValidation 2.0 - + diff --git a/src/Nancy.Validation.FluentValidation/project.json b/src/Nancy.Validation.FluentValidation/project.json index c64a5ccfa3..cbc8afd6a9 100644 --- a/src/Nancy.Validation.FluentValidation/project.json +++ b/src/Nancy.Validation.FluentValidation/project.json @@ -2,7 +2,7 @@ "version": "2.0.0-*", "description": "Adds Fluent Validation support to Nancy.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - + "packOptions": { "tags": [ "Nancy", "Validation", "FluentValidation" ], "projectUrl": "http://nancyfx.org", diff --git a/src/Nancy.ViewEngines.DotLiquid/Nancy.ViewEngines.DotLiquid.xproj b/src/Nancy.ViewEngines.DotLiquid/Nancy.ViewEngines.DotLiquid.xproj index 6361b2fe65..3e94683380 100644 --- a/src/Nancy.ViewEngines.DotLiquid/Nancy.ViewEngines.DotLiquid.xproj +++ b/src/Nancy.ViewEngines.DotLiquid/Nancy.ViewEngines.DotLiquid.xproj @@ -4,14 +4,17 @@ 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 98febb4d-cff9-4318-b2f0-c5dcc5436a47 - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.ViewEngines.DotLiquid + .\obj + .\bin\ + + + Nancy.ViewEngines.DotLiquid 2.0 - + diff --git a/src/Nancy.ViewEngines.DotLiquid/project.json b/src/Nancy.ViewEngines.DotLiquid/project.json index 54186972ac..1b28fa7cdd 100644 --- a/src/Nancy.ViewEngines.DotLiquid/project.json +++ b/src/Nancy.ViewEngines.DotLiquid/project.json @@ -2,7 +2,7 @@ "version": "2.0.0-*", "description": "Enables using the DotLiquid view engine with Nancy.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - + "packOptions": { "tags": [ "Nancy", "View Engine", "DotLiquid" ], "projectUrl": "http://nancyfx.org", diff --git a/src/Nancy.ViewEngines.Markdown/Nancy.ViewEngines.Markdown.xproj b/src/Nancy.ViewEngines.Markdown/Nancy.ViewEngines.Markdown.xproj index 654d4432e4..5e888b00dc 100644 --- a/src/Nancy.ViewEngines.Markdown/Nancy.ViewEngines.Markdown.xproj +++ b/src/Nancy.ViewEngines.Markdown/Nancy.ViewEngines.Markdown.xproj @@ -4,14 +4,17 @@ 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - cfa5bbcb-b41b-47c0-a4d2-fa243fc6ecc6 - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.ViewEngines.Markdown + .\obj + .\bin\ + + + Nancy.ViewEngines.Markdown 2.0 - + diff --git a/src/Nancy.ViewEngines.Nustache/Nancy.ViewEngines.Nustache.xproj b/src/Nancy.ViewEngines.Nustache/Nancy.ViewEngines.Nustache.xproj index 304c34e495..5ab901952b 100644 --- a/src/Nancy.ViewEngines.Nustache/Nancy.ViewEngines.Nustache.xproj +++ b/src/Nancy.ViewEngines.Nustache/Nancy.ViewEngines.Nustache.xproj @@ -4,14 +4,17 @@ 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 32e22782-7a5e-4546-b2db-f3628ea36361 - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.ViewEngines.Nustache + .\obj + .\bin\ + + + Nancy.ViewEngines.Nustache 2.0 - + diff --git a/src/Nancy.ViewEngines.Nustache/project.json b/src/Nancy.ViewEngines.Nustache/project.json index 64cb08c8aa..8ce5c994d5 100644 --- a/src/Nancy.ViewEngines.Nustache/project.json +++ b/src/Nancy.ViewEngines.Nustache/project.json @@ -2,7 +2,7 @@ "version": "2.0.0-*", "description": "Enables using the Nustache view engine with Nancy.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - + "packOptions": { "tags": [ "Nancy", "View Engine", "Nustache" ], "projectUrl": "http://nancyfx.org", diff --git a/src/Nancy.ViewEngines.Razor.BuildProviders/Nancy.ViewEngines.Razor.BuildProviders.xproj b/src/Nancy.ViewEngines.Razor.BuildProviders/Nancy.ViewEngines.Razor.BuildProviders.xproj index eed76a8626..2b399332ff 100644 --- a/src/Nancy.ViewEngines.Razor.BuildProviders/Nancy.ViewEngines.Razor.BuildProviders.xproj +++ b/src/Nancy.ViewEngines.Razor.BuildProviders/Nancy.ViewEngines.Razor.BuildProviders.xproj @@ -4,14 +4,17 @@ 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 26df3be0-146b-43a6-b230-d5b33355f415 - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.ViewEngines.Razor.BuildProviders + .\obj + .\bin\ + + + Nancy.ViewEngines.Razor.BuildProviders 2.0 - + diff --git a/src/Nancy.ViewEngines.Razor/Nancy.ViewEngines.Razor.xproj b/src/Nancy.ViewEngines.Razor/Nancy.ViewEngines.Razor.xproj index 738ca1746b..c0aff1da30 100644 --- a/src/Nancy.ViewEngines.Razor/Nancy.ViewEngines.Razor.xproj +++ b/src/Nancy.ViewEngines.Razor/Nancy.ViewEngines.Razor.xproj @@ -4,14 +4,17 @@ 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 3a376b78-dd7d-4450-9fde-f7236faa6e63 - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.ViewEngines.Razor + .\obj + .\bin\ + + + Nancy.ViewEngines.Razor 2.0 - + diff --git a/src/Nancy.ViewEngines.Razor/project.json b/src/Nancy.ViewEngines.Razor/project.json index b133ecac44..bf5a9b2914 100644 --- a/src/Nancy.ViewEngines.Razor/project.json +++ b/src/Nancy.ViewEngines.Razor/project.json @@ -2,7 +2,7 @@ "version": "2.0.0-*", "description": "Enables using the Razor view engine with Nancy.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - + "packOptions": { "tags": [ "Nancy", "View Engine", "Razor" ], "projectUrl": "http://nancyfx.org", @@ -16,13 +16,12 @@ "Microsoft.CodeAnalysis.CSharp": "1.1.0-rc1-20151109-01" }, - "resource": "Resources/**/*.*", + "buildOptions": { + "embed": "Resources/**/*.*" + }, "frameworks": { "net452": { - "buildOptions": { - "define": [ "DNX" ] - }, "dependencies": { "Microsoft.CodeDom.Providers.DotNetCompilerPlatform": "1.0.1" }, diff --git a/src/Nancy.ViewEngines.Spark/Nancy.ViewEngines.Spark.xproj b/src/Nancy.ViewEngines.Spark/Nancy.ViewEngines.Spark.xproj index f3bf70e8bf..56ef471b3f 100644 --- a/src/Nancy.ViewEngines.Spark/Nancy.ViewEngines.Spark.xproj +++ b/src/Nancy.ViewEngines.Spark/Nancy.ViewEngines.Spark.xproj @@ -4,14 +4,17 @@ 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 25e3ab38-d95e-4d11-b0f0-0f60571a97a0 - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.ViewEngines.Spark + .\obj + .\bin\ + + + Nancy.ViewEngines.Spark 2.0 - + diff --git a/src/Nancy.ViewEngines.Spark/project.json b/src/Nancy.ViewEngines.Spark/project.json index bb133a5de1..3a891e8667 100644 --- a/src/Nancy.ViewEngines.Spark/project.json +++ b/src/Nancy.ViewEngines.Spark/project.json @@ -2,9 +2,9 @@ "version": "2.0.0-*", "description": "Enables using the Spark view engine with Nancy.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - "tags": [ "Nancy", "View Engine", "Spark" ], - + "packOptions": { + "tags": [ "Nancy", "View Engine", "Spark" ], "projectUrl": "http://nancyfx.org", "licenseUrl": "https://github.com/NancyFx/Nancy/blob/master/license.txt", "iconUrl": "http://nancyfx.org/nancy-nuget.png" diff --git a/src/Nancy/Nancy.xproj b/src/Nancy/Nancy.xproj index c978a144db..88e5858e9d 100644 --- a/src/Nancy/Nancy.xproj +++ b/src/Nancy/Nancy.xproj @@ -4,14 +4,17 @@ 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 87c7c329-1824-4ac7-af25-3d06068a01f6 - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy + .\obj + .\bin\ + + + Nancy 2.0 - - \ No newline at end of file + + diff --git a/src/Nancy/project.json b/src/Nancy/project.json index 8b7ebe227f..fd2d064170 100644 --- a/src/Nancy/project.json +++ b/src/Nancy/project.json @@ -2,7 +2,7 @@ "version": "2.0.0-*", "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.", "authors": [ "Andreas HÃ¥kansson, Steven Robbins and contributors" ], - + "packOptions": { "tags": [ "Nancy" ], "projectUrl": "http://nancyfx.org", @@ -11,13 +11,15 @@ }, "dependencies": { - "Microsoft.Extensions.DependencyModel": "1.0.0-rc2-*" + "Microsoft.Extensions.DependencyModel": "1.0.0-rc2-final" }, - "resource": [ - "Diagnostics/Resources/**/*.*", - "Diagnostics/Views/**/*.*" - ], + "buildOptions": { + "embed": [ + "Diagnostics/Resources/**/*.*", + "Diagnostics/Views/**/*.*" + ] + }, "frameworks": { "netstandard1.5": { @@ -25,31 +27,31 @@ "define": [ "CORE" ] }, "dependencies": { - "Microsoft.CSharp": "4.0.1-rc2-*", - "Microsoft.Extensions.PlatformAbstractions": "1.0.0-rc2-*", - "System.Collections.Concurrent": "4.0.12-rc2-*", - "System.Collections.Specialized": "4.0.1-rc2-*", - "System.ComponentModel.TypeConverter": "4.0.1-rc2-*", - "System.Console": "4.0.0-rc2-*", - "System.Data.Common": "4.0.1-rc2-*", - "System.Diagnostics.Tools": "4.0.1-rc2-*", - "System.Dynamic.Runtime": "4.0.11-rc2-*", - "System.IO": "4.1.0-rc2-*", - "System.IO.FileSystem": "4.0.1-rc2-*", - "System.Linq": "4.1.0-rc2-*", - "System.Net.NameResolution": "4.0.0-rc2-*", - "System.Net.Primitives": "4.0.11-rc2-*", - "System.Reflection.Extensions": "4.0.1-rc2-*", - "System.Reflection.TypeExtensions": "4.1.0-rc2-*", - "System.Runtime": "4.1.0-rc2-*", - "System.Runtime.Serialization.Primitives": "4.1.1-rc2-*", - "System.Security.Claims": "4.0.1-rc2-*", - "System.Security.Cryptography.Algorithms": "4.1.0-rc2-*", - "System.Security.Cryptography.X509Certificates": "4.1.0-rc2-*", - "System.Text.RegularExpressions": "4.0.12-rc2-*", - "System.Threading": "4.0.11-rc2-*", - "System.Threading.Thread": "4.0.0-rc2-*", - "System.Xml.XmlSerializer": "4.0.11-rc2-*" + "Microsoft.CSharp": "4.0.1-rc2-24027", + "Microsoft.Extensions.PlatformAbstractions": "1.0.0-rc2-final", + "System.Collections.Concurrent": "4.0.12-rc2-24027", + "System.Collections.Specialized": "4.0.1-rc2-24027", + "System.ComponentModel.TypeConverter": "4.0.1-rc2-24027", + "System.Console": "4.0.0-rc2-24027", + "System.Data.Common": "4.0.1-rc2-24027", + "System.Diagnostics.Tools": "4.0.1-rc2-24027", + "System.Dynamic.Runtime": "4.0.11-rc2-24027", + "System.IO": "4.1.0-rc2-24027", + "System.IO.FileSystem": "4.0.1-rc2-24027", + "System.Linq": "4.1.0-rc2-24027", + "System.Net.NameResolution": "4.0.0-rc2-24027", + "System.Net.Primitives": "4.0.11-rc2-24027", + "System.Reflection.Extensions": "4.0.1-rc2-24027", + "System.Reflection.TypeExtensions": "4.1.0-rc2-24027", + "System.Runtime": "4.1.0-rc2-24027", + "System.Runtime.Serialization.Primitives": "4.1.1-rc2-24027", + "System.Security.Claims": "4.0.1-rc2-24027", + "System.Security.Cryptography.Algorithms": "4.1.0-rc2-24027", + "System.Security.Cryptography.X509Certificates": "4.1.0-rc2-24027", + "System.Text.RegularExpressions": "4.0.12-rc2-24027", + "System.Threading": "4.0.11-rc2-24027", + "System.Threading.Thread": "4.0.0-rc2-24027", + "System.Xml.XmlSerializer": "4.0.11-rc2-24027" }, "imports": [ "dotnet54", diff --git a/test/Nancy.Authentication.Basic.Tests/Nancy.Authentication.Basic.Tests.xproj b/test/Nancy.Authentication.Basic.Tests/Nancy.Authentication.Basic.Tests.xproj index f2f65aa499..40bfe78438 100644 --- a/test/Nancy.Authentication.Basic.Tests/Nancy.Authentication.Basic.Tests.xproj +++ b/test/Nancy.Authentication.Basic.Tests/Nancy.Authentication.Basic.Tests.xproj @@ -1,20 +1,20 @@ - + 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 51494B38-0D18-4B9D-AB75-39E804747D5F - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.Authentication.Basic.Tests + .\obj + .\bin\ + + + Nancy.Authentication.Basic.Tests 2.0 - - - - + diff --git a/test/Nancy.Authentication.Basic.Tests/project.json b/test/Nancy.Authentication.Basic.Tests/project.json index 0d6c7c68c4..fff1d0cc1a 100644 --- a/test/Nancy.Authentication.Basic.Tests/project.json +++ b/test/Nancy.Authentication.Basic.Tests/project.json @@ -1,16 +1,18 @@ { "dependencies": { - "dotnet-test-xunit": "1.0.0-*", - "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", + "dotnet-test-xunit": "1.0.0-rc3-build10019", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-24027", "Nancy": { "target": "project" }, "Nancy.Authentication.Basic": { "target": "project" }, "xunit": "2.1.0" }, - "compileFiles": [ - "../Nancy.Tests/Fakes/FakeRequest.cs", - "../Nancy.Tests/ShouldExtensions.cs" - ], + "buildOptions": { + "compile": [ + "../Nancy.Tests/Fakes/FakeRequest.cs", + "../Nancy.Tests/ShouldExtensions.cs" + ] + }, "frameworks": { "net452": { diff --git a/test/Nancy.Authentication.Forms.Tests/Nancy.Authentication.Forms.Tests.xproj b/test/Nancy.Authentication.Forms.Tests/Nancy.Authentication.Forms.Tests.xproj index 0832003493..39b586e635 100644 --- a/test/Nancy.Authentication.Forms.Tests/Nancy.Authentication.Forms.Tests.xproj +++ b/test/Nancy.Authentication.Forms.Tests/Nancy.Authentication.Forms.Tests.xproj @@ -1,20 +1,20 @@ - + 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 93e15be9-bf06-4f94-a42f-bfd664774dc5 - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.Authentication.Forms.Tests + .\obj + .\bin\ + + + Nancy.Authentication.Forms.Tests 2.0 - - - - + diff --git a/test/Nancy.Authentication.Forms.Tests/project.json b/test/Nancy.Authentication.Forms.Tests/project.json index e7f416264b..356c32f463 100644 --- a/test/Nancy.Authentication.Forms.Tests/project.json +++ b/test/Nancy.Authentication.Forms.Tests/project.json @@ -1,16 +1,18 @@ { "dependencies": { - "dotnet-test-xunit": "1.0.0-*", - "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", + "dotnet-test-xunit": "1.0.0-rc3-build10019", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-24027", "Nancy": { "target": "project" }, "Nancy.Authentication.Forms": { "target": "project" }, "xunit": "2.1.0" }, - "compileFiles": [ - "../Nancy.Tests/Fakes/FakeRequest.cs", - "../Nancy.Tests/ShouldExtensions.cs" - ], + "buildOptions": { + "compile": [ + "../Nancy.Tests/Fakes/FakeRequest.cs", + "../Nancy.Tests/ShouldExtensions.cs" + ] + }, "frameworks": { "net452": { diff --git a/test/Nancy.Embedded.Tests/Nancy.Embedded.Tests.xproj b/test/Nancy.Embedded.Tests/Nancy.Embedded.Tests.xproj index 4eb2353450..e58093ad19 100644 --- a/test/Nancy.Embedded.Tests/Nancy.Embedded.Tests.xproj +++ b/test/Nancy.Embedded.Tests/Nancy.Embedded.Tests.xproj @@ -1,20 +1,20 @@ - + 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 838f9240-4541-4646-aac2-0eaa6f05a654 - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.Embedded.Tests + .\obj + .\bin\ + + + Nancy.Embedded.Tests 2.0 - - - - + diff --git a/test/Nancy.Embedded.Tests/project.json b/test/Nancy.Embedded.Tests/project.json index 0ae98022b7..623bed6b56 100644 --- a/test/Nancy.Embedded.Tests/project.json +++ b/test/Nancy.Embedded.Tests/project.json @@ -1,17 +1,18 @@ { "dependencies": { - "dotnet-test-xunit": "1.0.0-*", - "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", + "dotnet-test-xunit": "1.0.0-rc3-build10019", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-24027", "Nancy": { "target": "project" }, "Nancy.Embedded": { "target": "project" }, "xunit": "2.1.0" }, - "compileFiles": [ - "../Nancy.Tests/ShouldExtensions.cs" - ], - - "resource": "Resources/**/*.*", + "buildOptions": { + "compile": [ + "../Nancy.Tests/ShouldExtensions.cs" + ], + "embed": "Resources/**/*.*" + }, "frameworks": { "net452": { diff --git a/test/Nancy.Encryption.MachineKey.Tests/Nancy.Encryption.MachineKey.Tests.xproj b/test/Nancy.Encryption.MachineKey.Tests/Nancy.Encryption.MachineKey.Tests.xproj index 928962b085..267c8e0df5 100644 --- a/test/Nancy.Encryption.MachineKey.Tests/Nancy.Encryption.MachineKey.Tests.xproj +++ b/test/Nancy.Encryption.MachineKey.Tests/Nancy.Encryption.MachineKey.Tests.xproj @@ -1,20 +1,20 @@ - + 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - ff8c9795-2ad5-45e6-851d-6bdf8a7841ce - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.Encryption.MachineKey.Tests + .\obj + .\bin\ + + + Nancy.Encryption.MachineKey.Tests 2.0 - - - - + diff --git a/test/Nancy.Encryption.MachineKey.Tests/project.json b/test/Nancy.Encryption.MachineKey.Tests/project.json index 9ab0ba9dc1..baf6836a3d 100644 --- a/test/Nancy.Encryption.MachineKey.Tests/project.json +++ b/test/Nancy.Encryption.MachineKey.Tests/project.json @@ -1,15 +1,17 @@ { "dependencies": { - "dotnet-test-xunit": "1.0.0-*", - "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", + "dotnet-test-xunit": "1.0.0-rc3-build10019", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-24027", "Nancy": { "target": "project" }, "Nancy.Encryption.MachineKey": { "target": "project" }, "xunit": "2.1.0" }, - "compileFiles": [ - "../Nancy.Tests/ShouldExtensions.cs" - ], + "buildOptions": { + "compile": [ + "../Nancy.Tests/ShouldExtensions.cs" + ] + }, "frameworks": { "net452": { diff --git a/test/Nancy.Hosting.Aspnet.Tests/Nancy.Hosting.Aspnet.Tests.xproj b/test/Nancy.Hosting.Aspnet.Tests/Nancy.Hosting.Aspnet.Tests.xproj index 6a4aa332ab..2a7e5c3eda 100644 --- a/test/Nancy.Hosting.Aspnet.Tests/Nancy.Hosting.Aspnet.Tests.xproj +++ b/test/Nancy.Hosting.Aspnet.Tests/Nancy.Hosting.Aspnet.Tests.xproj @@ -1,20 +1,20 @@ - + 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 98067ec0-5028-432f-b94a-99195d70b76f - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.Hosting.Aspnet.Tests + .\obj + .\bin\ + + + Nancy.Hosting.Aspnet.Tests 2.0 - - - - + diff --git a/test/Nancy.Hosting.Aspnet.Tests/project.json b/test/Nancy.Hosting.Aspnet.Tests/project.json index dac94a1a90..907a32417f 100644 --- a/test/Nancy.Hosting.Aspnet.Tests/project.json +++ b/test/Nancy.Hosting.Aspnet.Tests/project.json @@ -1,15 +1,17 @@ { "dependencies": { - "dotnet-test-xunit": "1.0.0-*", - "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", + "dotnet-test-xunit": "1.0.0-rc3-build10019", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-24027", "Nancy": { "target": "project" }, "Nancy.Hosting.Aspnet": { "target": "project" }, "xunit": "2.1.0" }, - - "compileFiles": [ - "../Nancy.Tests/ShouldExtensions.cs" - ], + + "buildOptions": { + "compile": [ + "../Nancy.Tests/ShouldExtensions.cs" + ] + }, "frameworks": { "net452": { diff --git a/test/Nancy.Hosting.Self.Tests/Nancy.Hosting.Self.Tests.xproj b/test/Nancy.Hosting.Self.Tests/Nancy.Hosting.Self.Tests.xproj index 579632f7c9..b66825ef94 100644 --- a/test/Nancy.Hosting.Self.Tests/Nancy.Hosting.Self.Tests.xproj +++ b/test/Nancy.Hosting.Self.Tests/Nancy.Hosting.Self.Tests.xproj @@ -1,20 +1,20 @@ - + 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 21aa5847-70df-4c96-9aed-1c9a9af9325c - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.Hosting.Self.Tests + .\obj + .\bin\ + + + Nancy.Hosting.Self.Tests 2.0 - - - - + diff --git a/test/Nancy.Hosting.Self.Tests/project.json b/test/Nancy.Hosting.Self.Tests/project.json index e96f4cc44f..2ab62df893 100644 --- a/test/Nancy.Hosting.Self.Tests/project.json +++ b/test/Nancy.Hosting.Self.Tests/project.json @@ -1,17 +1,19 @@ { "dependencies": { - "dotnet-test-xunit": "1.0.0-*", - "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", + "dotnet-test-xunit": "1.0.0-rc3-build10019", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-24027", "Nancy": { "target": "project" }, "Nancy.Hosting.Self": { "target": "project" }, "xunit": "2.1.0" }, - "compileFiles": [ - "../Nancy.Tests/ShouldExtensions.cs", - "../Nancy.Tests/xUnitExtensions/SkipException.cs", - "../Nancy.Tests/xUnitExtensions/SkippableFactAttribute.cs" - ], + "buildOptions": { + "compile": [ + "../Nancy.Tests/ShouldExtensions.cs", + "../Nancy.Tests/xUnitExtensions/SkipException.cs", + "../Nancy.Tests/xUnitExtensions/SkippableFactAttribute.cs" + ] + }, "frameworks": { "net452": { diff --git a/test/Nancy.Metadata.Modules.Tests/Nancy.Metadata.Modules.Tests.xproj b/test/Nancy.Metadata.Modules.Tests/Nancy.Metadata.Modules.Tests.xproj index 58101eeeea..4ce3381e56 100644 --- a/test/Nancy.Metadata.Modules.Tests/Nancy.Metadata.Modules.Tests.xproj +++ b/test/Nancy.Metadata.Modules.Tests/Nancy.Metadata.Modules.Tests.xproj @@ -1,20 +1,20 @@ - + 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - e5047274-5a15-41c6-986f-a6a36588a012 - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.Metadata.Modules.Tests + .\obj + .\bin\ + + + Nancy.Metadata.Modules.Tests 2.0 - - - - + diff --git a/test/Nancy.Metadata.Modules.Tests/project.json b/test/Nancy.Metadata.Modules.Tests/project.json index df09cf6ba8..5e8e1dad03 100644 --- a/test/Nancy.Metadata.Modules.Tests/project.json +++ b/test/Nancy.Metadata.Modules.Tests/project.json @@ -1,15 +1,17 @@ { "dependencies": { - "dotnet-test-xunit": "1.0.0-*", - "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", + "dotnet-test-xunit": "1.0.0-rc3-build10019", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-24027", "Nancy": { "target": "project" }, "Nancy.Metadata.Modules": { "target": "project" }, "xunit": "2.1.0" }, - "compileFiles": [ - "../Nancy.Tests/ShouldExtensions.cs" - ], + "buildOptions": { + "compile": [ + "../Nancy.Tests/ShouldExtensions.cs" + ] + }, "frameworks": { "net452": { diff --git a/test/Nancy.Owin.Tests/Nancy.Owin.Tests.xproj b/test/Nancy.Owin.Tests/Nancy.Owin.Tests.xproj index 9972741c10..c8385b286a 100644 --- a/test/Nancy.Owin.Tests/Nancy.Owin.Tests.xproj +++ b/test/Nancy.Owin.Tests/Nancy.Owin.Tests.xproj @@ -1,20 +1,20 @@ - + 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 10771591-d09d-4fcc-990e-3982006fb1fa - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.Owin.Tests + .\obj + .\bin\ + + + Nancy.Owin.Tests 2.0 - - - - + diff --git a/test/Nancy.Owin.Tests/project.json b/test/Nancy.Owin.Tests/project.json index b91877cef7..9e20b62b7e 100644 --- a/test/Nancy.Owin.Tests/project.json +++ b/test/Nancy.Owin.Tests/project.json @@ -1,7 +1,7 @@ { "dependencies": { - "dotnet-test-xunit": "1.0.0-*", - "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", + "dotnet-test-xunit": "1.0.0-rc3-build10019", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-24027", "Microsoft.Owin.Testing": "2.1.0", "Nancy": { "target": "project" }, "Nancy.Owin": { "target": "project" }, @@ -9,10 +9,12 @@ "xunit": "2.1.0" }, - "compileFiles": [ - "../Nancy.Tests/Fakes/FakeRequest.cs", - "../Nancy.Tests/ShouldExtensions.cs" - ], + "buildOptions": { + "compileFiles": [ + "../Nancy.Tests/Fakes/FakeRequest.cs", + "../Nancy.Tests/ShouldExtensions.cs" + ] + }, "frameworks": { "net452": { diff --git a/test/Nancy.Testing.Tests/Nancy.Testing.Tests.xproj b/test/Nancy.Testing.Tests/Nancy.Testing.Tests.xproj index cad934dd65..eeef0a7f39 100644 --- a/test/Nancy.Testing.Tests/Nancy.Testing.Tests.xproj +++ b/test/Nancy.Testing.Tests/Nancy.Testing.Tests.xproj @@ -1,20 +1,20 @@ - + 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - ceff8372-2f7a-41cb-8f13-164abba8aca2 - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.Testing.Tests + .\obj + .\bin\ + + + Nancy.Testing.Tests 2.0 - - - - + diff --git a/test/Nancy.Testing.Tests/project.json b/test/Nancy.Testing.Tests/project.json index 90f23c467b..f94e2d671a 100644 --- a/test/Nancy.Testing.Tests/project.json +++ b/test/Nancy.Testing.Tests/project.json @@ -1,21 +1,22 @@ { "dependencies": { "AngleSharp": "0.9.5", - "dotnet-test-xunit": "1.0.0-*", - "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", + "dotnet-test-xunit": "1.0.0-rc3-build10019", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-24027", "Nancy": { "target": "project" }, "Nancy.Testing": { "target": "project" }, "xunit": "2.1.0" }, - "compileFiles": [ - "../Nancy.Tests/ShouldExtensions.cs", - "../Nancy.Tests/xUnitExtensions/RecordAsync.cs" - ], - - "contentFiles": [ - "TestingViewExtensions/ViewFactoryTest.sshtml" - ], + "buildOptions": { + "compile": [ + "../Nancy.Tests/ShouldExtensions.cs", + "../Nancy.Tests/xUnitExtensions/RecordAsync.cs" + ], + "copyToOutput": [ + "TestingViewExtensions/ViewFactoryTest.sshtml" + ] + }, "frameworks": { "net452": { diff --git a/test/Nancy.Tests.Functional/Nancy.Tests.Functional.xproj b/test/Nancy.Tests.Functional/Nancy.Tests.Functional.xproj index 64b2ce6c2a..c25bf47097 100644 --- a/test/Nancy.Tests.Functional/Nancy.Tests.Functional.xproj +++ b/test/Nancy.Tests.Functional/Nancy.Tests.Functional.xproj @@ -1,20 +1,20 @@ - + 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 742ac687-fc9a-4534-bb50-3d91738563a7 - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.Tests.Functional + .\obj + .\bin\ + + + Nancy.Tests.Functional 2.0 - - - - + diff --git a/test/Nancy.Tests.Functional/project.json b/test/Nancy.Tests.Functional/project.json index 3b8895cd1d..aae7a5d352 100644 --- a/test/Nancy.Tests.Functional/project.json +++ b/test/Nancy.Tests.Functional/project.json @@ -1,20 +1,21 @@ { "dependencies": { - "dotnet-test-xunit": "1.0.0-*", - "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", + "dotnet-test-xunit": "1.0.0-rc3-build10019", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-24027", "Nancy": { "target": "project" }, "Nancy.Testing": { "target": "project" }, "xunit": "2.1.0" }, - "compileFiles": [ - "../Nancy.Tests/xUnitExtensions/RecordAsync.cs" - ], - - "content": [ - "Content/**/*", - "Views/**/*" - ], + "buildOptions": { + "compile": [ + "../Nancy.Tests/xUnitExtensions/RecordAsync.cs" + ], + "copyToOutput": [ + "Content/**/*", + "Views/**/*" + ] + }, "frameworks": { "netcoreapp1.0": { @@ -22,10 +23,9 @@ "define": [ "CORE" ] }, "dependencies": { - "dotnet-test-xunit": "1.0.0-*", "Microsoft.NETCore.App": { "type": "platform", - "version": "1.0.0-rc2-*" + "version": "1.0.0-rc2-3002702" } }, diff --git a/test/Nancy.Tests/Nancy.Tests.xproj b/test/Nancy.Tests/Nancy.Tests.xproj index c3530fd7ef..221bd9c4d2 100644 --- a/test/Nancy.Tests/Nancy.Tests.xproj +++ b/test/Nancy.Tests/Nancy.Tests.xproj @@ -1,20 +1,20 @@ - + 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 3ba7d452-98e5-47b0-bd1e-dc348e13a72a - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.Tests + .\obj + .\bin\ + + + Nancy.Tests 2.0 - - - - - \ No newline at end of file + + diff --git a/test/Nancy.Tests/project.json b/test/Nancy.Tests/project.json index 1b2eda2f88..0a0e84acc3 100644 --- a/test/Nancy.Tests/project.json +++ b/test/Nancy.Tests/project.json @@ -1,19 +1,20 @@ { "dependencies": { - "dotnet-test-xunit": "1.0.0-*", - "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", + "dotnet-test-xunit": "1.0.0-rc3-build10019", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-24027", "Nancy": { "target": "project" }, "Nancy.Testing": { "target": "project" }, "xunit": "2.1.0" }, - - "content": [ - "Resources/**/*" - ], - "resourceFiles": [ - "Resources/views/staticviewresource.html" - ], + "buildOptions": { + "copyToOutput": [ + "Resources/**/*" + ], + "embed": [ + "Resources/views/staticviewresource.html" + ] + }, "frameworks": { "net452": { diff --git a/test/Nancy.Validation.DataAnnotatioins.Tests/Nancy.Validation.DataAnnotatioins.Tests.xproj b/test/Nancy.Validation.DataAnnotatioins.Tests/Nancy.Validation.DataAnnotatioins.Tests.xproj index d62f32ddcc..e5da6d4f26 100644 --- a/test/Nancy.Validation.DataAnnotatioins.Tests/Nancy.Validation.DataAnnotatioins.Tests.xproj +++ b/test/Nancy.Validation.DataAnnotatioins.Tests/Nancy.Validation.DataAnnotatioins.Tests.xproj @@ -1,20 +1,20 @@ - + 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 8830dbe0-2162-4f35-8d81-1577f17abb10 - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.Validation.DataAnnotatioins.Tests + .\obj + .\bin\ + + + Nancy.Validation.DataAnnotatioins.Tests 2.0 - - - - + diff --git a/test/Nancy.Validation.DataAnnotatioins.Tests/project.json b/test/Nancy.Validation.DataAnnotatioins.Tests/project.json index 7dca3f0898..d738f8fb56 100644 --- a/test/Nancy.Validation.DataAnnotatioins.Tests/project.json +++ b/test/Nancy.Validation.DataAnnotatioins.Tests/project.json @@ -1,15 +1,17 @@ { "dependencies": { - "dotnet-test-xunit": "1.0.0-*", - "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", + "dotnet-test-xunit": "1.0.0-rc3-build10019", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-24027", "Nancy": { "target": "project" }, "Nancy.Validation.DataAnnotations": { "target": "project" }, "xunit": "2.1.0" }, - "compileFiles": [ - "../Nancy.Tests/ShouldExtensions.cs" - ], + "buildOptions": { + "compile": [ + "../Nancy.Tests/ShouldExtensions.cs" + ] + }, "frameworks": { "net452": { diff --git a/test/Nancy.Validation.FluentValidation.Tests/Nancy.Validation.FluentValidation.Tests.xproj b/test/Nancy.Validation.FluentValidation.Tests/Nancy.Validation.FluentValidation.Tests.xproj index ae72ba9e13..11a215e321 100644 --- a/test/Nancy.Validation.FluentValidation.Tests/Nancy.Validation.FluentValidation.Tests.xproj +++ b/test/Nancy.Validation.FluentValidation.Tests/Nancy.Validation.FluentValidation.Tests.xproj @@ -1,20 +1,20 @@ - + 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 8dd96d02-c6d3-435b-b0f7-2460161a250f - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.Validation.FluentValidation.Tests + .\obj + .\bin\ + + + Nancy.Validation.FluentValidation.Tests 2.0 - - - - + diff --git a/test/Nancy.Validation.FluentValidation.Tests/project.json b/test/Nancy.Validation.FluentValidation.Tests/project.json index c80af11716..8c2a006171 100644 --- a/test/Nancy.Validation.FluentValidation.Tests/project.json +++ b/test/Nancy.Validation.FluentValidation.Tests/project.json @@ -1,16 +1,18 @@ { "dependencies": { - "dotnet-test-xunit": "1.0.0-*", - "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", + "dotnet-test-xunit": "1.0.0-rc3-build10019", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-24027", "FluentValidation": "3.4.0", "Nancy": { "target": "project" }, "Nancy.Validation.FluentValidation": { "target": "project" }, "xunit": "2.1.0" }, - "compileFiles": [ - "../Nancy.Tests/ShouldExtensions.cs" - ], + "buildOptions": { + "compile": [ + "../Nancy.Tests/ShouldExtensions.cs" + ] + }, "frameworks": { "net452": { diff --git a/test/Nancy.ViewEngines.DotLiquid.Tests/Nancy.ViewEngines.DotLiquid.Tests.xproj b/test/Nancy.ViewEngines.DotLiquid.Tests/Nancy.ViewEngines.DotLiquid.Tests.xproj index 785aeba852..358b864eb7 100644 --- a/test/Nancy.ViewEngines.DotLiquid.Tests/Nancy.ViewEngines.DotLiquid.Tests.xproj +++ b/test/Nancy.ViewEngines.DotLiquid.Tests/Nancy.ViewEngines.DotLiquid.Tests.xproj @@ -1,20 +1,20 @@ - + 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 91f4ea23-788b-4e54-a38e-fe738b3bf2f1 - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.ViewEngines.DotLiquid.Tests + .\obj + .\bin\ + + + Nancy.ViewEngines.DotLiquid.Tests 2.0 - - - - + diff --git a/test/Nancy.ViewEngines.DotLiquid.Tests/project.json b/test/Nancy.ViewEngines.DotLiquid.Tests/project.json index d2b74a308e..89d9133985 100644 --- a/test/Nancy.ViewEngines.DotLiquid.Tests/project.json +++ b/test/Nancy.ViewEngines.DotLiquid.Tests/project.json @@ -1,21 +1,22 @@ { "dependencies": { "DotLiquid": "1.7.0", - "dotnet-test-xunit": "1.0.0-*", - "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", + "dotnet-test-xunit": "1.0.0-rc3-build10019", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-24027", "Nancy": { "target": "project" }, "Nancy.Testing": { "target": "project" }, "Nancy.ViewEngines.DotLiquid": { "target": "project" }, "xunit": "2.1.0" }, - - "compileFiles": [ - "../Nancy.Tests/ShouldExtensions.cs" - ], - - "content": [ - "Views/**/*" - ], + + "buildOptions": { + "compile": [ + "../Nancy.Tests/ShouldExtensions.cs" + ], + "copyToOutput": [ + "Views/**/*" + ] + }, "frameworks": { "net452": { diff --git a/test/Nancy.ViewEngines.Markdown.Tests/Nancy.ViewEngines.Markdown.Tests.xproj b/test/Nancy.ViewEngines.Markdown.Tests/Nancy.ViewEngines.Markdown.Tests.xproj index 20a389e053..1ea867e1d5 100644 --- a/test/Nancy.ViewEngines.Markdown.Tests/Nancy.ViewEngines.Markdown.Tests.xproj +++ b/test/Nancy.ViewEngines.Markdown.Tests/Nancy.ViewEngines.Markdown.Tests.xproj @@ -1,20 +1,20 @@ - + 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - c46bfaa7-f471-45a6-a5ac-fcf9390408ee - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.ViewEngines.Markdown.Tests + .\obj + .\bin\ + + + Nancy.ViewEngines.Markdown.Tests 2.0 - - - - + diff --git a/test/Nancy.ViewEngines.Markdown.Tests/project.json b/test/Nancy.ViewEngines.Markdown.Tests/project.json index f49ed9515e..85a7922935 100644 --- a/test/Nancy.ViewEngines.Markdown.Tests/project.json +++ b/test/Nancy.ViewEngines.Markdown.Tests/project.json @@ -1,20 +1,21 @@ { "dependencies": { - "dotnet-test-xunit": "1.0.0-*", - "MarkdownSharp": "1.13.0", - "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", + "dotnet-test-xunit": "1.0.0-rc3-build10019", + "MarkdownSharp": "1.13.0", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-24027", "Nancy": { "target": "project" }, "Nancy.ViewEngines.Markdown": { "target": "project" }, "xunit": "2.1.0" }, - "compileFiles": [ - "../Nancy.Tests/ShouldExtensions.cs" - ], - - "content": [ - "Markdown/**/*" - ], + "buildOptions": { + "compile": [ + "../Nancy.Tests/ShouldExtensions.cs" + ], + "copyToOutput": [ + "Markdown/**/*" + ] + }, "frameworks": { "net452": { diff --git a/test/Nancy.ViewEngines.Razor.Tests.Models/Nancy.ViewEngines.Razor.Tests.Models.xproj b/test/Nancy.ViewEngines.Razor.Tests.Models/Nancy.ViewEngines.Razor.Tests.Models.xproj index 75878d6dd1..ddaa71d9b9 100644 --- a/test/Nancy.ViewEngines.Razor.Tests.Models/Nancy.ViewEngines.Razor.Tests.Models.xproj +++ b/test/Nancy.ViewEngines.Razor.Tests.Models/Nancy.ViewEngines.Razor.Tests.Models.xproj @@ -1,20 +1,20 @@ - + 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 31fa18d3-24ad-4ab0-b297-5a2fd871989e - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.ViewEngines.Razor.Tests.Models + .\obj + .\bin\ + + + Nancy.ViewEngines.Razor.Tests.Models 2.0 - - - - + diff --git a/test/Nancy.ViewEngines.Razor.Tests.Models/project.json b/test/Nancy.ViewEngines.Razor.Tests.Models/project.json index 183cfa69ad..f8d1e23145 100644 --- a/test/Nancy.ViewEngines.Razor.Tests.Models/project.json +++ b/test/Nancy.ViewEngines.Razor.Tests.Models/project.json @@ -1,7 +1,5 @@ { "frameworks": { - "net452": { - - } + "net452": { } } } diff --git a/test/Nancy.ViewEngines.Razor.Tests/Nancy.ViewEngines.Razor.Tests.xproj b/test/Nancy.ViewEngines.Razor.Tests/Nancy.ViewEngines.Razor.Tests.xproj index 0bbf4f04a9..f1e3035214 100644 --- a/test/Nancy.ViewEngines.Razor.Tests/Nancy.ViewEngines.Razor.Tests.xproj +++ b/test/Nancy.ViewEngines.Razor.Tests/Nancy.ViewEngines.Razor.Tests.xproj @@ -1,20 +1,20 @@ - + 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - a24271fa-e058-42e0-bb7d-3c8c43df4b04 - ..\..\artifacts\obj\$(MSBuildProjectName) - ..\..\artifacts\bin\$(MSBuildProjectName)\ + Nancy.ViewEngines.Razor.Tests + .\obj + .\bin\ + + + Nancy.ViewEngines.Razor.Tests 2.0 - - - - + diff --git a/test/Nancy.ViewEngines.Razor.Tests/project.json b/test/Nancy.ViewEngines.Razor.Tests/project.json index 4ebd04c49f..5bd6714437 100644 --- a/test/Nancy.ViewEngines.Razor.Tests/project.json +++ b/test/Nancy.ViewEngines.Razor.Tests/project.json @@ -1,7 +1,7 @@ { "dependencies": { - "dotnet-test-xunit": "1.0.0-*", - "Microsoft.NETCore.Platforms": "1.0.1-rc2-*", + "dotnet-test-xunit": "1.0.0-rc3-build10019", + "Microsoft.NETCore.Platforms": "1.0.1-rc2-24027", "Nancy": { "target": "project" }, "Nancy.Testing": { "target": "project" }, "Nancy.ViewEngines.Razor": { "target": "project" }, @@ -9,13 +9,14 @@ "xunit": "2.1.0" }, - "compileFiles": [ - "../Nancy.Tests/ShouldExtensions.cs" - ], - - "content": [ - "TestViews/**/*" - ], + "buildOptions": { + "compile": [ + "../Nancy.Tests/ShouldExtensions.cs" + ], + "copyToOutput": [ + "TestViews/**/*" + ] + }, "frameworks": { "net452": { From a9c30af9fd5986681f0cc93dcba5b0af25d8ce26 Mon Sep 17 00:00:00 2001 From: Jonathan Channon Date: Fri, 20 May 2016 11:02:27 +0100 Subject: [PATCH 49/52] added aspnetcore configuration usage to Nancy.Demo.Hosting.Kestrel --- .gitignore | 1 + .../AppConfiguration.cs | 29 +++++++++++++++++ .../DemoBootstrapper.cs | 24 ++++++++++++++ samples/Nancy.Demo.Hosting.Kestrel/Program.cs | 6 ++-- samples/Nancy.Demo.Hosting.Kestrel/Startup.cs | 31 +++++++++++++++++++ .../appsettings.json | 16 ++++++++++ .../Nancy.Demo.Hosting.Kestrel/project.json | 4 ++- 7 files changed, 107 insertions(+), 4 deletions(-) create mode 100644 samples/Nancy.Demo.Hosting.Kestrel/AppConfiguration.cs create mode 100644 samples/Nancy.Demo.Hosting.Kestrel/DemoBootstrapper.cs create mode 100644 samples/Nancy.Demo.Hosting.Kestrel/Startup.cs create mode 100644 samples/Nancy.Demo.Hosting.Kestrel/appsettings.json diff --git a/.gitignore b/.gitignore index 0a5ed84321..da725c4fad 100644 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,4 @@ Gemfile.lock packages/ project.lock.json TestAssembly.dll +.vscode/ \ No newline at end of file diff --git a/samples/Nancy.Demo.Hosting.Kestrel/AppConfiguration.cs b/samples/Nancy.Demo.Hosting.Kestrel/AppConfiguration.cs new file mode 100644 index 0000000000..c0d2809fe6 --- /dev/null +++ b/samples/Nancy.Demo.Hosting.Kestrel/AppConfiguration.cs @@ -0,0 +1,29 @@ +namespace Nancy.Demo.Hosting.Kestrel +{ + public class AppConfiguration + { + public Logging Logging { get; set; } + public Smtp Smtp { get; set; } + } + + public class LogLevel + { + public string Default { get; set; } + public string System { get; set; } + public string Microsoft { get; set; } + } + + public class Logging + { + public bool IncludeScopes { get; set; } + public LogLevel LogLevel { get; set; } + } + + public class Smtp + { + public string Server { get; set; } + public string User { get; set; } + public string Pass { get; set; } + public string Port { get; set; } + } +} \ No newline at end of file diff --git a/samples/Nancy.Demo.Hosting.Kestrel/DemoBootstrapper.cs b/samples/Nancy.Demo.Hosting.Kestrel/DemoBootstrapper.cs new file mode 100644 index 0000000000..8864733f1e --- /dev/null +++ b/samples/Nancy.Demo.Hosting.Kestrel/DemoBootstrapper.cs @@ -0,0 +1,24 @@ +namespace Nancy.Demo.Hosting.Kestrel +{ + using System; + + public class DemoBootstrapper : DefaultNancyBootstrapper + { + public DemoBootstrapper() + { + + } + + public DemoBootstrapper(AppConfiguration appConfig) + { + /* + We could register appConfig as an instance in the container which can + be injected into areas that need it or we could create our own INancyEnvironment + extension and use that. + */ + Console.WriteLine(appConfig.Smtp.Server); + Console.WriteLine(appConfig.Smtp.User); + Console.WriteLine(appConfig.Logging.IncludeScopes); + } + } +} \ No newline at end of file diff --git a/samples/Nancy.Demo.Hosting.Kestrel/Program.cs b/samples/Nancy.Demo.Hosting.Kestrel/Program.cs index ef189578a5..a2a5353bef 100644 --- a/samples/Nancy.Demo.Hosting.Kestrel/Program.cs +++ b/samples/Nancy.Demo.Hosting.Kestrel/Program.cs @@ -1,17 +1,17 @@ namespace Nancy.Demo.Hosting.Kestrel { + using System.IO; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; - using Microsoft.AspNetCore.Http; - using Nancy.Owin; public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() + .UseContentRoot(Directory.GetCurrentDirectory()) .UseKestrel() - .Configure(app => app.UseOwin(x => x.UseNancy())) + .UseStartup() .Build(); host.Run(); diff --git a/samples/Nancy.Demo.Hosting.Kestrel/Startup.cs b/samples/Nancy.Demo.Hosting.Kestrel/Startup.cs new file mode 100644 index 0000000000..148b72f86b --- /dev/null +++ b/samples/Nancy.Demo.Hosting.Kestrel/Startup.cs @@ -0,0 +1,31 @@ +namespace Nancy.Demo.Hosting.Kestrel +{ + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Hosting; + using Microsoft.Extensions.Configuration; + using Nancy.Owin; + + public class Startup + { + public IConfiguration Configuration { get; set; } + + public Startup(IHostingEnvironment env) + { + var builder = new ConfigurationBuilder() + .AddJsonFile("appsettings.json") + .SetBasePath(env.ContentRootPath); + + Configuration = builder.Build(); + } + + public void Configure(IApplicationBuilder app) + { + + var config = this.Configuration; + var appConfig = new AppConfiguration(); + ConfigurationBinder.Bind(config, appConfig); + + app.UseOwin(x => x.UseNancy(opt => opt.Bootstrapper = new DemoBootstrapper(appConfig))); + } + } +} diff --git a/samples/Nancy.Demo.Hosting.Kestrel/appsettings.json b/samples/Nancy.Demo.Hosting.Kestrel/appsettings.json new file mode 100644 index 0000000000..920cf36175 --- /dev/null +++ b/samples/Nancy.Demo.Hosting.Kestrel/appsettings.json @@ -0,0 +1,16 @@ +{ + "Logging": { + "IncludeScopes": false, + "LogLevel": { + "Default": "Verbose", + "System": "Information", + "Microsoft": "Information" + } + }, + "Smtp": { + "Server": "0.0.0.1", + "User": "user@company.com", + "Pass": "123456789", + "Port": "25" + } +} \ No newline at end of file diff --git a/samples/Nancy.Demo.Hosting.Kestrel/project.json b/samples/Nancy.Demo.Hosting.Kestrel/project.json index c0e76a0acc..4d37943b0e 100644 --- a/samples/Nancy.Demo.Hosting.Kestrel/project.json +++ b/samples/Nancy.Demo.Hosting.Kestrel/project.json @@ -14,6 +14,8 @@ "Microsoft.AspNetCore.Hosting": "1.0.0-rc2-final", "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final", "Microsoft.AspNetCore.Owin": "1.0.0-rc2-final", + "Microsoft.Extensions.Configuration.Binder":"1.0.0-rc2-final", + "Microsoft.Extensions.Configuration.Json":"1.0.0-rc2-final", "Microsoft.NETCore.App": { "type": "platform", "version": "1.0.0-rc2-3002702" @@ -25,4 +27,4 @@ ] } } -} \ No newline at end of file +} From 244b9405e369b1efe4e9bc42fd08fe2d7ede2c9b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20H=C3=A5kansson?= Date: Fri, 20 May 2016 14:21:41 +0200 Subject: [PATCH 50/52] Removed unused TFM parameter (#2448) --- build.ps1 | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/build.ps1 b/build.ps1 index d79d412f47..f197d71657 100644 --- a/build.ps1 +++ b/build.ps1 @@ -17,10 +17,7 @@ function Restore-Packages function Test-Projects { - param([string] $framework) & dotnet test; - #& dotnet test -f $framework; - if($LASTEXITCODE -ne 0) { exit 3 @@ -44,7 +41,7 @@ Get-ChildItem -Path . -Filter *.xproj -Recurse | ForEach-Object { Restore-Packag Write-Host "Running tests" Get-ChildItem -Path .\test -Filter *.xproj -Exclude Nancy.ViewEngines.Razor.Tests.Models.xproj -Recurse | ForEach-Object { Push-Location $_.DirectoryName - Test-Projects "netcoreapp1.0" + Test-Projects Pop-Location } From d803cce4ade5caf22cd5ca5ca67e435a26e70cdd Mon Sep 17 00:00:00 2001 From: Kristian Hellang Date: Mon, 23 May 2016 02:03:12 +0200 Subject: [PATCH 51/52] Fix install script location The old URL is dead --- build.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.ps1 b/build.ps1 index f197d71657..71d423a099 100644 --- a/build.ps1 +++ b/build.ps1 @@ -5,7 +5,7 @@ function Install-Dotnet if(($LASTEXITCODE -ne 0) -Or ((Test-Path Env:\APPVEYOR) -eq $true)) { Write-Host "Dotnet CLI not found - downloading latest version" - & { iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/dotnet/cli/rel/1.0.0/scripts/obtain/install.ps1')) } + & { iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/dotnet/cli/rel/1.0.0/scripts/obtain/dotnet-install.ps1')) } } } From 301d1d0ccfb1f27a2141356e5c599d7c06a718e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20H=C3=A5kansson?= Date: Fri, 27 May 2016 13:16:23 +0200 Subject: [PATCH 52/52] Resolved merge conflicts between coreclr and master --- build.ps1 | 39 +++++++++++++++++-- .../Nancy.Demo.Hosting.Kestrel/HomeModule.cs | 4 +- src/Nancy/project.json | 1 + .../Nancy.Authentication.Basic.Tests.xproj | 7 +++- .../Nancy.Authentication.Forms.Tests.xproj | 7 +++- .../Nancy.Embedded.Tests.xproj | 7 +++- .../Nancy.Encryption.MachineKey.Tests.xproj | 7 +++- .../Nancy.Hosting.Aspnet.Tests.xproj | 7 +++- .../Nancy.Hosting.Self.Tests.xproj | 7 +++- .../Nancy.Metadata.Modules.Tests.xproj | 7 +++- .../AppBuilderExtensionsFixture.cs | 26 ++++--------- test/Nancy.Owin.Tests/Nancy.Owin.Tests.xproj | 7 +++- .../Nancy.Testing.Tests.xproj | 7 +++- .../Nancy.Tests.Functional.xproj | 7 +++- test/Nancy.Tests/Nancy.Tests.xproj | 7 +++- ...cy.Validation.DataAnnotatioins.Tests.xproj | 7 +++- ...cy.Validation.FluentValidation.Tests.xproj | 7 +++- .../Nancy.ViewEngines.DotLiquid.Tests.xproj | 7 +++- .../Nancy.ViewEngines.Markdown.Tests.xproj | 7 +++- .../Nancy.ViewEngines.Razor.Tests.xproj | 7 +++- 20 files changed, 126 insertions(+), 56 deletions(-) diff --git a/build.ps1 b/build.ps1 index 71d423a099..6a5971f4f5 100644 --- a/build.ps1 +++ b/build.ps1 @@ -5,19 +5,52 @@ function Install-Dotnet if(($LASTEXITCODE -ne 0) -Or ((Test-Path Env:\APPVEYOR) -eq $true)) { Write-Host "Dotnet CLI not found - downloading latest version" - & { iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/dotnet/cli/rel/1.0.0/scripts/obtain/dotnet-install.ps1')) } + + # Prepare the dotnet CLI folder + $env:DOTNET_INSTALL_DIR="$(Convert-Path "$PSScriptRoot")\.dotnet\win7-x64" + if (!(Test-Path $env:DOTNET_INSTALL_DIR)) + { + mkdir $env:DOTNET_INSTALL_DIR | Out-Null + } + + # Download the dotnet CLI install script + if (!(Test-Path .\dotnet\install.ps1)) + { + Invoke-WebRequest "https://raw.githubusercontent.com/dotnet/cli/rel/1.0.0/scripts/obtain/dotnet-install.ps1" -OutFile ".\.dotnet\dotnet-install.ps1" + } + + # Run the dotnet CLI install + & .\.dotnet\dotnet-install.ps1 + + # Add the dotnet folder path to the process. This gets skipped + # by Install-DotNetCli if it's already installed. + Remove-PathVariable $env:DOTNET_INSTALL_DIR + $env:PATH = "$env:DOTNET_INSTALL_DIR;$env:PATH" + } } +function Remove-PathVariable +{ + [cmdletbinding()] + param([string] $VariableToRemove) + $path = [Environment]::GetEnvironmentVariable("PATH", "User") + $newItems = $path.Split(';') | Where-Object { $_.ToString() -inotlike $VariableToRemove } + [Environment]::SetEnvironmentVariable("PATH", [System.String]::Join(';', $newItems), "User") + $path = [Environment]::GetEnvironmentVariable("PATH", "Process") + $newItems = $path.Split(';') | Where-Object { $_.ToString() -inotlike $VariableToRemove } + [Environment]::SetEnvironmentVariable("PATH", [System.String]::Join(';', $newItems), "Process") +} + function Restore-Packages { param([string] $DirectoryName) - & dotnet restore -v Error ("""" + $DirectoryName + """") + & dotnet restore -v Warning ("""" + $DirectoryName + """") } function Test-Projects { - & dotnet test; + & dotnet test -c Release; if($LASTEXITCODE -ne 0) { exit 3 diff --git a/samples/Nancy.Demo.Hosting.Kestrel/HomeModule.cs b/samples/Nancy.Demo.Hosting.Kestrel/HomeModule.cs index 05dc19cd48..0c48b5893e 100644 --- a/samples/Nancy.Demo.Hosting.Kestrel/HomeModule.cs +++ b/samples/Nancy.Demo.Hosting.Kestrel/HomeModule.cs @@ -6,9 +6,9 @@ public class HomeModule : NancyModule { public HomeModule() { - Get["/"] = (o, token) => Task.FromResult("Hello from Nancy running on CoreCLR"); + Get("/", (args, ct) => Task.FromResult("Hello from Nancy running on CoreCLR")); - Get["/conneg/{name}"] = (parameters, token) => Task.FromResult(new Person() { Name = parameters.name }); + Get("/conneg/{name}", (args, token) => Task.FromResult(new Person() { Name = args.name })); } } } diff --git a/src/Nancy/project.json b/src/Nancy/project.json index fd2d064170..5891a08b75 100644 --- a/src/Nancy/project.json +++ b/src/Nancy/project.json @@ -16,6 +16,7 @@ "buildOptions": { "embed": [ + "ErrorHandling/Resources/**/*.*", "Diagnostics/Resources/**/*.*", "Diagnostics/Views/**/*.*" ] diff --git a/test/Nancy.Authentication.Basic.Tests/Nancy.Authentication.Basic.Tests.xproj b/test/Nancy.Authentication.Basic.Tests/Nancy.Authentication.Basic.Tests.xproj index 40bfe78438..b2b902baa9 100644 --- a/test/Nancy.Authentication.Basic.Tests/Nancy.Authentication.Basic.Tests.xproj +++ b/test/Nancy.Authentication.Basic.Tests/Nancy.Authentication.Basic.Tests.xproj @@ -1,4 +1,4 @@ - + 14.0 @@ -16,5 +16,8 @@ 2.0 + + + - + \ No newline at end of file diff --git a/test/Nancy.Authentication.Forms.Tests/Nancy.Authentication.Forms.Tests.xproj b/test/Nancy.Authentication.Forms.Tests/Nancy.Authentication.Forms.Tests.xproj index 39b586e635..43e3e0df66 100644 --- a/test/Nancy.Authentication.Forms.Tests/Nancy.Authentication.Forms.Tests.xproj +++ b/test/Nancy.Authentication.Forms.Tests/Nancy.Authentication.Forms.Tests.xproj @@ -1,4 +1,4 @@ - + 14.0 @@ -16,5 +16,8 @@ 2.0 + + + - + \ No newline at end of file diff --git a/test/Nancy.Embedded.Tests/Nancy.Embedded.Tests.xproj b/test/Nancy.Embedded.Tests/Nancy.Embedded.Tests.xproj index e58093ad19..68519e0513 100644 --- a/test/Nancy.Embedded.Tests/Nancy.Embedded.Tests.xproj +++ b/test/Nancy.Embedded.Tests/Nancy.Embedded.Tests.xproj @@ -1,4 +1,4 @@ - + 14.0 @@ -16,5 +16,8 @@ 2.0 + + + - + \ No newline at end of file diff --git a/test/Nancy.Encryption.MachineKey.Tests/Nancy.Encryption.MachineKey.Tests.xproj b/test/Nancy.Encryption.MachineKey.Tests/Nancy.Encryption.MachineKey.Tests.xproj index 267c8e0df5..f6638c677f 100644 --- a/test/Nancy.Encryption.MachineKey.Tests/Nancy.Encryption.MachineKey.Tests.xproj +++ b/test/Nancy.Encryption.MachineKey.Tests/Nancy.Encryption.MachineKey.Tests.xproj @@ -1,4 +1,4 @@ - + 14.0 @@ -16,5 +16,8 @@ 2.0 + + + - + \ No newline at end of file diff --git a/test/Nancy.Hosting.Aspnet.Tests/Nancy.Hosting.Aspnet.Tests.xproj b/test/Nancy.Hosting.Aspnet.Tests/Nancy.Hosting.Aspnet.Tests.xproj index 2a7e5c3eda..a86bdd20e6 100644 --- a/test/Nancy.Hosting.Aspnet.Tests/Nancy.Hosting.Aspnet.Tests.xproj +++ b/test/Nancy.Hosting.Aspnet.Tests/Nancy.Hosting.Aspnet.Tests.xproj @@ -1,4 +1,4 @@ - + 14.0 @@ -16,5 +16,8 @@ 2.0 + + + - + \ No newline at end of file diff --git a/test/Nancy.Hosting.Self.Tests/Nancy.Hosting.Self.Tests.xproj b/test/Nancy.Hosting.Self.Tests/Nancy.Hosting.Self.Tests.xproj index b66825ef94..4b2d50a0f6 100644 --- a/test/Nancy.Hosting.Self.Tests/Nancy.Hosting.Self.Tests.xproj +++ b/test/Nancy.Hosting.Self.Tests/Nancy.Hosting.Self.Tests.xproj @@ -1,4 +1,4 @@ - + 14.0 @@ -16,5 +16,8 @@ 2.0 + + + - + \ No newline at end of file diff --git a/test/Nancy.Metadata.Modules.Tests/Nancy.Metadata.Modules.Tests.xproj b/test/Nancy.Metadata.Modules.Tests/Nancy.Metadata.Modules.Tests.xproj index 4ce3381e56..fb3352961c 100644 --- a/test/Nancy.Metadata.Modules.Tests/Nancy.Metadata.Modules.Tests.xproj +++ b/test/Nancy.Metadata.Modules.Tests/Nancy.Metadata.Modules.Tests.xproj @@ -1,4 +1,4 @@ - + 14.0 @@ -16,5 +16,8 @@ 2.0 + + + - + \ No newline at end of file diff --git a/test/Nancy.Owin.Tests/AppBuilderExtensionsFixture.cs b/test/Nancy.Owin.Tests/AppBuilderExtensionsFixture.cs index d22a90a5f1..2834727d9f 100644 --- a/test/Nancy.Owin.Tests/AppBuilderExtensionsFixture.cs +++ b/test/Nancy.Owin.Tests/AppBuilderExtensionsFixture.cs @@ -2,18 +2,12 @@ { using System; using System.Collections.Generic; - using System.IO; - using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Text; using global::Owin; - using Microsoft.Owin.Testing; - using Nancy.Testing; - using Xunit; - using HttpStatusCode = Nancy.HttpStatusCode; public class AppBuilderExtensionsFixture @@ -41,7 +35,6 @@ public void When_host_Nancy_via_IAppBuilder_should_read_X509Certificate2() // Given var bootstrapper = new ConfigurableBootstrapper(config => config.Module()); - using (var server = TestServer.Create(app => app.UseNancy(opts => { opts.Bootstrapper = bootstrapper; @@ -65,7 +58,7 @@ public void When_host_Nancy_via_IAppBuilder_should_read_X509Certificate2() -----END CERTIFICATE----- "; - byte[] embeddedCert = Encoding.UTF8.GetBytes(cert); + var embeddedCert = Encoding.UTF8.GetBytes(cert); var env = new Dictionary() { @@ -73,30 +66,25 @@ public void When_host_Nancy_via_IAppBuilder_should_read_X509Certificate2() { "owin.RequestScheme", "http" }, { "owin.RequestHeaders", new Dictionary() { { "Host", new[] { "localhost" } } } }, { "owin.RequestMethod", "GET" }, - {"ssl.ClientCertificate", new X509Certificate(embeddedCert) } + { "owin.ResponseHeaders", new Dictionary() }, + { "ssl.ClientCertificate", new X509Certificate(embeddedCert) } }; - server.Invoke(env); + var result = server.Invoke(env); + result.Wait(); // Then Assert.Equal(env["owin.ResponseStatusCode"], 200); } } #endif - public class TestModule : NancyModule { public TestModule() { - Get["/"] = _ => - { - return HttpStatusCode.OK; - }; + Get("/", args => HttpStatusCode.OK); - Get("/ssl", args => - { - return this.Request.ClientCertificate != null ? 200 : 500; - }); + Get("/ssl", args => this.Request.ClientCertificate != null ? 200 : 500); } } } diff --git a/test/Nancy.Owin.Tests/Nancy.Owin.Tests.xproj b/test/Nancy.Owin.Tests/Nancy.Owin.Tests.xproj index c8385b286a..9414b1968c 100644 --- a/test/Nancy.Owin.Tests/Nancy.Owin.Tests.xproj +++ b/test/Nancy.Owin.Tests/Nancy.Owin.Tests.xproj @@ -1,4 +1,4 @@ - + 14.0 @@ -16,5 +16,8 @@ 2.0 + + + - + \ No newline at end of file diff --git a/test/Nancy.Testing.Tests/Nancy.Testing.Tests.xproj b/test/Nancy.Testing.Tests/Nancy.Testing.Tests.xproj index eeef0a7f39..ffa1197064 100644 --- a/test/Nancy.Testing.Tests/Nancy.Testing.Tests.xproj +++ b/test/Nancy.Testing.Tests/Nancy.Testing.Tests.xproj @@ -1,4 +1,4 @@ - + 14.0 @@ -16,5 +16,8 @@ 2.0 + + + - + \ No newline at end of file diff --git a/test/Nancy.Tests.Functional/Nancy.Tests.Functional.xproj b/test/Nancy.Tests.Functional/Nancy.Tests.Functional.xproj index c25bf47097..35861b15d4 100644 --- a/test/Nancy.Tests.Functional/Nancy.Tests.Functional.xproj +++ b/test/Nancy.Tests.Functional/Nancy.Tests.Functional.xproj @@ -1,4 +1,4 @@ - + 14.0 @@ -16,5 +16,8 @@ 2.0 + + + - + \ No newline at end of file diff --git a/test/Nancy.Tests/Nancy.Tests.xproj b/test/Nancy.Tests/Nancy.Tests.xproj index 221bd9c4d2..609bbe4601 100644 --- a/test/Nancy.Tests/Nancy.Tests.xproj +++ b/test/Nancy.Tests/Nancy.Tests.xproj @@ -1,4 +1,4 @@ - + 14.0 @@ -16,5 +16,8 @@ 2.0 + + + - + \ No newline at end of file diff --git a/test/Nancy.Validation.DataAnnotatioins.Tests/Nancy.Validation.DataAnnotatioins.Tests.xproj b/test/Nancy.Validation.DataAnnotatioins.Tests/Nancy.Validation.DataAnnotatioins.Tests.xproj index e5da6d4f26..806196280d 100644 --- a/test/Nancy.Validation.DataAnnotatioins.Tests/Nancy.Validation.DataAnnotatioins.Tests.xproj +++ b/test/Nancy.Validation.DataAnnotatioins.Tests/Nancy.Validation.DataAnnotatioins.Tests.xproj @@ -1,4 +1,4 @@ - + 14.0 @@ -16,5 +16,8 @@ 2.0 + + + - + \ No newline at end of file diff --git a/test/Nancy.Validation.FluentValidation.Tests/Nancy.Validation.FluentValidation.Tests.xproj b/test/Nancy.Validation.FluentValidation.Tests/Nancy.Validation.FluentValidation.Tests.xproj index 11a215e321..e5671a3185 100644 --- a/test/Nancy.Validation.FluentValidation.Tests/Nancy.Validation.FluentValidation.Tests.xproj +++ b/test/Nancy.Validation.FluentValidation.Tests/Nancy.Validation.FluentValidation.Tests.xproj @@ -1,4 +1,4 @@ - + 14.0 @@ -16,5 +16,8 @@ 2.0 + + + - + \ No newline at end of file diff --git a/test/Nancy.ViewEngines.DotLiquid.Tests/Nancy.ViewEngines.DotLiquid.Tests.xproj b/test/Nancy.ViewEngines.DotLiquid.Tests/Nancy.ViewEngines.DotLiquid.Tests.xproj index 358b864eb7..f76a613c22 100644 --- a/test/Nancy.ViewEngines.DotLiquid.Tests/Nancy.ViewEngines.DotLiquid.Tests.xproj +++ b/test/Nancy.ViewEngines.DotLiquid.Tests/Nancy.ViewEngines.DotLiquid.Tests.xproj @@ -1,4 +1,4 @@ - + 14.0 @@ -16,5 +16,8 @@ 2.0 + + + - + \ No newline at end of file diff --git a/test/Nancy.ViewEngines.Markdown.Tests/Nancy.ViewEngines.Markdown.Tests.xproj b/test/Nancy.ViewEngines.Markdown.Tests/Nancy.ViewEngines.Markdown.Tests.xproj index 1ea867e1d5..f977a09614 100644 --- a/test/Nancy.ViewEngines.Markdown.Tests/Nancy.ViewEngines.Markdown.Tests.xproj +++ b/test/Nancy.ViewEngines.Markdown.Tests/Nancy.ViewEngines.Markdown.Tests.xproj @@ -1,4 +1,4 @@ - + 14.0 @@ -16,5 +16,8 @@ 2.0 + + + - + \ No newline at end of file diff --git a/test/Nancy.ViewEngines.Razor.Tests/Nancy.ViewEngines.Razor.Tests.xproj b/test/Nancy.ViewEngines.Razor.Tests/Nancy.ViewEngines.Razor.Tests.xproj index f1e3035214..0893a7bd41 100644 --- a/test/Nancy.ViewEngines.Razor.Tests/Nancy.ViewEngines.Razor.Tests.xproj +++ b/test/Nancy.ViewEngines.Razor.Tests/Nancy.ViewEngines.Razor.Tests.xproj @@ -1,4 +1,4 @@ - + 14.0 @@ -16,5 +16,8 @@ 2.0 + + + - + \ No newline at end of file