PageRenderTime 52ms CodeModel.GetById 2ms app.highlight 39ms RepoModel.GetById 1ms app.codeStats 1ms

/desktop_clients/Visual Studio/Crear beneficiarios/Json100r3/Source/Src/Newtonsoft.Json.Tests/Serialization/TraceWriterTests.cs

https://bitbucket.org/wfpcoslv/maps-examples
C# | 1294 lines | 1109 code | 163 blank | 22 comment | 35 complexity | f4bd844d63975e0052586c249e6ab6ba MD5 | raw file
   1using System;
   2using System.Collections.Generic;
   3using System.Diagnostics;
   4using System.Globalization;
   5using System.IO;
   6using Newtonsoft.Json.Linq;
   7#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3
   8using System.Numerics;
   9#endif
  10using System.Runtime.Serialization;
  11using System.Runtime.Serialization.Formatters;
  12using System.Text;
  13#if DNXCORE50
  14using Xunit;
  15using Test = Xunit.FactAttribute;
  16using Assert = Newtonsoft.Json.Tests.XUnitAssert;
  17#else
  18using NUnit.Framework;
  19#endif
  20using Newtonsoft.Json.Converters;
  21using Newtonsoft.Json.Serialization;
  22using Newtonsoft.Json.Tests.TestObjects;
  23using Newtonsoft.Json.Tests.TestObjects.Organization;
  24using Newtonsoft.Json.Utilities;
  25#if NET20
  26using Newtonsoft.Json.Utilities.LinqBridge;
  27#else
  28using System.Linq;
  29
  30#endif
  31#if !(NET20 || NET35 || NET40 || PORTABLE40 || PORTABLE) || DNXCORE50
  32using System.Threading.Tasks;
  33#endif
  34
  35namespace Newtonsoft.Json.Tests.Serialization
  36{
  37    public class Staff
  38    {
  39        public string Name { get; set; }
  40        public DateTime StartDate { get; set; }
  41        public IList<string> Roles { get; set; }
  42    }
  43
  44    [TestFixture]
  45    public class TraceWriterTests : TestFixtureBase
  46    {
  47#if !(PORTABLE || DNXCORE50 || PORTABLE40)
  48        [Test]
  49        public void DiagnosticsTraceWriterTest()
  50        {
  51            StringWriter sw = new StringWriter();
  52            TextWriterTraceListener listener = new TextWriterTraceListener(sw);
  53
  54            try
  55            {
  56                Trace.AutoFlush = true;
  57                Trace.Listeners.Add(listener);
  58
  59                DiagnosticsTraceWriter traceWriter = new DiagnosticsTraceWriter();
  60                traceWriter.Trace(TraceLevel.Verbose, "Verbose!", null);
  61                traceWriter.Trace(TraceLevel.Info, "Info!", null);
  62                traceWriter.Trace(TraceLevel.Warning, "Warning!", null);
  63                traceWriter.Trace(TraceLevel.Error, "Error!", null);
  64                traceWriter.Trace(TraceLevel.Off, "Off!", null);
  65
  66                StringAssert.AreEqual(@"Newtonsoft.Json Verbose: 0 : Verbose!
  67Newtonsoft.Json Information: 0 : Info!
  68Newtonsoft.Json Warning: 0 : Warning!
  69Newtonsoft.Json Error: 0 : Error!
  70", sw.ToString());
  71            }
  72            finally
  73            {
  74                Trace.Listeners.Remove(listener);
  75                Trace.AutoFlush = false;
  76            }
  77        }
  78#endif
  79
  80        [Test]
  81        public void WriteNullableByte()
  82        {
  83            StringWriter sw = new StringWriter();
  84            TraceJsonWriter traceJsonWriter = new TraceJsonWriter(new JsonTextWriter(sw));
  85            traceJsonWriter.WriteStartArray();
  86            traceJsonWriter.WriteValue((byte?)null);
  87            traceJsonWriter.WriteEndArray();
  88
  89            StringAssert.AreEqual(@"Serialized JSON: 
  90[
  91  null
  92]", traceJsonWriter.GetSerializedJsonMessage());
  93        }
  94
  95        [Test]
  96        public void WriteNullObject()
  97        {
  98            StringWriter sw = new StringWriter();
  99            TraceJsonWriter traceJsonWriter = new TraceJsonWriter(new JsonTextWriter(sw));
 100            traceJsonWriter.WriteStartArray();
 101            traceJsonWriter.WriteValue((object)null);
 102            traceJsonWriter.WriteEndArray();
 103
 104            StringAssert.AreEqual(@"Serialized JSON: 
 105[
 106  null
 107]", traceJsonWriter.GetSerializedJsonMessage());
 108        }
 109
 110        [Test]
 111        public void WriteNullString()
 112        {
 113            StringWriter sw = new StringWriter();
 114            TraceJsonWriter traceJsonWriter = new TraceJsonWriter(new JsonTextWriter(sw));
 115            traceJsonWriter.WriteStartArray();
 116            traceJsonWriter.WriteValue((string)null);
 117            traceJsonWriter.WriteEndArray();
 118
 119            StringAssert.AreEqual(@"Serialized JSON: 
 120[
 121  null
 122]", traceJsonWriter.GetSerializedJsonMessage());
 123        }
 124
 125        [Test]
 126        public void WriteNullUri()
 127        {
 128            StringWriter sw = new StringWriter();
 129            TraceJsonWriter traceJsonWriter = new TraceJsonWriter(new JsonTextWriter(sw));
 130            traceJsonWriter.WriteStartArray();
 131            traceJsonWriter.WriteValue((Uri)null);
 132            traceJsonWriter.WriteEndArray();
 133
 134            StringAssert.AreEqual(@"Serialized JSON: 
 135[
 136  null
 137]", traceJsonWriter.GetSerializedJsonMessage());
 138        }
 139
 140        [Test]
 141        public void WriteNullByteArray()
 142        {
 143            StringWriter sw = new StringWriter();
 144            TraceJsonWriter traceJsonWriter = new TraceJsonWriter(new JsonTextWriter(sw));
 145            traceJsonWriter.WriteStartArray();
 146            traceJsonWriter.WriteValue((byte[])null);
 147            traceJsonWriter.WriteEndArray();
 148
 149            StringAssert.AreEqual(@"Serialized JSON: 
 150[
 151  null
 152]", traceJsonWriter.GetSerializedJsonMessage());
 153        }
 154
 155        [Test]
 156        public void WriteJRaw()
 157        {
 158            ITraceWriter traceWriter = new MemoryTraceWriter();
 159
 160            JRaw settings = new JRaw("$('#element')");
 161            string json = JsonConvert.SerializeObject(settings, new JsonSerializerSettings
 162            {
 163                TraceWriter = traceWriter
 164            });
 165
 166            Assert.AreEqual("$('#element')", json);
 167
 168            Assert.IsTrue(traceWriter.ToString().EndsWith("Verbose Serialized JSON: " + Environment.NewLine + "$('#element')", StringComparison.Ordinal));
 169        }
 170
 171        [Test]
 172        public void WriteJRawInArray()
 173        {
 174            ITraceWriter traceWriter = new MemoryTraceWriter();
 175
 176            List<JRaw> raws = new List<JRaw>
 177            {
 178                new JRaw("$('#element')"),
 179                new JRaw("$('#element')"),
 180                new JRaw("$('#element')")
 181            };
 182
 183            string json = JsonConvert.SerializeObject(raws, new JsonSerializerSettings
 184            {
 185                TraceWriter = traceWriter,
 186                Formatting = Formatting.Indented
 187            });
 188
 189            StringAssert.AreEqual(@"[
 190  $('#element'),
 191  $('#element'),
 192  $('#element')
 193]", json);
 194
 195            Assert.IsTrue(traceWriter.ToString().EndsWith(@"Verbose Serialized JSON: 
 196[
 197  $('#element'),
 198  $('#element'),
 199  $('#element')
 200]", StringComparison.Ordinal));
 201        }
 202
 203        [Test]
 204        public void MemoryTraceWriterSerializeTest()
 205        {
 206            Staff staff = new Staff();
 207            staff.Name = "Arnie Admin";
 208            staff.Roles = new List<string> { "Administrator" };
 209            staff.StartDate = new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc);
 210
 211            ITraceWriter traceWriter = new MemoryTraceWriter();
 212
 213            JsonConvert.SerializeObject(
 214                staff,
 215                new JsonSerializerSettings { TraceWriter = traceWriter, Converters = { new JavaScriptDateTimeConverter() } });
 216
 217            // 2012-11-11T12:08:42.761 Info Started serializing Newtonsoft.Json.Tests.Serialization.Staff. Path ''.
 218            // 2012-11-11T12:08:42.785 Info Started serializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter. Path 'StartDate'.
 219            // 2012-11-11T12:08:42.791 Info Finished serializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter. Path 'StartDate'.
 220            // 2012-11-11T12:08:42.797 Info Started serializing System.Collections.Generic.List`1[System.String]. Path 'Roles'.
 221            // 2012-11-11T12:08:42.798 Info Finished serializing System.Collections.Generic.List`1[System.String]. Path 'Roles'.
 222            // 2012-11-11T12:08:42.799 Info Finished serializing Newtonsoft.Json.Tests.Serialization.Staff. Path ''.
 223
 224            MemoryTraceWriter memoryTraceWriter = (MemoryTraceWriter)traceWriter;
 225            string output = memoryTraceWriter.ToString();
 226
 227            Assert.AreEqual(916, output.Length);
 228            Assert.AreEqual(7, memoryTraceWriter.GetTraceMessages().Count());
 229
 230            string json = @"Serialized JSON: 
 231{
 232  ""Name"": ""Arnie Admin"",
 233  ""StartDate"": new Date(
 234    976623132000
 235  ),
 236  ""Roles"": [
 237    ""Administrator""
 238  ]
 239}";
 240
 241            json = StringAssert.Normalize(json);
 242            output = StringAssert.Normalize(output);
 243
 244            Assert.IsTrue(output.Contains(json));
 245        }
 246
 247        [Test]
 248        public void MemoryTraceWriterDeserializeTest()
 249        {
 250            string json = @"{
 251  ""Name"": ""Arnie Admin"",
 252  ""StartDate"": new Date(
 253    976623132000
 254  ),
 255  ""Roles"": [
 256    ""Administrator""
 257  ]
 258}";
 259
 260            Staff staff = new Staff();
 261            staff.Name = "Arnie Admin";
 262            staff.Roles = new List<string> { "Administrator" };
 263            staff.StartDate = new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc);
 264
 265            ITraceWriter traceWriter = new MemoryTraceWriter();
 266
 267            JsonConvert.DeserializeObject<Staff>(
 268                json,
 269                new JsonSerializerSettings
 270                {
 271                    TraceWriter = traceWriter,
 272                    Converters = { new JavaScriptDateTimeConverter() },
 273                    MetadataPropertyHandling = MetadataPropertyHandling.Default
 274                });
 275
 276            // 2012-11-11T12:08:42.761 Info Started serializing Newtonsoft.Json.Tests.Serialization.Staff. Path ''.
 277            // 2012-11-11T12:08:42.785 Info Started serializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter. Path 'StartDate'.
 278            // 2012-11-11T12:08:42.791 Info Finished serializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter. Path 'StartDate'.
 279            // 2012-11-11T12:08:42.797 Info Started serializing System.Collections.Generic.List`1[System.String]. Path 'Roles'.
 280            // 2012-11-11T12:08:42.798 Info Finished serializing System.Collections.Generic.List`1[System.String]. Path 'Roles'.
 281            // 2012-11-11T12:08:42.799 Info Finished serializing Newtonsoft.Json.Tests.Serialization.Staff. Path ''.
 282            // 2013-05-19T00:07:24.360 Verbose Deserialized JSON: 
 283            // {
 284            //   "Name": "Arnie Admin",
 285            //   "StartDate": new Date(
 286            //     976623132000
 287            //   ),
 288            //   "Roles": [
 289            //     "Administrator"
 290            //   ]
 291            // }
 292
 293            MemoryTraceWriter memoryTraceWriter = (MemoryTraceWriter)traceWriter;
 294            string output = memoryTraceWriter.ToString();
 295
 296            Assert.AreEqual(1058, output.Length);
 297            Assert.AreEqual(7, memoryTraceWriter.GetTraceMessages().Count());
 298
 299            json = StringAssert.Normalize(json);
 300            output = StringAssert.Normalize(output);
 301
 302            Assert.IsTrue(output.Contains(json));
 303        }
 304
 305        [Test]
 306        public void MemoryTraceWriterLimitTest()
 307        {
 308            MemoryTraceWriter traceWriter = new MemoryTraceWriter();
 309
 310            for (int i = 0; i < 1005; i++)
 311            {
 312                traceWriter.Trace(TraceLevel.Verbose, (i + 1).ToString(CultureInfo.InvariantCulture), null);
 313            }
 314
 315            IList<string> traceMessages = traceWriter.GetTraceMessages().ToList();
 316
 317            Assert.AreEqual(1000, traceMessages.Count);
 318
 319            Assert.IsTrue(traceMessages.First().EndsWith(" 6"));
 320            Assert.IsTrue(traceMessages.Last().EndsWith(" 1005"));
 321        }
 322
 323#if !(NET20 || NET35 || NET40 || PORTABLE40 || PORTABLE) || DNXCORE50
 324        [Test]
 325        public async Task MemoryTraceWriterThreadSafety_Trace()
 326        {
 327            List<Task> tasks = new List<Task>();
 328
 329            MemoryTraceWriter traceWriter = new MemoryTraceWriter();
 330
 331            for (int i = 0; i < 20; i++)
 332            {
 333                tasks.Add(Task.Run(() =>
 334                {
 335                    for (int j = 0; j < 1005; j++)
 336                    {
 337                        traceWriter.Trace(TraceLevel.Verbose, (j + 1).ToString(CultureInfo.InvariantCulture), null);
 338                    }
 339                }));
 340            }
 341
 342            await Task.WhenAll(tasks);
 343
 344            IList<string> traceMessages = traceWriter.GetTraceMessages().ToList();
 345
 346            Assert.AreEqual(1000, traceMessages.Count);
 347        }
 348
 349        [Test]
 350        public async Task MemoryTraceWriterThreadSafety_ToString()
 351        {
 352            List<Task> tasks = new List<Task>();
 353
 354            MemoryTraceWriter traceWriter = new MemoryTraceWriter();
 355
 356            tasks.Add(Task.Run(() =>
 357            {
 358                for (int j = 0; j < 10005; j++)
 359                {
 360                    traceWriter.Trace(TraceLevel.Verbose, (j + 1).ToString(CultureInfo.InvariantCulture), null);
 361                }
 362            }));
 363
 364            string s = null;
 365
 366            tasks.Add(Task.Run(() =>
 367            {
 368                for (int j = 0; j < 10005; j++)
 369                {
 370                    s = traceWriter.ToString();
 371                }
 372            }));
 373
 374            await Task.WhenAll(tasks);
 375
 376            Assert.IsNotNull(s);
 377        }
 378#endif
 379
 380        [Test]
 381        public void Serialize()
 382        {
 383            var traceWriter = new InMemoryTraceWriter
 384            {
 385                LevelFilter = TraceLevel.Info
 386            };
 387
 388            string json =
 389                JsonConvert.SerializeObject(
 390                    new TraceTestObject
 391                    {
 392                        StringArray = new[] { "1", "2" },
 393                        IntList = new List<int> { 1, 2 },
 394                        Version = new Version(1, 2, 3, 4),
 395                        StringDictionary =
 396                            new Dictionary<string, string>
 397                            {
 398                                { "1", "!" },
 399                                { "Two", "!!" },
 400                                { "III", "!!!" }
 401                            },
 402                        Double = 1.1d
 403                    },
 404                    new JsonSerializerSettings
 405                    {
 406                        TraceWriter = traceWriter,
 407                        Formatting = Formatting.Indented
 408                    });
 409
 410            Assert.AreEqual("Started serializing Newtonsoft.Json.Tests.Serialization.TraceTestObject. Path ''.", traceWriter.TraceRecords[0].Message);
 411            Assert.AreEqual("Started serializing System.Collections.Generic.List`1[System.Int32]. Path 'IntList'.", traceWriter.TraceRecords[1].Message);
 412            Assert.AreEqual("Finished serializing System.Collections.Generic.List`1[System.Int32]. Path 'IntList'.", traceWriter.TraceRecords[2].Message);
 413            Assert.AreEqual("Started serializing System.String[]. Path 'StringArray'.", traceWriter.TraceRecords[3].Message);
 414            Assert.AreEqual("Finished serializing System.String[]. Path 'StringArray'.", traceWriter.TraceRecords[4].Message);
 415            Assert.AreEqual("Started serializing System.Version. Path 'Version'.", traceWriter.TraceRecords[5].Message);
 416            Assert.AreEqual("Finished serializing System.Version. Path 'Version'.", traceWriter.TraceRecords[6].Message);
 417            Assert.AreEqual("Started serializing System.Collections.Generic.Dictionary`2[System.String,System.String]. Path 'StringDictionary'.", traceWriter.TraceRecords[7].Message);
 418            Assert.AreEqual("Finished serializing System.Collections.Generic.Dictionary`2[System.String,System.String]. Path 'StringDictionary'.", traceWriter.TraceRecords[8].Message);
 419            Assert.AreEqual("Finished serializing Newtonsoft.Json.Tests.Serialization.TraceTestObject. Path ''.", traceWriter.TraceRecords[9].Message);
 420
 421            Assert.IsFalse(traceWriter.TraceRecords.Any(r => r.Level == TraceLevel.Verbose));
 422        }
 423
 424        [Test]
 425        public void Deserialize()
 426        {
 427            InMemoryTraceWriter traceWriter = new InMemoryTraceWriter
 428            {
 429                LevelFilter = TraceLevel.Info
 430            };
 431
 432            TraceTestObject o2 = JsonConvert.DeserializeObject<TraceTestObject>(
 433                @"{
 434  ""IntList"": [
 435    1,
 436    2
 437  ],
 438  ""StringArray"": [
 439    ""1"",
 440    ""2""
 441  ],
 442  ""Version"": {
 443    ""Major"": 1,
 444    ""Minor"": 2,
 445    ""Build"": 3,
 446    ""Revision"": 4,
 447    ""MajorRevision"": 0,
 448    ""MinorRevision"": 4
 449  },
 450  ""StringDictionary"": {
 451    ""1"": ""!"",
 452    ""Two"": ""!!"",
 453    ""III"": ""!!!""
 454  },
 455  ""Double"": 1.1
 456}",
 457                new JsonSerializerSettings
 458                {
 459                    TraceWriter = traceWriter
 460                });
 461
 462            Assert.AreEqual(2, o2.IntList.Count);
 463            Assert.AreEqual(2, o2.StringArray.Length);
 464            Assert.AreEqual(1, o2.Version.Major);
 465            Assert.AreEqual(2, o2.Version.Minor);
 466            Assert.AreEqual(3, o2.StringDictionary.Count);
 467            Assert.AreEqual(1.1d, o2.Double);
 468
 469            Assert.AreEqual("Started deserializing Newtonsoft.Json.Tests.Serialization.TraceTestObject. Path 'IntList', line 2, position 12.", traceWriter.TraceRecords[0].Message);
 470            Assert.AreEqual("Started deserializing System.Collections.Generic.IList`1[System.Int32]. Path 'IntList', line 2, position 14.", traceWriter.TraceRecords[1].Message);
 471            Assert.IsTrue(traceWriter.TraceRecords[2].Message.StartsWith("Finished deserializing System.Collections.Generic.IList`1[System.Int32]. Path 'IntList'"));
 472            Assert.AreEqual("Started deserializing System.String[]. Path 'StringArray', line 6, position 18.", traceWriter.TraceRecords[3].Message);
 473            Assert.IsTrue(traceWriter.TraceRecords[4].Message.StartsWith("Finished deserializing System.String[]. Path 'StringArray'"));
 474            Assert.AreEqual("Deserializing System.Version using creator with parameters: Major, Minor, Build, Revision. Path 'Version.Major', line 11, position 12.", traceWriter.TraceRecords[5].Message);
 475            Assert.IsTrue(traceWriter.TraceRecords[6].Message.StartsWith("Started deserializing System.Version. Path 'Version'"));
 476            Assert.IsTrue(traceWriter.TraceRecords[7].Message.StartsWith("Finished deserializing System.Version. Path 'Version'"));
 477            Assert.AreEqual("Started deserializing System.Collections.Generic.IDictionary`2[System.String,System.String]. Path 'StringDictionary.1', line 19, position 8.", traceWriter.TraceRecords[8].Message);
 478            Assert.IsTrue(traceWriter.TraceRecords[9].Message.StartsWith("Finished deserializing System.Collections.Generic.IDictionary`2[System.String,System.String]. Path 'StringDictionary'"));
 479            Assert.IsTrue(traceWriter.TraceRecords[10].Message.StartsWith("Finished deserializing Newtonsoft.Json.Tests.Serialization.TraceTestObject. Path ''"));
 480
 481            Assert.IsFalse(traceWriter.TraceRecords.Any(r => r.Level == TraceLevel.Verbose));
 482        }
 483
 484        [Test]
 485        public void Populate()
 486        {
 487            InMemoryTraceWriter traceWriter = new InMemoryTraceWriter
 488            {
 489                LevelFilter = TraceLevel.Info
 490            };
 491
 492            TraceTestObject o2 = new TraceTestObject();
 493
 494            JsonConvert.PopulateObject(@"{
 495  ""IntList"": [
 496    1,
 497    2
 498  ],
 499  ""StringArray"": [
 500    ""1"",
 501    ""2""
 502  ],
 503  ""Version"": {
 504    ""Major"": 1,
 505    ""Minor"": 2,
 506    ""Build"": 3,
 507    ""Revision"": 4,
 508    ""MajorRevision"": 0,
 509    ""MinorRevision"": 4
 510  },
 511  ""StringDictionary"": {
 512    ""1"": ""!"",
 513    ""Two"": ""!!"",
 514    ""III"": ""!!!""
 515  },
 516  ""Double"": 1.1
 517}",
 518                o2,
 519                new JsonSerializerSettings
 520                {
 521                    TraceWriter = traceWriter,
 522                    MetadataPropertyHandling = MetadataPropertyHandling.Default
 523                });
 524
 525            Assert.AreEqual(2, o2.IntList.Count);
 526            Assert.AreEqual(2, o2.StringArray.Length);
 527            Assert.AreEqual(1, o2.Version.Major);
 528            Assert.AreEqual(2, o2.Version.Minor);
 529            Assert.AreEqual(3, o2.StringDictionary.Count);
 530            Assert.AreEqual(1.1d, o2.Double);
 531
 532            Assert.AreEqual("Started deserializing Newtonsoft.Json.Tests.Serialization.TraceTestObject. Path 'IntList', line 2, position 12.", traceWriter.TraceRecords[0].Message);
 533            Assert.AreEqual("Started deserializing System.Collections.Generic.IList`1[System.Int32]. Path 'IntList', line 2, position 14.", traceWriter.TraceRecords[1].Message);
 534            Assert.IsTrue(traceWriter.TraceRecords[2].Message.StartsWith("Finished deserializing System.Collections.Generic.IList`1[System.Int32]. Path 'IntList'"));
 535            Assert.AreEqual("Started deserializing System.String[]. Path 'StringArray', line 6, position 18.", traceWriter.TraceRecords[3].Message);
 536            Assert.IsTrue(traceWriter.TraceRecords[4].Message.StartsWith("Finished deserializing System.String[]. Path 'StringArray'"));
 537            Assert.AreEqual("Deserializing System.Version using creator with parameters: Major, Minor, Build, Revision. Path 'Version.Major', line 11, position 12.", traceWriter.TraceRecords[5].Message);
 538            Assert.IsTrue(traceWriter.TraceRecords[6].Message.StartsWith("Started deserializing System.Version. Path 'Version'"));
 539            Assert.IsTrue(traceWriter.TraceRecords[7].Message.StartsWith("Finished deserializing System.Version. Path 'Version'"));
 540            Assert.AreEqual("Started deserializing System.Collections.Generic.IDictionary`2[System.String,System.String]. Path 'StringDictionary.1', line 19, position 8.", traceWriter.TraceRecords[8].Message);
 541            Assert.IsTrue(traceWriter.TraceRecords[9].Message.StartsWith("Finished deserializing System.Collections.Generic.IDictionary`2[System.String,System.String]. Path 'StringDictionary'"));
 542            Assert.IsTrue(traceWriter.TraceRecords[10].Message.StartsWith("Finished deserializing Newtonsoft.Json.Tests.Serialization.TraceTestObject. Path ''"));
 543
 544            Assert.IsFalse(traceWriter.TraceRecords.Any(r => r.Level == TraceLevel.Verbose));
 545        }
 546
 547        [Test]
 548        public void ErrorDeserializing()
 549        {
 550            string json = @"{""Integer"":""hi""}";
 551
 552            var traceWriter = new InMemoryTraceWriter
 553            {
 554                LevelFilter = TraceLevel.Info
 555            };
 556
 557            ExceptionAssert.Throws<Exception>(() =>
 558            {
 559                JsonConvert.DeserializeObject<IntegerTestClass>(
 560                    json,
 561                    new JsonSerializerSettings
 562                    {
 563                        TraceWriter = traceWriter
 564                    });
 565            }, "Could not convert string to integer: hi. Path 'Integer', line 1, position 15.");
 566
 567            Assert.AreEqual(2, traceWriter.TraceRecords.Count);
 568
 569            Assert.AreEqual(TraceLevel.Info, traceWriter.TraceRecords[0].Level);
 570            Assert.AreEqual("Started deserializing Newtonsoft.Json.Tests.Serialization.IntegerTestClass. Path 'Integer', line 1, position 11.", traceWriter.TraceRecords[0].Message);
 571
 572            Assert.AreEqual(TraceLevel.Error, traceWriter.TraceRecords[1].Level);
 573            Assert.AreEqual("Error deserializing Newtonsoft.Json.Tests.Serialization.IntegerTestClass. Could not convert string to integer: hi. Path 'Integer', line 1, position 15.", traceWriter.TraceRecords[1].Message);
 574        }
 575
 576        [Test]
 577        public void ErrorDeserializingNested()
 578        {
 579            string json = @"{""IntList"":[1, ""two""]}";
 580
 581            var traceWriter = new InMemoryTraceWriter
 582            {
 583                LevelFilter = TraceLevel.Info
 584            };
 585
 586            ExceptionAssert.Throws<Exception>(() =>
 587            {
 588                JsonConvert.DeserializeObject<TraceTestObject>(
 589                    json,
 590                    new JsonSerializerSettings
 591                    {
 592                        TraceWriter = traceWriter
 593                    });
 594            }, "Could not convert string to integer: two. Path 'IntList[1]', line 1, position 20.");
 595
 596            Assert.AreEqual(3, traceWriter.TraceRecords.Count);
 597
 598            Assert.AreEqual(TraceLevel.Info, traceWriter.TraceRecords[0].Level);
 599            Assert.AreEqual("Started deserializing Newtonsoft.Json.Tests.Serialization.TraceTestObject. Path 'IntList', line 1, position 11.", traceWriter.TraceRecords[0].Message);
 600
 601            Assert.AreEqual(TraceLevel.Info, traceWriter.TraceRecords[1].Level);
 602            Assert.AreEqual("Started deserializing System.Collections.Generic.IList`1[System.Int32]. Path 'IntList', line 1, position 12.", traceWriter.TraceRecords[1].Message);
 603
 604            Assert.AreEqual(TraceLevel.Error, traceWriter.TraceRecords[2].Level);
 605            Assert.AreEqual("Error deserializing System.Collections.Generic.IList`1[System.Int32]. Could not convert string to integer: two. Path 'IntList[1]', line 1, position 20.", traceWriter.TraceRecords[2].Message);
 606        }
 607
 608        [Test]
 609        public void SerializeDictionarysWithPreserveObjectReferences()
 610        {
 611            PreserveReferencesHandlingTests.CircularDictionary circularDictionary = new PreserveReferencesHandlingTests.CircularDictionary();
 612            circularDictionary.Add("other", new PreserveReferencesHandlingTests.CircularDictionary { { "blah", null } });
 613            circularDictionary.Add("self", circularDictionary);
 614
 615            InMemoryTraceWriter traceWriter = new InMemoryTraceWriter
 616            {
 617                LevelFilter = TraceLevel.Verbose
 618            };
 619
 620            JsonConvert.SerializeObject(
 621                circularDictionary,
 622                Formatting.Indented,
 623                new JsonSerializerSettings
 624                {
 625                    PreserveReferencesHandling = PreserveReferencesHandling.All,
 626                    TraceWriter = traceWriter
 627                });
 628
 629            Assert.IsTrue(traceWriter.TraceRecords.Any(r => r.Message == "Writing object reference Id '1' for Newtonsoft.Json.Tests.Serialization.PreserveReferencesHandlingTests+CircularDictionary. Path ''."));
 630            Assert.IsTrue(traceWriter.TraceRecords.Any(r => r.Message == "Writing object reference Id '2' for Newtonsoft.Json.Tests.Serialization.PreserveReferencesHandlingTests+CircularDictionary. Path 'other'."));
 631            Assert.IsTrue(traceWriter.TraceRecords.Any(r => r.Message == "Writing object reference to Id '1' for Newtonsoft.Json.Tests.Serialization.PreserveReferencesHandlingTests+CircularDictionary. Path 'self'."));
 632        }
 633
 634        [Test]
 635        public void DeserializeDictionarysWithPreserveObjectReferences()
 636        {
 637            string json = @"{
 638  ""$id"": ""1"",
 639  ""other"": {
 640    ""$id"": ""2"",
 641    ""blah"": null
 642  },
 643  ""self"": {
 644    ""$ref"": ""1""
 645  }
 646}";
 647
 648            InMemoryTraceWriter traceWriter = new InMemoryTraceWriter
 649            {
 650                LevelFilter = TraceLevel.Verbose
 651            };
 652
 653            JsonConvert.DeserializeObject<PreserveReferencesHandlingTests.CircularDictionary>(json,
 654                new JsonSerializerSettings
 655                {
 656                    PreserveReferencesHandling = PreserveReferencesHandling.All,
 657                    MetadataPropertyHandling = MetadataPropertyHandling.Default,
 658                    TraceWriter = traceWriter
 659                });
 660
 661            Assert.IsTrue(traceWriter.TraceRecords.Any(r => r.Message == "Read object reference Id '1' for Newtonsoft.Json.Tests.Serialization.PreserveReferencesHandlingTests+CircularDictionary. Path 'other', line 3, position 10."));
 662            Assert.IsTrue(traceWriter.TraceRecords.Any(r => r.Message == "Read object reference Id '2' for Newtonsoft.Json.Tests.Serialization.PreserveReferencesHandlingTests+CircularDictionary. Path 'other.blah', line 5, position 11."));
 663            Assert.IsTrue(traceWriter.TraceRecords.Any(r => r.Message.StartsWith("Resolved object reference '1' to Newtonsoft.Json.Tests.Serialization.PreserveReferencesHandlingTests+CircularDictionary. Path 'self'")));
 664        }
 665
 666        [Test]
 667        public void WriteTypeNameForObjects()
 668        {
 669            InMemoryTraceWriter traceWriter = new InMemoryTraceWriter
 670            {
 671                LevelFilter = TraceLevel.Verbose
 672            };
 673
 674            IList<object> l = new List<object>
 675            {
 676                new Dictionary<string, string> { { "key!", "value!" } },
 677                new Version(1, 2, 3, 4)
 678            };
 679
 680            JsonConvert.SerializeObject(l, Formatting.Indented, new JsonSerializerSettings
 681            {
 682                TypeNameHandling = TypeNameHandling.All,
 683                TraceWriter = traceWriter
 684            });
 685
 686            Assert.AreEqual("Started serializing System.Collections.Generic.List`1[System.Object]. Path ''.", traceWriter.TraceRecords[0].Message);
 687            Assert.AreEqual("Writing type name '" + ReflectionUtils.GetTypeName(typeof(List<object>), 0, DefaultSerializationBinder.Instance) + "' for System.Collections.Generic.List`1[System.Object]. Path ''.", traceWriter.TraceRecords[1].Message);
 688            Assert.AreEqual("Started serializing System.Collections.Generic.Dictionary`2[System.String,System.String]. Path '$values'.", traceWriter.TraceRecords[2].Message);
 689            Assert.AreEqual("Writing type name '" + ReflectionUtils.GetTypeName(typeof(Dictionary<string, string>), 0, DefaultSerializationBinder.Instance) + "' for System.Collections.Generic.Dictionary`2[System.String,System.String]. Path '$values[0]'.", traceWriter.TraceRecords[3].Message);
 690            Assert.AreEqual("Finished serializing System.Collections.Generic.Dictionary`2[System.String,System.String]. Path '$values[0]'.", traceWriter.TraceRecords[4].Message);
 691            Assert.AreEqual("Started serializing System.Version. Path '$values[0]'.", traceWriter.TraceRecords[5].Message);
 692            Assert.AreEqual("Writing type name '" + ReflectionUtils.GetTypeName(typeof(Version), 0, DefaultSerializationBinder.Instance) + "' for System.Version. Path '$values[1]'.", traceWriter.TraceRecords[6].Message);
 693            Assert.AreEqual("Finished serializing System.Version. Path '$values[1]'.", traceWriter.TraceRecords[7].Message);
 694            Assert.AreEqual("Finished serializing System.Collections.Generic.List`1[System.Object]. Path ''.", traceWriter.TraceRecords[8].Message);
 695        }
 696
 697        [Test]
 698        public void SerializeConverter()
 699        {
 700            InMemoryTraceWriter traceWriter = new InMemoryTraceWriter
 701            {
 702                LevelFilter = TraceLevel.Verbose
 703            };
 704
 705            IList<DateTime> d = new List<DateTime>
 706            {
 707                new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc)
 708            };
 709
 710            string json = JsonConvert.SerializeObject(d, Formatting.Indented, new JsonSerializerSettings
 711            {
 712                Converters = { new JavaScriptDateTimeConverter() },
 713                TraceWriter = traceWriter
 714            });
 715
 716            Assert.AreEqual("Started serializing System.Collections.Generic.List`1[System.DateTime]. Path ''.", traceWriter.TraceRecords[0].Message);
 717            Assert.AreEqual("Started serializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter. Path ''.", traceWriter.TraceRecords[1].Message);
 718            Assert.AreEqual("Finished serializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter. Path '[0]'.", traceWriter.TraceRecords[2].Message);
 719            Assert.AreEqual("Finished serializing System.Collections.Generic.List`1[System.DateTime]. Path ''.", traceWriter.TraceRecords[3].Message);
 720        }
 721
 722        [Test]
 723        public void DeserializeConverter()
 724        {
 725            string json = @"[new Date(976623132000)]";
 726
 727            InMemoryTraceWriter traceWriter =
 728                new InMemoryTraceWriter
 729                {
 730                    LevelFilter = TraceLevel.Verbose
 731                };
 732
 733            JsonConvert.DeserializeObject<List<DateTime>>(
 734                json,
 735                new JsonSerializerSettings
 736                {
 737                    Converters = { new JavaScriptDateTimeConverter() },
 738                    TraceWriter = traceWriter
 739                });
 740
 741            Assert.AreEqual("Started deserializing System.Collections.Generic.List`1[System.DateTime]. Path '', line 1, position 1.", traceWriter.TraceRecords[0].Message);
 742            Assert.AreEqual("Started deserializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter. Path '[0]', line 1, position 10.", traceWriter.TraceRecords[1].Message);
 743            Assert.AreEqual("Finished deserializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter. Path '[0]', line 1, position 23.", traceWriter.TraceRecords[2].Message);
 744            Assert.AreEqual("Finished deserializing System.Collections.Generic.List`1[System.DateTime]. Path '', line 1, position 24.", traceWriter.TraceRecords[3].Message);
 745        }
 746
 747        [Test]
 748        public void DeserializeTypeName()
 749        {
 750            InMemoryTraceWriter traceWriter = new InMemoryTraceWriter
 751            {
 752                LevelFilter = TraceLevel.Verbose
 753            };
 754
 755            string json = @"{
 756  ""$type"": ""System.Collections.Generic.List`1[[System.Object, mscorlib]], mscorlib"",
 757  ""$values"": [
 758    {
 759      ""$type"": ""System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.String, mscorlib]], mscorlib"",
 760      ""key!"": ""value!""
 761    },
 762    {
 763      ""$type"": ""System.Version, mscorlib"",
 764      ""Major"": 1,
 765      ""Minor"": 2,
 766      ""Build"": 3,
 767      ""Revision"": 4,
 768      ""MajorRevision"": 0,
 769      ""MinorRevision"": 4
 770    }
 771  ]
 772}";
 773
 774            JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
 775            {
 776                TypeNameHandling = TypeNameHandling.All,
 777                MetadataPropertyHandling = MetadataPropertyHandling.Default,
 778                TraceWriter = traceWriter
 779            });
 780
 781            Assert.AreEqual("Resolved type 'System.Collections.Generic.List`1[[System.Object, mscorlib]], mscorlib' to System.Collections.Generic.List`1[System.Object]. Path '$type', line 2, position 83.", traceWriter.TraceRecords[0].Message);
 782            Assert.AreEqual("Started deserializing System.Collections.Generic.List`1[System.Object]. Path '$values', line 3, position 14.", traceWriter.TraceRecords[1].Message);
 783            Assert.AreEqual("Resolved type 'System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.String, mscorlib]], mscorlib' to System.Collections.Generic.Dictionary`2[System.String,System.String]. Path '$values[0].$type', line 5, position 119.", traceWriter.TraceRecords[2].Message);
 784            Assert.AreEqual("Started deserializing System.Collections.Generic.Dictionary`2[System.String,System.String]. Path '$values[0].key!', line 6, position 13.", traceWriter.TraceRecords[3].Message);
 785            Assert.IsTrue(traceWriter.TraceRecords[4].Message.StartsWith("Finished deserializing System.Collections.Generic.Dictionary`2[System.String,System.String]. Path '$values[0]'"));
 786            Assert.AreEqual("Resolved type 'System.Version, mscorlib' to System.Version. Path '$values[1].$type', line 9, position 41.", traceWriter.TraceRecords[5].Message);
 787            Assert.AreEqual("Deserializing System.Version using creator with parameters: Major, Minor, Build, Revision. Path '$values[1].Major', line 10, position 14.", traceWriter.TraceRecords[6].Message);
 788            Assert.IsTrue(traceWriter.TraceRecords[7].Message.StartsWith("Started deserializing System.Version. Path '$values[1]'"));
 789            Assert.IsTrue(traceWriter.TraceRecords[8].Message.StartsWith("Finished deserializing System.Version. Path '$values[1]'"));
 790            Assert.IsTrue(traceWriter.TraceRecords[9].Message.StartsWith("Finished deserializing System.Collections.Generic.List`1[System.Object]. Path '$values'"));
 791        }
 792
 793#if !(PORTABLE || DNXCORE50 || PORTABLE40)
 794        [Test]
 795        public void DeserializeISerializable()
 796        {
 797            InMemoryTraceWriter traceWriter = new InMemoryTraceWriter
 798            {
 799                LevelFilter = TraceLevel.Verbose
 800            };
 801
 802            ExceptionAssert.Throws<SerializationException>(() =>
 803            {
 804                JsonConvert.DeserializeObject<Exception>(
 805                    "{}",
 806                    new JsonSerializerSettings
 807                    {
 808                        TraceWriter = traceWriter
 809                    });
 810            }, "Member 'ClassName' was not found.");
 811
 812            Assert.IsTrue(traceWriter.TraceRecords[0].Message.StartsWith("Deserializing System.Exception using ISerializable constructor. Path ''"));
 813            Assert.AreEqual(TraceLevel.Info, traceWriter.TraceRecords[0].Level);
 814            Assert.AreEqual("Error deserializing System.Exception. Member 'ClassName' was not found. Path '', line 1, position 2.", traceWriter.TraceRecords[1].Message);
 815            Assert.AreEqual(TraceLevel.Error, traceWriter.TraceRecords[1].Level);
 816        }
 817#endif
 818
 819        [Test]
 820        public void DeserializeMissingMember()
 821        {
 822            InMemoryTraceWriter traceWriter = new InMemoryTraceWriter
 823            {
 824                LevelFilter = TraceLevel.Verbose
 825            };
 826
 827            JsonConvert.DeserializeObject<Person>(
 828                "{'MissingMemberProperty':'!!'}",
 829                new JsonSerializerSettings
 830                {
 831                    TraceWriter = traceWriter
 832                });
 833
 834            Assert.AreEqual("Started deserializing Newtonsoft.Json.Tests.TestObjects.Organization.Person. Path 'MissingMemberProperty', line 1, position 25.", traceWriter.TraceRecords[0].Message);
 835            Assert.AreEqual("Could not find member 'MissingMemberProperty' on Newtonsoft.Json.Tests.TestObjects.Organization.Person. Path 'MissingMemberProperty', line 1, position 25.", traceWriter.TraceRecords[1].Message);
 836            Assert.IsTrue(traceWriter.TraceRecords[2].Message.StartsWith("Finished deserializing Newtonsoft.Json.Tests.TestObjects.Organization.Person. Path ''"));
 837        }
 838
 839        [Test]
 840        public void DeserializeMissingMemberConstructor()
 841        {
 842            InMemoryTraceWriter traceWriter = new InMemoryTraceWriter
 843            {
 844                LevelFilter = TraceLevel.Verbose
 845            };
 846
 847            string json = @"{
 848  ""Major"": 1,
 849  ""Minor"": 2,
 850  ""Build"": 3,
 851  ""Revision"": 4,
 852  ""MajorRevision"": 0,
 853  ""MinorRevision"": 4,
 854  ""MissingMemberProperty"": null
 855}";
 856
 857            JsonConvert.DeserializeObject<Version>(json, new JsonSerializerSettings
 858            {
 859                TraceWriter = traceWriter
 860            });
 861
 862            Assert.AreEqual("Deserializing System.Version using creator with parameters: Major, Minor, Build, Revision. Path 'Major', line 2, position 10.", traceWriter.TraceRecords[0].Message);
 863            Assert.AreEqual("Could not find member 'MissingMemberProperty' on System.Version. Path 'MissingMemberProperty', line 8, position 31.", traceWriter.TraceRecords[1].Message);
 864            Assert.IsTrue(traceWriter.TraceRecords[2].Message.StartsWith("Started deserializing System.Version. Path ''"));
 865            Assert.IsTrue(traceWriter.TraceRecords[3].Message.StartsWith("Finished deserializing System.Version. Path ''"));
 866        }
 867
 868        [Test]
 869        public void PublicParameterizedConstructorWithPropertyNameConflictWithAttribute()
 870        {
 871            InMemoryTraceWriter traceWriter = new InMemoryTraceWriter
 872            {
 873                LevelFilter = TraceLevel.Verbose
 874            };
 875
 876            string json = @"{name:""1""}";
 877
 878            PublicParameterizedConstructorWithPropertyNameConflictWithAttribute c = JsonConvert.DeserializeObject<PublicParameterizedConstructorWithPropertyNameConflictWithAttribute>(json, new JsonSerializerSettings
 879            {
 880                TraceWriter = traceWriter
 881            });
 882
 883            Assert.IsNotNull(c);
 884            Assert.AreEqual(1, c.Name);
 885
 886            Assert.AreEqual("Deserializing Newtonsoft.Json.Tests.TestObjects.PublicParameterizedConstructorWithPropertyNameConflictWithAttribute using creator with parameters: name. Path 'name', line 1, position 6.", traceWriter.TraceRecords[0].Message);
 887        }
 888
 889        [Test]
 890        public void ShouldSerializeTestClass()
 891        {
 892            ShouldSerializeTestClass c = new ShouldSerializeTestClass();
 893            c.Age = 29;
 894            c.Name = "Jim";
 895            c._shouldSerializeName = true;
 896
 897            InMemoryTraceWriter traceWriter = new InMemoryTraceWriter
 898            {
 899                LevelFilter = TraceLevel.Verbose
 900            };
 901
 902            JsonConvert.SerializeObject(c, new JsonSerializerSettings { TraceWriter = traceWriter });
 903
 904            Assert.AreEqual("ShouldSerialize result for property 'Name' on Newtonsoft.Json.Tests.Serialization.ShouldSerializeTestClass: True. Path ''.", traceWriter.TraceRecords[1].Message);
 905            Assert.AreEqual(TraceLevel.Verbose, traceWriter.TraceRecords[1].Level);
 906
 907            traceWriter = new InMemoryTraceWriter
 908            {
 909                LevelFilter = TraceLevel.Verbose
 910            };
 911
 912            c._shouldSerializeName = false;
 913
 914            JsonConvert.SerializeObject(c, new JsonSerializerSettings { TraceWriter = traceWriter });
 915
 916            Assert.AreEqual("ShouldSerialize result for property 'Name' on Newtonsoft.Json.Tests.Serialization.ShouldSerializeTestClass: False. Path ''.", traceWriter.TraceRecords[1].Message);
 917            Assert.AreEqual(TraceLevel.Verbose, traceWriter.TraceRecords[1].Level);
 918        }
 919
 920        [Test]
 921        public void SpecifiedTest()
 922        {
 923            SpecifiedTestClass c = new SpecifiedTestClass();
 924            c.Name = "James";
 925            c.Age = 27;
 926            c.NameSpecified = false;
 927
 928            InMemoryTraceWriter traceWriter = new InMemoryTraceWriter
 929            {
 930                LevelFilter = TraceLevel.Verbose
 931            };
 932
 933            string json = JsonConvert.SerializeObject(c, Formatting.Indented, new JsonSerializerSettings { TraceWriter = traceWriter });
 934
 935            Assert.AreEqual("Started serializing Newtonsoft.Json.Tests.Serialization.SpecifiedTestClass. Path ''.", traceWriter.TraceRecords[0].Message);
 936            Assert.AreEqual("IsSpecified result for property 'Name' on Newtonsoft.Json.Tests.Serialization.SpecifiedTestClass: False. Path ''.", traceWriter.TraceRecords[1].Message);
 937            Assert.AreEqual("IsSpecified result for property 'Weight' on Newtonsoft.Json.Tests.Serialization.SpecifiedTestClass: False. Path 'Age'.", traceWriter.TraceRecords[2].Message);
 938            Assert.AreEqual("IsSpecified result for property 'Height' on Newtonsoft.Json.Tests.Serialization.SpecifiedTestClass: False. Path 'Age'.", traceWriter.TraceRecords[3].Message);
 939            Assert.AreEqual("IsSpecified result for property 'FavoriteNumber' on Newtonsoft.Json.Tests.Serialization.SpecifiedTestClass: False. Path 'Age'.", traceWriter.TraceRecords[4].Message);
 940            Assert.AreEqual("Finished serializing Newtonsoft.Json.Tests.Serialization.SpecifiedTestClass. Path ''.", traceWriter.TraceRecords[5].Message);
 941
 942            StringAssert.AreEqual(@"{
 943  ""Age"": 27
 944}", json);
 945
 946            traceWriter = new InMemoryTraceWriter
 947            {
 948                LevelFilter = TraceLevel.Verbose
 949            };
 950
 951            SpecifiedTestClass deserialized = JsonConvert.DeserializeObject<SpecifiedTestClass>(json, new JsonSerializerSettings { TraceWriter = traceWriter });
 952
 953            Assert.AreEqual("Started deserializing Newtonsoft.Json.Tests.Serialization.SpecifiedTestClass. Path 'Age', line 2, position 8.", traceWriter.TraceRecords[0].Message);
 954            Assert.IsTrue(traceWriter.TraceRecords[1].Message.StartsWith("Finished deserializing Newtonsoft.Json.Tests.Serialization.SpecifiedTestClass. Path ''"));
 955
 956            Assert.IsNull(deserialized.Name);
 957            Assert.IsFalse(deserialized.NameSpecified);
 958            Assert.IsFalse(deserialized.WeightSpecified);
 959            Assert.IsFalse(deserialized.HeightSpecified);
 960            Assert.IsFalse(deserialized.FavoriteNumberSpecified);
 961            Assert.AreEqual(27, deserialized.Age);
 962
 963            c.NameSpecified = true;
 964            c.WeightSpecified = true;
 965            c.HeightSpecified = true;
 966            c.FavoriteNumber = 23;
 967            json = JsonConvert.SerializeObject(c, Formatting.Indented);
 968
 969            StringAssert.AreEqual(@"{
 970  ""Name"": ""James"",
 971  ""Age"": 27,
 972  ""Weight"": 0,
 973  ""Height"": 0,
 974  ""FavoriteNumber"": 23
 975}", json);
 976
 977            traceWriter = new InMemoryTraceWriter
 978            {
 979                LevelFilter = TraceLevel.Verbose
 980            };
 981
 982            deserialized = JsonConvert.DeserializeObject<SpecifiedTestClass>(json, new JsonSerializerSettings { TraceWriter = traceWriter });
 983
 984            Assert.AreEqual("Started deserializing Newtonsoft.Json.Tests.Serialization.SpecifiedTestClass. Path 'Name', line 2, position 9.", traceWriter.TraceRecords[0].Message);
 985            Assert.AreEqual("IsSpecified for property 'Name' on Newtonsoft.Json.Tests.Serialization.SpecifiedTestClass set to true. Path 'Name', line 2, position 17.", traceWriter.TraceRecords[1].Message);
 986            Assert.AreEqual("IsSpecified for property 'Weight' on Newtonsoft.Json.Tests.Serialization.SpecifiedTestClass set to true. Path 'Weight', line 4, position 13.", traceWriter.TraceRecords[2].Message);
 987            Assert.AreEqual("IsSpecified for property 'Height' on Newtonsoft.Json.Tests.Serialization.SpecifiedTestClass set to true. Path 'Height', line 5, position 13.", traceWriter.TraceRecords[3].Message);
 988            Assert.IsTrue(traceWriter.TraceRecords[4].Message.StartsWith("Finished deserializing Newtonsoft.Json.Tests.Serialization.SpecifiedTestClass. Path ''"));
 989
 990            Assert.AreEqual("James", deserialized.Name);
 991            Assert.IsTrue(deserialized.NameSpecified);
 992            Assert.IsTrue(deserialized.WeightSpecified);
 993            Assert.IsTrue(deserialized.HeightSpecified);
 994            Assert.IsTrue(deserialized.FavoriteNumberSpecified);
 995            Assert.AreEqual(27, deserialized.Age);
 996            Assert.AreEqual(23, deserialized.FavoriteNumber);
 997        }
 998
 999#if !(NET20 || NET35 || PORTABLE || PORTABLE40) || NETSTANDARD1_3
1000        [Test]
1001        public void TraceJsonWriterTest()
1002        {
1003            StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
1004            JsonTextWriter w = new JsonTextWriter(sw);
1005            TraceJsonWriter traceWriter = new TraceJsonWriter(w);
1006
1007            traceWriter.WriteStartObject();
1008            traceWriter.WritePropertyName("Array");
1009            traceWriter.WriteStartArray();
1010            traceWriter.WriteValue("String!");
1011            traceWriter.WriteValue(new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc));
1012            traceWriter.WriteValue(new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.FromHours(2)));
1013            traceWriter.WriteValue(1.1f);
1014            traceWriter.WriteValue(1.1d);
1015            traceWriter.WriteValue(1.1m);
1016            traceWriter.WriteValue(1);
1017            traceWriter.WriteValue((char)'!');
1018            traceWriter.WriteValue((short)1);
1019            traceWriter.WriteValue((ushort)1);
1020            traceWriter.WriteValue((int)1);
1021            traceWriter.WriteValue((uint)1);
1022            traceWriter.WriteValue((sbyte)1);
1023            traceWriter.WriteValue((byte)1);
1024            traceWriter.WriteValue((long)1);
1025            traceWriter.WriteValue((ulong)1);
1026            traceWriter.WriteValue((bool)true);
1027
1028            traceWriter.WriteValue((DateTime?)new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc));
1029            traceWriter.WriteValue((DateTimeOffset?)new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.FromHours(2)));
1030            traceWriter.WriteValue((float?)1.1f);
1031            traceWriter.WriteValue((double?)1.1d);
1032            traceWriter.WriteValue((decimal?)1.1m);
1033            traceWriter.WriteValue((int?)1);
1034            traceWriter.WriteValue((char?)'!');
1035            traceWriter.WriteValue((short?)1);
1036            traceWriter.WriteValue((ushort?)1);
1037            traceWriter.WriteValue((int?)1);
1038            traceWriter.WriteValue((uint?)1);
1039            traceWriter.WriteValue((sbyte?)1);
1040            traceWriter.WriteValue((byte?)1);
1041            traceWriter.WriteValue((long?)1);
1042            traceWriter.WriteValue((ulong?)1);
1043            traceWriter.WriteValue((bool?)true);
1044            traceWriter.WriteValue(BigInteger.Parse("9999999990000000000000000000000000000000000"));
1045
1046            traceWriter.WriteValue((object)true);
1047            traceWriter.WriteValue(TimeSpan.FromMinutes(1));
1048            traceWriter.WriteValue(Guid.Empty);
1049            traceWriter.WriteValue(new Uri("http://www.google.com/"));
1050            traceWriter.WriteValue(Encoding.UTF8.GetBytes("String!"));
1051            traceWriter.WriteRawValue("[1],");
1052            traceWriter.WriteRaw("[2]");
1053            traceWriter.WriteNull();
1054            traceWriter.WriteUndefined();
1055            traceWriter.WriteStartConstructor("ctor");
1056            traceWriter.WriteValue(1);
1057            traceWriter.WriteEndConstructor();
1058            traceWriter.WriteComment("A comment");
1059            traceWriter.WriteWhitespace("       ");
1060            traceWriter.WriteEnd();
1061            traceWriter.WriteEndObject();
1062            traceWriter.Flush();
1063            traceWriter.Close();
1064
1065            string json = @"{
1066  ""Array"": [
1067    ""String!"",
1068    ""2000-12-12T12:12:12Z"",
1069    ""2000-12-12T12:12:12+02:00"",
1070    1.1,
1071    1.1,
1072    1.1,
1073    1,
1074    ""!"",
1075    1,
1076    1,
1077    1,
1078    1,
1079    1,
1080    1,
1081    1,
1082    1,
1083    true,
1084    ""2000-12-12T12:12:12Z"",
1085    ""2000-12-12T12:12:12+02:00"",
1086    1.1,
1087    1.1,
1088    1.1,
1089    1,
1090    ""!"",
1091    1,
1092    1,
1093    1,
1094    1,
1095    1,
1096    1,
1097    1,
1098    1,
1099    true,
1100    9999999990000000000000000000000000000000000,
1101    true,
1102    true,
1103    ""00:01:00"",
1104    ""00000000-0000-0000-0000-000000000000"",
1105    ""http://www.google.com/"",
1106    ""U3RyaW5nIQ=="",
1107    [1],[2],
1108    null,
1109    undefined,
1110    new ctor(
1111      1
1112    )
1113    /*A comment*/       
1114  ]
1115}";
1116
1117            StringAssert.AreEqual("Serialized JSON: " + Environment.NewLine + json, traceWriter.GetSerializedJsonMessage());
1118        }
1119
1120        [Test]
1121        public void TraceJsonReaderTest()
1122        {
1123            string json = @"{
1124  ""Array"": [
1125    ""String!"",
1126    ""2000-12-12T12:12:12Z"",
1127    ""2000-12-12T12:12:12Z"",
1128    ""2000-12-12T12:12:12+00:00"",
1129    ""U3RyaW5nIQ=="",
1130    1,
1131    1.1,
1132    1.2,
1133    9999999990000000000000000000000000000000000,
1134    null,
1135    undefined,
1136    new ctor(
1137      1
1138    )
1139    /*A comment*/
1140  ]
1141}";
1142
1143            StringReader sw = new StringReader(json);
1144            JsonTextReader w = new JsonTextReader(sw);
1145            TraceJsonReader traceReader = new TraceJsonReader(w);
1146
1147            traceReader.Read();
1148            Assert.AreEqual(JsonToken.StartObject, traceReader.TokenType);
1149
1150            traceReader.Read();
1151            Assert.AreEqual(JsonToken.PropertyName, traceReader.TokenType);
1152            Assert.AreEqual("Array", traceReader.Value);
1153
1154            traceReader.Read();
1155            Assert.AreEqual(JsonToken.StartArray, traceReader.TokenType);
1156            Assert.AreEqual(null, traceReader.Value);
1157
1158            traceReader.ReadAsString();
1159            Assert.AreEqual(JsonToken.String, traceReader.TokenType);
1160            Assert.AreEqual('"', traceReader.QuoteChar);
1161            Assert.AreEqual("String!", traceReader.Value);
1162
1163            // for great code coverage justice!
1164            traceReader.QuoteChar = '\'';
1165            Assert.AreEqual('\'', traceReader.QuoteChar);
1166
1167            traceReader.ReadAsString();
1168            Assert.AreEqual(JsonToken.String, traceReader.TokenType);
1169            Assert.AreEqual("2000-12-12T12:12:12Z", traceReader.Value);
1170
1171            traceReader.ReadAsDateTime();
1172            Assert.AreEqual(JsonToken.Date, traceReader.TokenType);
1173            Assert.AreEqual(new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc), traceReader.Value);
1174
1175            traceReader.ReadAsDateTimeOffset();
1176            Assert.AreEqual(JsonToken.Date, traceReader.TokenType);
1177            Assert.AreEqual(new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.Zero), traceReader.Value);
1178
1179            traceReader.ReadAsBytes();
1180            Assert.AreEqual(JsonToken.Bytes, traceReader.TokenType);
1181            CollectionAssert.AreEqual(Encoding.UTF8.GetBytes("String!"), (byte[])traceReader.Value);
1182
1183            traceReader.ReadAsInt32();
1184            Assert.AreEqual(JsonToken.Integer, traceReader.TokenType);
1185            Assert.AreEqual(1, traceReader.Value);
1186
1187            traceReader.ReadAsDecimal();
1188            Assert.AreEqual(JsonToken.Float, traceReader.TokenType);
1189            Assert.AreEqual(1.1m, traceReader.Value);
1190
1191            traceReader.ReadAsDouble();
1192            Assert.AreEqual(JsonToken.Float, traceReader.TokenType);
1193            Assert.AreEqual(1.2d, traceReader.Value);
1194
1195            traceReader.Read();
1196            Assert.AreEqual(JsonToken.Integer, traceReader.TokenType);
1197            Assert.AreEqual(typeof(BigInteger), traceReader.ValueType);
1198            Assert.AreEqual(BigInteger.Parse("9999999990000000000000000000000000000000000"), traceReader.Value);
1199
1200            traceReader.Read();
1201            Assert.AreEqual(JsonToken.Null, traceReader.TokenType);
1202
1203            traceReader.Read();
1204            Assert.AreEqual(JsonToken.Undefined, traceReader.TokenType);
1205
1206            traceReader.Read();
1207            Assert.AreEqual(JsonToken.StartConstructor, traceReader.TokenType);
1208
1209            traceReader.Read();
1210            Assert.AreEqual(JsonToken.Integer, traceReader.TokenType);
1211            Assert.AreEqual(1L, traceReader.Value);
1212
1213            traceReader.Read();
1214            Assert.AreEqual(JsonToken.EndConstructor, traceReader.TokenType);
1215
1216            traceReader.Read();
1217            Assert.AreEqual(JsonToken.Comment, traceReader.TokenType);
1218            Assert.AreEqual("A comment", traceReader.Value);
1219
1220            traceReader.Read();
1221            Assert.AreEqual(JsonToken.EndArray, traceReader.TokenType);
1222
1223            traceReader.Read();
1224            Assert.AreEqual(JsonToken.EndObject, traceReader.TokenType);
1225
1226            Assert.IsFalse(traceReader.Read());
1227
1228            traceReader.Close();
1229
1230            StringAssert.AreEqual("Deserialized JSON: " + Environment.NewLine + json, traceReader.GetDeserializedJsonMessage());
1231        }
1232#endif
1233    }
1234
1235    public class TraceRecord
1236    {
1237        public string Message { get; set; }
1238        public TraceLevel Level { get; set; }
1239        public Exception Exception { get; set; }
1240
1241        public override string ToString()
1242        {
1243            return Level + " - " + Message;
1244        }
1245    }
1246
1247    public class InMemoryTraceWriter : ITraceWriter
1248    {
1249        public TraceLevel LevelFilter { get; set; }
1250        public IList<TraceRecord> TraceRecords { get; set; }
1251
1252        public InMemoryTraceWriter()
1253        {
1254            LevelFilter = TraceLevel.Verbose;
1255            TraceRecords = new List<TraceRecord>();
1256        }
1257
1258        public void Trace(TraceLevel level, string message, Exception ex)
1259        {
1260            TraceRecords.Add(
1261                new TraceRecord
1262                {
1263                    Level = level,
1264                    Message = message,
1265                    Exception = ex
1266                });
1267        }
1268
1269        public override string ToString()
1270        {
1271            StringBuilder sb = new StringBuilder();
1272            foreach (var traceRecord in TraceRecords)
1273            {
1274                sb.AppendLine(traceRecord.Message);
1275            }
1276
1277            return sb.ToString();
1278        }
1279    }
1280
1281    public class TraceTestObject
1282    {
1283        public IList<int> IntList { get; set; }
1284        public string[] StringArray { get; set; }
1285        public Version Version { get; set; }
1286        public IDictionary<string, string> StringDictionary { get; set; }
1287        public double Double { get; set; }
1288    }
1289
1290    public class IntegerTestClass
1291    {
1292        public int Integer { get; set; }
1293    }
1294}