Exemplo n.º 1
0
        public static void Serialize(object target, bool prettyPrint, System.IO.TextWriter pOutput, string callback)
        {
            Newtonsoft.Json.JsonSerializer ser = new Newtonsoft.Json.JsonSerializer();

            ser.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
            ser.Formatting         = prettyPrint ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None;
            ser.NullValueHandling  = Newtonsoft.Json.NullValueHandling.Ignore;


            if (string.IsNullOrEmpty(callback))
            {
                ser.Serialize(pOutput, target);
                return;
            }

            // typeof foobar != 'undefined' ? foobar(bla) : alert('Callback-Funktion "foobar" undefiniert...');
            pOutput.Write("typeof ");
            pOutput.Write(callback);
            pOutput.Write(" != 'undefined' ? ");
            pOutput.Write(callback);
            pOutput.Write("(");
            ser.Serialize(pOutput, target);
            pOutput.Write(")");
            pOutput.Write(" : alert('Callback-Funktion \"");
            pOutput.Write(callback);
            pOutput.Write("\" undefiniert...');");
        }
Exemplo n.º 2
0
        protected Task Serialize(Dictionary <string, object> parameters, bool wrapped, bool ordered)
        {
            var serializer = new Newtonsoft.Json.JsonSerializer();

            if (ordered)
            {
                serializer.ContractResolver = new OrderedContractResolver();
            }
            serializer.Converters.Add(new SDTConverter());
            TextWriter ms = new StringWriter();

            if (parameters.Count == 1 && !wrapped)             //In Dataproviders, with one parameter BodyStyle is WebMessageBodyStyle.Bare, Both requests and responses are not wrapped.
            {
                string key = parameters.First().Key;
                using (var writer = new Newtonsoft.Json.JsonTextWriter(ms))
                {
                    serializer.Serialize(writer, parameters[key]);
                }
            }
            else
            {
                using (var writer = new Newtonsoft.Json.JsonTextWriter(ms))
                {
                    serializer.Serialize(writer, parameters);
                }
            }
            _httpContext.Response.Write(ms.ToString());             // Use intermediate StringWriter in order to avoid chunked response
            return(Task.CompletedTask);
        }
Exemplo n.º 3
0
        public void Save()
        {
            List <WebcamFullScreen> wfs    = new List <WebcamFullScreen>();
            List <VUMeter>          meters = new List <VUMeter>();

            foreach (Job j in toProcess)
            {
                if (j.GetType() == typeof(WebcamFullScreen))
                {
                    wfs.Add((WebcamFullScreen)j);
                }
                if (j.GetType() == typeof(VUMeter))
                {
                    meters.Add((VUMeter)j);
                }
            }
            Newtonsoft.Json.JsonSerializer s = new Newtonsoft.Json.JsonSerializer();
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter("settingswebcam.txt"))

                using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
                {
                    s.Serialize(writer, wfs);
                    // {"ExpiryDate":new Date(1230375600000),"Price":0}
                }
            using (System.IO.StreamWriter sw2 = new System.IO.StreamWriter("settingsvumeter.txt"))
                using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw2))
                {
                    s.Serialize(writer, meters);
                    // {"ExpiryDate":new Date(1230375600000),"Price":0}
                }
        }
        static void Main(string[] args)
        {
            Write("Input format of serialization (json/xml/binary):");
            string serializationFormat = ReadLine();

            using (DbNorthwind db = new DbNorthwind()){
                List <Category> categories = db.Categories.ToList();
                List <Product>  products   = db.Products.ToList();
                switch (serializationFormat)
                {
                case ("json"):
                    Newtonsoft.Json.JsonSerializer jsonSerializer = new Newtonsoft.Json.JsonSerializer();
                    using (StreamWriter file = File.CreateText("Categories.json"))
                    {
                        jsonSerializer.Serialize(file, categories);
                    }
                    using (StreamWriter file = File.CreateText("Products.json"))
                    {
                        jsonSerializer.Serialize(file, products);
                    }
                    break;

                case ("xml"):
                    XmlSerializer xmlSerializerCategories = new XmlSerializer(typeof(List <Category>));
                    XmlSerializer xmlSerializerProducts   = new XmlSerializer(typeof(List <Product>));
                    using (FileStream file = File.Create("Categories.xml"))
                    {
                        xmlSerializerCategories.Serialize(file, categories);
                    }
                    using (FileStream file = File.Create("Products.xml"))
                    {
                        xmlSerializerProducts.Serialize(file, products);
                    }
                    break;

                case ("binary"):
                    BinaryFormatter binarySerializer = new BinaryFormatter();
                    using (FileStream file = File.Create("Categories.dat"))
                    {
                        binarySerializer.Serialize(file, categories);
                    }
                    using (FileStream file = File.Create("Products.dat"))
                    {
                        binarySerializer.Serialize(file, products);
                    }
                    break;

                default:
                    WriteLine("Unknown format of serialization");
                    break;
                }
            }
        }
Exemplo n.º 5
0
        public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object untypedValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            if (untypedValue == null)
            {
                serializer.Serialize(writer, null);
                return;
            }
            var value = (long)untypedValue;

            serializer.Serialize(writer, value.ToString());
            return;
        }
Exemplo n.º 6
0
        public void NewtonsoftJsonSerializeDeserializeBenchmark()
        {
            var serializer = new Newtonsoft.Json.JsonSerializer()
            {
                DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore,
                NullValueHandling    = Newtonsoft.Json.NullValueHandling.Ignore,
            };

            int      runs = 50000;
            DateTime start, stop;

            MessageModel msg = null;

            start = DateTime.UtcNow;
            for (int i = 0; i < runs; i++)
            {
                var writer = new StringWriter();
                serializer.Serialize(writer, SimpleMessage);
                var reader     = new StringReader(writer.ToString());
                var jsonReader = new Newtonsoft.Json.JsonTextReader(reader);
                var dtoMsg     = serializer.Deserialize <MessageDtoModelV1>(jsonReader);
            }
            stop = DateTime.UtcNow;
            Assert.AreEqual(ComplexMessage, msg);
            var total = (stop - start).TotalMilliseconds;

            Console.WriteLine(
                "NewtonsoftJsonSerialize+Deserialize(Simple): avg: {0:0.00} ms runs: {1} took: {2:0.00} ms",
                total / runs,
                runs,
                total
                );

            start = DateTime.UtcNow;
            for (int i = 0; i < runs; i++)
            {
                var writer = new StringWriter();
                serializer.Serialize(writer, ComplexMessage);
                var reader     = new StringReader(writer.ToString());
                var jsonReader = new Newtonsoft.Json.JsonTextReader(reader);
                var dtoMsg     = serializer.Deserialize <MessageDtoModelV1>(jsonReader);
            }
            stop = DateTime.UtcNow;
            Assert.AreEqual(ComplexMessage, msg);
            total = (stop - start).TotalMilliseconds;
            Console.WriteLine(
                "NewtonsoftJsonSerialize+Deserialize(ComplexMessage): avg: {0:0.00} ms runs: {1} took: {2:0.00} ms",
                total / runs,
                runs,
                total
                );
        }
Exemplo n.º 7
0
            public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
            {
                var hasValue = (bool)value.GetType().GetProperty(nameof(Maybe <object> .HasValue)).GetValue(value);

                if (hasValue)
                {
                    var underlyingValue = value.GetType().GetProperty(nameof(Maybe <object> .Value)).GetValue(value);
                    serializer.Serialize(writer, underlyingValue);
                }
                else
                {
                    serializer.Serialize(writer, null);
                }
            }
Exemplo n.º 8
0
        public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
        {
            byte[] body;
            Newtonsoft.Json.JsonSerializer serializer = endpoint.NewtonsoftSettings().JsonSerializer;

            using (MemoryStream ms = new MemoryStream())
            {
                using (StreamWriter sw = new StreamWriter(ms, Encoding.UTF8))
                {
                    using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
                    {
                        if (parameters.Length == 1)
                        {
                            // Single parameter, assuming bare
                            serializer.Serialize(sw, parameters[0]);
                        }
                        else
                        {
                            writer.WriteStartObject();
                            for (int i = 0; i < this.operation.Messages[0].Body.Parts.Count; i++)
                            {
                                writer.WritePropertyName(this.operation.Messages[0].Body.Parts[i].Name);
                                serializer.Serialize(writer, parameters[i]);
                            }

                            writer.WriteEndObject();
                        }

                        writer.Flush();
                        sw.Flush();
                        body = ms.ToArray();
                    }
                }
            }
            if (traceSource.Switch.ShouldTrace(TraceEventType.Information))
            {
                traceSource.TraceEvent(TraceEventType.Information, 1004, System.Text.Encoding.UTF8.GetString(body));
            }

            Message requestMessage = Message.CreateMessage(messageVersion, operation.Messages[0].Action, new RawBodyWriter(body));

            requestMessage.Headers.To = operationUri;
            requestMessage.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Raw));
            HttpRequestMessageProperty reqProp = new HttpRequestMessageProperty();

            reqProp.Headers[HttpRequestHeader.ContentType] = "application/json";
            requestMessage.Properties.Add(HttpRequestMessageProperty.Name, reqProp);
            return(requestMessage);
        }
        public void Serialize(Stream outputStream, object data, Type type = null)
        {
            var formatter = new Newtonsoft.Json.JsonSerializer();

            using (var writer = new StreamWriter(outputStream, Utf8WithoutBom, _streamBuffer, true))
                formatter.Serialize(writer, data);
        }
Exemplo n.º 10
0
        public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
        {
            var exception = value as System.Exception;

            if (exception != null)
            {
                var resolver = serializer.ContractResolver as Newtonsoft.Json.Serialization.DefaultContractResolver ?? _defaultContractResolver;

                var jObject = new Newtonsoft.Json.Linq.JObject();
                jObject.Add(resolver.GetResolvedPropertyName("discriminator"), exception.GetType().Name);
                jObject.Add(resolver.GetResolvedPropertyName("Message"), exception.Message);
                jObject.Add(resolver.GetResolvedPropertyName("StackTrace"), _hideStackTrace ? "HIDDEN" : exception.StackTrace);
                jObject.Add(resolver.GetResolvedPropertyName("Source"), exception.Source);
                jObject.Add(resolver.GetResolvedPropertyName("InnerException"),
                            exception.InnerException != null ? Newtonsoft.Json.Linq.JToken.FromObject(exception.InnerException, serializer) : null);

                foreach (var property in GetExceptionProperties(value.GetType()))
                {
                    var propertyValue = property.Key.GetValue(exception);
                    if (propertyValue != null)
                    {
                        jObject.AddFirst(new Newtonsoft.Json.Linq.JProperty(resolver.GetResolvedPropertyName(property.Value),
                                                                            Newtonsoft.Json.Linq.JToken.FromObject(propertyValue, serializer)));
                    }
                }

                value = jObject;
            }

            serializer.Serialize(writer, value);
        }
        public async Task <bool> TriggerBuzzer()
        {
            HttpClient httpClient = new HttpClient();

            Newtonsoft.Json.JsonSerializer jser = new Newtonsoft.Json.JsonSerializer();

            httpClient.BaseAddress = new Uri("https://ptnetsuite.a2asmartcity.io/");

            System.IO.StringWriter stringWriter = new System.IO.StringWriter();

            MqttMessage triggerBuzzerMex = new MqttMessage(1, 0);

            jser.Serialize(stringWriter, triggerBuzzerMex);

            StringContent authContent = new StringContent(stringWriter.ToString(), Encoding.UTF8, "application/json");

            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken.accessToken);

            HttpResponseMessage resp = await httpClient.PostAsync($"/api/mqtt/v1/users/{username}/apps/{appid}/devices/{deveui}/downlink", authContent);

            string respBody = await resp.Content.ReadAsStringAsync();


            if (resp.IsSuccessStatusCode)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemplo n.º 12
0
        public static string SerializeToContent(object obj)
        {
            Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
            serializer.Converters.Add(new Newtonsoft.Json.Converters.JavaScriptDateTimeConverter());
            serializer.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
            serializer.TypeNameHandling  = Newtonsoft.Json.TypeNameHandling.Auto;
            Stream objectStream;

            using (objectStream = new MemoryStream())
            {
                using (StreamWriter writter = new StreamWriter(objectStream, Encoding))
                {
                    using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(writter))
                    {
                        serializer.Serialize(writer, obj);

                        objectStream.Seek(0, SeekOrigin.Begin);
                    }
                }
            }

            using (StreamReader sr = new StreamReader(objectStream))
            {
                return(sr.ReadToEnd());
            }
        }
Exemplo n.º 13
0
        public void GuardarJson(string A)
        {
            string path;
            string pathJ;

            path  = @"~/App_Data/ " + A + ".txt";
            pathJ = @"~/App_Data/ " + A + ".txt";
            string root = @"~/App_Data/ ";

            if (!Directory.Exists(root))
            {
                Directory.CreateDirectory(root);
            }
            if (!System.IO.File.Exists(path))
            {
                using (FileStream strm = System.IO.File.Create(path))
                    using (StreamWriter sw = new StreamWriter(strm))
                    {
                        sw.WriteLine("No_Info");
                        sw.Close();
                    }
            }
            using (StreamWriter file = System.IO.File.CreateText(@"C:\LAB3\" + A + ".txt"))
            {
                Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
                serializer.Serialize(file, mostrar);
            }
        }
Exemplo n.º 14
0
 public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
 {
     if (value is KeyValueObject)
     {
         serializer.Serialize(writer, value?.ToString());
     }
 }
Exemplo n.º 15
0
        public static void NewLocalData(string dataDirectory)
        {
            var      file     = new System.IO.DirectoryInfo(dataDirectory).GetFiles(PatchLauncher.DATAINFOFILENAME).FirstOrDefault();
            DataInfo dataInfo = default;

            if (file is null)
            {
                dataInfo = new DataInfo {
                    DataVersion = DefaultLocalDataVersion
                };
            }
            else
            {
                using (var streamReader = new System.IO.StreamReader(file.FullName))
                    using (var jsonTxtReader = new Newtonsoft.Json.JsonTextReader(streamReader))
                    {
                        var jser = new Newtonsoft.Json.JsonSerializer();
                        dataInfo             = jser.Deserialize <DataInfo>(jsonTxtReader);
                        dataInfo.DataVersion = DefaultLocalDataVersion;
                    }
                file.Delete();
            }
            using (var stream = System.IO.File.OpenWrite(System.IO.Path.Combine(dataDirectory, PatchLauncher.DATAINFOFILENAME)))
                using (var streamWriter = new System.IO.StreamWriter(stream))
                    using (var jsonTxtWriter = new Newtonsoft.Json.JsonTextWriter(streamWriter))
                    {
                        var jser = new Newtonsoft.Json.JsonSerializer();
                        jser.Serialize(jsonTxtWriter, dataInfo);
                    }
        }
Exemplo n.º 16
0
            public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
            {
                var fi      = value as FieldInfo;
                var pi      = value as PropertyInfo;
                var details = new
                {
                    Name =
                        fi != null ? fi.Name :
                        pi != null ? pi.Name :
                        null,
                    MemberType =
                        fi != null ? fi.FieldType :
                        pi != null ? pi.PropertyType :
                        null,
                };

                if (details.Name != null)
                {
                    serializer.Serialize(writer, details);
                }
                else
                {
                    writer.WriteNull();
                }
            }
Exemplo n.º 17
0
        public IHttpActionResult Get(string format = "yaml")
        {
            var         stream = this.GetType().Assembly.GetManifestResourceStream("ConferenceWebApi.OpenApi2.yaml");
            HttpContent responseContent;

            if (format == "json" || this.Request.Headers.Accept.Contains(new MediaTypeWithQualityHeaderValue("application/json")))
            {
                var serializer = new Serializer(new SerializerSettings()
                {
                    EmitJsonComptible = true
                });
                var yamlObject = serializer.Deserialize(stream);

                var buffer      = new StringBuilder();
                var jserializer = new Newtonsoft.Json.JsonSerializer();
                jserializer.Serialize(new StringWriter(buffer), yamlObject);
                responseContent = new StringContent(buffer.ToString());
                responseContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            }
            else
            {
                responseContent = new StreamContent(stream);
                responseContent.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
            }


            return(new OkResult(Request)
                   .WithContent(responseContent));
        }
Exemplo n.º 18
0
        // convert string/file to YAML object
        public static void Test()
        {
            using (System.IO.FileStream fs = System.IO.File.OpenRead(@"d:\username\Documents\Visual Studio 2017\Projects\BlueMine\BlueMine\Code\en.yml"))
            {
                //using (System.IO.TextReader r = new System.IO.StringReader(@""))
                using (System.IO.TextReader r = new System.IO.StreamReader(fs, System.Text.Encoding.UTF8))
                {
                    YamlDotNet.Serialization.Deserializer deserializer =
                        new YamlDotNet.Serialization.Deserializer();

                    object yamlObject = deserializer.Deserialize(r);

                    Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
                    serializer.Formatting = Newtonsoft.Json.Formatting.Indented;

                    // serializer.Serialize(Console.Out, yamlObject);

                    using (System.IO.Stream ws = System.IO.File.OpenWrite(@"d:\username\Documents\Visual Studio 2017\Projects\BlueMine\BlueMine\Code\en.json"))
                    {
                        using (System.IO.TextWriter sw = new System.IO.StreamWriter(ws, System.Text.Encoding.UTF8))
                        {
                            serializer.Serialize(sw, yamlObject);
                        } // End using sw
                    }     // End Using ws
                }         // End Using r
            }             // End Using fr
        }                 // End Sub Test
Exemplo n.º 19
0
        private string ConvertJsonString(string str)
        {
            //格式化json字符串
            Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
            TextReader tr = new StringReader(str);

            Newtonsoft.Json.JsonTextReader jtr = new Newtonsoft.Json.JsonTextReader(tr);
            object obj = serializer.Deserialize(jtr);

            if (obj != null)
            {
                StringWriter textWriter = new StringWriter();
                Newtonsoft.Json.JsonTextWriter jsonWriter = new Newtonsoft.Json.JsonTextWriter(textWriter)
                {
                    Formatting  = Newtonsoft.Json.Formatting.Indented,
                    Indentation = 4,
                    IndentChar  = ' '
                };
                serializer.Serialize(jsonWriter, obj);
                return(textWriter.ToString());
            }
            else
            {
                return(str);
            }
        }
Exemplo n.º 20
0
        public void TestSerialization()
        {
            // Arrange.
            Student expected = new Student("Vsevolod", Faculty.CS, 4);

            // Act.
            using (Newtonsoft.Json.JsonTextWriter fs = new Newtonsoft.Json.JsonTextWriter(new StreamWriter(JSON_TEST_FILE)))
            {
                Newtonsoft.Json.JsonSerializer jsonSerializer = new Newtonsoft.Json.JsonSerializer();
                jsonSerializer.Serialize(fs, expected);
            }

            // Assert.
            Student actual;

            using (StreamReader file = File.OpenText(JSON_TEST_FILE))
            {
                Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
                actual = (Student)serializer.Deserialize(file, typeof(Student));
            }

            Assert.AreEqual(expected.Name, actual.Name, "Actual name is incorrect");
            Assert.AreEqual(expected.Faculty, actual.Faculty, "Faculty is incorrect");
            Assert.AreEqual(expected.Mark, actual.Mark, "Mark is incorrect");
        }
Exemplo n.º 21
0
        /// <summary>
        /// Saves an object to a json-file.
        /// </summary>
        public static bool SaveJsonFile(string filePath, object data, out string errorMessage, Newtonsoft.Json.JsonConverter converter = null)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                errorMessage = "File path is empty.\nCouldn't be saved.";
                return(false);
            }

            errorMessage = null;
            try
            {
                using (StreamWriter sw = File.CreateText(filePath))
                {
                    var ser = new Newtonsoft.Json.JsonSerializer();
                    if (converter != null)
                    {
                        ser.Converters.Add(converter);
                    }
                    ser.Serialize(sw, data);
                }
                return(true);
            }
            catch (SerializationException ex)
            {
                errorMessage = $"File\n{Path.GetFullPath(filePath)}\ncouldn't be saved.\nError message:\n\n" + ex.Message;
            }
            return(false);
        }
        static unsafe void GetBoth <T>(LowWriter <T> lw, T s, out IEnumerable <byte> newtonsoft, out IEnumerable <byte> unsafeJson, int?minBuffer = null)
        {
            var ms = new MemoryStream();
            int len;

            using (var writer = new StreamWriter(ms, _utf8))
            {
                _serializer.Serialize(writer, s, typeof(string));
                writer.Flush();
                len = (int)ms.Position;
            }
            newtonsoft = ms.GetBuffer().Take(len);

            if (minBuffer.HasValue && minBuffer.Value > len)
            {
                len = minBuffer.Value;
            }
            var mine = new byte[len];

            fixed(byte *bs = mine)
            {
                var result = lw.Invoke(s, bs, len);

                unsafeJson = result < 0 ? null : mine.Take(result);
            }
        }
 public void Serialize(System.IO.Stream stream, object obj)
 {
     using (var sw = new StreamWriter(stream, Encoding ?? System.Text.Encoding.UTF8))
     {
         serializer.Serialize(sw, obj);
     }
 }
Exemplo n.º 24
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            HttpResponseBase response = context.HttpContext.Response;

            if (string.IsNullOrEmpty(this.ContentType))
            {
                response.ContentType = this.ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (this.ContentEncoding != null)
            {
                response.ContentEncoding = this.ContentEncoding;
            }
            if (this.Data != null)
            {
                var Serializer = new Newtonsoft.Json.JsonSerializer();
                Serializer.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                StringBuilder JsonStr = new StringBuilder();
                Serializer.Serialize(new System.IO.StringWriter(JsonStr), this.Data);
                response.Write(JsonStr);
            }
        }
        public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
        {
            byte[] body;
            Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
            using (MemoryStream ms = new MemoryStream())
            {
                using (StreamWriter sw = new StreamWriter(ms, Encoding.UTF8))
                {
                    using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
                    {
                        writer.Formatting = Newtonsoft.Json.Formatting.Indented;
                        serializer.Serialize(writer, result);
                        sw.Flush();
                        body = ms.ToArray();
                    }
                }
            }

            Message replyMessage = Message.CreateMessage(messageVersion, operation.Messages[1].Action, new RawBodyWriter(body));

            replyMessage.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Raw));
            HttpResponseMessageProperty respProp = new HttpResponseMessageProperty();

            respProp.Headers[HttpResponseHeader.ContentType] = "application/json";
            replyMessage.Properties.Add(HttpResponseMessageProperty.Name, respProp);
            return(replyMessage);
        }
Exemplo n.º 26
0
        /// <summary>
        /// 格式化json输出
        /// </summary>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static string FormatJson(this string jsonString)
        {
            try
            {
                Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
                StringReader sr  = new StringReader(jsonString);
                object       obj = serializer.Deserialize(new Newtonsoft.Json.JsonTextReader(sr));

                if (obj != null)
                {
                    StringWriter sw = new StringWriter();
                    Newtonsoft.Json.JsonWriter jsonWriter = new Newtonsoft.Json.JsonTextWriter(sw)
                    {
                        Formatting  = Newtonsoft.Json.Formatting.Indented,
                        Indentation = 4,
                        IndentChar  = ' '
                    };
                    serializer.Serialize(jsonWriter, obj);
                    return(sw.ToString());
                }
                else
                {
                    return(jsonString);
                }
            }
            catch
            {
                return(jsonString);
            }
        }
        public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
        {
            byte[] body;
            var    serializer = new Newtonsoft.Json.JsonSerializer();

            serializer.Converters.Add(new IsoDateTimeConverter()
            {
                DateTimeFormat = "yyyy-MM-ddTHH:mm:ssZ", DateTimeStyles = DateTimeStyles.AdjustToUniversal
            });

            using (var ms = new MemoryStream())
            {
                using (var sw = new StreamWriter(ms, Encoding.UTF8))
                {
                    using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
                    {
                        //writer.Formatting = Newtonsoft.Json.Formatting.Indented;
                        serializer.Serialize(writer, result);
                        sw.Flush();
                        body = ms.ToArray();
                    }
                }
            }

            var replyMessage = Message.CreateMessage(messageVersion, _operation.Messages[1].Action, new RawBodyWriter(body));

            replyMessage.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Raw));
            var respProp = new HttpResponseMessageProperty();

            respProp.Headers[HttpResponseHeader.ContentType] = "application/json";
            replyMessage.Properties.Add(HttpResponseMessageProperty.Name, respProp);
            return(replyMessage);
        }
Exemplo n.º 28
0
 /// <summary>返回格式化后json字符串</summary>
 /// <param name="str">json字符串</param>
 /// <param name="errs">发生错误则返回错误信息</param>
 /// <returns>返回格式化后json字符串</returns>
 public static string FormatJsonString(string str, ref string errs)
 {
     try
     {
         Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
         TextReader tr = new StringReader(str);
         Newtonsoft.Json.JsonTextReader jtr = new Newtonsoft.Json.JsonTextReader(tr);
         object obj = serializer.Deserialize(jtr);
         if (obj != null)
         {
             StringWriter textWriter = new StringWriter();
             Newtonsoft.Json.JsonTextWriter jsonWriter = new Newtonsoft.Json.JsonTextWriter(textWriter)
             {
                 Formatting  = Newtonsoft.Json.Formatting.Indented,
                 Indentation = 4,
                 IndentChar  = ' '
             };
             serializer.Serialize(jsonWriter, obj);
             return(textWriter.ToString());
         }
     }
     catch (Exception ex)
     {
         errs = "格式化json失败,错误信息:" + ex.Message;
     }
     return(str);
 }
        public string SerializeJsonNet(object value)
        {
            Type type = value.GetType();

            Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();

            json.NullValueHandling = NullValueHandling.Ignore;

            json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace;
            json.MissingMemberHandling  = Newtonsoft.Json.MissingMemberHandling.Ignore;
            json.ReferenceLoopHandling  = ReferenceLoopHandling.Ignore;


            StringWriter sw = new StringWriter();

            Newtonsoft.Json.JsonTextWriter writer = new JsonTextWriter(sw);

            writer.Formatting = Formatting.None;

            writer.QuoteChar = '"';
            json.Serialize(writer, value);

            string output = sw.ToString();

            writer.Close();

            return(output);
        }
Exemplo n.º 30
0
        private void SaveArchiveLastCommit(string destination, string filename, string hash)
        {
            var path     = Path.Combine(destination, filename);
            var jsonPath = path + ".json";

            if (File.Exists(path))
            {
                try
                {
                    Log.Verbose("Checking last commit hash in archive json file {0}", jsonPath);
                    using (var textReader = new StreamWriter(jsonPath, false))
                        using (var jsonReader = new Newtonsoft.Json.JsonTextWriter(textReader))
                        {
                            var serializer = new Newtonsoft.Json.JsonSerializer();
                            serializer.Serialize(jsonReader, new ArchiveInfo()
                            {
                                LastCommit = hash
                            });
                        }
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "GetArchiveLastCommit:: unable to write last commit hash to json file");
                }
            }
            else
            {
                Log.Warning("Archive file {0} is missing", path);
            }
        }
 /// <summary>
 /// Serialize the object into a byte array
 /// </summary>
 /// <param name="obj">Object to serialize</param>
 /// <returns>Byte array to send in the request body</returns>
 public byte[] Serialize(object obj)
 {
     var serializer = new Newtonsoft.Json.JsonSerializer();
     ConfigureSerializer(serializer);
     var output = new System.IO.MemoryStream();
     using (var writer = new System.IO.StreamWriter(output))
         serializer.Serialize(writer, obj);
     return output.ToArray();
 }
        public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
        {
            byte[] body;
            Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
            using (MemoryStream ms = new MemoryStream())
            {
                using (StreamWriter sw = new StreamWriter(ms, Encoding.UTF8))
                {
                    using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
                    {
                        writer.Formatting = Newtonsoft.Json.Formatting.Indented;
                        if (parameters.Length == 1)
                        {
                            // Single parameter, assuming bare
                            serializer.Serialize(sw, parameters[0]);
                        }
                        else
                        {
                            writer.WriteStartObject();
                            for (int i = 0; i < this.operation.Messages[0].Body.Parts.Count; i++)
                            {
                                writer.WritePropertyName(this.operation.Messages[0].Body.Parts[i].Name);
                                serializer.Serialize(writer, parameters[0]);
                            }

                            writer.WriteEndObject();
                        }

                        writer.Flush();
                        sw.Flush();
                        body = ms.ToArray();
                    }
                }
            }

            Message requestMessage = Message.CreateMessage(messageVersion, operation.Messages[0].Action, new RawBodyWriter(body));
            requestMessage.Headers.To = operationUri;
            requestMessage.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Raw));
            HttpRequestMessageProperty reqProp = new HttpRequestMessageProperty();
            reqProp.Headers[HttpRequestHeader.ContentType] = "application/json";
            requestMessage.Properties.Add(HttpRequestMessageProperty.Name, reqProp);
            return requestMessage;
        }
Exemplo n.º 33
0
        public void ProcessRequest(System.Web.HttpContext context)
        {
            context.Response.ContentType = "application/json";

            Newtonsoft.Json.JsonTextWriter jsonWriter = new Newtonsoft.Json.JsonTextWriter(context.Response.Output);
            Newtonsoft.Json.JsonSerializer ser = new Newtonsoft.Json.JsonSerializer();

            using (System.Data.DataTable dt = Basic_SQL.SQL.GetDataTable("SELECT COL_Hex FROM T_SYS_ApertureColorToHex ORDER BY COL_Aperture"))
            {
                jsonWriter.Formatting = Newtonsoft.Json.Formatting.Indented;
                ser.Serialize(jsonWriter, dt);
                jsonWriter.Flush();
            } // End Using dt
        }
 /// <summary>
 /// Stream an IObject to JSON
 /// </summary>
 /// <param name="stream">the stream to serialize the object to</param>
 /// <param name="o">the oject to be serialized</param>
 public void Stream( System.IO.StreamWriter stream, IObject o )
 {
     try
     {
         Newtonsoft.Json.JsonWriter jw = new Newtonsoft.Json.JsonTextWriter(stream);
         jw.Formatting = Newtonsoft.Json.Formatting.Indented;
         var js = new Newtonsoft.Json.JsonSerializer();
         js.Serialize(jw, o);
     }
     catch (Exception)
     {
         throw new NotImplementedException("Method Stream not yet implemented for objects like \"" + o.Name + "\" of class \"SimpleObject\"");
     }
 }
Exemplo n.º 35
0
 public virtual void Write(Entry e, int deep)
 {
     writer.WriteLine();
     for (int i = 0; i < deep; ++i)
         writer.Write("\t");
     var str = new StringWriter();
     var jsonSer = new Newtonsoft.Json.JsonSerializer();
     jsonSer.Serialize(str, e.Properties);
     writer.WriteLine("{{ description: '{0}', offset: {1:0.000}, duration: {2:0.000}, severity: {3}, properties: {4}, entries: [", e.Description, e.Offset, e.Duration, e.Severity, str.ToString());
     foreach (Entry s in e.Entries)
     {
         Write(s, deep + 1);
     }
     writer.WriteLine("]}}");
 }
 protected override void Send(ManagementReport report, String activityId, String agentId)
 {
     var reportJson = new Dictionary<String, Object>{
         {"ID", report.ID},
         {"SourceID", report.SourceID },
         {"DateTime", report.DateTime},
         {"State", new Dictionary<String, Object> {
                 {"Health", report.State.Health.ToString() },
                 {"Execution", report.State.Execution.ToString()},
                 {"Failures", (from f in report.State.Failures
                       select new Dictionary<String, Object> {
                            {"FailureID", f.FailureID},
                            {"SourceID", f.SourceID},
                            {"Details", f.Details}
                       }).ToArray()}
         }},
         {"Metrics", report.Metrics != null ? (from m in report.Metrics
                       select new Dictionary<String, Object> {
                            {"MetricID", m.MetricID},
                            {"SourceID", m.SourceID},
                            {"Reference", m.Reference},
                            {"Value", m.Value},
                            {"Details", m.Details},
                            {"CategoryID", m.CategoryID},
                            {"DateTime", m.DateTime }
                       }).ToArray() : null},
         {"ActivityID", activityId},
         {"AgentID", agentId},
         };
     
     var str = new StringWriter();
     var jsonSer = new Newtonsoft.Json.JsonSerializer();
     jsonSer.Serialize(str, reportJson);
     NetBrokerMessage brokerMessage = new NetBrokerMessage(str.ToString());
     this.brokerClient.Publish(brokerMessage, this.topic);
 }        
        public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
        {
            byte[] body;

            var serializer = new Newtonsoft.Json.JsonSerializer();

            using (var ms = new MemoryStream())
            {
                using (var sw = new StreamWriter(ms, Encoding.UTF8))
                {
                    using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
                    {
                        //writer.Formatting = Newtonsoft.Json.Formatting.Indented;
                        serializer.Serialize(writer, result);
                        sw.Flush();
                        body = ms.ToArray();
                    }
                }
            }

            var replyMessage = Message.CreateMessage(messageVersion, _operation.Messages[1].Action, new RawBodyWriter(body));

            replyMessage.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Raw));

            var respProp = new HttpResponseMessageProperty();

            respProp.Headers[HttpResponseHeader.ContentType] = "application/json";

            replyMessage.Properties.Add(HttpResponseMessageProperty.Name, respProp);

            return replyMessage;
        }
 public static void WriteJsonUsingNewtonsoftSerializer(object obj, TextWriter writer)
 {
     Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
     serializer.Serialize(writer, obj);
 }
Exemplo n.º 39
0
        private void SaveData(object sender, EventArgs e)
        {
            try
            {
                if (!System.IO.Directory.Exists(
                    Application.StartupPath + "/_DarkestQuirksBackup/"))
                {
                    System.IO.Directory.CreateDirectory(
                        Application.StartupPath + "/_DarkestQuirksBackup/");
                }

                if (!System.IO.File.Exists(
                    Application.StartupPath + "/_DarkestQuirksBackup/quirk_library.json"))
                {
                    System.IO.File.Move(Application.StartupPath + "/shared/quirk/quirk_library.json",
                        Application.StartupPath + "/_DarkestQuirksBackup/quirk_library.json");
                }
                else goto BACKUPS_EXIST;

                if (!System.IO.File.Exists(
                    Application.StartupPath + "/_DarkestQuirksBackup/quirks.string_table.xml"))
                {
                    System.IO.File.Move(Application.StartupPath + "/localization/quirks.string_table.xml",
                        Application.StartupPath + "/_DarkestQuirksBackup/quirks.string_table.xml");
                }
                else goto BACKUPS_EXIST;

                if (!System.IO.File.Exists(
                    Application.StartupPath + "/_DarkestQuirksBackup/dialogue.string_table.xml"))
                {
                    System.IO.File.Move(Application.StartupPath + "/localization/dialogue.string_table.xml",
                        Application.StartupPath + "/_DarkestQuirksBackup/dialogue.string_table.xml");
                }

                BACKUPS_EXIST:

                using (System.IO.FileStream fs = System.IO.File.OpenWrite(
                    Application.StartupPath + "/shared/quirk/quirk_library.json"))
                using (System.IO.StreamWriter sw =
                    new System.IO.StreamWriter(fs))
                using (Newtonsoft.Json.JsonWriter jw =
                    new Newtonsoft.Json.JsonTextWriter(sw))
                {
                    jw.Formatting = Newtonsoft.Json.Formatting.Indented;

                    Newtonsoft.Json.JsonSerializer js = new Newtonsoft.Json.JsonSerializer();

                    quirk_data.quirks = quirks.ToArray();

                    js.Serialize(jw, quirk_data);

                    jw.Close();
                }

                descriptions.Save(
                    Application.StartupPath + "/localization/quirks.string_table.xml");

                dialogue.Save(
                    Application.StartupPath + "/localization/dialogue.string_table.xml");

                MessageBox.Show("Modifications saved");
            }
            catch //(Exception ex)
            {
                //System.Diagnostics.Debug.WriteLine(ex);
            }
        }
Exemplo n.º 40
0
 // Code to execute when the application is closing (eg, user hit Back)
 // This code will not execute when the application is deactivated
 private void Application_Closing(object sender, ClosingEventArgs e)
 {
     using (var store = IsolatedStorageFile.GetUserStoreForApplication())
     using (var stream = new IsolatedStorageFileStream("data.txt",
                                                     FileMode.Create,
                                                     FileAccess.Write,
                                                     store))
     using (var writer = new StreamWriter(stream))
     {
         var serializer = new Newtonsoft.Json.JsonSerializer();
         serializer.Serialize(writer, ViewModel);
     }
 }
Exemplo n.º 41
0
 /// <summary>
 /// Creates a temporary verification file.
 /// </summary>
 /// <returns>The verification file.</returns>
 /// <param name="db">The database instance</param>
 /// <param name="stream">The stream to write to</param>
 public static void CreateVerificationFile(LocalDatabase db, System.IO.StreamWriter stream)
 {
     var s = new Newtonsoft.Json.JsonSerializer();
     s.Serialize(stream, db.GetRemoteVolumes().Cast<IRemoteVolume>().ToArray());
 }
Exemplo n.º 42
0
            private bool _SyncToDisk(Item item, List<Item> children)
            {
                try
                {
                  if (_cancelProcessing)
                  {
                return false;
                  }

                  if (String.IsNullOrEmpty(RootFolderId))
                  {
                Log.Error("Cannot sync Journal to disk - RootFolderId is blank.");
                return false;
                  }

                  MutexSyncToDisk.Wait();

                  try
                  {
                _UpdateProcessCount("_SyncToDisk", 1);

                _syncingToDisk = true;

                try
                {
                  if (_lastSyncedRootFolderId == null || _lastSyncedRootFolderId != RootFolderId)
                  {
                System.IO.File.WriteAllText(Settings.RootIdFilePath, RootFolderId);

                _lastSyncedRootFolderId = RootFolderId;
                  }

                  if (_lastLargestChangeId == null || _lastLargestChangeId != RootFolderId)
                  {
                System.IO.File.WriteAllText(Settings.LastChangeIdPath, LargestChangeId.ToString());

                _lastSyncedRootFolderId = RootFolderId;
                  }

                  string journalFilePath = Settings.GetJournalFilePath(item.File.Id + ".item");

                  using (
                System.IO.FileStream fileStream = OpenFile(journalFilePath,
                                                           System.IO.FileMode.Create,
                                                           System.IO.FileAccess.Write,
                                                           System.IO.FileShare.Write))
                  {
                using (var streamWriter = new System.IO.StreamWriter(fileStream))
                {
                  using (Newtonsoft.Json.JsonWriter jsonWriter = new Newtonsoft.Json.JsonTextWriter(streamWriter))
                  {
                    jsonWriter.Formatting = Newtonsoft.Json.Formatting.None;

                    var jsonSerializer = new Newtonsoft.Json.JsonSerializer();

                    jsonSerializer.Serialize(jsonWriter, item);
                  }
                }
                  }

                  System.IO.File.SetCreationTime(journalFilePath, DateTime.Now);

                  journalFilePath = Settings.GetJournalFilePath(item.File.Id + ".children");

                  using (
                System.IO.FileStream fileStream = OpenFile(journalFilePath,
                                                           System.IO.FileMode.Create,
                                                           System.IO.FileAccess.Write,
                                                           System.IO.FileShare.Write))
                  {
                using (var streamWriter = new System.IO.StreamWriter(fileStream))
                {
                  using (Newtonsoft.Json.JsonWriter jsonWriter = new Newtonsoft.Json.JsonTextWriter(streamWriter))
                  {
                    jsonWriter.Formatting = Newtonsoft.Json.Formatting.None;

                    var jsonSerializer = new Newtonsoft.Json.JsonSerializer();

                    jsonSerializer.Serialize(jsonWriter, children);
                  }
                }
                  }

                  System.IO.File.SetCreationTime(journalFilePath, DateTime.Now);
                }
                finally
                {
                  _syncingToDisk = false;

                  _UpdateProcessCount("_SyncToDisk", -1);
                }
                  }
                  finally
                  {
                MutexSyncToDisk.Release();
                  }

                  return true;
                }
                catch (Exception exception)
                {
                  Log.Error(exception, false);

                  return false;
                }
            }
Exemplo n.º 43
0
 public void NewtonsoftJsonSerialize()
 {
     var serializer = new Newtonsoft.Json.JsonSerializer() {
         DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore,
         NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
     };
     var writer = new StringWriter();
     serializer.Serialize(writer, ComplexMessage);
     Console.WriteLine(writer.ToString());
 }
Exemplo n.º 44
0
        public void NewtonsoftJsonSerializeDeserializeBenchmark()
        {
            var serializer = new Newtonsoft.Json.JsonSerializer() {
                DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore,
                NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
            };

            int runs = 50000;
            DateTime start, stop;

            MessageModel msg = null;
            start = DateTime.UtcNow;
            for (int i = 0; i < runs; i++) {
                var writer = new StringWriter();
                serializer.Serialize(writer, SimpleMessage);
                var reader = new StringReader(writer.ToString());
                var jsonReader = new Newtonsoft.Json.JsonTextReader(reader);
                var dtoMsg = serializer.Deserialize<MessageDtoModelV1>(jsonReader);
            }
            stop = DateTime.UtcNow;
            Assert.AreEqual(ComplexMessage, msg);
            var total = (stop - start).TotalMilliseconds;
            Console.WriteLine(
                "NewtonsoftJsonSerialize+Deserialize(Simple): avg: {0:0.00} ms runs: {1} took: {2:0.00} ms",
                total / runs,
                runs,
                total
            );

            start = DateTime.UtcNow;
            for (int i = 0; i < runs; i++) {
                var writer = new StringWriter();
                serializer.Serialize(writer, ComplexMessage);
                var reader = new StringReader(writer.ToString());
                var jsonReader = new Newtonsoft.Json.JsonTextReader(reader);
                var dtoMsg = serializer.Deserialize<MessageDtoModelV1>(jsonReader);
            }
            stop = DateTime.UtcNow;
            Assert.AreEqual(ComplexMessage, msg);
            total = (stop - start).TotalMilliseconds;
            Console.WriteLine(
                "NewtonsoftJsonSerialize+Deserialize(ComplexMessage): avg: {0:0.00} ms runs: {1} took: {2:0.00} ms",
                total / runs,
                runs,
                total
            );
        }
Exemplo n.º 45
0
 private void SerializeJsonNetBinaryBenchInner(object o, MemoryStream ms)
 {
     for (int i = 0; i < Iterations; i++)
     {
         var s = new Newtonsoft.Json.JsonSerializer();
         var w = new BsonWriter(ms);
         s.Serialize(w, o);
         Escape(w);
         w.Flush();
     }
 }
Exemplo n.º 46
0
 public string ToBson()
 {
     StringBuilder sb = new StringBuilder();
     System.IO.StringWriter sWriter = new System.IO.StringWriter(sb);
     Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sWriter);
     Newtonsoft.Json.JsonSerializer jSerial = new Newtonsoft.Json.JsonSerializer();
     writer.Formatting = Newtonsoft.Json.Formatting.None;
     Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer {
         NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
         ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore,
         ContractResolver = new Misc.BSONResolver(),
     };
     serializer.Serialize(writer, this);
     writer.Close();
     sWriter.Close();
     return sb.ToString();
 }
Exemplo n.º 47
0
 private static void SerializeJsonNet(int count)
 {
     var s2 = new Newtonsoft.Json.JsonSerializer();
     var m = new MemoryStream(8000);
     for (int i = 0; i < count; i++)
     {
         var t = new StreamWriter(m);
         s2.Serialize(t, testData);
         t.Flush();
         m.Position = 0;
     }
 }
Exemplo n.º 48
0
		private string Serialize(object body)
		{
			var jsonSerializer = new Newtonsoft.Json.JsonSerializer();
			var sb = new StringBuilder();
			using (var textWriter = new System.IO.StringWriter(sb))
			{
				using (var jsonWriter = new Newtonsoft.Json.JsonTextWriter(textWriter))
				{
					jsonSerializer.Serialize(jsonWriter, body);
				}
			}
			var result = sb.ToString();
			return result;
		}
Exemplo n.º 49
0
 private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
 {
     SaveFileDialog sfd1 = new SaveFileDialog();
     sfd1.Title = "Save DataSource";
     sfd1.Filter = "StatBot DataSource (*.statds)|*.statds";
     sfd1.DefaultExt = ".statdt";
     sfd1.InitialDirectory = Instance.study.StatBotFileLocation;
     if (sfd1.ShowDialog() == DialogResult.OK)
     {
         using (StreamWriter file = File.CreateText(sfd1.FileName))
         {
             Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
             serializer.Serialize(file, bindingSource1.DataSource);
         }
     }
 }