Merge branch 'master' into eisber-master

This commit is contained in:
James Newton-King
2016-09-11 16:19:27 +12:00
65 changed files with 683 additions and 1024 deletions
+25
View File
@@ -18,6 +18,31 @@
<group targetFramework=".NETFramework2.0" />
<group targetFramework=".NETPortable4.5-Profile259" />
<group targetFramework=".NETPortable4.0-Profile328" />
<group targetFramework=".NETStandard1.1">
<dependency id="Microsoft.CSharp" version="4.0.1" />
<dependency id="System.Collections" version="4.0.11" />
<dependency id="System.Diagnostics.Debug" version="4.0.11" />
<dependency id="System.Dynamic.Runtime" version="4.0.11" />
<dependency id="System.Globalization" version="4.0.11" />
<dependency id="System.IO" version="4.1.0" />
<dependency id="System.Linq" version="4.1.0" />
<dependency id="System.Linq.Expressions" version="4.1.0" />
<dependency id="System.ObjectModel" version="4.0.12" />
<dependency id="System.Reflection" version="4.1.0" />
<dependency id="System.Reflection.Extensions" version="4.0.1" />
<dependency id="System.Resources.ResourceManager" version="4.0.1" />
<dependency id="System.Runtime" version="4.1.0" />
<dependency id="System.Runtime.Extensions" version="4.1.0" />
<dependency id="System.Runtime.Numerics" version="4.0.1" />
<dependency id="System.Runtime.Serialization.Primitives" version="4.1.1" />
<dependency id="System.Text.Encoding" version="4.0.11" />
<dependency id="System.Text.Encoding.Extensions" version="4.0.11" />
<dependency id="System.Text.RegularExpressions" version="4.1.0" />
<dependency id="System.Threading" version="4.0.11" />
<dependency id="System.Threading.Tasks" version="4.0.11" />
<dependency id="System.Xml.ReaderWriter" version="4.0.11" />
<dependency id="System.Xml.XDocument" version="4.0.11" />
</group>
<group targetFramework=".NETStandard1.0">
<dependency id="Microsoft.CSharp" version="4.0.1" />
<dependency id="System.Collections" version="4.0.11" />
+5 -3
View File
@@ -22,7 +22,8 @@
$workingDir = "$baseDir\$workingName"
$workingSourceDir = "$workingDir\Src"
$builds = @(
@{Name = "Newtonsoft.Json.Dotnet"; TestsName = "Newtonsoft.Json.Tests.Dotnet"; BuildFunction = "NetCliBuild"; TestsFunction = "NetCliTests"; Constants="dotnet"; FinalDir="netstandard1.0"; NuGetDir = "netstandard1.0"; Framework=$null},
@{Name = "Newtonsoft.Json.Dotnet"; TestsName = "Newtonsoft.Json.Tests.Dotnet"; BuildFunction = "NetCliBuild"; TestsFunction = "NetCliTests"; Constants="NETSTANDARD1_0"; FinalDir="netstandard1.0"; NuGetDir = "netstandard1.0"; Framework=$null},
@{Name = "Newtonsoft.Json.Dotnet"; TestsName = "Newtonsoft.Json.Tests.Dotnet"; BuildFunction = "NetCliBuild"; TestsFunction = "NetCliTests"; Constants="NETSTANDARD1_1"; FinalDir="netstandard1.1"; NuGetDir = "netstandard1.1"; Framework=$null},
@{Name = "Newtonsoft.Json"; TestsName = "Newtonsoft.Json.Tests"; BuildFunction = "MSBuildBuild"; TestsFunction = "NUnitTests"; Constants=""; FinalDir="Net45"; NuGetDir = "net45"; Framework="net-4.0"},
@{Name = "Newtonsoft.Json.Portable"; TestsName = "Newtonsoft.Json.Tests.Portable"; BuildFunction = "MSBuildBuild"; TestsFunction = "NUnitTests"; Constants="PORTABLE"; FinalDir="Portable"; NuGetDir = "portable-net45+wp80+win8+wpa81"; Framework="net-4.0"},
@{Name = "Newtonsoft.Json.Portable40"; TestsName = "Newtonsoft.Json.Tests.Portable40"; BuildFunction = "MSBuildBuild"; TestsFunction = "NUnitTests"; Constants="PORTABLE40"; FinalDir="Portable40"; NuGetDir = "portable-net40+sl5+wp80+win8+wpa81"; Framework="net-4.0"},
@@ -203,6 +204,7 @@ function MSBuildBuild($build)
function NetCliBuild($build)
{
$name = $build.Name
$framework = $build.NuGetDir
$projectPath = "$workingSourceDir\Newtonsoft.Json\project.json"
exec { .\Tools\Dotnet\dotnet-install.ps1 -Version $netCliVersion | Out-Default }
@@ -212,8 +214,8 @@ function NetCliBuild($build)
Write-Host
exec { dotnet restore $projectPath | Out-Default }
Write-Host -ForegroundColor Green "Building $projectPath"
exec { dotnet build $projectPath -f netstandard1.0 -c Release -o bin\Release\netstandard1.0 | Out-Default }
Write-Host -ForegroundColor Green "Building $projectPath $framework"
exec { dotnet build $projectPath -f $framework -c Release -o bin\Release\$framework | Out-Default }
}
function NetCliTests($build)
+4
View File
@@ -124,6 +124,10 @@
<para>The <codeEntityReference>T:Newtonsoft.Json.JsonExtensionDataAttribute</codeEntityReference> instructs the
<codeEntityReference>T:Newtonsoft.Json.JsonSerializer</codeEntityReference> to deserialize properties with no matching field or property
on the type into the specified collection. During serialization the values in this collection are written back to the instance's JSON object.</para>
<alert class="note">
<para>All extension data values will be written during serialization, even if a property the same name has already been written.</para>
</alert>
<para>This example shows the JsonExtensionDataAttribute being applied to a field, unmatched JSON properties being added to the field's collection during deserialization.</para>
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\Samples\Serializer\DeserializeExtensionData.cs" region="Types" title="Types" />
<code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\Samples\Serializer\DeserializeExtensionData.cs" region="Usage" title="Usage" />
@@ -30,7 +30,7 @@ using System.Reflection;
using System.Runtime.Serialization;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
#if !(NET20 || NET35 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
using System.Numerics;
#endif
using System.Text;
@@ -1508,7 +1508,7 @@ namespace Newtonsoft.Json.Tests.Bson
}
#endif
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
public class BigIntegerTestClass
{
public BigInteger Blah { get; set; }
@@ -25,7 +25,7 @@
using System;
using System.Collections.Generic;
#if !(NET20 || NET35 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
using System.Numerics;
#endif
using System.Text;
@@ -800,7 +800,7 @@ namespace Newtonsoft.Json.Tests.Bson
Assert.AreEqual(c.AGuid, c2.AGuid.ToString());
}
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
[Test]
public void WriteBigInteger()
{
@@ -23,13 +23,14 @@
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System.Globalization;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
using System.Text;
#if !(NETFX_CORE || PORTABLE || DNXCORE50 || PORTABLE40)
#if !(NETFX_CORE || DNXCORE50 || PORTABLE40)
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Tests.Serialization;
@@ -61,6 +62,7 @@ namespace Newtonsoft.Json.Tests.Converters
[TestFixture]
public class XmlNodeConverterTest : TestFixtureBase
{
#if !PORTABLE
private string SerializeXmlNode(XmlNode node)
{
string json = JsonConvert.SerializeXmlNode(node, Formatting.Indented);
@@ -128,6 +130,24 @@ namespace Newtonsoft.Json.Tests.Converters
return node;
}
#endif
private string IndentXml(string xml)
{
XmlReader reader = XmlReader.Create(new StringReader(xml));
StringWriter sw = new StringWriter();
XmlWriter writer = XmlWriter.Create(sw, new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true });
while (reader.Read())
{
writer.WriteNode(reader, false);
}
writer.Flush();
return sw.ToString();
}
#if !NET20
[Test]
@@ -228,6 +248,7 @@ namespace Newtonsoft.Json.Tests.Converters
}
#endif
#if !PORTABLE
[Test]
public void MultipleNamespacesXmlDocument()
{
@@ -293,6 +314,7 @@ namespace Newtonsoft.Json.Tests.Converters
}
]", json);
}
#endif
#if !NET20
[Test]
@@ -405,6 +427,7 @@ namespace Newtonsoft.Json.Tests.Converters
</root>", doc.ToString());
}
#if !PORTABLE
[Test]
public void SerializeEmptyDocument()
{
@@ -430,6 +453,7 @@ namespace Newtonsoft.Json.Tests.Converters
json = JsonConvert.SerializeXNode(doc1, Formatting.Indented, true);
Assert.AreEqual(@"""""", json);
}
#endif
[Test]
public void SerializeAndDeserializeXmlWithNamespaceInChildrenAndNoValueInChildren()
@@ -449,6 +473,7 @@ namespace Newtonsoft.Json.Tests.Converters
Assert.IsTrue(equals);
}
#if !PORTABLE
[Test]
public void DeserializeUndeclaredNamespacePrefix()
{
@@ -461,7 +486,9 @@ namespace Newtonsoft.Json.Tests.Converters
Assert.AreEqual(doc.OuterXml, xdoc.ToString());
}
#endif
#endif
#if !PORTABLE
[Test]
public void DeserializeMultipleRootElements()
{
@@ -1150,6 +1177,7 @@ namespace Newtonsoft.Json.Tests.Converters
() => { JsonConvert.DeserializeXmlNode(json); },
"JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName. Path 'photos', line 1, position 26.");
}
#endif
#if !NET20
[Test]
@@ -1168,9 +1196,11 @@ namespace Newtonsoft.Json.Tests.Converters
{
string json = @"{""count"": 773840,""photos"": 773840}";
#if !PORTABLE
XmlDocument newDoc = JsonConvert.DeserializeXmlNode(json, "myRoot");
Assert.AreEqual(@"<myRoot><count>773840</count><photos>773840</photos></myRoot>", newDoc.InnerXml);
#endif
#if !NET20
XDocument newXDoc = JsonConvert.DeserializeXNode(json, "myRoot");
@@ -1198,7 +1228,8 @@ namespace Newtonsoft.Json.Tests.Converters
]
}";
XmlDocument newDoc = JsonConvert.DeserializeXmlNode(json, "myRoot");
#if !PORTABLE
XmlDocument newDoc = JsonConvert.DeserializeXmlNode(json, "myRoot");
string xml = IndentXml(newDoc.InnerXml);
@@ -1215,6 +1246,7 @@ namespace Newtonsoft.Json.Tests.Converters
<available_sizes>assets/images/resized/0001/1070/11070v1-max-250x250.jpg</available_sizes>
</available_sizes>
</myRoot>", IndentXml(newDoc.InnerXml));
#endif
#if !NET20
XDocument newXDoc = JsonConvert.DeserializeXNode(json, "myRoot");
@@ -1234,8 +1266,10 @@ namespace Newtonsoft.Json.Tests.Converters
</myRoot>", IndentXml(newXDoc.ToString(SaveOptions.DisableFormatting)));
#endif
#if !PORTABLE
string newJson = JsonConvert.SerializeXmlNode(newDoc, Formatting.Indented);
Console.WriteLine(newJson);
#endif
}
[Test]
@@ -1257,6 +1291,7 @@ namespace Newtonsoft.Json.Tests.Converters
]
}";
#if !PORTABLE
XmlDocument newDoc = JsonConvert.DeserializeXmlNode(json, "myRoot", true);
StringAssert.AreEqual(@"<myRoot>
@@ -1272,6 +1307,7 @@ namespace Newtonsoft.Json.Tests.Converters
<available_sizes json:Array=""true"">assets/images/resized/0001/1070/11070v1-max-250x250.jpg</available_sizes>
</available_sizes>
</myRoot>", IndentXml(newDoc.InnerXml));
#endif
#if !NET20
XDocument newXDoc = JsonConvert.DeserializeXNode(json, "myRoot", true);
@@ -1291,8 +1327,10 @@ namespace Newtonsoft.Json.Tests.Converters
</myRoot>", IndentXml(newXDoc.ToString(SaveOptions.DisableFormatting)));
#endif
#if !PORTABLE
string newJson = JsonConvert.SerializeXmlNode(newDoc, Formatting.Indented, true);
StringAssert.AreEqual(json, newJson);
#endif
}
[Test]
@@ -1315,9 +1353,11 @@ namespace Newtonsoft.Json.Tests.Converters
]
}";
#if !PORTABLE
XmlDocument newDoc = JsonConvert.DeserializeXmlNode(json, "myRoot");
Assert.AreEqual(@"<myRoot><available_sizes><available_sizes><available_sizes>113</available_sizes><available_sizes>150</available_sizes></available_sizes><available_sizes>assets/images/resized/0001/1070/11070v1-max-150x150.jpg</available_sizes></available_sizes><available_sizes><available_sizes><available_sizes>189</available_sizes><available_sizes>250</available_sizes></available_sizes><available_sizes>assets/images/resized/0001/1070/11070v1-max-250x250.jpg</available_sizes></available_sizes><available_sizes><available_sizes><available_sizes>341</available_sizes><available_sizes>450</available_sizes></available_sizes><available_sizes>assets/images/resized/0001/1070/11070v1-max-450x450.jpg</available_sizes></available_sizes></myRoot>", newDoc.InnerXml);
#endif
#if !NET20
XDocument newXDoc = JsonConvert.DeserializeXNode(json, "myRoot");
@@ -1326,6 +1366,7 @@ namespace Newtonsoft.Json.Tests.Converters
#endif
}
#if !PORTABLE
[Test]
public void Encoding()
{
@@ -1338,7 +1379,9 @@ namespace Newtonsoft.Json.Tests.Converters
""name"": ""O\""Connor""
}", json);
}
#endif
#if !PORTABLE
[Test]
public void SerializeComment()
{
@@ -1895,23 +1938,6 @@ namespace Newtonsoft.Json.Tests.Converters
}", output2);
}
private string IndentXml(string xml)
{
XmlReader reader = XmlReader.Create(new StringReader(xml));
StringWriter sw = new StringWriter();
XmlWriter writer = XmlWriter.Create(sw, new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true });
while (reader.Read())
{
writer.WriteNode(reader, false);
}
writer.Flush();
return sw.ToString();
}
[Test]
public void OmitRootObject()
{
@@ -2062,6 +2088,7 @@ namespace Newtonsoft.Json.Tests.Converters
}
}
}
#endif
#if !NET20
[Test]
@@ -2302,6 +2329,7 @@ namespace Newtonsoft.Json.Tests.Converters
}
#endif
#if !PORTABLE
[Test]
public void DeserializeXmlNodeDefaultNamespace()
{
@@ -2560,6 +2588,7 @@ namespace Newtonsoft.Json.Tests.Converters
Assert.AreEqual(@"<item action=""update"" itemid=""1"" description=""temp""><elements action=""none"" id=""2"" /><elements action=""none"" id=""3"" /></item>", xmldoc.InnerXml);
}
#endif
[Test]
public void SerializingXmlNamespaceScope()
@@ -2577,7 +2606,7 @@ namespace Newtonsoft.Json.Tests.Converters
Assert.AreEqual(@"{""root"":{""@xmlns"":""http://www.example.com/ns"",""a"":null,""bns:b"":{""@xmlns:bns"":""http://www.example.com/ns""},""c"":null}}", json1);
#endif
#if !(NETFX_CORE)
#if !(PORTABLE)
var xml1 = new XmlDocument();
xml1.LoadXml(xmlString);
@@ -2628,6 +2657,7 @@ namespace Newtonsoft.Json.Tests.Converters
}
#endif
#if !PORTABLE
[Test]
public void SerializeAndDeserializeXmlElementWithNamespaceInChildrenRootDontHaveNameSpace()
{
@@ -2646,7 +2676,7 @@ namespace Newtonsoft.Json.Tests.Converters
Assert.AreEqual(@"<root><b xmlns=""http://www.example.com/ns"">Asd</b><c>AAA</c><test>adad</test></root>", xmlBack.OuterXml);
}
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
[Test]
public void DeserializeBigInteger()
{
@@ -2687,8 +2717,41 @@ namespace Newtonsoft.Json.Tests.Converters
Assert.AreEqual("null", json);
}
#endif
#if !NET20
[Test]
public void DateTimeToXml_Unspecified()
{
string json = @"{""CreatedDate"": ""2014-01-23T00:00:00""}";
var dxml = JsonConvert.DeserializeXNode(json, "root");
Assert.AreEqual("2014-01-23T00:00:00", dxml.Root.Element("CreatedDate").Value);
Console.WriteLine("DateTimeToXml_Unspecified: " + dxml.Root.Element("CreatedDate").Value);
}
[Test]
public void DateTimeToXml_Utc()
{
string json = @"{""CreatedDate"": ""2014-01-23T00:00:00Z""}";
var dxml = JsonConvert.DeserializeXNode(json, "root");
Assert.AreEqual("2014-01-23T00:00:00Z", dxml.Root.Element("CreatedDate").Value);
Console.WriteLine("DateTimeToXml_Utc: " + dxml.Root.Element("CreatedDate").Value);
}
[Test]
public void DateTimeToXml_Local()
{
DateTime dt = DateTime.Parse("2014-01-23T00:00:00+01:00");
string json = @"{""CreatedDate"": ""2014-01-23T00:00:00+01:00""}";
var dxml = JsonConvert.DeserializeXNode(json, "root");
Assert.AreEqual(dt.ToString("yyyy-MM-ddTHH:mm:sszzzzzzz", CultureInfo.InvariantCulture), dxml.Root.Element("CreatedDate").Value);
Console.WriteLine("DateTimeToXml_Local: " + dxml.Root.Element("CreatedDate").Value);
}
[Test]
public void SerializeEmptyNodeAndOmitRoot_XElement()
{
@@ -39,6 +39,8 @@ using System.Runtime.Serialization;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using Autofac;
using Autofac.Core;
using Autofac.Core.Activators.Reflection;
using Newtonsoft.Json.Tests.Serialization;
using LogService = Newtonsoft.Json.Tests.Serialization.LogManager;
@@ -59,15 +61,33 @@ namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer
protected override JsonObjectContract CreateObjectContract(Type objectType)
{
JsonObjectContract contract = base.CreateObjectContract(objectType);
// use Autofac to create types that have been registered with it
if (_container.IsRegistered(objectType))
{
JsonObjectContract contract = ResolveContact(objectType);
contract.DefaultCreator = () => _container.Resolve(objectType);
return contract;
}
return contract;
return base.CreateObjectContract(objectType);
}
private JsonObjectContract ResolveContact(Type objectType)
{
// attempt to create the contact from the resolved type
IComponentRegistration registration;
if (_container.ComponentRegistry.TryGetRegistration(new TypedService(objectType), out registration))
{
Type viewType = (registration.Activator as ReflectionActivator)?.LimitType;
if (viewType != null)
{
return base.CreateObjectContract(viewType);
}
}
// fall back to using the registered type
return base.CreateObjectContract(objectType);
}
}
+2 -2
View File
@@ -28,7 +28,7 @@ using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Newtonsoft.Json.Schema;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
using System.Numerics;
#endif
using System.Runtime.Serialization;
@@ -1202,7 +1202,7 @@ namespace Newtonsoft.Json.Tests
writer.Flush();
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
[Test]
public void IntegerLengthOverflows()
{
@@ -28,7 +28,7 @@ using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json.Linq;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
using System.Numerics;
#endif
using System.Text;
@@ -344,7 +344,7 @@ second line
third line", jsonTextReader.Value);
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
[Test]
public void ReadBigInteger()
{
@@ -1245,7 +1245,7 @@ third line", jsonTextReader.Value);
}
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
[Test]
public void ReadInt64Overflow()
{
@@ -30,7 +30,7 @@ using System.IO;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#endif
#if !(NET20 || NET35 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
using System.Numerics;
#endif
using System.Text;
@@ -357,7 +357,7 @@ namespace Newtonsoft.Json.Tests
Assert.IsNotNull(validationEventArgs);
}
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
[Test]
public void IntegerGreaterThanMaximumValue_BigInteger()
{
@@ -610,7 +610,7 @@ namespace Newtonsoft.Json.Tests
Assert.IsNotNull(validationEventArgs);
}
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
[Test]
public void BigIntegerDivisibleBy_Success()
{
+13 -13
View File
@@ -29,7 +29,7 @@ using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
#if !(NET20 || NET35 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
using System.Numerics;
#endif
using System.Text;
@@ -263,7 +263,7 @@ namespace Newtonsoft.Json.Tests.Linq
new JProperty("Uri", new Uri("http://json.codeplex.com/")),
new JProperty("Guid", new Guid("EA27FE1D-0D80-44F2-BF34-4654156FA7AF")),
new JProperty("TimeSpan", TimeSpan.FromDays(1))
#if !(NET20 || NET35 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
, new JProperty("BigInteger", BigInteger.Parse("1"))
#endif
);
@@ -296,7 +296,7 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.IsTrue(d.Decimal == 1.1m);
Assert.IsTrue(d.Decimal != 1.0f);
Assert.IsTrue(d.Decimal != 1.0d);
#if !(NET20 || NET35 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
Assert.IsTrue(d.Decimal > new BigInteger(0));
#endif
@@ -312,11 +312,11 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.IsTrue(d.Float == 1.1m);
Assert.IsTrue(d.Float != 1.0f);
Assert.IsTrue(d.Float != 1.0d);
#if !(NET20 || NET35 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
Assert.IsTrue(d.Float > new BigInteger(0));
#endif
#if !(NET20 || NET35 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
Assert.IsTrue(d.BigInteger == d.BigInteger);
Assert.IsTrue(d.BigInteger > 0);
Assert.IsTrue(d.BigInteger > 0.0m);
@@ -372,7 +372,7 @@ namespace Newtonsoft.Json.Tests.Linq
new JProperty("Uri", new Uri("http://json.codeplex.com/")),
new JProperty("Guid", new Guid("EA27FE1D-0D80-44F2-BF34-4654156FA7AF")),
new JProperty("TimeSpan", TimeSpan.FromDays(1))
#if !(NET20 || NET35 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
, new JProperty("BigInteger", new BigInteger(100))
#endif
);
@@ -451,7 +451,7 @@ namespace Newtonsoft.Json.Tests.Linq
r += 2;
Assert.AreEqual(null, r.Value);
#if !(NET20 || NET35 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
r = d.BigInteger + null;
Assert.AreEqual(null, r.Value);
r += 2;
@@ -530,7 +530,7 @@ namespace Newtonsoft.Json.Tests.Linq
r -= 2;
Assert.AreEqual(null, r.Value);
#if !(NET20 || NET35 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
r = d.BigInteger - null;
Assert.AreEqual(null, r.Value);
r -= 2;
@@ -604,7 +604,7 @@ namespace Newtonsoft.Json.Tests.Linq
r *= 2;
Assert.AreEqual(null, r.Value);
#if !(NET20 || NET35 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
r = d.BigInteger * 1.1d;
Assert.AreEqual(100m, (decimal)r);
r *= 2;
@@ -678,7 +678,7 @@ namespace Newtonsoft.Json.Tests.Linq
r /= 2;
Assert.AreEqual(null, r.Value);
#if !(NET20 || NET35 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
r = d.BigInteger / 1.1d;
Assert.AreEqual(100m, (decimal)r);
r /= 2;
@@ -706,7 +706,7 @@ namespace Newtonsoft.Json.Tests.Linq
new JProperty("Uri", new Uri("http://json.codeplex.com/")),
new JProperty("Guid", new Guid("EA27FE1D-0D80-44F2-BF34-4654156FA7AF")),
new JProperty("TimeSpan", TimeSpan.FromDays(1))
#if !(NET20 || NET35 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
, new JProperty("BigInteger", new BigInteger(100))
#endif
);
@@ -723,7 +723,7 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual("http://json.codeplex.com/", d.Uri.ToString());
Assert.AreEqual("ea27fe1d-0d80-44f2-bf34-4654156fa7af", d.Guid.ToString());
Assert.AreEqual("1.00:00:00", d.TimeSpan.ToString());
#if !(NET20 || NET35 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
Assert.AreEqual("100", d.BigInteger.ToString());
#endif
}
@@ -807,7 +807,7 @@ namespace Newtonsoft.Json.Tests.Linq
AssertValueConverted<Guid?>(null);
AssertValueConverted<Uri>(new Uri("http://json.codeplex.com/"));
AssertValueConverted<Uri>(null);
#if !(NET20 || NET35 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
AssertValueConverted<BigInteger>(new BigInteger(100));
AssertValueConverted<BigInteger?>(null);
#endif
@@ -39,7 +39,7 @@ using NUnit.Framework;
#endif
using Newtonsoft.Json;
using System.IO;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
using System.Numerics;
#endif
using Newtonsoft.Json.Linq;
@@ -51,7 +51,7 @@ namespace Newtonsoft.Json.Tests.Linq
[TestFixture]
public class JTokenReaderTest : TestFixtureBase
{
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
[Test]
public void ConvertBigIntegerToDouble()
{
@@ -876,7 +876,7 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual(1d, reader.ReadAsDouble());
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
[Test]
public void ReadAsBoolean_BigInteger_Success()
{
@@ -25,7 +25,7 @@
using System;
using System.Collections.Generic;
#if !(NET20 || NET35 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
using System.Numerics;
#endif
using System.Text;
@@ -372,7 +372,7 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual(5, (int)(new JValue(StringComparison.OrdinalIgnoreCase)));
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
string bigIntegerText = "1234567899999999999999999999999999999999999999999999999999999999999990";
Assert.AreEqual(BigInteger.Parse(bigIntegerText), (new JValue(BigInteger.Parse(bigIntegerText))).Value);
@@ -452,7 +452,7 @@ namespace Newtonsoft.Json.Tests.Linq
#endif
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(true); }, "Can not convert Boolean to Uri.");
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
ExceptionAssert.Throws<ArgumentException>(() => { var i = (new JValue(new Uri("http://www.google.com"))).ToObject<BigInteger>(); }, "Can not convert Uri to BigInteger.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (JValue.CreateNull()).ToObject<BigInteger>(); }, "Can not convert Null to BigInteger.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (new JValue(Guid.NewGuid())).ToObject<BigInteger>(); }, "Can not convert Guid to BigInteger.");
@@ -469,7 +469,7 @@ namespace Newtonsoft.Json.Tests.Linq
[Test]
public void ToObject()
{
#if !(NET20 || NET35 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
Assert.AreEqual((BigInteger)1, (new JValue(1).ToObject(typeof(BigInteger))));
Assert.AreEqual((BigInteger)1, (new JValue(1).ToObject(typeof(BigInteger?))));
Assert.AreEqual((BigInteger?)null, (JValue.CreateNull().ToObject(typeof(BigInteger?))));
@@ -526,7 +526,7 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.IsTrue(JToken.DeepEquals(new JValue((DateTimeOffset?)null), (JValue)(DateTimeOffset?)null));
#endif
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
// had to remove implicit casting to avoid user reference to System.Numerics.dll
Assert.IsTrue(JToken.DeepEquals(new JValue(new BigInteger(1)), new JValue(new BigInteger(1))));
Assert.IsTrue(JToken.DeepEquals(new JValue((BigInteger?)null), new JValue((BigInteger?)null)));
@@ -25,7 +25,7 @@
using System;
using System.Collections.Generic;
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
using System.Numerics;
#endif
using System.Text;
@@ -124,7 +124,7 @@ namespace Newtonsoft.Json.Tests.Linq
jsonWriter.WriteValue("DVD read/writer");
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
jsonWriter.WriteValue(new BigInteger(123));
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
#endif
@@ -176,7 +176,7 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
Assert.AreEqual(a[a.Count - 1], jsonWriter.CurrentToken);
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
jsonWriter.WriteValue(new BigInteger(123));
Assert.AreEqual(WriteState.Array, jsonWriter.WriteState);
Assert.AreEqual(a[a.Count - 1], jsonWriter.CurrentToken);
@@ -209,7 +209,7 @@ namespace Newtonsoft.Json.Tests.Linq
/*fail*/]", writer.Token.ToString());
}
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
[Test]
public void WriteBigInteger()
{
@@ -28,7 +28,7 @@ using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
#if !(NET20 || NET35 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
using System.Numerics;
#endif
using System.Text;
@@ -183,7 +183,7 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual(g, v.Value);
Assert.AreEqual(JTokenType.Guid, v.Type);
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
BigInteger i = BigInteger.Parse("123456789999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999990");
v.Value = i;
Assert.AreEqual(i, v.Value);
@@ -243,13 +243,13 @@ namespace Newtonsoft.Json.Tests.Linq
v = new JValue(new Guid("B282ADE7-C520-496C-A448-4084F6803DE5"));
Assert.AreEqual("b282ade7-c520-496c-a448-4084f6803de5", v.ToString(null, CultureInfo.InvariantCulture));
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
v = new JValue(BigInteger.Parse("123456789999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999990"));
Assert.AreEqual("123456789999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999990", v.ToString(null, CultureInfo.InvariantCulture));
#endif
}
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
[Test]
public void JValueParse()
{
@@ -517,7 +517,7 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual(Int32.MaxValue, Convert.ToInt32(new JValue(Int32.MaxValue)));
}
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
[Test]
public void ConvertsToInt32_BigInteger()
{
@@ -679,7 +679,7 @@ namespace Newtonsoft.Json.Tests.Linq
v = new JValue(new Uri("http://www.google.com"));
Assert.AreEqual(TypeCode.Object, v.GetTypeCode());
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
v = new JValue(new BigInteger(3));
Assert.AreEqual(TypeCode.Object, v.GetTypeCode());
#endif
@@ -698,7 +698,7 @@ namespace Newtonsoft.Json.Tests.Linq
int i = (int)v.ToType(typeof(int), CultureInfo.InvariantCulture);
Assert.AreEqual(9, i);
#if !(NET20 || NET35 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
BigInteger bi = (BigInteger)v.ToType(typeof(BigInteger), CultureInfo.InvariantCulture);
Assert.AreEqual(new BigInteger(9), bi);
#endif
@@ -713,7 +713,7 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual("2013", v.ToString("yyyy"));
}
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
[Test]
public void ToStringNewTypes()
{
@@ -26,7 +26,7 @@
using System;
using System.Collections.Generic;
using System.Text;
#if !(PORTABLE || PORTABLE40 || NET35 || NET20)
#if !(PORTABLE || PORTABLE40 || NET35 || NET20) || NETSTANDARD1_1
using System.Numerics;
#endif
using Newtonsoft.Json.Linq.JsonPath;
@@ -652,7 +652,7 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 3)), t[1]));
}
#if !(PORTABLE || DNXCORE50 || PORTABLE40 || NET35 || NET20)
#if !(PORTABLE || DNXCORE50 || PORTABLE40 || NET35 || NET20) || NETSTANDARD1_1
[Test]
public void GreaterQueryBigInteger()
{
@@ -949,5 +949,57 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
result = a.SelectTokens("$.[?(@.value)]").ToList();
Assert.AreEqual(4, result.Count);
}
[Test]
public void RootInFilter()
{
string json = @"[
{
""store"" : {
""book"" : [
{
""category"" : ""reference"",
""author"" : ""Nigel Rees"",
""title"" : ""Sayings of the Century"",
""price"" : 8.95
},
{
""category"" : ""fiction"",
""author"" : ""Evelyn Waugh"",
""title"" : ""Sword of Honour"",
""price"" : 12.99
},
{
""category"" : ""fiction"",
""author"" : ""Herman Melville"",
""title"" : ""Moby Dick"",
""isbn"" : ""0-553-21311-3"",
""price"" : 8.99
},
{
""category"" : ""fiction"",
""author"" : ""J. R. R. Tolkien"",
""title"" : ""The Lord of the Rings"",
""isbn"" : ""0-395-19395-8"",
""price"" : 22.99
}
],
""bicycle"" : {
""color"" : ""red"",
""price"" : 19.95
}
},
""expensive"" : 10
}
]";
JArray a = JArray.Parse(json);
List<JToken> result = a.SelectTokens("$.[?($.store.bicycle.price < 20)]").ToList();
Assert.AreEqual(1, result.Count);
result = a.SelectTokens("$.[?($.store.bicycle.price < 10)]").ToList();
Assert.AreEqual(0, result.Count);
}
}
}
@@ -419,6 +419,16 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
Assert.AreEqual(QueryOperator.Exists, orExpression.Expressions[1].Operator);
}
[Test]
public void FilterWithRoot()
{
JPath path = new JPath("[?($.name>=12.1)]");
BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression;
Assert.AreEqual(2, expressions.Path.Count);
Assert.IsInstanceOf(typeof(RootFilter), expressions.Path[0]);
Assert.IsInstanceOf(typeof(FieldFilter), expressions.Path[1]);
}
[Test]
public void BadOr1()
{
@@ -86,7 +86,7 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
{ "LastName", "LastName!" }
};
Assert.IsTrue(compositeExpression.IsMatch(o1));
Assert.IsTrue(compositeExpression.IsMatch(o1, o1));
JObject o2 = new JObject
{
@@ -94,14 +94,14 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
{ "FirstName", "FirstName!" }
};
Assert.IsFalse(compositeExpression.IsMatch(o2));
Assert.IsFalse(compositeExpression.IsMatch(o2, o2));
JObject o3 = new JObject
{
{ "Title", "Title!" }
};
Assert.IsFalse(compositeExpression.IsMatch(o3));
Assert.IsFalse(compositeExpression.IsMatch(o3, o3));
}
[Test]
@@ -144,7 +144,7 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
{ "LastName", "LastName!" }
};
Assert.IsTrue(compositeExpression.IsMatch(o1));
Assert.IsTrue(compositeExpression.IsMatch(o1, o1));
JObject o2 = new JObject
{
@@ -152,14 +152,14 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
{ "FirstName", "FirstName!" }
};
Assert.IsTrue(compositeExpression.IsMatch(o2));
Assert.IsTrue(compositeExpression.IsMatch(o2, o2));
JObject o3 = new JObject
{
{ "Title", "Title!" }
};
Assert.IsFalse(compositeExpression.IsMatch(o3));
Assert.IsFalse(compositeExpression.IsMatch(o3, o3));
}
[Test]
@@ -175,10 +175,10 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
}
};
Assert.IsTrue(e1.IsMatch(new JArray(1, 2, 3, 4, 5)));
Assert.IsTrue(e1.IsMatch(new JArray(2, 3, 4, 5)));
Assert.IsFalse(e1.IsMatch(new JArray(3, 4, 5)));
Assert.IsFalse(e1.IsMatch(new JArray(4, 5)));
Assert.IsTrue(e1.IsMatch(null, new JArray(1, 2, 3, 4, 5)));
Assert.IsTrue(e1.IsMatch(null, new JArray(2, 3, 4, 5)));
Assert.IsFalse(e1.IsMatch(null, new JArray(3, 4, 5)));
Assert.IsFalse(e1.IsMatch(null, new JArray(4, 5)));
BooleanQueryExpression e2 = new BooleanQueryExpression
{
@@ -190,10 +190,10 @@ namespace Newtonsoft.Json.Tests.Linq.JsonPath
}
};
Assert.IsTrue(e2.IsMatch(new JArray(1, 2, 3, 4, 5)));
Assert.IsTrue(e2.IsMatch(new JArray(2, 3, 4, 5)));
Assert.IsTrue(e2.IsMatch(new JArray(3, 4, 5)));
Assert.IsFalse(e2.IsMatch(new JArray(4, 5)));
Assert.IsTrue(e2.IsMatch(null, new JArray(1, 2, 3, 4, 5)));
Assert.IsTrue(e2.IsMatch(null, new JArray(2, 3, 4, 5)));
Assert.IsTrue(e2.IsMatch(null, new JArray(3, 4, 5)));
Assert.IsFalse(e2.IsMatch(null, new JArray(4, 5)));
}
}
}
@@ -31,8 +31,10 @@ using System.Security;
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
#if NETSTANDARD10
#if NETSTANDARD1_0
[assembly: AssemblyTitle("Json.NET Tests .NET Standard 1.0")]
#elif NETSTANDARD1_1
[assembly: AssemblyTitle("Json.NET Tests .NET Standard 1.1")]
#elif PORTABLE40
[assembly: AssemblyTitle("Json.NET Tests Portable .NET 4.0")]
#elif PORTABLE
@@ -30,8 +30,11 @@ using Newtonsoft.Json.Tests.TestObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using Autofac.Core;
using Autofac.Core.Activators.Reflection;
using Microsoft.FSharp.Collections;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
@@ -126,6 +129,30 @@ namespace Newtonsoft.Json.Tests.Serialization
}
}
#if !NET20
[DataContract]
public class User
{
[DataMember(Name = "first_name")]
public string FirstName { get; set; }
[DataMember(Name = "company")]
public ICompany Company { get; set; }
}
public interface ICompany
{
string CompanyName { get; set; }
}
[DataContract]
public class Company : ICompany
{
[DataMember(Name = "company_name")]
public string CompanyName { get; set; }
}
#endif
public class AutofacContractResolver : DefaultContractResolver
{
private readonly IContainer _container;
@@ -137,21 +164,57 @@ namespace Newtonsoft.Json.Tests.Serialization
protected override JsonObjectContract CreateObjectContract(Type objectType)
{
JsonObjectContract contract = base.CreateObjectContract(objectType);
// use Autofac to create types that have been registered with it
if (_container.IsRegistered(objectType))
{
JsonObjectContract contract = ResolveContact(objectType);
contract.DefaultCreator = () => _container.Resolve(objectType);
return contract;
}
return contract;
return base.CreateObjectContract(objectType);
}
private JsonObjectContract ResolveContact(Type objectType)
{
// attempt to create the contact from the resolved type
IComponentRegistration registration;
if (_container.ComponentRegistry.TryGetRegistration(new TypedService(objectType), out registration))
{
Type viewType = (registration.Activator as ReflectionActivator)?.LimitType;
if (viewType != null)
{
return base.CreateObjectContract(viewType);
}
}
// fall back to using the registered type
return base.CreateObjectContract(objectType);
}
}
[TestFixture]
public class DependencyInjectionTests : TestFixtureBase
{
[Test]
public void ResolveContractFromAutofac()
{
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<Company>().As<ICompany>();
IContainer container = builder.Build();
AutofacContractResolver resolver = new AutofacContractResolver(container);
User user = JsonConvert.DeserializeObject<User>("{'company':{'company_name':'Company name!'}}", new JsonSerializerSettings
{
ContractResolver = resolver
});
Assert.AreEqual("Company name!", user.Company.CompanyName);
}
[Test]
public void CreateObjectWithParameters()
{
@@ -29,7 +29,7 @@ using System.ComponentModel;
using System.Collections.Concurrent;
#endif
using System.Collections.Generic;
#if !(NET20 || NET35 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE) || NETSTANDARD1_1
using System.Numerics;
#endif
#if !(NET20 || NETFX_CORE || DNXCORE50)
@@ -8208,7 +8208,7 @@ Path '', line 1, position 1.");
}
#if !(NET20 || NET35 || NET40 || PORTABLE40)
#if !PORTABLE
#if !PORTABLE || NETSTANDARD1_1
[Test]
public void DeserializeReadOnlyListWithBigInteger()
{
@@ -8551,7 +8551,7 @@ Path '', line 1, position 1.");
}
#endif
#if !(PORTABLE || NET35 || NET20 || PORTABLE40)
#if !(PORTABLE || NET35 || NET20 || PORTABLE40) || NETSTANDARD1_1
[Test]
public void ReadTooLargeInteger()
{
@@ -8734,7 +8734,7 @@ Path '', line 1, position 1.");
}
#endif
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
[Test]
public void SerializeBigInteger()
{
@@ -4,7 +4,7 @@ using System.Diagnostics;
using System.Globalization;
using System.IO;
using Newtonsoft.Json.Linq;
#if !(NET20 || NET35 || PORTABLE ||PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
using System.Numerics;
#endif
using System.Runtime.Serialization;
@@ -879,7 +879,7 @@ Newtonsoft.Json Error: 0 : Error!
Assert.AreEqual(23, deserialized.FavoriteNumber);
}
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
[Test]
public void TraceJsonWriterTest()
{
@@ -1891,6 +1891,50 @@ namespace Newtonsoft.Json.Tests.Serialization
Assert.AreEqual("property", deserialized.Rows["key"].First().SomeProperty);
}
#endif
#if !(NET20 || PORTABLE || PORTABLE40)
[Test]
public void DeserializeComplexGenericDictionary_Simple()
{
JsonSerializerSettings serializerSettings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple
};
Dictionary<int, HashSet<string>> dictionary = new Dictionary<int, HashSet<string>>
{
{ 1, new HashSet<string>(new[] { "test" }) },
};
string obtainedJson = JsonConvert.SerializeObject(dictionary, serializerSettings);
Dictionary<int, HashSet<string>> obtainedDictionary = (Dictionary<int, HashSet<string>>)JsonConvert.DeserializeObject(obtainedJson, serializerSettings);
Assert.IsNotNull(obtainedDictionary);
}
[Test]
public void DeserializeComplexGenericDictionary_Full()
{
JsonSerializerSettings serializerSettings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
};
Dictionary<int, HashSet<string>> dictionary = new Dictionary<int, HashSet<string>>
{
{ 1, new HashSet<string>(new[] { "test" }) },
};
string obtainedJson = JsonConvert.SerializeObject(dictionary, serializerSettings);
Dictionary<int, HashSet<string>> obtainedDictionary = (Dictionary<int, HashSet<string>>)JsonConvert.DeserializeObject(obtainedJson, serializerSettings);
Assert.IsNotNull(obtainedDictionary);
}
#endif
}
public class DataType
@@ -2163,5 +2207,4 @@ namespace Newtonsoft.Json.Tests.Serialization
}
#endif
}
#endif
+1 -1
View File
@@ -84,7 +84,7 @@
},*/
"netcoreapp1.0": {
"buildOptions": {
"define": [ "NETSTANDARD10", "DNXCORE50", "PORTABLE" ]
"define": [ "NETSTANDARD1_1", "DNXCORE50", "PORTABLE" ]
},
"dependencies": {
"Microsoft.NETCore.App": {
+2 -2
View File
@@ -27,7 +27,7 @@ using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
using System.Numerics;
#endif
using System.Text;
@@ -232,7 +232,7 @@ namespace Newtonsoft.Json.Bson
/// <param name="value">The <see cref="Object"/> value to write.</param>
public override void WriteValue(object value)
{
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
if (value is BigInteger)
{
InternalWriteValue(JsonToken.Integer);
@@ -24,7 +24,7 @@
#endregion
#if !PORTABLE40
#if !(PORTABLE || NET20 || NET35)
#if !(PORTABLE || NET20 || NET35) || NETSTANDARD1_1
using System.Numerics;
#endif
using System;
@@ -1635,7 +1635,7 @@ namespace Newtonsoft.Json.Converters
}
else if (reader.TokenType == JsonToken.Integer)
{
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
if (reader.Value is BigInteger)
{
return ((BigInteger)reader.Value).ToString(CultureInfo.InvariantCulture);
@@ -1674,7 +1674,7 @@ namespace Newtonsoft.Json.Converters
#if !PORTABLE
return XmlConvert.ToString(d, DateTimeUtils.ToSerializationMode(d.Kind));
#else
return XmlConvert.ToString(d);
return XmlConvert.ToString(d, DateTimeUtils.ToDateTimeFormat(d.Kind));
#endif
}
else if (reader.TokenType == JsonToken.Null)
+3 -3
View File
@@ -26,7 +26,7 @@
using System;
using System.IO;
using System.Globalization;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
using System.Numerics;
#endif
#if !(NET20 || NET35 || PORTABLE40)
@@ -238,7 +238,7 @@ namespace Newtonsoft.Json
return value.ToString(null, CultureInfo.InvariantCulture);
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
private static string ToStringInternal(BigInteger value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
@@ -510,7 +510,7 @@ namespace Newtonsoft.Json
return ToString((Uri)value);
case PrimitiveTypeCode.TimeSpan:
return ToString((TimeSpan)value);
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
case PrimitiveTypeCode.BigInteger:
return ToStringInternal((BigInteger)value);
#endif
+3 -3
View File
@@ -27,7 +27,7 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Globalization;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
using System.Numerics;
#endif
using Newtonsoft.Json.Serialization;
@@ -623,7 +623,7 @@ namespace Newtonsoft.Json
if (!(Value is double))
{
double d;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (Value is BigInteger)
{
d = (double)(BigInteger)Value;
@@ -683,7 +683,7 @@ namespace Newtonsoft.Json
case JsonToken.Integer:
case JsonToken.Float:
bool b;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (Value is BigInteger)
{
b = (BigInteger)Value != 0;
+4 -4
View File
@@ -30,7 +30,7 @@ using System.Runtime.CompilerServices;
using System.Text;
using System.IO;
using System.Globalization;
#if !(PORTABLE || PORTABLE40 || NET35 || NET20)
#if !(PORTABLE || PORTABLE40 || NET35 || NET20) || NETSTANDARD1_1
using System.Numerics;
#endif
using Newtonsoft.Json.Utilities;
@@ -747,7 +747,7 @@ namespace Newtonsoft.Json
case '9':
ParseNumber(ReadType.Read);
bool b;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (Value is BigInteger)
{
b = (BigInteger)Value != 0;
@@ -2021,7 +2021,7 @@ namespace Newtonsoft.Json
}
else if (parseResult == ParseResult.Overflow)
{
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
string number = _stringReference.ToString();
if (number.Length > MaximumJavascriptIntegerCharacterLength)
@@ -2076,7 +2076,7 @@ namespace Newtonsoft.Json
SetToken(numberType, numberValue, false);
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
// By using the BigInteger type in a separate method,
// the runtime can execute the ParseNumber even if
// the System.Numerics.BigInteger.Parse method is
+2 -2
View File
@@ -26,7 +26,7 @@
using System;
using System.Collections.Generic;
using System.Globalization;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
using System.Numerics;
#endif
using System.Text;
@@ -359,7 +359,7 @@ namespace Newtonsoft.Json
/// <param name="value">The <see cref="Object"/> value to write.</param>
public override void WriteValue(object value)
{
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
if (value is BigInteger)
{
InternalWriteValue(JsonToken.Integer);
+2 -2
View File
@@ -25,7 +25,7 @@
using System;
using System.Collections.Generic;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
using System.Numerics;
#endif
using Newtonsoft.Json.Linq;
@@ -840,7 +840,7 @@ namespace Newtonsoft.Json
if (schema.DivisibleBy != null)
{
bool notDivisible;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (value is BigInteger)
{
// not that this will lose any decimal point on DivisibleBy
+4 -4
View File
@@ -26,7 +26,7 @@
using System;
using System.Collections.Generic;
using System.IO;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
using System.Numerics;
#endif
using Newtonsoft.Json.Utilities;
@@ -532,7 +532,7 @@ namespace Newtonsoft.Json
break;
case JsonToken.Integer:
ValidationUtils.ArgumentNotNull(value, nameof(value));
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
if (value is BigInteger)
{
WriteValue((BigInteger)value);
@@ -1392,7 +1392,7 @@ namespace Newtonsoft.Json
}
else
{
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
// this is here because adding a WriteValue(BigInteger) to JsonWriter will
// mean the user has to add a reference to System.Numerics.dll
if (value is BigInteger)
@@ -1550,7 +1550,7 @@ namespace Newtonsoft.Json
case PrimitiveTypeCode.TimeSpanNullable:
writer.WriteValue((value == null) ? (TimeSpan?)null : (TimeSpan)value);
break;
#if !(PORTABLE || PORTABLE40 || NET35 || NET20)
#if !(PORTABLE || PORTABLE40 || NET35 || NET20) || NETSTANDARD1_1
case PrimitiveTypeCode.BigInteger:
// this will call to WriteValue(object)
writer.WriteValue((BigInteger)value);
+2 -8
View File
@@ -706,10 +706,7 @@ namespace Newtonsoft.Json.Linq
/// <param name="propertyName">Name of the property.</param>
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#if !(PORTABLE40 || PORTABLE || NET20)
@@ -719,10 +716,7 @@ namespace Newtonsoft.Json.Linq
/// <param name="propertyName">Name of the property.</param>
protected virtual void OnPropertyChanging(string propertyName)
{
if (PropertyChanging != null)
{
PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
}
PropertyChanging?.Invoke(this, new PropertyChangingEventArgs(propertyName));
}
#endif
+34 -34
View File
@@ -31,7 +31,7 @@ using System.Dynamic;
using System.Linq.Expressions;
#endif
using System.IO;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
using System.Numerics;
#endif
using System.Text;
@@ -68,7 +68,7 @@ namespace Newtonsoft.Json.Linq
private static readonly JTokenType[] BooleanTypes = new[] { JTokenType.Integer, JTokenType.Float, JTokenType.String, JTokenType.Comment, JTokenType.Raw, JTokenType.Boolean };
private static readonly JTokenType[] NumberTypes = new[] { JTokenType.Integer, JTokenType.Float, JTokenType.String, JTokenType.Comment, JTokenType.Raw, JTokenType.Boolean };
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
private static readonly JTokenType[] BigIntegerTypes = new[] { JTokenType.Integer, JTokenType.Float, JTokenType.String, JTokenType.Comment, JTokenType.Raw, JTokenType.Boolean, JTokenType.Bytes };
#endif
private static readonly JTokenType[] StringTypes = new[] { JTokenType.Date, JTokenType.Integer, JTokenType.Float, JTokenType.String, JTokenType.Comment, JTokenType.Raw, JTokenType.Boolean, JTokenType.Bytes, JTokenType.Guid, JTokenType.TimeSpan, JTokenType.Uri };
@@ -492,7 +492,7 @@ namespace Newtonsoft.Json.Linq
throw new ArgumentException("Can not convert {0} to Boolean.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return Convert.ToBoolean((int)(BigInteger)v.Value);
@@ -546,7 +546,7 @@ namespace Newtonsoft.Json.Linq
throw new ArgumentException("Can not convert {0} to Boolean.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return Convert.ToBoolean((int)(BigInteger)v.Value);
@@ -569,7 +569,7 @@ namespace Newtonsoft.Json.Linq
throw new ArgumentException("Can not convert {0} to Int64.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return (long)(BigInteger)v.Value;
@@ -660,7 +660,7 @@ namespace Newtonsoft.Json.Linq
throw new ArgumentException("Can not convert {0} to Decimal.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return (decimal?)(BigInteger)v.Value;
@@ -688,7 +688,7 @@ namespace Newtonsoft.Json.Linq
throw new ArgumentException("Can not convert {0} to Double.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return (double?)(BigInteger)v.Value;
@@ -716,7 +716,7 @@ namespace Newtonsoft.Json.Linq
throw new ArgumentException("Can not convert {0} to Char.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return (char?)(BigInteger)v.Value;
@@ -739,7 +739,7 @@ namespace Newtonsoft.Json.Linq
throw new ArgumentException("Can not convert {0} to Int32.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return (int)(BigInteger)v.Value;
@@ -762,7 +762,7 @@ namespace Newtonsoft.Json.Linq
throw new ArgumentException("Can not convert {0} to Int16.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return (short)(BigInteger)v.Value;
@@ -786,7 +786,7 @@ namespace Newtonsoft.Json.Linq
throw new ArgumentException("Can not convert {0} to UInt16.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return (ushort)(BigInteger)v.Value;
@@ -810,7 +810,7 @@ namespace Newtonsoft.Json.Linq
throw new ArgumentException("Can not convert {0} to Char.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return (char)(BigInteger)v.Value;
@@ -833,7 +833,7 @@ namespace Newtonsoft.Json.Linq
throw new ArgumentException("Can not convert {0} to Byte.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return (byte)(BigInteger)v.Value;
@@ -857,7 +857,7 @@ namespace Newtonsoft.Json.Linq
throw new ArgumentException("Can not convert {0} to SByte.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return (sbyte)(BigInteger)v.Value;
@@ -885,7 +885,7 @@ namespace Newtonsoft.Json.Linq
throw new ArgumentException("Can not convert {0} to Int32.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return (int?)(BigInteger)v.Value;
@@ -913,7 +913,7 @@ namespace Newtonsoft.Json.Linq
throw new ArgumentException("Can not convert {0} to Int16.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return (short?)(BigInteger)v.Value;
@@ -942,7 +942,7 @@ namespace Newtonsoft.Json.Linq
throw new ArgumentException("Can not convert {0} to UInt16.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return (ushort?)(BigInteger)v.Value;
@@ -970,7 +970,7 @@ namespace Newtonsoft.Json.Linq
throw new ArgumentException("Can not convert {0} to Byte.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return (byte?)(BigInteger)v.Value;
@@ -999,7 +999,7 @@ namespace Newtonsoft.Json.Linq
throw new ArgumentException("Can not convert {0} to SByte.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return (sbyte?)(BigInteger)v.Value;
@@ -1050,7 +1050,7 @@ namespace Newtonsoft.Json.Linq
throw new ArgumentException("Can not convert {0} to Int64.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return (long?)(BigInteger)v.Value;
@@ -1078,7 +1078,7 @@ namespace Newtonsoft.Json.Linq
throw new ArgumentException("Can not convert {0} to Single.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return (float?)(BigInteger)v.Value;
@@ -1101,7 +1101,7 @@ namespace Newtonsoft.Json.Linq
throw new ArgumentException("Can not convert {0} to Decimal.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return (decimal)(BigInteger)v.Value;
@@ -1130,7 +1130,7 @@ namespace Newtonsoft.Json.Linq
throw new ArgumentException("Can not convert {0} to UInt32.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return (uint?)(BigInteger)v.Value;
@@ -1159,7 +1159,7 @@ namespace Newtonsoft.Json.Linq
throw new ArgumentException("Can not convert {0} to UInt64.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return (ulong?)(BigInteger)v.Value;
@@ -1182,7 +1182,7 @@ namespace Newtonsoft.Json.Linq
throw new ArgumentException("Can not convert {0} to Double.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return (double)(BigInteger)v.Value;
@@ -1205,7 +1205,7 @@ namespace Newtonsoft.Json.Linq
throw new ArgumentException("Can not convert {0} to Single.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return (float)(BigInteger)v.Value;
@@ -1241,7 +1241,7 @@ namespace Newtonsoft.Json.Linq
{
return Convert.ToBase64String((byte[])v.Value);
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return ((BigInteger)v.Value).ToString(CultureInfo.InvariantCulture);
@@ -1265,7 +1265,7 @@ namespace Newtonsoft.Json.Linq
throw new ArgumentException("Can not convert {0} to UInt32.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return (uint)(BigInteger)v.Value;
@@ -1289,7 +1289,7 @@ namespace Newtonsoft.Json.Linq
throw new ArgumentException("Can not convert {0} to UInt64.".FormatWith(CultureInfo.InvariantCulture, GetType(value)));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return (ulong)(BigInteger)v.Value;
@@ -1321,7 +1321,7 @@ namespace Newtonsoft.Json.Linq
{
return Convert.FromBase64String(Convert.ToString(v.Value, CultureInfo.InvariantCulture));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (v.Value is BigInteger)
{
return ((BigInteger)v.Value).ToByteArray();
@@ -1456,7 +1456,7 @@ namespace Newtonsoft.Json.Linq
return (v.Value is Uri) ? (Uri)v.Value : new Uri(Convert.ToString(v.Value, CultureInfo.InvariantCulture));
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
private static BigInteger ToBigInteger(JToken value)
{
JValue v = EnsureValue(value);
@@ -2035,7 +2035,7 @@ namespace Newtonsoft.Json.Linq
return (TimeSpan?)this;
case PrimitiveTypeCode.TimeSpan:
return (TimeSpan)this;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
case PrimitiveTypeCode.BigIntegerNullable:
return ToBigIntegerNullable(this);
case PrimitiveTypeCode.BigInteger:
@@ -2305,7 +2305,7 @@ namespace Newtonsoft.Json.Linq
JPath p = new JPath(path);
JToken token = null;
foreach (JToken t in p.Evaluate(this, errorWhenNoMatch))
foreach (JToken t in p.Evaluate(this, this, errorWhenNoMatch))
{
if (token != null)
{
@@ -2341,7 +2341,7 @@ namespace Newtonsoft.Json.Linq
public IEnumerable<JToken> SelectTokens(string path, bool errorWhenNoMatch)
{
JPath p = new JPath(path);
return p.Evaluate(this, errorWhenNoMatch);
return p.Evaluate(this, this, errorWhenNoMatch);
}
#if !(NET35 || NET20 || PORTABLE40)
+2 -2
View File
@@ -25,7 +25,7 @@
using System;
using System.Globalization;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
using System.Numerics;
#endif
using Newtonsoft.Json.Utilities;
@@ -221,7 +221,7 @@ namespace Newtonsoft.Json.Linq
/// <param name="value">The <see cref="Object"/> value to write.</param>
public override void WriteValue(object value)
{
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
if (value is BigInteger)
{
InternalWriteValue(JsonToken.Integer);
+7 -7
View File
@@ -31,7 +31,7 @@ using System.Globalization;
using System.Dynamic;
using System.Linq.Expressions;
#endif
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
using System.Numerics;
#endif
@@ -219,7 +219,7 @@ namespace Newtonsoft.Json.Linq
get { return false; }
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
private static int CompareBigInteger(BigInteger i1, object i2)
{
int result = i1.CompareTo(ConvertUtils.ToBigInteger(i2));
@@ -264,7 +264,7 @@ namespace Newtonsoft.Json.Linq
switch (valueType)
{
case JTokenType.Integer:
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (objA is BigInteger)
{
return CompareBigInteger((BigInteger)objA, objB);
@@ -287,7 +287,7 @@ namespace Newtonsoft.Json.Linq
return Convert.ToInt64(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToInt64(objB, CultureInfo.InvariantCulture));
}
case JTokenType.Float:
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (objA is BigInteger)
{
return CompareBigInteger((BigInteger)objA, objB);
@@ -428,7 +428,7 @@ namespace Newtonsoft.Json.Linq
}
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (objA is BigInteger || objB is BigInteger)
{
if (objA == null || objB == null)
@@ -632,7 +632,7 @@ namespace Newtonsoft.Json.Linq
{
return JTokenType.Integer;
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
else if (value is BigInteger)
{
return JTokenType.Integer;
@@ -768,7 +768,7 @@ namespace Newtonsoft.Json.Linq
{
writer.WriteValue((ulong)_value);
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
else if (_value is BigInteger)
{
writer.WriteValue((BigInteger)_value);
@@ -8,7 +8,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
{
public int? Index { get; set; }
public override IEnumerable<JToken> ExecuteFilter(IEnumerable<JToken> current, bool errorWhenNoMatch)
public override IEnumerable<JToken> ExecuteFilter(JToken root, IEnumerable<JToken> current, bool errorWhenNoMatch)
{
foreach (JToken t in current)
{
@@ -6,7 +6,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
{
public List<int> Indexes { get; set; }
public override IEnumerable<JToken> ExecuteFilter(IEnumerable<JToken> current, bool errorWhenNoMatch)
public override IEnumerable<JToken> ExecuteFilter(JToken root, IEnumerable<JToken> current, bool errorWhenNoMatch)
{
foreach (JToken t in current)
{
@@ -11,7 +11,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
public int? End { get; set; }
public int? Step { get; set; }
public override IEnumerable<JToken> ExecuteFilter(IEnumerable<JToken> current, bool errorWhenNoMatch)
public override IEnumerable<JToken> ExecuteFilter(JToken root, IEnumerable<JToken> current, bool errorWhenNoMatch)
{
if (Step == 0)
{
@@ -8,7 +8,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
{
public string Name { get; set; }
public override IEnumerable<JToken> ExecuteFilter(IEnumerable<JToken> current, bool errorWhenNoMatch)
public override IEnumerable<JToken> ExecuteFilter(JToken root, IEnumerable<JToken> current, bool errorWhenNoMatch)
{
foreach (JToken t in current)
{
@@ -13,7 +13,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
{
public List<string> Names { get; set; }
public override IEnumerable<JToken> ExecuteFilter(IEnumerable<JToken> current, bool errorWhenNoMatch)
public override IEnumerable<JToken> ExecuteFilter(JToken root, IEnumerable<JToken> current, bool errorWhenNoMatch)
{
foreach (JToken t in current)
{
+11 -7
View File
@@ -429,15 +429,19 @@ namespace Newtonsoft.Json.Linq.JsonPath
{
EatWhitespace();
if (_expression[_currentIndex] != '@')
List<PathFilter> expressionPath = new List<PathFilter>();
if (_expression[_currentIndex] == '$')
{
expressionPath.Add(new RootFilter());
}
else if (_expression[_currentIndex] != '@')
{
throw new JsonException("Unexpected character while parsing path query: " + _expression[_currentIndex]);
}
_currentIndex++;
List<PathFilter> expressionPath = new List<PathFilter>();
if (ParsePath(expressionPath, _currentIndex, true))
{
throw new JsonException("Path ended with open query.");
@@ -758,17 +762,17 @@ namespace Newtonsoft.Json.Linq.JsonPath
}
}
internal IEnumerable<JToken> Evaluate(JToken t, bool errorWhenNoMatch)
internal IEnumerable<JToken> Evaluate(JToken root, JToken t, bool errorWhenNoMatch)
{
return Evaluate(Filters, t, errorWhenNoMatch);
return Evaluate(Filters, root, t, errorWhenNoMatch);
}
internal static IEnumerable<JToken> Evaluate(List<PathFilter> filters, JToken t, bool errorWhenNoMatch)
internal static IEnumerable<JToken> Evaluate(List<PathFilter> filters, JToken root, JToken t, bool errorWhenNoMatch)
{
IEnumerable<JToken> current = new[] { t };
foreach (PathFilter filter in filters)
{
current = filter.ExecuteFilter(current, errorWhenNoMatch);
current = filter.ExecuteFilter(root, current, errorWhenNoMatch);
}
return current;
@@ -6,7 +6,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
{
internal abstract class PathFilter
{
public abstract IEnumerable<JToken> ExecuteFilter(IEnumerable<JToken> current, bool errorWhenNoMatch);
public abstract IEnumerable<JToken> ExecuteFilter(JToken root, IEnumerable<JToken> current, bool errorWhenNoMatch);
protected static JToken GetTokenIndex(JToken t, bool errorWhenNoMatch, int index)
{
@@ -24,7 +24,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
{
public QueryOperator Operator { get; set; }
public abstract bool IsMatch(JToken t);
public abstract bool IsMatch(JToken root, JToken t);
}
internal class CompositeExpression : QueryExpression
@@ -36,14 +36,14 @@ namespace Newtonsoft.Json.Linq.JsonPath
Expressions = new List<QueryExpression>();
}
public override bool IsMatch(JToken t)
public override bool IsMatch(JToken root, JToken t)
{
switch (Operator)
{
case QueryOperator.And:
foreach (QueryExpression e in Expressions)
{
if (!e.IsMatch(t))
if (!e.IsMatch(root, t))
{
return false;
}
@@ -52,7 +52,7 @@ namespace Newtonsoft.Json.Linq.JsonPath
case QueryOperator.Or:
foreach (QueryExpression e in Expressions)
{
if (e.IsMatch(t))
if (e.IsMatch(root, t))
{
return true;
}
@@ -69,9 +69,9 @@ namespace Newtonsoft.Json.Linq.JsonPath
public List<PathFilter> Path { get; set; }
public JValue Value { get; set; }
public override bool IsMatch(JToken t)
public override bool IsMatch(JToken root, JToken t)
{
IEnumerable<JToken> pathResult = JPath.Evaluate(Path, t, false);
IEnumerable<JToken> pathResult = JPath.Evaluate(Path, root, t, false);
foreach (JToken r in pathResult)
{
@@ -7,13 +7,13 @@ namespace Newtonsoft.Json.Linq.JsonPath
{
public QueryExpression Expression { get; set; }
public override IEnumerable<JToken> ExecuteFilter(IEnumerable<JToken> current, bool errorWhenNoMatch)
public override IEnumerable<JToken> ExecuteFilter(JToken root, IEnumerable<JToken> current, bool errorWhenNoMatch)
{
foreach (JToken t in current)
{
foreach (JToken v in t)
{
if (Expression.IsMatch(v))
if (Expression.IsMatch(root, v))
{
yield return v;
}
@@ -0,0 +1,12 @@
using System.Collections.Generic;
namespace Newtonsoft.Json.Linq.JsonPath
{
internal class RootFilter : PathFilter
{
public override IEnumerable<JToken> ExecuteFilter(JToken root, IEnumerable<JToken> current, bool errorWhenNoMatch)
{
return root;
}
}
}
@@ -6,17 +6,17 @@ namespace Newtonsoft.Json.Linq.JsonPath
{
public string Name { get; set; }
public override IEnumerable<JToken> ExecuteFilter(IEnumerable<JToken> current, bool errorWhenNoMatch)
public override IEnumerable<JToken> ExecuteFilter(JToken root, IEnumerable<JToken> current, bool errorWhenNoMatch)
{
foreach (JToken root in current)
foreach (JToken c in current)
{
if (Name == null)
{
yield return root;
yield return c;
}
JToken value = root;
JToken container = root;
JToken value = c;
JToken container = c;
while (true)
{
@@ -26,12 +26,12 @@ namespace Newtonsoft.Json.Linq.JsonPath
}
else
{
while (value != null && value != root && value == value.Parent.Last)
while (value != null && value != c && value == value.Parent.Last)
{
value = value.Parent;
}
if (value == null || value == root)
if (value == null || value == c)
{
break;
}
@@ -123,6 +123,7 @@
<Compile Include="Linq\JsonPath\PathFilter.cs" />
<Compile Include="Linq\JsonPath\QueryExpression.cs" />
<Compile Include="Linq\JsonPath\QueryFilter.cs" />
<Compile Include="Linq\JsonPath\RootFilter.cs" />
<Compile Include="Linq\JsonPath\ScanFilter.cs" />
<Compile Include="Linq\MergeArrayHandling.cs" />
<Compile Include="Linq\MergeNullValueHandling.cs" />
@@ -137,6 +137,7 @@
<Compile Include="Linq\JsonPath\PathFilter.cs" />
<Compile Include="Linq\JsonPath\QueryExpression.cs" />
<Compile Include="Linq\JsonPath\QueryFilter.cs" />
<Compile Include="Linq\JsonPath\RootFilter.cs" />
<Compile Include="Linq\JsonPath\ScanFilter.cs" />
<Compile Include="Linq\MergeArrayHandling.cs" />
<Compile Include="Linq\MergeNullValueHandling.cs" />
@@ -137,6 +137,7 @@
<Compile Include="Linq\JsonPath\PathFilter.cs" />
<Compile Include="Linq\JsonPath\QueryExpression.cs" />
<Compile Include="Linq\JsonPath\QueryFilter.cs" />
<Compile Include="Linq\JsonPath\RootFilter.cs" />
<Compile Include="Linq\JsonPath\ScanFilter.cs" />
<Compile Include="Linq\MergeArrayHandling.cs" />
<Compile Include="Linq\MergeNullValueHandling.cs" />
@@ -128,6 +128,7 @@
<Compile Include="Linq\JsonPath\PathFilter.cs" />
<Compile Include="Linq\JsonPath\QueryExpression.cs" />
<Compile Include="Linq\JsonPath\QueryFilter.cs" />
<Compile Include="Linq\JsonPath\RootFilter.cs" />
<Compile Include="Linq\JsonPath\ScanFilter.cs" />
<Compile Include="Linq\JToken.cs" />
<Compile Include="Linq\JTokenEqualityComparer.cs" />
@@ -133,6 +133,7 @@
<Compile Include="Linq\JsonPath\PathFilter.cs" />
<Compile Include="Linq\JsonPath\QueryExpression.cs" />
<Compile Include="Linq\JsonPath\QueryFilter.cs" />
<Compile Include="Linq\JsonPath\RootFilter.cs" />
<Compile Include="Linq\JsonPath\ScanFilter.cs" />
<Compile Include="Linq\JToken.cs" />
<Compile Include="Linq\JTokenEqualityComparer.cs" />
@@ -131,6 +131,7 @@
<Compile Include="Linq\JsonPath\PathFilter.cs" />
<Compile Include="Linq\JsonPath\QueryExpression.cs" />
<Compile Include="Linq\JsonPath\QueryFilter.cs" />
<Compile Include="Linq\JsonPath\RootFilter.cs" />
<Compile Include="Linq\JsonPath\ScanFilter.cs" />
<Compile Include="Linq\JToken.cs" />
<Compile Include="Linq\JTokenEqualityComparer.cs" />
@@ -32,8 +32,10 @@ using System.Security;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
#if NETSTANDARD10
#if NETSTANDARD1_0
[assembly: AssemblyTitle("Json.NET .NET Standard 1.0")]
#elif NETSTANDARD1_1
[assembly: AssemblyTitle("Json.NET .NET Standard 1.1")]
#elif PORTABLE40
[assembly: AssemblyTitle("Json.NET Portable .NET 4.0")]
#elif PORTABLE
@@ -487,7 +487,7 @@ namespace Newtonsoft.Json.Schema
case PrimitiveTypeCode.UInt32:
case PrimitiveTypeCode.Int64:
case PrimitiveTypeCode.UInt64:
#if !(PORTABLE || NET35 || NET20)
#if !(PORTABLE || NET35 || NET20) || NETSTANDARD1_1
case PrimitiveTypeCode.BigInteger:
#endif
return schemaType | JsonSchemaType.Integer;
@@ -28,6 +28,7 @@ using System.Runtime.Serialization;
using System.Reflection;
using System.Globalization;
using Newtonsoft.Json.Utilities;
using System.Collections.Generic;
namespace Newtonsoft.Json.Serialization
{
@@ -38,9 +39,17 @@ namespace Newtonsoft.Json.Serialization
{
internal static readonly DefaultSerializationBinder Instance = new DefaultSerializationBinder();
private readonly ThreadSafeStore<TypeNameKey, Type> _typeCache = new ThreadSafeStore<TypeNameKey, Type>(GetTypeFromTypeNameKey);
private readonly ThreadSafeStore<TypeNameKey, Type> _typeCache;
private static Type GetTypeFromTypeNameKey(TypeNameKey typeNameKey)
/// <summary>
/// Initializes a new instance of the <see cref="DefaultSerializationBinder"/> class.
/// </summary>
public DefaultSerializationBinder()
{
_typeCache = new ThreadSafeStore<TypeNameKey, Type>(GetTypeFromTypeNameKey);
}
private Type GetTypeFromTypeNameKey(TypeNameKey typeNameKey)
{
string assemblyName = typeNameKey.AssemblyName;
string typeName = typeNameKey.TypeName;
@@ -68,7 +77,8 @@ namespace Newtonsoft.Json.Serialization
Assembly[] loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly a in loadedAssemblies)
{
if (a.FullName == assemblyName)
// check for both full name or partial name match
if (a.FullName == assemblyName || a.GetName().Name == assemblyName)
{
assembly = a;
break;
@@ -85,7 +95,24 @@ namespace Newtonsoft.Json.Serialization
Type type = assembly.GetType(typeName);
if (type == null)
{
throw new JsonSerializationException("Could not find type '{0}' in assembly '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeName, assembly.FullName));
// if generic type, try manually parsing the type arguments for the case of dynamically loaded assemblies
// example generic typeName format: System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
if (typeName.IndexOf('`') >= 0)
{
try
{
type = GetGenericTypeFromTypeName(typeName, assembly);
}
catch (Exception ex)
{
throw new JsonSerializationException("Could not find type '{0}' in assembly '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeName, assembly.FullName), ex);
}
}
if (type == null)
{
throw new JsonSerializationException("Could not find type '{0}' in assembly '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeName, assembly.FullName));
}
}
return type;
@@ -96,37 +123,55 @@ namespace Newtonsoft.Json.Serialization
}
}
internal struct TypeNameKey : IEquatable<TypeNameKey>
private Type GetGenericTypeFromTypeName(string typeName, Assembly assembly)
{
internal readonly string AssemblyName;
internal readonly string TypeName;
public TypeNameKey(string assemblyName, string typeName)
Type type = null;
int openBracketIndex = typeName.IndexOf('[');
if (openBracketIndex >= 0)
{
AssemblyName = assemblyName;
TypeName = typeName;
}
public override int GetHashCode()
{
return ((AssemblyName != null) ? AssemblyName.GetHashCode() : 0)
^ ((TypeName != null) ? TypeName.GetHashCode() : 0);
}
public override bool Equals(object obj)
{
if (!(obj is TypeNameKey))
string genericTypeDefName = typeName.Substring(0, openBracketIndex);
Type genericTypeDef = assembly.GetType(genericTypeDefName);
if (genericTypeDef != null)
{
return false;
List<Type> genericTypeArguments = new List<Type>();
int scope = 0;
int typeArgStartIndex = 0;
int endIndex = typeName.Length - 1;
for (int i = openBracketIndex + 1; i < endIndex; ++i)
{
char current = typeName[i];
switch (current)
{
case '[':
if (scope == 0)
{
typeArgStartIndex = i + 1;
}
++scope;
break;
case ']':
--scope;
if (scope == 0)
{
string typeArgAssemblyQualifiedName = typeName.Substring(typeArgStartIndex, i - typeArgStartIndex);
TypeNameKey typeNameKey = ReflectionUtils.SplitFullyQualifiedTypeName(typeArgAssemblyQualifiedName);
genericTypeArguments.Add(GetTypeByName(typeNameKey));
}
break;
}
}
type = genericTypeDef.MakeGenericType(genericTypeArguments.ToArray());
}
return Equals((TypeNameKey)obj);
}
public bool Equals(TypeNameKey other)
{
return (AssemblyName == other.AssemblyName && TypeName == other.TypeName);
}
return type;
}
private Type GetTypeByName(TypeNameKey typeNameKey)
{
return _typeCache.Get(typeNameKey);
}
/// <summary>
@@ -139,7 +184,7 @@ namespace Newtonsoft.Json.Serialization
/// </returns>
public override Type BindToType(string assemblyName, string typeName)
{
return _typeCache.Get(new TypeNameKey(assemblyName, typeName));
return GetTypeByName(new TypeNameKey(assemblyName, typeName));
}
#if !(NET35 || NET20)
@@ -33,7 +33,7 @@ using System.Dynamic;
#endif
using System.Diagnostics;
using System.Globalization;
#if !(PORTABLE || PORTABLE40 || NET35 || NET20)
#if !(PORTABLE || PORTABLE40 || NET35 || NET20) || NETSTANDARD1_1
using System.Numerics;
#endif
using System.Reflection;
@@ -778,14 +778,12 @@ namespace Newtonsoft.Json.Serialization
if (resolvedTypeNameHandling != TypeNameHandling.None)
{
string typeName;
string assemblyName;
ReflectionUtils.SplitFullyQualifiedTypeName(qualifiedTypeName, out typeName, out assemblyName);
TypeNameKey typeNameKey = ReflectionUtils.SplitFullyQualifiedTypeName(qualifiedTypeName);
Type specifiedType;
try
{
specifiedType = Serializer._binder.BindToType(assemblyName, typeName);
specifiedType = Serializer._binder.BindToType(typeNameKey.AssemblyName, typeNameKey.TypeName);
}
catch (Exception ex)
{
@@ -968,7 +966,7 @@ namespace Newtonsoft.Json.Serialization
}
}
#if !(PORTABLE || PORTABLE40 || NET35 || NET20)
#if !(PORTABLE || PORTABLE40 || NET35 || NET20) || NETSTANDARD1_1
if (value is BigInteger)
{
return ConvertUtils.FromBigInteger((BigInteger)value, contract.NonNullableUnderlyingType);
@@ -2,7 +2,7 @@
using System.Collections.Generic;
using System.Globalization;
using System.IO;
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
using System.Numerics;
#endif
using System.Text;
@@ -139,7 +139,7 @@ namespace Newtonsoft.Json.Serialization
public override void WriteValue(object value)
{
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
if (value is BigInteger)
{
_textWriter.WriteValue(value);
+3
View File
@@ -61,6 +61,9 @@ namespace Newtonsoft.Json
/// <summary>
/// Include the .NET type name when the type of the object being serialized is not the same as its declared type.
/// Note that this doesn't include the root serialized object by default. To include the root object's type name in JSON
/// you must specify a root type object with <see cref="Newtonsoft.Json.JsonConvert.SerializeObject(object, Type, Newtonsoft.Json.JsonSerializerSettings)"/>
/// or <see cref="Newtonsoft.Json.JsonSerializer.Serialize(Newtonsoft.Json.JsonWriter, object, Type)" />.
/// </summary>
Auto = 4
}
@@ -27,7 +27,7 @@ using System;
using System.Collections.Generic;
using System.Globalization;
using System.ComponentModel;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
using System.Numerics;
#endif
using System.Text;
@@ -145,7 +145,7 @@ namespace Newtonsoft.Json.Utilities
{ typeof(Guid?), PrimitiveTypeCode.GuidNullable },
{ typeof(TimeSpan), PrimitiveTypeCode.TimeSpan },
{ typeof(TimeSpan?), PrimitiveTypeCode.TimeSpanNullable },
#if !(PORTABLE || PORTABLE40 || NET35 || NET20)
#if !(PORTABLE || PORTABLE40 || NET35 || NET20) || NETSTANDARD1_1
{ typeof(BigInteger), PrimitiveTypeCode.BigInteger },
{ typeof(BigInteger?), PrimitiveTypeCode.BigIntegerNullable },
#endif
@@ -311,7 +311,7 @@ namespace Newtonsoft.Json.Utilities
return o => call(null, o);
}
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_1
internal static BigInteger ToBigInteger(object value)
{
if (value is BigInteger)
@@ -540,7 +540,7 @@ namespace Newtonsoft.Json.Utilities
}
}
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE) || NETSTANDARD1_1
if (targetType == typeof(BigInteger))
{
value = ToBigInteger(initialValue);
@@ -73,6 +73,21 @@ namespace Newtonsoft.Json.Utilities
throw MiscellaneousUtils.CreateArgumentOutOfRangeException("kind", kind, "Unexpected DateTimeKind value.");
}
}
#else
public static string ToDateTimeFormat(DateTimeKind kind)
{
switch (kind)
{
case DateTimeKind.Local:
return "yyyy-MM-ddTHH:mm:sszzzzzzz";
case DateTimeKind.Unspecified:
return "s";
case DateTimeKind.Utc:
return "yyyy-MM-ddTHH:mm:ssZ";
default:
throw new Exception("Unexpected DateTimeKind value.");
}
}
#endif
internal static DateTime EnsureDateTime(DateTime value, DateTimeZoneHandling timeZone)
@@ -25,7 +25,7 @@
using System;
using System.Collections.Generic;
#if !(PORTABLE || PORTABLE40 || NET35 || NET20)
#if !(PORTABLE || PORTABLE40 || NET35 || NET20) || NETSTANDARD1_1
using System.Numerics;
#endif
using System.Reflection;
@@ -858,10 +858,13 @@ namespace Newtonsoft.Json.Utilities
}
#endif
public static void SplitFullyQualifiedTypeName(string fullyQualifiedTypeName, out string typeName, out string assemblyName)
public static TypeNameKey SplitFullyQualifiedTypeName(string fullyQualifiedTypeName)
{
int? assemblyDelimiterIndex = GetAssemblyDelimiterIndex(fullyQualifiedTypeName);
string typeName;
string assemblyName;
if (assemblyDelimiterIndex != null)
{
typeName = fullyQualifiedTypeName.Substring(0, assemblyDelimiterIndex.GetValueOrDefault()).Trim();
@@ -872,6 +875,8 @@ namespace Newtonsoft.Json.Utilities
typeName = fullyQualifiedTypeName;
assemblyName = null;
}
return new TypeNameKey(assemblyName, typeName);
}
private static int? GetAssemblyDelimiterIndex(string fullyQualifiedTypeName)
@@ -1100,7 +1105,7 @@ namespace Newtonsoft.Json.Utilities
return 0m;
case PrimitiveTypeCode.DateTime:
return new DateTime();
#if !(PORTABLE || PORTABLE40 || NET35 || NET20)
#if !(PORTABLE || PORTABLE40 || NET35 || NET20) || NETSTANDARD1_1
case PrimitiveTypeCode.BigInteger:
return new BigInteger();
#endif
@@ -1121,4 +1126,36 @@ namespace Newtonsoft.Json.Utilities
return Activator.CreateInstance(type);
}
}
internal struct TypeNameKey : IEquatable<TypeNameKey>
{
internal readonly string AssemblyName;
internal readonly string TypeName;
public TypeNameKey(string assemblyName, string typeName)
{
AssemblyName = assemblyName;
TypeName = typeName;
}
public override int GetHashCode()
{
return (AssemblyName?.GetHashCode() ?? 0) ^ (TypeName?.GetHashCode() ?? 0);
}
public override bool Equals(object obj)
{
if (!(obj is TypeNameKey))
{
return false;
}
return Equals((TypeNameKey)obj);
}
public bool Equals(TypeNameKey other)
{
return (AssemblyName == other.AssemblyName && TypeName == other.TypeName);
}
}
}
+34 -1
View File
@@ -101,7 +101,7 @@
"netstandard1.0": {
"buildOptions": {
"define": [
"NETSTANDARD10",
"NETSTANDARD1_0",
"PORTABLE"
]
},
@@ -129,6 +129,39 @@
"System.Xml.ReaderWriter": "4.0.11",
"System.Xml.XDocument": "4.0.11"
}
},
"netstandard1.1": {
"buildOptions": {
"define": [
"NETSTANDARD1_1",
"PORTABLE"
]
},
"dependencies": {
"Microsoft.CSharp": "4.0.1",
"System.Collections": "4.0.11",
"System.Diagnostics.Debug": "4.0.11",
"System.Dynamic.Runtime": "4.0.11",
"System.Globalization": "4.0.11",
"System.IO": "4.1.0",
"System.Linq": "4.1.0",
"System.Linq.Expressions": "4.1.0",
"System.ObjectModel": "4.0.12",
"System.Reflection": "4.1.0",
"System.Reflection.Extensions": "4.0.1",
"System.Resources.ResourceManager": "4.0.1",
"System.Runtime": "4.1.0",
"System.Runtime.Extensions": "4.1.0",
"System.Runtime.Numerics": "4.0.1",
"System.Runtime.Serialization.Primitives": "4.1.1",
"System.Text.Encoding": "4.0.11",
"System.Text.Encoding.Extensions": "4.0.11",
"System.Text.RegularExpressions": "4.1.0",
"System.Threading": "4.0.11",
"System.Threading.Tasks": "4.0.11",
"System.Xml.ReaderWriter": "4.0.11",
"System.Xml.XDocument": "4.0.11"
}
}
}
}
-8
View File
@@ -1,8 +0,0 @@
@Echo off
PowerShell -NoProfile -NoLogo -ExecutionPolicy unrestricted -Command "[System.Threading.Thread]::CurrentThread.CurrentCulture = ''; [System.Threading.Thread]::CurrentThread.CurrentUICulture = '';& '%~dp0kvm.ps1' %*"
IF EXIST "%USERPROFILE%\.kre\run-once.cmd" (
CALL "%USERPROFILE%\.kre\run-once.cmd"
DEL "%USERPROFILE%\.kre\run-once.cmd"
)
-766
View File
@@ -1,766 +0,0 @@
param(
[parameter(Position=0)]
[string] $Command,
[string] $Proxy,
[switch] $Verbosity = $false,
[alias("g")][switch] $Global = $false,
[alias("p")][switch] $Persistent = $false,
[alias("f")][switch] $Force = $false,
[alias("r")][string] $Runtime,
[switch] $X86 = $false,
[switch] $Amd64 = $false,
#deprecated
[switch] $X64 = $false,
#deprecated
[switch] $Svr50 = $false,
#deprecated
[switch] $Svrc50 = $false,
[alias("w")][switch] $Wait = $false,
[alias("a")]
[string] $Alias = $null,
[switch] $NoNative = $false,
[parameter(Position=1, ValueFromRemainingArguments=$true)]
[string[]]$Args=@()
)
$selectedArch=$null;
$defaultArch="x86"
$selectedRuntime=$null
$defaultRuntime="CLR"
$userKrePath = $env:USERPROFILE + "\.kre"
$userKrePackages = $userKrePath + "\packages"
$globalKrePath = $env:ProgramFiles + "\KRE"
$globalKrePackages = $globalKrePath + "\packages"
$feed = $env:KRE_NUGET_API_URL
function String-IsEmptyOrWhitespace([string]$str) {
return [string]::IsNullOrEmpty($str) -or $str.Trim().length -eq 0
}
if (!$feed)
{
$feed = "https://www.myget.org/F/aspnetvnext/api/v2";
}
$scriptPath = $myInvocation.MyCommand.Definition
function Kvm-Help {
@"
K Runtime Environment Version Manager - Build {{BUILD_NUMBER}}
USAGE: kvm <command> [options]
kvm upgrade [-X86][-Amd64] [-r|-Runtime CLR|CoreCLR] [-g|-Global] [-f|-Force] [-Proxy <ADDRESS>] [-NoNative]
install latest KRE from feed
set 'default' alias to installed version
add KRE bin to user PATH environment variable
-g|-Global install to machine-wide location
-f|-Force upgrade even if latest is already installed
-Proxy <ADDRESS> use given address as proxy when accessing remote server
-NoNative Do not generate native images (Effective only for CoreCLR flavors)
kvm install <semver>|<alias>|<nupkg>|latest [-X86][-Amd64] [-r|-Runtime CLR|CoreCLR] [-a|-Alias <alias>] [-g|-Global] [-f|-Force] [-NoNative]
<semver>|<alias> install requested KRE from feed
<nupkg> install requested KRE from package on local filesystem
latest install latest KRE from feed
add KRE bin to path of current command line
-p|-Persistent add KRE bin to PATH environment variables persistently
-a|-Alias <alias> set alias <alias> for requested KRE on install
-g|-Global install to machine-wide location
-f|-Force install even if specified version is already installed
-NoNative Do not generate native images (Effective only for CoreCLR flavors)
kvm use <semver>|<alias>|none [-X86][-Amd64] [-r|-Runtime CLR|CoreCLR] [-p|-Persistent] [-g|-Global]
<semver>|<alias> add KRE bin to path of current command line
none remove KRE bin from path of current command line
-p|-Persistent add KRE bin to PATH environment variables persistently
-g|-Global combined with -p to change machine PATH instead of user PATH
kvm list
list KRE versions installed
kvm alias
list KRE aliases which have been defined
kvm alias <alias>
display value of the specified alias
kvm alias <alias> <semver>|<alias> [-X86][-Amd64] [-r|-Runtime CLR|CoreCLR]
<alias> The name of the alias to set
<semver>|<alias> The KRE version to set the alias to. Alternatively use the version of the specified alias
kvm unalias <alias>
remove the specified alias
"@ -replace "`n","`r`n" | Write-Host
}
function Kvm-Global-Setup {
$kvmBinPath = "$userKrePath\bin"
If (Needs-Elevation)
{
$arguments = "-ExecutionPolicy unrestricted & '$scriptPath' setup -global -wait"
Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments -Wait
Write-Host "Adding $kvmBinPath to process PATH"
Set-Path (Change-Path $env:Path $kvmBinPath ($kvmBinPath))
Write-Host "Adding $globalKrePath;%USERPROFILE%\.kre to process KRE_HOME"
$envKreHome = $env:KRE_HOME
$envKreHome = Change-Path $envKreHome "%USERPROFILE%\.kre" ("%USERPROFILE%\.kre")
$envKreHome = Change-Path $envKreHome $globalKrePath ($globalKrePath)
$env:KRE_HOME = $envKreHome
Write-Host "Setup complete"
break
}
$scriptFolder = [System.IO.Path]::GetDirectoryName($scriptPath)
Write-Host "Copying file $kvmBinPath\kvm.ps1"
md $kvmBinPath -Force | Out-Null
copy "$scriptFolder\kvm.ps1" "$kvmBinPath\kvm.ps1"
Write-Host "Copying file $kvmBinPath\kvm.cmd"
copy "$scriptFolder\kvm.cmd" "$kvmBinPath\kvm.cmd"
Write-Host "Adding $kvmBinPath to process PATH"
Set-Path (Change-Path $env:Path $kvmBinPath ($kvmBinPath))
Write-Host "Adding $kvmBinPath to user PATH"
$userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User)
$userPath = Change-Path $userPath $kvmBinPath ($kvmBinPath)
[Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User)
Write-Host "Adding $globalKrePath;%USERPROFILE%\.kre to process KRE_HOME"
$envKreHome = $env:KRE_HOME
$envKreHome = Change-Path $envKreHome "%USERPROFILE%\.kre" ("%USERPROFILE%\.kre")
$envKreHome = Change-Path $envKreHome $globalKrePath ($globalKrePath)
$env:KRE_HOME = $envKreHome
Write-Host "Adding $globalKrePath;%USERPROFILE%\.kre to machine KRE_HOME"
$machineKreHome = [Environment]::GetEnvironmentVariable("KRE_HOME", [System.EnvironmentVariableTarget]::Machine)
$machineKreHome = Change-Path $machineKreHome "%USERPROFILE%\.kre" ("%USERPROFILE%\.kre")
$machineKreHome = Change-Path $machineKreHome $globalKrePath ($globalKrePath)
[Environment]::SetEnvironmentVariable("KRE_HOME", $machineKreHome, [System.EnvironmentVariableTarget]::Machine)
}
function Kvm-Global-Upgrade {
$Persistent = $true
$Alias="default"
$versionOrAlias = Kvm-Find-Latest $selectedRuntime $selectedArch
If (Needs-Elevation) {
$arguments = "-ExecutionPolicy unrestricted & '$scriptPath' install '$versionOrAlias' -global $(Requested-Switches) -wait"
Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments -Wait
Kvm-Set-Global-Process-Path $versionOrAlias
break
}
Kvm-Install $versionOrAlias $true
}
function Kvm-Upgrade {
$Persistent = $true
$Alias="default"
Kvm-Install "latest" $false
}
function Add-Proxy-If-Specified {
param(
[System.Net.WebClient] $wc
)
if (!$Proxy) {
$Proxy = $env:http_proxy
}
if ($Proxy) {
$wp = New-Object System.Net.WebProxy($Proxy)
$pb = New-Object UriBuilder($Proxy)
if (!$pb.UserName) {
$wp.Credentials = [System.Net.CredentialCache]::DefaultCredentials
} else {
$wp.Credentials = New-Object System.Net.NetworkCredential($pb.UserName, $pb.Password)
}
$wc.Proxy = $wp
}
}
function Kvm-Find-Latest {
param(
[string] $platform,
[string] $architecture
)
Write-Host "Determining latest version"
$url = "$feed/GetUpdates()?packageIds=%27KRE-$platform-$architecture%27&versions=%270.0%27&includePrerelease=true&includeAllVersions=false"
$wc = New-Object System.Net.WebClient
$wc.Credentials = new-object System.Net.NetworkCredential("aspnetreadonly", "4d8a2d9c-7b80-4162-9978-47e918c9658c")
Add-Proxy-If-Specified($wc)
[xml]$xml = $wc.DownloadString($url)
$version = Select-Xml "//d:Version" -Namespace @{d='http://schemas.microsoft.com/ado/2007/08/dataservices'} $xml
if (String-IsEmptyOrWhitespace($version)) {
throw "There are no packages for platform '$platform', architecture '$architecture' in the feed '$feed'"
}
return $version
}
function Do-Kvm-Download {
param(
[string] $kreFullName,
[string] $packagesFolder
)
$parts = $kreFullName.Split(".", 2)
$url = "$feed/package/" + $parts[0] + "/" + $parts[1]
$kreFolder = Join-Path $packagesFolder $kreFullName
$kreFile = Join-Path $kreFolder "$kreFullName.nupkg"
If (Test-Path $kreFolder) {
if($Force)
{
rm $kreFolder -Recurse -Force
} else {
Write-Host "$kreFullName already installed."
return;
}
}
Write-Host "Downloading" $kreFullName "from $feed"
#Downloading to temp location
$kreTempDownload = Join-Path $packagesFolder "temp"
$tempKreFile = Join-Path $kreTempDownload "$kreFullName.nupkg"
if(Test-Path $kreTempDownload) {
del "$kreTempDownload\*" -recurse
} else {
md $kreTempDownload -Force | Out-Null
}
$wc = New-Object System.Net.WebClient
$wc.Credentials = new-object System.Net.NetworkCredential("aspnetreadonly", "4d8a2d9c-7b80-4162-9978-47e918c9658c")
Add-Proxy-If-Specified($wc)
$wc.DownloadFile($url, $tempKreFile)
Do-Kvm-Unpack $tempKreFile $kreTempDownload
md $kreFolder -Force | Out-Null
Write-Host "Installing to $kreFolder"
mv "$kreTempDownload\*" $kreFolder
Remove-Item "$kreTempDownload" -Force | Out-Null
}
function Do-Kvm-Unpack {
param(
[string] $kreFile,
[string] $kreFolder
)
Write-Host "Unpacking to" $kreFolder
$compressionLib = [System.Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem')
if($compressionLib -eq $null) {
try {
# Shell will not recognize nupkg as a zip and throw, so rename it to zip
$kreZip = [System.IO.Path]::ChangeExtension($kreFile, "zip")
Rename-Item $kreFile $kreZip
# Use the shell to uncompress the nupkg
$shell_app=new-object -com shell.application
$zip_file = $shell_app.namespace($kreZip)
$destination = $shell_app.namespace($kreFolder)
$destination.Copyhere($zip_file.items(), 0x14) #0x4 = don't show UI, 0x10 = overwrite files
}
finally {
# make it a nupkg again
Rename-Item $kreZip $kreFile
}
} else {
[System.IO.Compression.ZipFile]::ExtractToDirectory($kreFile, $kreFolder)
}
If (Test-Path ($kreFolder + "\[Content_Types].xml")) {
Remove-Item ($kreFolder + "\[Content_Types].xml")
}
If (Test-Path ($kreFolder + "\_rels\")) {
Remove-Item ($kreFolder + "\_rels\") -Force -Recurse
}
If (Test-Path ($kreFolder + "\package\")) {
Remove-Item ($kreFolder + "\package\") -Force -Recurse
}
}
function Kvm-Install {
param(
[string] $versionOrAlias,
[boolean] $isGlobal
)
if ($versionOrAlias -eq "latest") {
$versionOrAlias = Kvm-Find-Latest (Requested-Platform $defaultRuntime) (Requested-Architecture $defaultArch)
}
if ($versionOrAlias.EndsWith(".nupkg")) {
$kreFullName = [System.IO.Path]::GetFileNameWithoutExtension($versionOrAlias)
} else {
$kreFullName = Requested-VersionOrAlias $versionOrAlias
}
if ($isGlobal) {
if (Needs-Elevation) {
$arguments = "-ExecutionPolicy unrestricted & '$scriptPath' install '$versionOrAlias' -global $(Requested-Switches) -wait"
Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments -Wait
Kvm-Set-Global-Process-Path $versionOrAlias
break
}
$packageFolder = $globalKrePackages
} else {
$packageFolder = $userKrePackages
}
if ($versionOrAlias.EndsWith(".nupkg")) {
Set-Variable -Name "selectedArch" -Value (Package-Arch $kreFullName) -Scope Script
Set-Variable -Name "selectedRuntime" -Value (Package-Platform $kreFullName) -Scope Script
$kreFolder = "$packageFolder\$kreFullName"
$folderExists = Test-Path $kreFolder
if ($folderExists -and $Force) {
del $kreFolder -Recurse -Force
$folderExists = $false;
}
if ($folderExists) {
Write-Host "Target folder '$kreFolder' already exists"
} else {
$tempUnpackFolder = Join-Path $packageFolder "temp"
$tempKreFile = Join-Path $tempUnpackFolder "$kreFullName.nupkg"
if(Test-Path $tempUnpackFolder) {
del "$tempUnpackFolder\*" -recurse
} else {
md $tempUnpackFolder -Force | Out-Null
}
copy $versionOrAlias $tempKreFile
Do-Kvm-Unpack $tempKreFile $tempUnpackFolder
md $kreFolder -Force | Out-Null
Write-Host "Installing to $kreFolder"
mv "$tempUnpackFolder\*" $kreFolder
Remove-Item "$tempUnpackFolder" -Force | Out-Null
}
$packageVersion = Package-Version $kreFullName
Kvm-Use $packageVersion
if (!$(String-IsEmptyOrWhitespace($Alias))) {
Kvm-Alias-Set $Alias $packageVersion
}
}
else
{
Do-Kvm-Download $kreFullName $packageFolder
Kvm-Use $versionOrAlias
if (!$(String-IsEmptyOrWhitespace($Alias))) {
Kvm-Alias-Set "$Alias" $versionOrAlias
}
}
if ($kreFullName.Contains("CoreCLR")) {
if ($NoNative) {
Write-Host "Native image generation is skipped"
}
else {
Write-Host "Compiling native images for $kreFullName to improve startup performance..."
Start-Process "K" -ArgumentList "crossgen" -Wait
Write-Host "Finished native image compilation."
}
}
}
function Kvm-List {
$kreHome = $env:KRE_HOME
if (!$kreHome) {
$kreHome = "$globalKrePath;$userKrePath"
}
md ($userKrePath + "\alias\") -Force | Out-Null
$aliases = Get-ChildItem ($userKrePath + "\alias\") | Select @{label='Alias';expression={$_.BaseName}}, @{label='Name';expression={Get-Content $_.FullName }}
$items = @()
foreach($portion in $kreHome.Split(';')) {
$path = [System.Environment]::ExpandEnvironmentVariables($portion)
if (Test-Path("$path\packages")) {
$items += Get-ChildItem ("$path\packages\KRE-*") | List-Parts $aliases
}
}
$items | Sort-Object Version, Runtime, Architecture, Alias | Format-Table -AutoSize -Property @{name="Active";expression={$_.Active};alignment="center"}, "Version", "Runtime", "Architecture", "Location", "Alias"
}
filter List-Parts {
param($aliases)
$hasBin = Test-Path($_.FullName+"\bin")
if (!$hasBin) {
return
}
$active = $false
foreach($portion in $env:Path.Split(';')) {
if ($portion.StartsWith($_.FullName)) {
$active = $true
}
}
$fullAlias=""
$delim=""
foreach($alias in $aliases){
if($_.Name.Split('\', 2) -contains $alias.Name){
$fullAlias += $delim + $alias.Alias
$delim = ", "
}
}
$parts1 = $_.Name.Split('.', 2)
$parts2 = $parts1[0].Split('-', 3)
return New-Object PSObject -Property @{
Active = if ($active) { "*" } else { "" }
Version = $parts1[1]
Runtime = $parts2[1]
Architecture = $parts2[2]
Location = $_.Parent.FullName
Alias = $fullAlias
}
}
function Kvm-Global-Use {
param(
[string] $versionOrAlias
)
If (Needs-Elevation) {
$arguments = "-ExecutionPolicy unrestricted & '$scriptPath' use '$versionOrAlias' -global $(Requested-Switches) -wait"
Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments -Wait
Kvm-Set-Global-Process-Path $versionOrAlias
break
}
Kvm-Set-Global-Process-Path "$versionOrAlias"
if ($versionOrAlias -eq "none") {
if ($Persistent) {
Write-Host "Removing KRE from machine PATH"
$machinePath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::Machine)
$machinePath = Change-Path $machinePath "" ($globalKrePackages, $userKrePackages)
[Environment]::SetEnvironmentVariable("Path", $machinePath, [System.EnvironmentVariableTarget]::Machine)
}
return;
}
$kreFullName = Requested-VersionOrAlias "$versionOrAlias"
$kreBin = Locate-KreBinFromFullName $kreFullName
if ($kreBin -eq $null) {
Write-Host "Cannot find $kreFullName, do you need to run 'kvm install $versionOrAlias'?"
return
}
if ($Persistent) {
Write-Host "Adding $kreBin to machine PATH"
$machinePath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::Machine)
$machinePath = Change-Path $machinePath $kreBin ($globalKrePackages, $userKrePackages)
[Environment]::SetEnvironmentVariable("Path", $machinePath, [System.EnvironmentVariableTarget]::Machine)
}
}
function Kvm-Set-Global-Process-Path {
param(
[string] $versionOrAlias
)
if ($versionOrAlias -eq "none") {
Write-Host "Removing KRE from process PATH"
Set-Path (Change-Path $env:Path "" ($globalKrePackages, $userKrePackages))
return
}
$kreFullName = Requested-VersionOrAlias $versionOrAlias
$kreBin = Locate-KreBinFromFullName $kreFullName
if ($kreBin -eq $null) {
Write-Host "Cannot find $kreFullName, do you need to run 'kvm install $versionOrAlias'?"
return
}
Write-Host "Adding" $kreBin "to process PATH"
Set-Path (Change-Path $env:Path $kreBin ($globalKrePackages, $userKrePackages))
}
function Kvm-Use {
param(
[string] $versionOrAlias
)
if ($versionOrAlias -eq "none") {
Write-Host "Removing KRE from process PATH"
Set-Path (Change-Path $env:Path "" ($globalKrePackages, $userKrePackages))
if ($Persistent) {
Write-Host "Removing KRE from user PATH"
$userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User)
$userPath = Change-Path $userPath "" ($globalKrePackages, $userKrePackages)
[Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User)
}
return;
}
$kreFullName = Requested-VersionOrAlias $versionOrAlias
$kreBin = Locate-KreBinFromFullName $kreFullName
if ($kreBin -eq $null) {
Write-Host "Cannot find $kreFullName, do you need to run 'kvm install $versionOrAlias'?"
return
}
Write-Host "Adding" $kreBin "to process PATH"
Set-Path (Change-Path $env:Path $kreBin ($globalKrePackages, $userKrePackages))
if ($Persistent) {
Write-Host "Adding $kreBin to user PATH"
$userPath = [Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User)
$userPath = Change-Path $userPath $kreBin ($globalKrePackages, $userKrePackages)
[Environment]::SetEnvironmentVariable("Path", $userPath, [System.EnvironmentVariableTarget]::User)
}
}
function Kvm-Alias-List {
md ($userKrePath + "\alias\") -Force | Out-Null
Get-ChildItem ($userKrePath + "\alias\") | Select @{label='Alias';expression={$_.BaseName}}, @{label='Name';expression={Get-Content $_.FullName }} | Format-Table -AutoSize
}
function Kvm-Alias-Get {
param(
[string] $name
)
md ($userKrePath + "\alias\") -Force | Out-Null
$aliasFilePath=$userKrePath + "\alias\" + $name + ".txt"
if (!(Test-Path $aliasFilePath)) {
Write-Host "Alias '$name' does not exist"
} else {
Write-Host "Alias '$name' is set to" (Get-Content ($userKrePath + "\alias\" + $name + ".txt"))
}
}
function Kvm-Alias-Set {
param(
[string] $name,
[string] $value
)
$kreFullName = Requested-VersionOrAlias $value
$aliasFilePath = $userKrePath + "\alias\" + $name + ".txt"
$action = if (Test-Path $aliasFilePath) { "Updating" } else { "Setting" }
Write-Host "$action alias '$name' to '$kreFullName'"
md ($userKrePath + "\alias\") -Force | Out-Null
$kreFullName | Out-File ($aliasFilePath) ascii
}
function Kvm-Unalias {
param(
[string] $name
)
$aliasPath=$userKrePath + "\alias\" + $name + ".txt"
if (Test-Path -literalPath "$aliasPath") {
Write-Host "Removing alias $name"
Remove-Item -literalPath $aliasPath
} else {
Write-Host "Cannot remove alias, '$name' is not a valid alias name"
}
}
function Locate-KreBinFromFullName() {
param(
[string] $kreFullName
)
$kreHome = $env:KRE_HOME
if (!$kreHome) {
$kreHome = "$globalKrePath;$userKrePath"
}
foreach($portion in $kreHome.Split(';')) {
$path = [System.Environment]::ExpandEnvironmentVariables($portion)
$kreBin = "$path\packages\$kreFullName\bin"
if (Test-Path "$kreBin") {
return $kreBin
}
}
return $null
}
function Package-Version() {
param(
[string] $kreFullName
)
return $kreFullName -replace '[^.]*.(.*)', '$1'
}
function Package-Platform() {
param(
[string] $kreFullName
)
return $kreFullName -replace 'KRE-([^-]*).*', '$1'
}
function Package-Arch() {
param(
[string] $kreFullName
)
return $kreFullName -replace 'KRE-[^-]*-([^.]*).*', '$1'
}
function Requested-VersionOrAlias() {
param(
[string] $versionOrAlias
)
If (Test-Path ($userKrePath + "\alias\" + $versionOrAlias + ".txt")) {
$aliasValue = Get-Content ($userKrePath + "\alias\" + $versionOrAlias + ".txt")
$parts = $aliasValue.Split('.', 2)
$pkgVersion = $parts[1]
$parts =$parts[0].Split('-', 3)
$pkgPlatform = Requested-Platform $parts[1]
$pkgArchitecture = Requested-Architecture $parts[2]
} else {
$pkgVersion = $versionOrAlias
$pkgPlatform = Requested-Platform $defaultRuntime
$pkgArchitecture = Requested-Architecture $defaultArch
}
return "KRE-" + $pkgPlatform + "-" + $pkgArchitecture + "." + $pkgVersion
}
function Requested-Platform() {
param(
[string] $default
)
if (!(String-IsEmptyOrWhitespace($selectedRuntime))) {return $selectedRuntime}
return $default
}
function Requested-Architecture() {
param(
[string] $default
)
if (!(String-IsEmptyOrWhitespace($selectedArch))) {return $selectedArch}
return $default
}
function Change-Path() {
param(
[string] $existingPaths,
[string] $prependPath,
[string[]] $removePaths
)
$newPath = $prependPath
foreach($portion in $existingPaths.Split(';')) {
$skip = $portion -eq ""
foreach($removePath in $removePaths) {
if ($portion.StartsWith($removePath)) {
$skip = $true
}
}
if (!$skip) {
$newPath = $newPath + ";" + $portion
}
}
return $newPath
}
function Set-Path() {
param(
[string] $newPath
)
md $userKrePath -Force | Out-Null
$env:Path = $newPath
@"
SET "PATH=$newPath"
"@ | Out-File ($userKrePath + "\run-once.cmd") ascii
}
function Needs-Elevation() {
$user = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
$elevated = $user.IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
return -NOT $elevated
}
function Requested-Switches() {
$arguments = ""
if ($X86) {$arguments = "$arguments -x86"}
if ($Amd64) {$arguments = "$arguments -amd64"}
#deprecated
if ($X64) {$arguments = "$arguments -x64"}
if ($selectedRuntime) {$arguments = "$arguments -runtime $selectedRuntime"}
if ($Persistent) {$arguments = "$arguments -persistent"}
if ($Force) {$arguments = "$arguments -force"}
if (!$(String-IsEmptyOrWhitespace($Alias))) {$arguments = "$arguments -alias '$Alias'"}
return $arguments
}
function Validate-And-Santitise-Switches()
{
if ($Svr50 -and $Runtime) {throw "You cannot select both the -runtime switch and the -svr50 runtimes"}
if ($Svrc50 -and $Runtime) {throw "You cannot select both the -runtime switch and the -svrc50 runtimes"}
if ($X86 -and $Amd64) {throw "You cannot select both x86 and amd64 architectures"}
if ($X86 -and $X64) {throw "You cannot select both x86 and x64 architectures"}
if ($X64 -and $Amd64) {throw "You cannot select both x64 and amd64 architectures"}
if ($Runtime) {
$validRuntimes = "CoreCLR", "CLR", "svr50", "svrc50"
$match = $validRuntimes | ? { $_ -like $Runtime } | Select -First 1
if (!$match) {throw "'$runtime' is not a valid runtime"}
Set-Variable -Name "selectedRuntime" -Value $match -Scope Script
} elseif ($Svr50) {
Write-Host "Warning: -svr50 is deprecated, use -runtime CLR for new packages."
Set-Variable -Name "selectedRuntime" -Value "svr50" -Scope Script
} elseif ($Svrc50) {
Write-Host "Warning: -svrc50 is deprecated, use -runtime CoreCLR for new packages."
Set-Variable -Name "selectedRuntime" -Value "svrc50" -Scope Script
}
if ($X64) {
Write-Host "Warning: -x64 is deprecated, use -amd64 for new packages."
Set-Variable -Name "selectedArch" -Value "x64" -Scope Script
} elseif ($Amd64) {
Set-Variable -Name "selectedArch" -Value "amd64" -Scope Script
} elseif ($X86) {
Set-Variable -Name "selectedArch" -Value "x86" -Scope Script
}
}
try {
Validate-And-Santitise-Switches
if ($Global) {
switch -wildcard ($Command + " " + $Args.Count) {
"setup 0" {Kvm-Global-Setup}
"upgrade 0" {Kvm-Global-Upgrade}
"install 1" {Kvm-Install $Args[0] $true}
"use 1" {Kvm-Global-Use $Args[0]}
default {throw "Unknown command, or global switch not supported"};
}
} else {
switch -wildcard ($Command + " " + $Args.Count) {
"setup 0" {Kvm-Global-Setup}
"upgrade 0" {Kvm-Upgrade}
"install 1" {Kvm-Install $Args[0] $false}
"list 0" {Kvm-List}
"use 1" {Kvm-Use $Args[0]}
"alias 0" {Kvm-Alias-List}
"alias 1" {Kvm-Alias-Get $Args[0]}
"alias 2" {Kvm-Alias-Set $Args[0] $Args[1]}
"unalias 1" {Kvm-Unalias $Args[0]}
"help 0" {Kvm-Help}
" 0" {Kvm-Help}
default {throw "Unknown command"};
}
}
}
catch {
Write-Host $_ -ForegroundColor Red ;
Write-Host "Type 'kvm help' for help on how to use kvm."
}
if ($Wait) {
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown,AllowCtrlC")
}