Example #1
0
        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var serializer = new Newtonsoft.Json.JsonSerializer();

            serializer.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
            serializer.TypeNameHandling  = Newtonsoft.Json.TypeNameHandling.Auto;
            serializer.Formatting        = Newtonsoft.Json.Formatting.Indented;

            var saveFileDialog = new SaveFileDialog();

            saveFileDialog.Filter = "MyElement | *.element";
            if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
            var filename = saveFileDialog.FileName;

            using (StreamWriter streamwriter = new StreamWriter(filename))
            {
                using (Newtonsoft.Json.JsonWriter jwriter = new Newtonsoft.Json.JsonTextWriter(streamwriter))
                {
                    serializer.Serialize(jwriter, ListElement.list);
                }
                MessageBox.Show("Сохранено");
            }
        }
Example #2
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);
                    }
        }
        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);
        }
Example #4
0
        public Message Serialize(OperationDescription operation, MessageVersion version, 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();
                    }
                }
            }
            WebOperationContext.Current.OutgoingResponse.Format = null;

            System.ServiceModel.Channels.Message replyMessage = System.ServiceModel.Channels.Message.CreateMessage(version, 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);
        }
Example #5
0
        public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
        {
            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))
                    {
                        serializer.Serialize(writer, result);
                        sw.Flush();
                        body = ms.ToArray();
                    }
                }
            }
            if (traceSource.Switch.ShouldTrace(TraceEventType.Information))
            {
                traceSource.TraceEvent(TraceEventType.Information, 1000, System.Text.Encoding.UTF8.GetString(body));
            }

            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);
        }
Example #6
0
 private void SetKeyValue(string KeyName, object TheValue, RegistryValueKind type)
 {
     if (this.readJson())
     {
         JToken token;
         bool   write = true;
         if (AIDASettings.TryGetValue(KeyName, out token))
         {
             string asdd = (token.Value <object>()).ToString();
             if (type == RegistryValueKind.String || type == RegistryValueKind.DWord || type == RegistryValueKind.ExpandString || type == RegistryValueKind.MultiString || type == RegistryValueKind.QWord)
             {
                 write = (!string.IsNullOrEmpty(asdd) && asdd.ToLower() != TheValue.ToString().ToLower());
             }
         }
         if (write)
         {
             using (JTokenWriter asd = new JTokenWriter())
             {
                 asd.WriteValue(TheValue);
                 asd.Flush();
                 AIDASettings[KeyName] = asd.Token;
                 using (StreamWriter sr = new StreamWriter(AIDASettingsLocation, false))
                     using (Newtonsoft.Json.JsonTextWriter jr = new Newtonsoft.Json.JsonTextWriter(sr))
                     {
                         AIDASettings.WriteTo(jr);
                         jr.Flush();
                     }
                 this.jsonLastWrite = DateTime.Now;
                 File.SetLastWriteTime(AIDASettingsLocation, this.jsonLastWrite);
             }
         }
     }
     this.theReg.SetValue(KeyName, TheValue, type);
     this.theReg.Flush();
 }
Example #7
0
        private void DoPack(string path, string output)
        {
            var root = System.IO.Path.GetDirectoryName(path);

            JToken obj;

            using (var reader = System.IO.File.OpenText(path)) {
                using (var jReader = new Newtonsoft.Json.JsonTextReader(reader)) {
                    obj = JToken.ReadFrom(jReader);
                }
            }

            foreach (var objPath in filenamePaths)
            {
                ProcessPath(obj, objPath);
            }

            foreach (var referencedFile in files)
            {
                var externalFile = System.IO.Path.Combine(root, referencedFile.Key);
                var embeddedFile = referencedFile.Value;

                var b64 = Convert.ToBase64String(System.IO.File.ReadAllBytes(externalFile));
                obj["files"][embeddedFile] = b64;
            }

            using (var writer = System.IO.File.CreateText(output)) {
                using (var jWrite = new Newtonsoft.Json.JsonTextWriter(writer)) {
                    obj.WriteTo(jWrite);
                }
            }
        }
        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);
        }
        private void StandardExceptionSerialization(StringBuilder builder, System.Exception exception)
        {
            StringBuilder stringBuilder = new StringBuilder();

            try
            {
                Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings
                {
                    Formatting            = Newtonsoft.Json.Formatting.Indented,
                    ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                };

                /* builder.Append(Newtonsoft.Json.JsonConvert.SerializeObject(exception, settings)); */

                var jsonSerializer = Newtonsoft.Json.JsonSerializer.CreateDefault(settings);
                var stringWriter   = new System.IO.StringWriter(stringBuilder, System.Globalization.CultureInfo.InvariantCulture);
                using (var jsonTextWriter = new Newtonsoft.Json.JsonTextWriter(stringWriter))
                {
                    jsonTextWriter.Formatting = jsonSerializer.Formatting;

                    jsonSerializer.Serialize(jsonTextWriter, exception, null);
                }
            }
            catch (Exception ex)
            {
                NLog.Common.InternalLogger.Error(ex, "Exception serialization failed. Newtonsoft.Json error.");
            }

            builder.Append(stringBuilder);
        }
Example #10
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}
                }
        }
Example #11
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);
 }
Example #12
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);
        }
        } // End Sub WriteAssociativeArray

        private static void WriteAssociativeArray(Newtonsoft.Json.JsonTextWriter jsonWriter, System.Data.Common.DbDataReader dr, bool dataType)
        {
            // JSON:
            //{
            //     "column_1":{ "index":0,"fieldType":"int"}
            //    ,"column_2":{ "index":1,"fieldType":"int"}
            //}

            jsonWriter.WriteStartObject();

            for (int i = 0; i < dr.FieldCount; ++i)
            {
                jsonWriter.WritePropertyName(dr.GetName(i));
                jsonWriter.WriteStartObject();

                jsonWriter.WritePropertyName("index");
                jsonWriter.WriteValue(i);

#if false
                jsonWriter.WritePropertyName("columnName");
                jsonWriter.WriteValue(dr.GetName(i));
#endif

                if (dataType)
                {
                    jsonWriter.WritePropertyName("fieldType");
                    jsonWriter.WriteValue(GetAssemblyQualifiedNoVersionName(dr.GetFieldType(i)));
                } // End if (dataType)

                jsonWriter.WriteEndObject();
            } // Next i

            jsonWriter.WriteEndObject();
        } // End Sub WriteAssociativeArray
Example #14
0
        public static void Serialize(Madingley.Common.Environment environment, TextWriter sw)
        {
            Action <Newtonsoft.Json.JsonWriter, Tuple <int, int> > JsonAddPropertyFocusCell = (jsonWriter, value) =>
            {
                jsonWriter.WriteStartArray();
                Common.Writer.WriteInt(jsonWriter, value.Item1);
                Common.Writer.WriteInt(jsonWriter, value.Item2);
                jsonWriter.WriteEndArray();
            };

            Action <Newtonsoft.Json.JsonWriter, IEnumerable <KeyValuePair <string, double[]> > > JsonAddPropertyCellEnvironment = (jsonWriter, value) =>
            {
                Common.Writer.WriteKeyValuePairs(jsonWriter, value, (JsonWriter, key, val) => Common.Writer.PropertyInlineArray(JsonWriter, key, val, Common.Writer.WriteDouble));
            };

            using (var writer = new Newtonsoft.Json.JsonTextWriter(sw))
            {
                writer.Formatting = Newtonsoft.Json.Formatting.Indented;

                writer.WriteStartObject();
                Common.Writer.PropertyDouble(writer, "CellSize", environment.CellSize);
                Common.Writer.PropertyDouble(writer, "BottomLatitude", environment.BottomLatitude);
                Common.Writer.PropertyDouble(writer, "TopLatitude", environment.TopLatitude);
                Common.Writer.PropertyDouble(writer, "LeftmostLongitude", environment.LeftmostLongitude);
                Common.Writer.PropertyDouble(writer, "RightmostLongitude", environment.RightmostLongitude);
                Common.Writer.PropertyKeyValuePairs(writer, "Units", environment.Units, Common.Writer.PropertyString);
                Common.Writer.PropertyBoolean(writer, "SpecificLocations", environment.SpecificLocations);
                Common.Writer.PropertyInlineArray(writer, "FocusCells", environment.FocusCells, JsonAddPropertyFocusCell);
                Common.Writer.PropertyArray(writer, "CellEnvironment", environment.CellEnvironment, JsonAddPropertyCellEnvironment);
                Common.Writer.PropertyInlineArray(writer, "FileNames", environment.FileNames, Common.Writer.WriteString);
                writer.WriteEndObject();
            }
        }
        public Message Serialize(OperationDescription operation, MessageVersion version, 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();
                    }
                }
            }
            System.ServiceModel.Channels.Message replyMessage = System.ServiceModel.Channels.Message.CreateMessage(version, 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 Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
        {
            byte[] body = null;
            if (operation.Messages[1].Body.ReturnValue.Type == typeof(string))
            {
                body = Encoding.UTF8.GetBytes((string)result);
            }
            else
            {
                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();
                        }
                    }
                }
            }

            System.ServiceModel.Channels.Message replyMessage = System.ServiceModel.Channels.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);
        }
Example #17
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);
            }
        }
Example #18
0
        /// <summary>
        /// 部分更新
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="doc"></param>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public BulkOpBuilder Update <T>(ESDocument <T> doc, params Expression <Func <T, object> >[] predicate)
        {
            if (doc != null)
            {
                sb.AppendFormat("{{\"{0}\":{{ \"_index\":\"{1}\",\"_type\":\"{2}\",\"_id\":\"{3}\",\"_retry_on_conflict\":3}}}}\n", OpTypes.update, doc.IndexName, doc.DocumentType, doc.DocumentID);
                if (predicate == null || predicate.Length == 0)
                {
                    sb.AppendFormat("{{\"doc\":{0}}}\n", doc.ToString());
                }
                else
                {
                    sb.Append("{{");

                    string membername = string.Empty;
                    using (Newtonsoft.Json.JsonTextWriter jw = new Newtonsoft.Json.JsonTextWriter(new StringWriter(sb)))
                    {
                        foreach (var selecter in predicate)
                        {
                            jw.WritePropertyName(JsonHelper.GetJsonTag(selecter, out membername));
                            var val = doc.Document.Eval(membername);

                            jw.WriteValue(val);
                        }
                    }

                    sb.Append("}}\n");
                }
            }
            return(this);
        }
        } // GetAssemblyQualifiedNoVersionName

        private static async System.Threading.Tasks.Task WriteAssociativeColumnsArray(
            Newtonsoft.Json.JsonTextWriter jsonWriter
            , System.Data.Common.DbDataReader dr, RenderType_t renderType)
        {
            //await jsonWriter.WriteStartObjectAsync();
            await jsonWriter.WriteStartObjectAsync();

            for (int i = 0; i <= dr.FieldCount - 1; i++)
            {
                await jsonWriter.WritePropertyNameAsync(dr.GetName(i));

                await jsonWriter.WriteStartObjectAsync();

                await jsonWriter.WritePropertyNameAsync("index");

                await jsonWriter.WriteValueAsync(i);

                if (renderType.HasFlag(RenderType_t.WithDetail))
                {
                    await jsonWriter.WritePropertyNameAsync("fieldType");

                    // await jsonWriter.WriteValueAsync(GetAssemblyQualifiedNoVersionName(dr.GetFieldType(i)));
                    await jsonWriter.WriteValueAsync(GetTypeName(dr.GetFieldType(i), renderType));
                }

                await jsonWriter.WriteEndObjectAsync();
            } // Next i

            await jsonWriter.WriteEndObjectAsync();
        } // WriteAssociativeArray
Example #20
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);
            }
        }
Example #21
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());
            }
        }
Example #22
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);
            }
        }
Example #23
0
        public override void BuildString(Newtonsoft.Json.JsonTextWriter writer)
        {
            if (this._namevalues.Count > 0)
            {
                foreach (var kv in this._namevalues)
                {
                    writer.WriteStartObject();
                    writer.WritePropertyName(Condition);

                    writer.WriteStartObject();

                    writer.WritePropertyName(kv.Key);

                    writer.WriteStartObject();
                    foreach (var kv2 in (Dictionary <string, object>)kv.Value)
                    {
                        writer.WritePropertyName(kv2.Key);
                        writer.WriteValue(kv2.Value);
                    }
                    writer.WriteEndObject();
                    writer.WriteEndObject();

                    writer.WriteEndObject();
                }
            }
            else
            {
            }
        }
Example #24
0
        /// <summary>
        /// Writes the messages section of a protocol definition
        /// </summary>
        /// <param name="writer">writer</param>
        /// <param name="names">list of names written</param>
        /// <param name="encspace">enclosing namespace</param>
        internal void writeJson(Newtonsoft.Json.JsonTextWriter writer, SchemaNames names, string encspace)
        {
            writer.WriteStartObject();
            JsonHelper.writeIfNotNullOrEmpty(writer, "doc", this.Doc);

            if (null != this.Request)
                this.Request.WriteJsonFields(writer, names, null);

            if (null != this.Response)
            {
                writer.WritePropertyName("response");
                Response.WriteJson(writer, names, encspace);
            }

            if (null != this.Error)
            {
                writer.WritePropertyName("errors");
                this.Error.WriteJson(writer, names, encspace);
            }

            if (null != Oneway)
            {
                writer.WritePropertyName("one-way");
                writer.WriteValue(Oneway);
            }

            writer.WriteEndObject();
        }
Example #25
0
        } // WriteAssociativeArray

        private static void WriteComplexArray(Newtonsoft.Json.JsonTextWriter jsonWriter, System.Data.Common.DbDataReader dr, RenderType_t renderType)
        {
            //jsonWriter.WriteStartObject();
            jsonWriter.WriteStartArray();

            for (int i = 0; i <= dr.FieldCount - 1; i++)
            {
                jsonWriter.WriteStartObject();

                jsonWriter.WritePropertyName("name");
                jsonWriter.WriteValue(dr.GetName(i));

                jsonWriter.WritePropertyName("index");
                jsonWriter.WriteValue(i);

                if (renderType.HasFlag(RenderType_t.WithDetail))
                {
                    jsonWriter.WritePropertyName("fieldType");
                    //jsonWriter.WriteValue(GetAssemblyQualifiedNoVersionName(dr.GetFieldType(i)));
                    jsonWriter.WriteValue(GetTypeName(dr.GetFieldType(i), renderType));
                }

                jsonWriter.WriteEndObject();
            }

            // jsonWriter.WriteEndObject();
            jsonWriter.WriteEndArray();
        } // WriteAssociativeArray
Example #26
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");
        }
Example #27
0
        /// <summary>
        /// Writes Protocol in JSON format
        /// </summary>
        /// <param name="writer">JSON writer</param>
        /// <param name="names">list of named schemas already written</param>
        internal void WriteJson(Newtonsoft.Json.JsonTextWriter writer, SchemaNames names)
        {
            writer.WriteStartObject();

            JsonHelper.writeIfNotNullOrEmpty(writer, "protocol", this.Name);
            JsonHelper.writeIfNotNullOrEmpty(writer, "namespace", this.Namespace);
            JsonHelper.writeIfNotNullOrEmpty(writer, "doc", this.Doc);

            writer.WritePropertyName("types");
            writer.WriteStartArray();

            foreach (Schema type in this.Types)
            {
                type.WriteJson(writer, names, this.Namespace);
            }

            writer.WriteEndArray();

            writer.WritePropertyName("messages");
            writer.WriteStartObject();

            foreach (KeyValuePair <string, Message> message in this.Messages)
            {
                writer.WritePropertyName(message.Key);
                message.Value.writeJson(writer, names, this.Namespace);
            }

            writer.WriteEndObject();
            writer.WriteEndObject();
        }
Example #28
0
 public void Serialize(System.IO.TextWriter writer, IEnumerable<object> array)
 {
     using (var textWriter = new Newtonsoft.Json.JsonTextWriter(writer) { CloseOutput = false })
     {
         _serializer.Serialize(textWriter, array);
     }
 }
Example #29
0
        } // End Sub TestJsonGeneration

        public static async System.Threading.Tasks.Task TestJsonGeneration1()
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            using (System.IO.StringWriter sw = new System.IO.StringWriter(sb))
            {
                using (Newtonsoft.Json.JsonTextWriter jsonWriter = new Newtonsoft.Json.JsonTextWriter(sw))
                {
                    jsonWriter.Formatting = Newtonsoft.Json.Formatting.Indented;

                    await jsonWriter.WriteStartObjectAsync();

                    await jsonWriter.WritePropertyNameAsync("tables");

                    await jsonWriter.WriteStartArrayAsync();

                    await jsonWriter.WriteEndArrayAsync();

                    await jsonWriter.WriteEndObjectAsync();
                } // End Using jsonWriter
            }     // End Using sw

            string txt = sb.ToString();

            System.Console.WriteLine(txt);
        } // End Sub TestJsonGeneration1
        public static void Serialize(Madingley.Common.Environment environment, TextWriter sw)
        {
            Action<Newtonsoft.Json.JsonWriter, Tuple<int, int>> JsonAddPropertyFocusCell = (jsonWriter, value) =>
            {
                jsonWriter.WriteStartArray();
                Common.Writer.WriteInt(jsonWriter, value.Item1);
                Common.Writer.WriteInt(jsonWriter, value.Item2);
                jsonWriter.WriteEndArray();
            };

            Action<Newtonsoft.Json.JsonWriter, IEnumerable<KeyValuePair<string, double[]>>> JsonAddPropertyCellEnvironment = (jsonWriter, value) =>
            {
                Common.Writer.WriteKeyValuePairs(jsonWriter, value, (JsonWriter, key, val) => Common.Writer.PropertyInlineArray(JsonWriter, key, val, Common.Writer.WriteDouble));
            };

            using (var writer = new Newtonsoft.Json.JsonTextWriter(sw))
            {
                writer.Formatting = Newtonsoft.Json.Formatting.Indented;

                writer.WriteStartObject();
                Common.Writer.PropertyDouble(writer, "CellSize", environment.CellSize);
                Common.Writer.PropertyDouble(writer, "BottomLatitude", environment.BottomLatitude);
                Common.Writer.PropertyDouble(writer, "TopLatitude", environment.TopLatitude);
                Common.Writer.PropertyDouble(writer, "LeftmostLongitude", environment.LeftmostLongitude);
                Common.Writer.PropertyDouble(writer, "RightmostLongitude", environment.RightmostLongitude);
                Common.Writer.PropertyKeyValuePairs(writer, "Units", environment.Units, Common.Writer.PropertyString);
                Common.Writer.PropertyBoolean(writer, "SpecificLocations", environment.SpecificLocations);
                Common.Writer.PropertyInlineArray(writer, "FocusCells", environment.FocusCells, JsonAddPropertyFocusCell);
                Common.Writer.PropertyArray(writer, "CellEnvironment", environment.CellEnvironment, JsonAddPropertyCellEnvironment);
                Common.Writer.PropertyInlineArray(writer, "FileNames", environment.FileNames, Common.Writer.WriteString);
                writer.WriteEndObject();
            }
        }
Example #31
0
        public static string ToJSON(ContractValue contract, object value)
        {
            var sb = new StringBuilder();
            var sw = new StringWriter(sb);

            using (var writer = new Newtonsoft.Json.JsonTextWriter(sw))
            {
                writer.WriteStartObject();
                var datacontract = ServicesFactory.GetDataContract(contract.Type);

                if (datacontract != null)
                {
                    foreach (var p in datacontract.Properties)
                    {
                        var v = p.Property.GetValue(value, new object[0]);

                        writer.WritePropertyName(p.Name);
                        writer.WriteValue(ValueConverter.ToString(p, v));
                    }
                }
                else
                {
                    writer.WritePropertyName("result");
                    writer.WriteValue(ValueConverter.ToString(contract, value));
                }
                writer.WriteEndObject();
            }
            return(sb.ToString());
        }
Example #32
0
        static async Task WriteResultsToStream(AdomdDataReader results, Stream stream, CancellationToken cancel, ILogger log)
        {
            if (results == null)
            {
                log.LogInformation("Null results");
                return;
            }

            using var rdr = results;

            //can't call Dispose on these without syncronous IO on the underlying connection
            var tw   = new StreamWriter(stream, encoding, 1024 * 4, true);
            var w    = new Newtonsoft.Json.JsonTextWriter(tw);
            int rows = 0;

            try
            {
                await w.WriteStartArrayAsync(cancel);

                while (rdr.Read())
                {
                    if (cancel.IsCancellationRequested)
                    {
                        throw new TaskCanceledException();
                    }
                    rows++;
                    await w.WriteStartObjectAsync(cancel);

                    for (int i = 0; i < rdr.FieldCount; i++)
                    {
                        string name  = rdr.GetName(i);
                        object value = rdr.GetValue(i);

                        await w.WritePropertyNameAsync(name, cancel);

                        await w.WriteValueAsync(value, cancel);
                    }
                    await w.WriteEndObjectAsync(cancel);

                    if (rows % 50000 == 0)
                    {
                        log.LogInformation($"Wrote {rows} rows to output stream.");
                    }
                }
                log.LogInformation($"Finished Writing {rows} rows to output stream.");

                await w.WriteEndArrayAsync(cancel);

                await w.FlushAsync();

                await tw.FlushAsync();

                await stream.FlushAsync();
            }
            catch (TaskCanceledException ex)
            {
                log.LogWarning($"Writing results canceled after {rows} rows.");
            }
        }
        public static JsonNewtonsoftWriter Create()
        {
            StringBuilder sb = new StringBuilder();
            StringWriter  sw = new StringWriter(sb);

            Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw);
            return(new JsonNewtonsoftWriter(writer, sb));
        }
Example #34
0
 public int Two()
 {
     var a3 = new A3.A3Class();
     
     using (var x = new Newtonsoft.Json.JsonTextWriter(System.IO.File.AppendText("")))
     {
         return 2;
     }
 }
Example #35
0
 protected override System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context)
 {
     var jw = new Newtonsoft.Json.JsonTextWriter(new System.IO.StreamWriter(stream))
     {
         Formatting = Newtonsoft.Json.Formatting.Indented
     };
     _value.WriteTo(jw);
     jw.Flush();
     return System.Threading.Tasks.Task.FromResult<object>(null);
 }
        public static void Serialize(Madingley.Common.ModelState modelState, TextWriter sw)
        {
            Action<Newtonsoft.Json.JsonWriter, Madingley.Common.Cohort> JsonAddPropertyCohort = (jsonWriter, value) =>
            {
                jsonWriter.WriteStartObject();
                Common.Writer.PropertyInt(jsonWriter, "FunctionalGroupIndex", value.FunctionalGroupIndex);
                Common.Writer.PropertyInt(jsonWriter, "BirthTimeStep", value.BirthTimeStep);
                Common.Writer.PropertyInt(jsonWriter, "MaturityTimeStep", value.MaturityTimeStep);
                Common.Writer.PropertyInlineArray(jsonWriter, "IDs", value.IDs, Common.Writer.WriteInt);
                Common.Writer.PropertyDouble(jsonWriter, "JuvenileMass", value.JuvenileMass);
                Common.Writer.PropertyDouble(jsonWriter, "AdultMass", value.AdultMass);
                Common.Writer.PropertyDouble(jsonWriter, "IndividualBodyMass", value.IndividualBodyMass);
                Common.Writer.PropertyDouble(jsonWriter, "IndividualReproductivePotentialMass", value.IndividualReproductivePotentialMass);
                Common.Writer.PropertyDouble(jsonWriter, "MaximumAchievedBodyMass", value.MaximumAchievedBodyMass);
                Common.Writer.PropertyDouble(jsonWriter, "Abundance", value.Abundance);
                Common.Writer.PropertyBoolean(jsonWriter, "Merged", value.Merged);
                Common.Writer.PropertyDouble(jsonWriter, "ProportionTimeActive", value.ProportionTimeActive);
                Common.Writer.PropertyDouble(jsonWriter, "TrophicIndex", value.TrophicIndex);
                Common.Writer.PropertyDouble(jsonWriter, "LogOptimalPreyBodySizeRatio", value.LogOptimalPreyBodySizeRatio);
                jsonWriter.WriteEndObject();
            };

            Action<Newtonsoft.Json.JsonWriter, Madingley.Common.Stock> JsonAddPropertyStock = (jsonWriter, value) =>
            {
                jsonWriter.WriteStartObject();
                Common.Writer.PropertyInt(jsonWriter, "FunctionalGroupIndex", value.FunctionalGroupIndex);
                Common.Writer.PropertyDouble(jsonWriter, "IndividualBodyMass", value.IndividualBodyMass);
                Common.Writer.PropertyDouble(jsonWriter, "TotalBiomass", value.TotalBiomass);
                jsonWriter.WriteEndObject();
            };

            Action<Newtonsoft.Json.JsonWriter, Madingley.Common.GridCell> JsonAddPropertyGridCell = (jsonWriter, gridCell) =>
            {
                jsonWriter.WriteStartObject();
                Common.Writer.PropertyDouble(jsonWriter, "Latitude", gridCell.Latitude);
                Common.Writer.PropertyDouble(jsonWriter, "Longitude", gridCell.Longitude);
                Common.Writer.PropertyArray(jsonWriter, "Cohorts", gridCell.Cohorts, (JsonWriter, value) => Common.Writer.WriteArray(JsonWriter, value, JsonAddPropertyCohort));
                Common.Writer.PropertyArray(jsonWriter, "Stocks", gridCell.Stocks, (JsonWriter, value) => Common.Writer.WriteArray(JsonWriter, value, JsonAddPropertyStock));
                Common.Writer.PropertyKeyValuePairs(jsonWriter, "Environment", gridCell.Environment, (JsonWriter, key, val) => Common.Writer.PropertyInlineArray(JsonWriter, key, val, Common.Writer.WriteDouble));
                jsonWriter.WriteEndObject();
            };

            using (var writer = new Newtonsoft.Json.JsonTextWriter(sw))
            {
                writer.Formatting = Newtonsoft.Json.Formatting.Indented;

                writer.WriteStartObject();
                Common.Writer.PropertyInt(writer, "TimestepsComplete", modelState.TimestepsComplete);
                Common.Writer.PropertyKeyValuePairs(writer, "GlobalDiagnosticVariables", modelState.GlobalDiagnosticVariables, Common.Writer.PropertyDouble);
                Common.Writer.PropertyArray(writer, "GridCells", modelState.GridCells, JsonAddPropertyGridCell);
                Common.Writer.PropertyLong(writer, "NextCohortID", modelState.NextCohortID);
                writer.WriteEndObject();
            }
        }
 /// <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\"");
     }
 }
        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
        }
        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;
        }
Example #40
0
        public System.ServiceModel.Channels.Message OrleanStats()
        {
            if (Orleans.GrainClient.IsInitialized == false)
                return WebOperationContext.Current.CreateTextResponse("Error: Client not initialised", "text/plain", Encoding.UTF8);

            IManagementGrain systemManagement = GrainClient.GrainFactory.GetGrain<IManagementGrain>(RuntimeInterfaceConstants.SYSTEM_MANAGEMENT_ID);

            if (systemManagement == null)
                return WebOperationContext.Current.CreateTextResponse("Error: System management not found", "text/plain", Encoding.UTF8);

            var stats = systemManagement.GetSimpleGrainStatistics().Result;

            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            Newtonsoft.Json.JsonTextWriter writer = new Newtonsoft.Json.JsonTextWriter(sw);
            writer.Formatting = Newtonsoft.Json.Formatting.Indented;

            writer.WriteStartObject();
            writer.WritePropertyName("stats");
            writer.WriteStartArray();

            foreach (var s in stats)
            {
                writer.WriteStartObject();
                writer.WritePropertyName("activations");
                writer.WriteValue(s.ActivationCount);
                writer.WritePropertyName("address");
                writer.WriteValue(s.SiloAddress.ToString());
                writer.WritePropertyName("type");
                writer.WriteValue(s.GrainType);
                writer.WriteEndObject();

            }

            writer.WriteEndArray();
            writer.WriteEndObject();

            string ret = sb.ToString();
            return WebOperationContext.Current.CreateTextResponse(ret, "text/plain", Encoding.UTF8);
        }
Example #41
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;
                }
            }
Example #42
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();
 }
Example #43
0
        /// <summary>
        /// Streams the structural metadata.
        /// </summary>
        /// <param name="schemaVersion">The schema version.</param>
        /// <param name="stream">The stream.</param>
        /// <param name="streamController">The stream controller.</param>
        /// <param name="encoding">The response encoding.</param>
        public static void StreamJson(Stream stream,
                                      IStreamController<Newtonsoft.Json.JsonTextWriter> streamController,
                                      Encoding encoding)
        {
            try
            {
                using (var writer = new Newtonsoft.Json.JsonTextWriter(new StreamWriter(stream, encoding)))
                {
                    streamController.StreamTo(writer, new Queue<Action>());
                    writer.Flush();

                }
            }
            catch (Exception e)
            {
                _logger.Error(e.Message, e);
                throw _builder.Build(e);
            }
        }
Example #44
0
        public static void StreamJsonZip(Stream stream, IStreamController<Newtonsoft.Json.JsonTextWriter> streamController, Encoding encoding)
        {
            try
            {
                Stream zipStream = new System.IO.Compression.GZipStream(stream,
                                                System.IO.Compression.CompressionMode.Compress);

                using (var writer = new Newtonsoft.Json.JsonTextWriter(new StreamWriter(zipStream, encoding)))
                {
                    streamController.StreamTo(writer, new Queue<Action>());
                    writer.Flush();
                }
            }
            catch (Exception e)
            {
                _logger.Error(e.Message, e);
                throw _builder.Build(e);
            }
        }
Example #45
0
 public override string ToString()
 {
     System.IO.StringWriter sw = new System.IO.StringWriter();
     Newtonsoft.Json.JsonTextWriter writer = new Newtonsoft.Json.JsonTextWriter(sw);
     writeJson(writer);
     return sw.ToString();
 }
        public static void Serialize(Madingley.Common.Configuration configuration, TextWriter textWriter)
        {
            Action<Newtonsoft.Json.JsonWriter, Madingley.Common.FunctionalGroupDefinition> JsonAddPropertyFunctionalGroupDefinition = (JsonWriter, value) =>
            {
                JsonWriter.WriteStartObject();
                Common.Writer.PropertyKeyValuePairs(JsonWriter, "Definitions", value.Definitions, Common.Writer.PropertyString);
                Common.Writer.PropertyKeyValuePairs(JsonWriter, "Properties", value.Properties, Common.Writer.PropertyDouble);
                JsonWriter.WriteEndObject();
            };

            Action<Newtonsoft.Json.JsonWriter, string, Madingley.Common.FunctionalGroupDefinitions> JsonAddPropertyFunctionalGroupDefinitions = (JsonWriter, name, value) =>
            {
                JsonWriter.WritePropertyName(name);
                JsonWriter.WriteStartObject();
                Common.Writer.PropertyArray(JsonWriter, "Data", value.Data, JsonAddPropertyFunctionalGroupDefinition);
                Common.Writer.PropertyInlineArray(JsonWriter, "Definitions", value.Definitions, Common.Writer.WriteString);
                Common.Writer.PropertyInlineArray(JsonWriter, "Properties", value.Properties, Common.Writer.WriteString);
                JsonWriter.WriteEndObject();
            };

            Action<Newtonsoft.Json.JsonWriter, string, Madingley.Common.ScenarioParameter> JsonAddPropertyScenarioParameter = (JsonWriter, name, value) =>
            {
                JsonWriter.WritePropertyName(name);
                JsonWriter.WriteStartObject();
                Common.Writer.PropertyString(JsonWriter, "ParamString", value.ParamString);
                Common.Writer.PropertyDouble(JsonWriter, "ParamDouble1", value.ParamDouble1);
                Common.Writer.PropertyDouble(JsonWriter, "ParamDouble2", value.ParamDouble2);
                JsonWriter.WriteEndObject();
            };

            Action<Newtonsoft.Json.JsonWriter, Madingley.Common.ScenarioParameters> JsonAddScenarioParameter = (JsonWriter, value) =>
            {
                JsonWriter.WriteStartObject();
                Common.Writer.PropertyString(JsonWriter, "Label", value.Label);
                Common.Writer.PropertyInt(JsonWriter, "SimulationNumber", value.SimulationNumber);
                Common.Writer.PropertyKeyValuePairs(JsonWriter, "Parameters", value.Parameters, JsonAddPropertyScenarioParameter);
                JsonWriter.WriteEndObject();
            };

            Action<Newtonsoft.Json.JsonWriter, string, Madingley.Common.EcologicalParameters> JsonAddEcologicalParameters = (JsonWriter, name, ecologicalParameters) =>
            {
                JsonWriter.WritePropertyName(name);
                JsonWriter.WriteStartObject();
                Common.Writer.PropertyKeyValuePairs(JsonWriter, "Parameters", ecologicalParameters.Parameters, Common.Writer.PropertyDouble);
                Common.Writer.PropertyInlineArray(JsonWriter, "TimeUnits", ecologicalParameters.TimeUnits, Common.Writer.WriteString);
                JsonWriter.WriteEndObject();
            };

            using (var writer = new Newtonsoft.Json.JsonTextWriter(textWriter))
            {
                writer.Formatting = Newtonsoft.Json.Formatting.Indented;

                writer.WriteStartObject();
                Common.Writer.PropertyString(writer, "GlobalModelTimeStepUnit", configuration.GlobalModelTimeStepUnit);
                Common.Writer.PropertyInt(writer, "NumTimeSteps", configuration.NumTimeSteps);
                Common.Writer.PropertyInt(writer, "BurninTimeSteps", configuration.BurninTimeSteps);
                Common.Writer.PropertyInt(writer, "ImpactTimeSteps", configuration.ImpactTimeSteps);
                Common.Writer.PropertyInt(writer, "RecoveryTimeSteps", configuration.RecoveryTimeSteps);
                Common.Writer.PropertyBoolean(writer, "RunCellsInParallel", configuration.RunCellsInParallel);
                Common.Writer.PropertyBoolean(writer, "RunSimulationsInParallel", configuration.RunSimulationsInParallel);
                Common.Writer.PropertyString(writer, "RunRealm", configuration.RunRealm);
                Common.Writer.PropertyBoolean(writer, "DrawRandomly", configuration.DrawRandomly);
                Common.Writer.PropertyDouble(writer, "ExtinctionThreshold", configuration.ExtinctionThreshold);
                Common.Writer.PropertyInt(writer, "MaxNumberOfCohorts", configuration.MaxNumberOfCohorts);
                Common.Writer.PropertyBoolean(writer, "DispersalOnly", configuration.DispersalOnly);
                Common.Writer.PropertyString(writer, "DispersalOnlyType", configuration.DispersalOnlyType);
                Common.Writer.PropertyDouble(writer, "PlanktonDispersalThreshold", configuration.PlanktonDispersalThreshold);
                JsonAddPropertyFunctionalGroupDefinitions(writer, "CohortFunctionalGroupDefinitions", configuration.CohortFunctionalGroupDefinitions);
                JsonAddPropertyFunctionalGroupDefinitions(writer, "StockFunctionalGroupDefinitions", configuration.StockFunctionalGroupDefinitions);
                Common.Writer.PropertyInlineArray(writer, "ImpactCellIndices", configuration.ImpactCellIndices, Common.Writer.WriteInt);
                Common.Writer.PropertyBoolean(writer, "ImpactAll", configuration.ImpactAll);
                Common.Writer.PropertyArray(writer, "ScenarioParameters", configuration.ScenarioParameters, JsonAddScenarioParameter);
                Common.Writer.PropertyInt(writer, "ScenarioIndex", configuration.ScenarioIndex);
                Common.Writer.PropertyInt(writer, "Simulation", configuration.Simulation);
                JsonAddEcologicalParameters(writer, "EcologicalParameters", configuration.EcologicalParameters);
                Common.Writer.PropertyInlineArray(writer, "FileNames", configuration.FileNames, Common.Writer.WriteString);
                writer.WriteEndObject();
            }
        }
Example #47
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);
            }
        }
Example #48
0
        public override string ToString()
        {
            using (StringWriter sw = new StringWriter())
            {
                using (Newtonsoft.Json.JsonTextWriter writer = new Newtonsoft.Json.JsonTextWriter(sw))
                {
                    #if(DEBUG)
                    writer.Formatting = Newtonsoft.Json.Formatting.Indented;
                    #endif

                    writeJson(writer);
                    writer.Flush();
                    return sw.ToString();
                }
            }
        }
Example #49
0
	public string ToJson(object context)
	{
		var serializer = Newtonsoft.Json.JsonSerializer.Create(new Newtonsoft.Json.JsonSerializerSettings());
		var sb = new System.Text.StringBuilder();

        var writer = new Newtonsoft.Json.JsonTextWriter(new System.IO.StringWriter(sb));
        writer.Formatting = Newtonsoft.Json.Formatting.Indented;

        serializer.Serialize(writer, context);

		return sb.ToString();
		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;
		}