public void Wrapped()
        {
            MockMessageBroker  broker = new MockMessageBroker();
            MockExecutionTimer timer  = new MockExecutionTimer();

            MemoryTraceWriter innerWriter = new MemoryTraceWriter();

            GlimpseTraceWriter writer = new GlimpseTraceWriter(broker, () => timer, innerWriter);

            writer.Trace(TraceLevel.Verbose, "Random text", null);
            writer.Trace(TraceLevel.Error, "More random text", null);
            Assert.AreEqual(2, writer.TraceMessages.Count);

            Assert.AreEqual(2, innerWriter.GetTraceMessages().Count());

            Assert.AreEqual("Verbose Random text", innerWriter.GetTraceMessages().ElementAt(0).Substring(24));
            Assert.AreEqual("Error More random text", innerWriter.GetTraceMessages().ElementAt(1).Substring(24));

            innerWriter.LevelFilter = TraceLevel.Warning;
            writer.Trace(TraceLevel.Verbose, "Random text", null);
            writer.Trace(TraceLevel.Warning, "More random text", null);
            writer.Trace(TraceLevel.Error, "More random text", null);
            Assert.AreEqual(4, innerWriter.GetTraceMessages().Count());

            Assert.AreEqual(TraceLevel.Verbose, writer.LevelFilter);
        }
Esempio n. 2
0
        public void Example()
        {
            #region Usage
            string json =
                @"{
              'FullName': 'Dan Deleted',
              'Deleted': true,
              'DeletedDate': '2013-01-20T00:00:00'
            }";

            MemoryTraceWriter traceWriter = new MemoryTraceWriter();

            Account account = JsonConvert.DeserializeObject <Account>(
                json,
                new JsonSerializerSettings {
                TraceWriter = traceWriter
            }
                );

            Console.WriteLine(traceWriter.ToString());
            // 2013-01-21T01:36:24.422 Info Started deserializing Newtonsoft.Json.Tests.Documentation.Examples.TraceWriter+Account. Path 'FullName', line 2, position 20.
            // 2013-01-21T01:36:24.442 Verbose Could not find member 'DeletedDate' on Newtonsoft.Json.Tests.Documentation.Examples.TraceWriter+Account. Path 'DeletedDate', line 4, position 23.
            // 2013-01-21T01:36:24.447 Info Finished deserializing Newtonsoft.Json.Tests.Documentation.Examples.TraceWriter+Account. Path '', line 5, position 8.
            // 2013-01-21T01:36:24.450 Verbose Deserialized JSON:
            // {
            //   "FullName": "Dan Deleted",
            //   "Deleted": true,
            //   "DeletedDate": "2013-01-20T00:00:00"
            // }
            #endregion

            Assert.AreEqual(4, traceWriter.GetTraceMessages().Count());
        }
Esempio n. 3
0
        public void SerializationBasics()
        {
            IList <string> roles = new List <string>
            {
                "User",
                "Admin"
            };

            MemoryTraceWriter traceWriter = new MemoryTraceWriter();

            string j = JsonConvert.SerializeObject(roles, new JsonSerializerSettings
            {
                Formatting  = Formatting.Indented,
                TraceWriter = traceWriter
            });

            string trace = traceWriter.ToString();
            // Started serializing System.Collections.Generic.List`1[System.String].
            // Finished serializing System.Collections.Generic.List`1[System.String].
            // Verbose Serialized JSON:
            // [
            //   "User",
            //   "Admin"
            // ]
        }
Esempio n. 4
0
        static void Main2()
        {
            Console.WriteLine("Testing DataSetConverter in NetCore2 with DBNull column ");
            DataSet dataSet = new DataSet("dataset");

            dataSet.Namespace = "NetFrameWork";
            DataTable dataTable = CreateDataTable("table1");

            dataSet.Tables.Add(dataTable);

            Console.WriteLine("****** XML dataset Serialized *******");
            StringBuilder sb = new StringBuilder();
            TextWriter    tw = new StringWriter(sb);

            dataSet.WriteXml(tw);
            Console.WriteLine(sb);

            ITraceWriter traceWriter = new MemoryTraceWriter();
            var          settings    = new JsonSerializerSettings
            {
                TraceWriter       = traceWriter,
                Formatting        = Formatting.Indented,
                NullValueHandling = NullValueHandling.Ignore,
                //MissingMemberHandling = MissingMemberHandling.Ignore
            };

            settings.Converters.Add(new DataSetConverter());;
            var json = JsonConvert.SerializeObject(dataSet, settings);

            Console.WriteLine("****** Serialized json *******");
            Console.WriteLine(json);
            Console.WriteLine("****** json Trace *******");
            Console.WriteLine(traceWriter);
        }
        // Debugging serialization using MemoryTraceWriter

        public void Test()
        {
            Product p2 = new Product
            {
                Name       = "Product 2",
                Price      = 12.50m,
                ExpiryDate = new DateTime(2009, 7, 31, 0, 0, 0, DateTimeKind.Utc),
            };

            ITraceWriter traceWriter = new MemoryTraceWriter();

            JsonConvert.SerializeObject(
                p2,
                new JsonSerializerSettings {
                TraceWriter = traceWriter, Converters = { new JavaScriptDateTimeConverter() }
            });

            Console.WriteLine(traceWriter);

            //2020 - 07 - 31T15: 42:15.527 Info Started serializing Json.NetDemo.Product.Path ''.
            //2020 - 07 - 31T15: 42:15.551 Info Started serializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter.Path 'ExpiryDate'.
            //2020 - 07 - 31T15: 42:15.556 Info Finished serializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter.Path 'ExpiryDate'.
            //2020 - 07 - 31T15: 42:15.565 Info Finished serializing Json.NetDemo.Product.Path ''.
            //2020 - 07 - 31T15: 42:15.565 Verbose Serialized JSON:
            //            {
            //                "Name": "Product 2",
            //                "ExpiryDate": new Date(
            //                      1248998400000
            //                              ),
            //                "Price": 12.50,
            //                 "Sizes": null
            //            }
        }
Esempio n. 6
0
        public void ShouldDeserialize_False()
        {
            string json = @"{'HasName':false,'Name':'Name!'}";

            MemoryTraceWriter          traceWriter = new MemoryTraceWriter();
            ShouldDeserializeTestClass c           =
                JsonConvert.DeserializeObject <ShouldDeserializeTestClass>(
                    json,
                    new JsonSerializerSettings
            {
                ContractResolver = ShouldDeserializeContractResolver.Instance,
                TraceWriter      = traceWriter
            }
                    );

            Assert.AreEqual(1, c.ExtensionData.Count);
            Assert.AreEqual("Name!", (string)c.ExtensionData["Name"]);
            Assert.AreEqual(false, c.HasName);
            Assert.AreEqual(null, c.Name);

            Assert.IsTrue(
                traceWriter
                .GetTraceMessages()
                .Any(
                    m =>
                    m.EndsWith(
                        "Verbose ShouldDeserialize result for property 'Name' on Newtonsoft.Json.Tests.Serialization.ShouldDeserializeTestClass: False. Path 'Name'."
                        )
                    )
                );
        }
Esempio n. 7
0
        public void MemoryTraceWriterDeserializeTest()
        {
            string json = @"{
  ""Name"": ""Arnie Admin"",
  ""StartDate"": new Date(
    976623132000
  ),
  ""Roles"": [
    ""Administrator""
  ]
}";

            Staff staff = new Staff();

            staff.Name  = "Arnie Admin";
            staff.Roles = new List <string> {
                "Administrator"
            };
            staff.StartDate = new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc);

            ITraceWriter traceWriter = new MemoryTraceWriter();

            JsonConvert.DeserializeObject <Staff>(
                json,
                new JsonSerializerSettings
            {
                TraceWriter = traceWriter,
                Converters  = { new JavaScriptDateTimeConverter() },
                MetadataPropertyHandling = MetadataPropertyHandling.Default
            });

            Console.WriteLine(traceWriter);
            // 2012-11-11T12:08:42.761 Info Started serializing Newtonsoft.Json.Tests.Serialization.Staff. Path ''.
            // 2012-11-11T12:08:42.785 Info Started serializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter. Path 'StartDate'.
            // 2012-11-11T12:08:42.791 Info Finished serializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter. Path 'StartDate'.
            // 2012-11-11T12:08:42.797 Info Started serializing System.Collections.Generic.List`1[System.String]. Path 'Roles'.
            // 2012-11-11T12:08:42.798 Info Finished serializing System.Collections.Generic.List`1[System.String]. Path 'Roles'.
            // 2012-11-11T12:08:42.799 Info Finished serializing Newtonsoft.Json.Tests.Serialization.Staff. Path ''.
            // 2013-05-19T00:07:24.360 Verbose Deserialized JSON:
            // {
            //   "Name": "Arnie Admin",
            //   "StartDate": new Date(
            //     976623132000
            //   ),
            //   "Roles": [
            //     "Administrator"
            //   ]
            // }

            MemoryTraceWriter memoryTraceWriter = (MemoryTraceWriter)traceWriter;
            string            output            = memoryTraceWriter.ToString();

            Assert.AreEqual(1059, output.Length);
            Assert.AreEqual(7, memoryTraceWriter.GetTraceMessages().Count());

            json   = StringAssert.Normalize(json);
            output = StringAssert.Normalize(output);

            Assert.IsTrue(output.Contains(json));
        }
        public async Task ValuesController_Get_Id_Writes_Expected_Traces_InTheCorrectOrder()
        {
            HttpConfiguration config = new HttpConfiguration();

            config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional });
            Mock <DelegatingHandler> customMessageHandler = new Mock <DelegatingHandler>()
            {
                CallBase = true
            };

            config.MessageHandlers.Add(customMessageHandler.Object);
            MemoryTraceWriter traceWriter = new MemoryTraceWriter();

            config.Services.Replace(typeof(ITraceWriter), traceWriter);

            using (HttpServer server = new HttpServer(config))
            {
                using (HttpClient client = new HttpClient(server))
                {
                    traceWriter.Start();

                    // Calls ValueController.Get(id) using query string
                    string              uri      = _baseAddress + "/api/Values?id=5";
                    HttpRequestMessage  request  = new HttpRequestMessage(HttpMethod.Get, uri);
                    HttpResponseMessage response = await client.SendAsync(request);

                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                    traceWriter.Finish();

                    Assert.True(ConfirmTracingOrder(ExpectedTraceRecordOrder, traceWriter.Records));
                }
            }
        }
Esempio n. 9
0
        public void NewtonSoft_ReadDataModel()
        {
            ITraceWriter traceWriter = new MemoryTraceWriter();

            var result   = collectionModelNewton.Find(model => model.Name.Equals("Newton Model 1")).FirstOrDefault();
            var settings = new JsonSerializerSettings();

            settings.DateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'FFF'Z'";
            settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            output.WriteLine(JsonConvert.SerializeObject(result, Formatting.Indented, settings));

            JObject actual = JObject.Parse(JsonConvert.SerializeObject(result, Formatting.Indented, settings));
            var     file   = @"Data\Serialization.Models.Newton.json";
            JObject expected;

            using (StreamReader reader = new StreamReader(file))
            {
                expected = JObject.Parse(reader.ReadToEnd());
            }

            Assert.True(JObject.DeepEquals(actual, expected));
            //output.WriteLine(json);

            //var jsonReplace = json.Replace("\r\n", "");
            //output.WriteLine(jsonReplace);
        }
Esempio n. 10
0
        private void ExportExcel(object sender, EventArgs e)
        {
            OpenFileDialog openDlg = new OpenFileDialog();

            openDlg.Filter = "CSV Files (.csv)| *.csv|All files (.)| *.";
            if (openDlg.ShowDialog() == DialogResult.OK)
            {
                File.Delete(@"NodeJS\test.json");
                Process.Start("cmd", @"/C cd " + Application.StartupPath + "/NodeJS & node ./csvtojson " + openDlg.FileName);
                Thread.Sleep(3000);
                string                 json        = File.ReadAllText(@"NodeJS\test.json");
                ITraceWriter           writer      = new MemoryTraceWriter();
                JsonSerializerSettings serSettings = new JsonSerializerSettings();
                serSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                serSettings.ContractResolver      = new CamelCasePropertyNamesContractResolver();
                serSettings.TraceWriter           = writer;

                //var neuronNet = JsonConvert.DeserializeObject<List<string>>(json.ToString(), serSettings);
                //var neuronNet = JsonConvert.DeserializeObject<List<NeuronNet>>(json.ToString(), serSettings);
                var test = JsonConvert.DeserializeObject <List <Root2> >(json.ToString(), serSettings);
                net = AcceptJson(test[0]);
                net.AccessChangeNet = true;
                //Console.WriteLine(writer);
            }
        }
Esempio n. 11
0
        public void ValuesController_Get_Id_Writes_Expected_Traces()
        {
            HttpConfiguration config = new HttpConfiguration();

            config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional });
            MemoryTraceWriter traceWriter = new MemoryTraceWriter();

            config.Services.Replace(typeof(ITraceWriter), traceWriter);

            using (HttpServer server = new HttpServer(config))
            {
                using (HttpClient client = new HttpClient(server))
                {
                    traceWriter.Start();

                    // Calls ValueController.Get(id) using query string
                    string              uri      = _baseAddress + "/api/Values?id=5";
                    HttpRequestMessage  request  = new HttpRequestMessage(HttpMethod.Get, uri);
                    HttpResponseMessage response = client.SendAsync(request).Result;
                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                    traceWriter.Finish();

                    IList <string> missingTraces = MissingTraces(ExpectedTraceRecords, traceWriter.Records);
                    Assert.True(missingTraces.Count == 0,
                                string.Format("These expected traces were missing:{0}    {1}",
                                              Environment.NewLine, string.Join(Environment.NewLine + "    ", missingTraces)));

                    IList <string> unexpectedTraces = UnexpectedTraces(ExpectedTraceRecords, traceWriter.Records);
                    Assert.True(unexpectedTraces.Count == 0,
                                string.Format("These traces were not expected:{0}    {1}",
                                              Environment.NewLine, string.Join(Environment.NewLine + "    ", unexpectedTraces)));
                }
            }
        }
        public void MemoryTraceWriterTest()
        {
            #region MemoryTraceWriterExample
            Staff staff = new Staff();
            staff.Name  = "Arnie Admin";
            staff.Roles = new List <string> {
                "Administrator"
            };
            staff.StartDate = DateTime.Now;

            ITraceWriter traceWriter = new MemoryTraceWriter();

            JsonConvert.SerializeObject(
                staff,
                new JsonSerializerSettings {
                TraceWriter = traceWriter, Converters = { new JavaScriptDateTimeConverter() }
            });

            Console.WriteLine(traceWriter);
            // 2012-11-11T12:08:42.761 Info Started serializing Newtonsoft.Json.Tests.Serialization.Staff. Path ''.
            // 2012-11-11T12:08:42.785 Info Started serializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter. Path 'StartDate'.
            // 2012-11-11T12:08:42.791 Info Finished serializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter. Path 'StartDate'.
            // 2012-11-11T12:08:42.797 Info Started serializing System.Collections.Generic.List`1[System.String]. Path 'Roles'.
            // 2012-11-11T12:08:42.798 Info Finished serializing System.Collections.Generic.List`1[System.String]. Path 'Roles'.
            // 2012-11-11T12:08:42.799 Info Finished serializing Newtonsoft.Json.Tests.Serialization.Staff. Path ''.
            #endregion

            MemoryTraceWriter memoryTraceWriter = (MemoryTraceWriter)traceWriter;

            Assert.AreEqual(743, memoryTraceWriter.ToString().Length);
            Assert.AreEqual(6, memoryTraceWriter.GetTraceMessages().Count());
        }
Esempio n. 13
0
        public static T Deserialize <T>(string json)
        {
            ITraceWriter traceWriter = new MemoryTraceWriter();

            return(JsonConvert.DeserializeObject <T>(json, new JsonSerializerSettings {
                TraceWriter = traceWriter
            }));
        }
Esempio n. 14
0
        /// <summary>
        ///     Saves the settingsObjects provided out to disk, if possible.
        /// </summary>
        /// <typeparam name="TSettings">The settings object type to be saved</typeparam>
        /// <param name="instance">Any serializable object</param>
        /// <param name="fileExistsAlready">Lets the user know if the settings file was overwritten</param>
        /// <param name="nameMarker">
        ///     Additional filename specifier for the case where many of the same types of settings are used
        ///     for the same instance in the same class
        /// </param>
        /// <param name="overwrite">If the file already exists, must be true to persist the current settings.</param>
        /// <returns>True if successful, false if not</returns>
        public static bool Save <TSettings>(TSettings instance, out bool fileExistsAlready, string nameMarker = null, bool overwrite = true)
            where TSettings : class, ISettingsBase
        {
            Contract.Requires(typeof(TSettings).IsSerializable);
            Contract.Requires(instance != null);
            fileExistsAlready = false;
            if (Globals.NoPersistence)
            {
                return(false);
            }

            try
            {
                // get the filename
                var fileName = BuildFileName <TSettings>(nameMarker);
                fileExistsAlready = File.Exists(fileName);
                if (fileExistsAlready && !overwrite)
                {
                    return(false);
                }

                if (fileExistsAlready)
                {
                    try
                    {
                        File.Delete(fileName);
                    }
                    catch (Exception)
                    {
                        return(false);
                    }
                }
                else
                {
                    if (!Directory.Exists(Path.GetDirectoryName(fileName)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(fileName));
                    }
                }

                var memoryTraceWriter = new MemoryTraceWriter();
                var json = JsonConvert.SerializeObject(instance, Formatting.Indented,
                                                       new JsonSerializerSettings
                {
                    TraceWriter      = memoryTraceWriter,
                    TypeNameHandling = TypeNameHandling.Auto,
                    TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple,
                    PreserveReferencesHandling     = PreserveReferencesHandling.All
                });
                File.WriteAllText(fileName, json);

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Esempio n. 15
0
        static public T Deserialize <T>(string serialized, ResponseType response_type) where T : class
        {
            ITraceWriter           traceWriter;
            JsonSerializerSettings settings;
            XmlDocument            doc;
            string json;
            T      result;

            try {
#if DEBUG
                traceWriter = new MemoryTraceWriter();
#else
                traceWriter = null;
#endif
                result   = null;
                json     = null;
                settings = null;
                switch (response_type)
                {
                case ResponseType.XML:
                    doc = new XmlDocument();
                    doc.LoadXml(serialized);
                    json = JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.None, true);
                    break;

                case ResponseType.JSON:
                    json = serialized;
                    break;
                }

                if (!string.IsNullOrEmpty(json))
                {
                    if (traceWriter != null)
                    {
                        settings             = new JsonSerializerSettings();
                        settings.TraceWriter = traceWriter;
                        settings.Error       = (sender, args) => {
                            if (System.Diagnostics.Debugger.IsAttached)
                            {
                                System.Diagnostics.Debugger.Break();
                            }
                        };
                    }
                }

                if (settings != null)
                {
                    result = JsonConvert.DeserializeObject <T>(json, settings);
                }
                else
                {
                    result = JsonConvert.DeserializeObject <T>(json);
                }
                return(result);
            } catch {
                return(null);
            }
        }
Esempio n. 16
0
        /// <summary>
        /// 日志
        /// </summary>
        /// <param name="dynamic"></param>
        /// <returns></returns>
        public static string Log(dynamic dynamic)
        {
            MemoryTraceWriter traceWriter = new MemoryTraceWriter();

            JsonConvert.SerializeObject(dynamic, Formatting.Indented, new JsonSerializerSettings {
                TraceWriter = traceWriter
            });
            return(traceWriter.ToString());
        }
Esempio n. 17
0
        public static void Register(HttpConfiguration config)
        {
            // This code registers the In-memory trace writer using
            // a memory-based store.  To view what is in the store
            // browse to the app's root URL + "/Trace"

            ITraceWriter traceWriter = new MemoryTraceWriter(MemoryTraceStore.Instance);
            config.Services.Replace(typeof(ITraceWriter), traceWriter);
        }
Esempio n. 18
0
        public static void Register(HttpConfiguration config)
        {
            // This code registers the In-memory trace writer using
            // a memory-based store.  To view what is in the store
            // browse to the app's root URL + "/Trace"

            ITraceWriter traceWriter = new MemoryTraceWriter(MemoryTraceStore.Instance);

            config.Services.Replace(typeof(ITraceWriter), traceWriter);
        }
Esempio n. 19
0
 static ModelExtensions()
 {
     _tracer     = new MemoryTraceWriter();
     _serializer = JsonSerializer.CreateDefault(new JsonSerializerSettings
     {
         ContractResolver = new CamelCasePropertyNamesContractResolver(),
         TraceWriter      = _tracer
     });
     _serializer.Error += (sender, args) => Logger.Debug("Deserialization error: " + args.ToString());
 }
Esempio n. 20
0
        public static T Load <T>(string json)
        {
            var trace = new MemoryTraceWriter();

            return(JsonConvert.DeserializeObject <T>(json, new JsonSerializerSettings()
            {
                TraceWriter = trace,
                TypeNameHandling = TypeNameHandling.Auto,
                Formatting = Formatting.Indented
            }));
        }
Esempio n. 21
0
        private async void ProcessModelResponse(IModelMessagingService sender, object message)
        {
            ITraceWriter traceWriter        = new MemoryTraceWriter();
            var          analyticsFromModel = JsonConvert.DeserializeObject <StaticInfo>((string)message, new JsonSerializerSettings {
                TraceWriter = traceWriter
            });

            foreach (GenreInfo genreInfo in analyticsFromModel.GenresInfo)
            {
                var regionsInfo = JsonConvert.SerializeObject(genreInfo.RegionsInfo);
                await _redisAccessService.SetAsync(genreInfo.Genre, regionsInfo);
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Deserialize a valid json string into it object type
        /// </summary>
        /// <typeparam name="T">Type of object to serialize</typeparam>
        /// <param name="json">Json string representing the object</param>
        /// <returns>Object of the type specified</returns>
        public static T?FromJson <T>(this string json)
        {
            ITraceWriter traceWriter = new MemoryTraceWriter();
            var          settings    = GetSettings();

            settings.TraceWriter = traceWriter;

            var data = JsonConvert.DeserializeObject <T>(json, settings);

            Debug.WriteLine(traceWriter);

            return(data);
        }
Esempio n. 23
0
        public static T Deserialize <T>(string json, bool debug)
        {
            var tw = new MemoryTraceWriter();

            if (debug)
            {
                var result = JsonConvert.DeserializeObject <T>(json, new JsonSerializerSettings {
                    TraceWriter = tw
                });
                Console.WriteLine(tw);
                return(result);
            }
            return(JsonConvert.DeserializeObject <T>(json));
        }
Esempio n. 24
0
        private JobLogEntry ParseEntry(string line)
        {
            var writer = new MemoryTraceWriter();
            var old    = _serializerSettings.TraceWriter;

            _serializerSettings.TraceWriter = writer;
            var result = JsonConvert.DeserializeObject <JobLogEntry>(line.Trim(), _serializerSettings);

            _serializerSettings.TraceWriter = old;
            foreach (var message in writer.GetTraceMessages())
            {
                Console.WriteLine(message);
            }
            return(result);
        }
Esempio n. 25
0
        public void MemoryTraceWriterSerializeTest()
        {
            Staff staff = new Staff();

            staff.Name  = "Arnie Admin";
            staff.Roles = new List <string> {
                "Administrator"
            };
            staff.StartDate = new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc);

            ITraceWriter traceWriter = new MemoryTraceWriter();

            JsonConvert.SerializeObject(
                staff,
                new JsonSerializerSettings {
                TraceWriter = traceWriter, Converters = { new JavaScriptDateTimeConverter() }
            });

            Console.WriteLine(traceWriter);
            // 2012-11-11T12:08:42.761 Info Started serializing Newtonsoft.Json.Tests.Serialization.Staff. Path ''.
            // 2012-11-11T12:08:42.785 Info Started serializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter. Path 'StartDate'.
            // 2012-11-11T12:08:42.791 Info Finished serializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter. Path 'StartDate'.
            // 2012-11-11T12:08:42.797 Info Started serializing System.Collections.Generic.List`1[System.String]. Path 'Roles'.
            // 2012-11-11T12:08:42.798 Info Finished serializing System.Collections.Generic.List`1[System.String]. Path 'Roles'.
            // 2012-11-11T12:08:42.799 Info Finished serializing Newtonsoft.Json.Tests.Serialization.Staff. Path ''.

            MemoryTraceWriter memoryTraceWriter = (MemoryTraceWriter)traceWriter;
            string            output            = memoryTraceWriter.ToString();

            Assert.AreEqual(916, output.Length);
            Assert.AreEqual(7, memoryTraceWriter.GetTraceMessages().Count());

            string json = @"Serialized JSON: 
{
  ""Name"": ""Arnie Admin"",
  ""StartDate"": new Date(
    976623132000
  ),
  ""Roles"": [
    ""Administrator""
  ]
}";

            json   = StringAssert.Normalize(json);
            output = StringAssert.Normalize(output);

            Assert.IsTrue(output.Contains(json));
        }
Esempio n. 26
0
        public void Test()
        {
            string            json        = "{'Value':'hi'}";
            MemoryTraceWriter traceWriter = new MemoryTraceWriter {
                LevelFilter = TraceLevel.Info
            };
            PrivateSetterTestClass o = JsonConvert.DeserializeObject <PrivateSetterTestClass>(json, new JsonSerializerSettings
            {
                TraceWriter = traceWriter
            });
            List <string> messages = traceWriter.GetTraceMessages().ToList();

            bool hasMessage = messages.Any(message => message.Contains("Info Unable to deserialize value to non-writable property 'Value' on Newtonsoft.Json.Tests.Issues.Issue0573+PrivateSetterTestClass. Path 'Value', line 1, position 13."));

            Assert.IsTrue(hasMessage);
        }
Esempio n. 27
0
        public void MemoryTraceWriterLimitTest()
        {
            MemoryTraceWriter traceWriter = new MemoryTraceWriter();

            for (int i = 0; i < 1005; i++)
            {
                traceWriter.Trace(TraceLevel.Verbose, (i + 1).ToString(CultureInfo.InvariantCulture), null);
            }

            IList <string> traceMessages = traceWriter.GetTraceMessages().ToList();

            Assert.AreEqual(1000, traceMessages.Count);

            Assert.IsTrue(traceMessages.First().EndsWith(" 6"));
            Assert.IsTrue(traceMessages.Last().EndsWith(" 1005"));
        }
 public T Deserialize <T>(IRestResponse response)
 {
     try
     {
         ITraceWriter traceWriter  = new MemoryTraceWriter();
         var          deserialized = JsonConvert.DeserializeObject <T>(response.Content, new JsonSerializerSettings {
             TraceWriter = traceWriter
         });
         Console.WriteLine(traceWriter);
         return(deserialized);
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         return(default(T));
     }
 }
Esempio n. 29
0
        public void MemoryTraceWriterTest()
        {
            #region MemoryTraceWriterExample
            Staff staff = new Staff();
            staff.Name  = "Arnie Admin";
            staff.Roles = new List <string> {
                "Administrator"
            };
            staff.StartDate = new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc);

            ITraceWriter traceWriter = new MemoryTraceWriter();

            JsonConvert.SerializeObject(
                staff,
                new JsonSerializerSettings
            {
                TraceWriter = traceWriter,
                Converters  = { new JavaScriptDateTimeConverter() }
            }
                );

            Console.WriteLine(traceWriter);
            // 2012-11-11T12:08:42.761 Info Started serializing Newtonsoft.Json.Tests.Serialization.Staff. Path ''.
            // 2012-11-11T12:08:42.785 Info Started serializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter. Path 'StartDate'.
            // 2012-11-11T12:08:42.791 Info Finished serializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter. Path 'StartDate'.
            // 2012-11-11T12:08:42.797 Info Started serializing System.Collections.Generic.List`1[System.String]. Path 'Roles'.
            // 2012-11-11T12:08:42.798 Info Finished serializing System.Collections.Generic.List`1[System.String]. Path 'Roles'.
            // 2012-11-11T12:08:42.799 Info Finished serializing Newtonsoft.Json.Tests.Serialization.Staff. Path ''.
            // 2013-05-18T21:38:11.255 Verbose Serialized JSON:
            // {
            //   "Name": "Arnie Admin",
            //   "StartDate": new Date(
            //     976623132000
            //   ),
            //   "Roles": [
            //     "Administrator"
            //   ]
            // }
            #endregion

            MemoryTraceWriter memoryTraceWriter = (MemoryTraceWriter)traceWriter;

            Assert.AreEqual(916, memoryTraceWriter.ToString().Length);
            Assert.AreEqual(7, memoryTraceWriter.GetTraceMessages().Count());
        }
Esempio n. 30
0
        private string Serialize(Foo1 f)
        {
            //Code copied from JsonConvert.SerializeObject(), with addition of trace writing
            JsonSerializer jsonSerializer = JsonSerializer.CreateDefault();
            var            traceWriter    = new MemoryTraceWriter();

            jsonSerializer.TraceWriter = traceWriter;

            StringBuilder sb = new StringBuilder(256);
            StringWriter  sw = new StringWriter(sb, CultureInfo.InvariantCulture);

            using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
            {
                jsonWriter.Formatting = Formatting.None;
                jsonSerializer.Serialize(jsonWriter, f, typeof(Foo1));
            }

            return(sw.ToString());
        }
Esempio n. 31
0
        public void JsonTest()
        {
            dynamic o = new NullableDynamicObject();

            o.Magic = 100;
            var memoryTraceWriter      = new MemoryTraceWriter();
            var jsonSerializerSettings = new JsonSerializerSettings
            {
                TraceWriter = memoryTraceWriter
            };
            NullableDynamicObject dynamicObject = o as NullableDynamicObject;

            Assert.NotNull(dynamicObject);

            string  json = JsonConvert.SerializeObject(dynamicObject, jsonSerializerSettings);
            dynamic n    = JsonConvert.DeserializeObject <NullableDynamicObject>(json, jsonSerializerSettings);

            _output.WriteLine(memoryTraceWriter.ToString());
            Assert.Equal((int)n.Magic, (int)o.Magic);
        }