} // 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
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()); }
} // 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
public override void BuildString(Newtonsoft.Json.JsonTextWriter writer) { if (_namevalues.Count > 0) { foreach (var kv in _namevalues) { var list = (List <object>)kv.Value; if (list.Count > 1) { //writer.WriteStartObject(); //writer.WritePropertyName(this.Condition+"s"); //writer.WriteStartObject(); //writer.WritePropertyName(kv.Key); //writer.WriteStartArray(); //foreach(var it in list) //{ // writer.WriteValue(it); //} //writer.WriteEndArray(); foreach (var it in list) { writer.WriteStartObject(); writer.WritePropertyName(this.Condition); writer.WriteStartObject(); writer.WritePropertyName(kv.Key); writer.WriteValue(it); writer.WriteEndObject(); writer.WriteEndObject(); } } else { writer.WriteStartObject(); writer.WritePropertyName(this.Condition); writer.WriteStartObject(); writer.WritePropertyName(kv.Key); writer.WriteValue(list[0]); writer.WriteEndObject(); writer.WriteEndObject(); } } } else { writer.WriteStartObject(); writer.WritePropertyName(Condition); writer.WriteStartObject(); writer.WriteEndObject(); writer.WriteEndObject(); } }
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 { } }
/// <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(); }
/// <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); }
private static string GetExpectedString(bool prettyPrint, bool isUtf8, int[] data) { MemoryStream ms = new MemoryStream(); StreamWriter streamWriter = new StreamWriter(ms, new UTF8Encoding(false), 1024, true); StringBuilder sb = new StringBuilder(); StringWriter stringWriter = new StringWriter(sb); TextWriter writer = isUtf8 ? streamWriter : (TextWriter)stringWriter; var json = new Newtonsoft.Json.JsonTextWriter(writer) { Formatting = prettyPrint ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None }; json.WriteStartObject(); json.WritePropertyName("age"); json.WriteValue(42); json.WritePropertyName("first"); json.WriteValue("John"); json.WritePropertyName("last"); json.WriteValue("Smith"); json.WritePropertyName("phoneNumbers"); json.WriteStartArray(); json.WriteValue("425-000-1212"); json.WriteValue("425-000-1213"); json.WriteEnd(); json.WritePropertyName("address"); json.WriteStartObject(); json.WritePropertyName("street"); json.WriteValue("1 Microsoft Way"); json.WritePropertyName("city"); json.WriteValue("Redmond"); json.WritePropertyName("zip"); json.WriteValue(98052); json.WriteEnd(); // Add a large array of values json.WritePropertyName("ExtraArray"); json.WriteStartArray(); for (var i = 0; i < ExtraArraySize; i++) { json.WriteValue(data[i]); } json.WriteEnd(); json.WriteEnd(); json.Flush(); return(isUtf8 ? Encoding.UTF8.GetString(ms.ToArray()) : sb.ToString()); }
/// <summary> /// Writes enum schema in JSON format /// </summary> /// <param name="writer">JSON writer</param> /// <param name="names">list of named schema already written</param> /// <param name="encspace">enclosing namespace of the enum schema</param> protected internal override void WriteJsonFields(Newtonsoft.Json.JsonTextWriter writer, SchemaNames names, string encspace) { base.WriteJsonFields(writer, names, encspace); writer.WritePropertyName("symbols"); writer.WriteStartArray(); foreach (string s in this.Symbols) { writer.WriteValue(s); } writer.WriteEndArray(); if (null != Default) { writer.WritePropertyName("default"); writer.WriteValue(Default); } }
public static void Serialize(Newtonsoft.Json.JsonTextWriter Writer, TimingDebugger TimingDebuggerObj) { Writer.WritePropertyName("TimingGroup"); Writer.WriteStartArray(); foreach (var t in TimingDebuggerObj) { var timing = t.Where(tt => tt.Name == t.Name).First(); Writer.WriteStartObject(); Writer.WritePropertyName("Name"); Writer.WriteValue(t.Name); Writer.WritePropertyName("ExecutionTime"); Writer.WriteValue(timing.ExecutionTime); Timing.Serialize(Writer, t); Writer.WriteEndObject(); } Writer.WriteEndArray(); }
} // WriteAssociativeArray private static void WriteArray(Newtonsoft.Json.JsonTextWriter jsonWriter, System.Data.Common.DbDataReader dr) { jsonWriter.WriteStartArray(); for (int i = 0; i <= dr.FieldCount - 1; i++) { jsonWriter.WriteValue(dr.GetName(i)); } jsonWriter.WriteEndArray(); } // End Sub WriteArray
private static void WriterNewtonsoftHelloWorld(bool formatted, TextWriter writer) { using (var json = new Newtonsoft.Json.JsonTextWriter(writer)) { json.Formatting = formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None; json.WriteStartObject(); json.WritePropertyName("message"); json.WriteValue("Hello, World!"); json.WriteEnd(); } }
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); }
} // End Sub WriteAssociativeArray private static void WriteArray(Newtonsoft.Json.JsonTextWriter jsonWriter, System.Data.Common.DbDataReader dr) { jsonWriter.WriteStartArray(); for (int i = 0; i < dr.FieldCount; ++i) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("index"); jsonWriter.WriteValue(i); jsonWriter.WritePropertyName("columnName"); jsonWriter.WriteValue(dr.GetName(i)); jsonWriter.WritePropertyName("fieldType"); jsonWriter.WriteValue(GetAssemblyQualifiedNoVersionName(dr.GetFieldType(i))); jsonWriter.WriteEndObject(); } // Next i jsonWriter.WriteEndArray(); } // End Sub WriteArray
/// <summary> /// Writes logical schema in JSON format /// </summary> /// <param name="writer">JSON writer</param> /// <param name="names">list of named schemas already written</param> /// <param name="encspace">enclosing namespace of the schema</param> protected internal override void WriteJson(Newtonsoft.Json.JsonTextWriter writer, SchemaNames names, string encspace) { writer.WriteStartObject(); writer.WritePropertyName("type"); BaseSchema.WriteJson(writer, names, encspace); writer.WritePropertyName("logicalType"); writer.WriteValue(LogicalTypeName); if (null != Props) { Props.WriteJson(writer); } writer.WriteEndObject(); }
//[Benchmark] public void NewtonsoftNullUnescaped() { using (var json = new Newtonsoft.Json.JsonTextWriter(GetWriter())) { json.Formatting = Formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None; json.WriteStartObject(); for (int i = 0; i < 100; i++) { json.WritePropertyName("first", escape: false); json.WriteValue((object)null); } json.WriteEndObject(); } }
//[Benchmark] public void NewtonsoftEscapingRequired() { using (var json = new Newtonsoft.Json.JsonTextWriter(GetWriter())) { json.Formatting = Formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None; json.WriteStartObject(); for (int i = 0; i < 100; i++) { json.WritePropertyName("fir\nst"); json.WriteValue("Joh\nn"); } json.WriteEndObject(); } }
//[Benchmark] public void NewtonsoftEscapeUnnecessarily() { using (var json = new Newtonsoft.Json.JsonTextWriter(GetWriter())) { json.Formatting = Formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None; json.WriteStartObject(); for (int i = 0; i < 100; i++) { json.WritePropertyName("first", escape: true); json.WriteValue("John"); } json.WriteEndObject(); } }
//[Benchmark] public void NewtonsoftDateTimeUnescapedOverhead() { using (var json = new Newtonsoft.Json.JsonTextWriter(GetWriter())) { json.Formatting = Formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None; json.WriteStartObject(); for (int i = 0; i < 100; i++) { json.WritePropertyName("first", escape: true); json.WriteValue(MyDate); } json.WriteEndObject(); } }
/// <summary> /// Writes named schema in JSON format /// </summary> /// <param name="writer">JSON writer</param> /// <param name="names">list of named schemas already written</param> /// <param name="encspace">enclosing namespace of the named schema</param> protected internal override void WriteJsonFields(Newtonsoft.Json.JsonTextWriter writer, SchemaNames names, string encspace) { this.SchemaName.WriteJson(writer, names, encspace); if (null != aliases) { writer.WritePropertyName("aliases"); writer.WriteStartArray(); foreach (SchemaName name in aliases) { string fullname = (null != name.Space) ? name.Space + "." + name.Name : name.Name; writer.WriteValue(fullname); } writer.WriteEndArray(); } }
private static void WriterNewtonsoftBasic(bool formatted, StreamWriter writer) { using (var json = new Newtonsoft.Json.JsonTextWriter(writer)) { json.Formatting = formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None; json.WriteStartObject(); json.WritePropertyName("age"); json.WriteValue(42); json.WritePropertyName("first"); json.WriteValue("John"); json.WritePropertyName("last"); json.WriteValue("Smith"); json.WritePropertyName("phoneNumbers"); json.WriteStartArray(); json.WriteValue("425-000-1212"); json.WriteValue("425-000-1213"); json.WriteEnd(); json.WritePropertyName("address"); json.WriteStartObject(); json.WritePropertyName("street"); json.WriteValue("1 Microsoft Way"); json.WritePropertyName("city"); json.WriteValue("Redmond"); json.WritePropertyName("zip"); json.WriteValue(98052); json.WriteEnd(); // Add a large array of values json.WritePropertyName("ExtraArray"); json.WriteStartArray(); for (var i = 0; i < ExtraArraySize; i++) { json.WriteValue(i); } json.WriteEnd(); json.WriteEnd(); } }
private static void WriterNewtonsoftBasic(bool formatted, TextWriter writer, ReadOnlySpan <int> data) { using (var json = new Newtonsoft.Json.JsonTextWriter(writer)) { json.Formatting = formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None; json.WriteStartObject(); json.WritePropertyName("age"); json.WriteValue(42); json.WritePropertyName("first"); json.WriteValue("John"); json.WritePropertyName("last"); json.WriteValue("Smith"); json.WritePropertyName("phoneNumbers"); json.WriteStartArray(); json.WriteValue("425-000-1212"); json.WriteValue("425-000-1213"); json.WriteEnd(); json.WritePropertyName("address"); json.WriteStartObject(); json.WritePropertyName("street"); json.WriteValue("1 Microsoft Way"); json.WritePropertyName("city"); json.WriteValue("Redmond"); json.WritePropertyName("zip"); json.WriteValue(98052); json.WriteEnd(); json.WritePropertyName("ExtraArray"); json.WriteStartArray(); for (var i = 0; i < data.Length; i++) { json.WriteValue(data[i]); } json.WriteEnd(); json.WriteEnd(); } }
//[Benchmark] public void WriteArrayNewtonsoft() { using (var json = new Newtonsoft.Json.JsonTextWriter(GetWriter())) { json.Formatting = Formatted ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None; json.WriteStartObject(); json.WritePropertyName("message"); json.WriteStartArray(); for (var i = 0; i < _longs.Length; i++) { json.WriteValue(_longs[i]); } json.WriteEnd(); json.WriteEnd(); } }
/// <summary> /// 返回结果的存储过程 /// </summary> /// <param name="strSql">任何SQL语句</param> /// <param name="parameters">参数值</param> /// <returns></returns> public override string ExecuteJson(string strSql, params DbParameter[] parameters) { try { DbCommand cmd = BuilderQueryCommand(strSql, parameters); System.IO.StringWriter sw = null; Newtonsoft.Json.JsonWriter writer = null; sw = new System.IO.StringWriter(); writer = new Newtonsoft.Json.JsonTextWriter(sw); writer.WriteStartArray(); using (DbDataReader dr = cmd.ExecuteReader()) { do { while (dr.Read()) { writer.WriteStartObject(); for (int i = 0; i < dr.FieldCount; i++) { writer.WritePropertyName(dr.GetName(i)); writer.WriteValue(Convert.ToString(dr[i])); } writer.WriteEndObject(); } }while (dr.NextResult()); } writer.WriteEndArray(); writer.Flush(); return(sw.GetStringBuilder().ToString()); } catch (DbException ex) { throw ex; } catch { throw; } }
public string ToJson() { System.IO.StringWriter sw = new System.IO.StringWriter(); Newtonsoft.Json.JsonTextWriter writer = new Newtonsoft.Json.JsonTextWriter(sw); // { writer.WriteStartObject(); // "query" : "" writer.WritePropertyName("query"); writer.WriteValue(query); // "name" : "" writer.WritePropertyName("name"); writer.WriteValue(name); // "latitude" : "" writer.WritePropertyName("latitude"); writer.WriteValue(latitude); // "longitude" : "" writer.WritePropertyName("longitude"); writer.WriteValue(longitude); // "tz_long" : "" writer.WritePropertyName("tz_long"); writer.WriteValue(tz_long); // "locationType" : "" writer.WritePropertyName("locationType"); writer.WriteValue((int)locationType); // "source" : "" writer.WritePropertyName("source"); writer.WriteValue(source); // } writer.WriteEndObject(); return(sw.ToString()); }
/// <summary> /// Writes named schema in JSON format /// </summary> /// <param name="writer">JSON writer</param> /// <param name="names">list of named schemas already written</param> /// <param name="encspace">enclosing namespace of the named schema</param> protected internal override void WriteJson(Newtonsoft.Json.JsonTextWriter writer, SchemaNames names, string encspace) { if (!names.Add(this)) { // schema is already in the list, write name only SchemaName schemaName = this.SchemaName; string name; if (schemaName.Namespace != encspace) { name = schemaName.Namespace + "." + schemaName.Name; // we need to add the qualifying namespace of the target schema if it's not the same as current namespace } else { name = schemaName.Name; } writer.WriteValue(name); } else { // schema is not in the list, write full schema definition base.WriteJson(writer, names, encspace); } }
private static string GetHelloWorldExpectedString(bool prettyPrint, bool isUtf8) { MemoryStream ms = new MemoryStream(); StreamWriter streamWriter = new StreamWriter(ms, new UTF8Encoding(false), 1024, true); StringBuilder sb = new StringBuilder(); StringWriter stringWriter = new StringWriter(sb); TextWriter writer = isUtf8 ? streamWriter : (TextWriter)stringWriter; var json = new Newtonsoft.Json.JsonTextWriter(writer) { Formatting = prettyPrint ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None }; json.WriteStartObject(); json.WritePropertyName("message"); json.WriteValue("Hello, World!"); json.WriteEnd(); json.Flush(); return(isUtf8 ? Encoding.UTF8.GetString(ms.ToArray()) : sb.ToString()); }
/// <summary> /// Writes the fixed schema class in JSON format /// </summary> /// <param name="writer">JSON writer</param> /// <param name="names">list of named schema already written</param> /// <param name="encspace">enclosing namespace for the fixed schema</param> protected internal override void WriteJsonFields(Newtonsoft.Json.JsonTextWriter writer, SchemaNames names, string encspace) { base.WriteJsonFields(writer, names, encspace); writer.WritePropertyName("size"); writer.WriteValue(this.Size); }
/// <summary> /// Convert the sql results to UtilityResponce /// </summary> /// <param name="sqlReadResults">the source</param> /// <param name="result">the target.</param> public static void ConvertReadResultsToResponce(List <SqlReadResult> sqlReadResults, UtilityResponce result) { int kind = 0; var stringBuilder = new System.Text.StringBuilder(); if (sqlReadResults.Count > 0) { var sqlReadResult = sqlReadResults[0]; if ((sqlReadResult.FieldCount == 1) && (sqlReadResult.Rows.Count > 0) && ((string.Equals(sqlReadResult.FieldNames[0], "kind", StringComparison.OrdinalIgnoreCase)) || (string.Equals(sqlReadResult.FieldNames[0], "mimetype", StringComparison.OrdinalIgnoreCase)))) { var cell00 = sqlReadResult.Rows[0][0] as string; if ((string.Equals(cell00, "text", StringComparison.OrdinalIgnoreCase)) || (string.Equals(cell00, Consts.MimeTypeText, StringComparison.OrdinalIgnoreCase)) || (string.Equals(cell00, Consts.MimeTypeJavascript, StringComparison.OrdinalIgnoreCase))) { result.Kind = Consts.MimeTypeText; kind = 1; sqlReadResults.RemoveAt(0); } else if ((string.Equals(cell00, Consts.MimeTypeHTML, StringComparison.OrdinalIgnoreCase)) || (string.Equals(cell00, "html", StringComparison.OrdinalIgnoreCase))) { result.Kind = Consts.MimeTypeHTML; kind = 2; sqlReadResults.RemoveAt(0); } else if ((string.Equals(cell00, "json", StringComparison.OrdinalIgnoreCase)) || (string.Equals(cell00, Consts.MimeTypeJSON, StringComparison.OrdinalIgnoreCase))) { result.Kind = Consts.MimeTypeJSON; kind = 3; sqlReadResults.RemoveAt(0); } else if ((string.Equals(cell00, Consts.MimeTypeXML, StringComparison.OrdinalIgnoreCase)) || (string.Equals(cell00, Consts.MimeTypeTextXML, StringComparison.OrdinalIgnoreCase))) { result.Kind = cell00; kind = 4; sqlReadResults.RemoveAt(0); } else { result.Kind = cell00; kind = 1; } } else if (sqlReadResult.FieldCount >= 1) { var fieldName0 = sqlReadResult.FieldNames[0] as string; if ((string.Equals(fieldName0, "text", StringComparison.OrdinalIgnoreCase)) || (string.Equals(fieldName0, Consts.MimeTypeText, StringComparison.OrdinalIgnoreCase))) { result.Kind = Consts.MimeTypeText; kind = 1; } else if ((string.Equals(fieldName0, Consts.MimeTypeHTML, StringComparison.OrdinalIgnoreCase)) || (string.Equals(fieldName0, "html", StringComparison.OrdinalIgnoreCase))) { result.Kind = Consts.MimeTypeHTML; kind = 2; } else if ((string.Equals(fieldName0, "json", StringComparison.OrdinalIgnoreCase)) || (string.Equals(fieldName0, Consts.MimeTypeJSON, StringComparison.OrdinalIgnoreCase))) { result.Kind = Consts.MimeTypeJSON; kind = 3; } else if ((string.Equals(fieldName0, Consts.MimeTypeXML, StringComparison.OrdinalIgnoreCase)) || (string.Equals(fieldName0, Consts.MimeTypeTextXML, StringComparison.OrdinalIgnoreCase))) { result.Kind = fieldName0; kind = 4; } else { result.Kind = "application/json"; kind = 3; } } } if (kind == 1) { foreach (var sqlReadResult in sqlReadResults) { foreach (var row in sqlReadResult.Rows) { for (int fieldIndex = 0; fieldIndex < sqlReadResult.FieldCount; fieldIndex++) { var value = row[fieldIndex]; if (value == null) { continue; } stringBuilder.Append(value); } } } } else if (kind == 2) { foreach (var sqlReadResult in sqlReadResults) { foreach (var row in sqlReadResult.Rows) { for (int fieldIndex = 0; fieldIndex < sqlReadResult.FieldCount; fieldIndex++) { var value = row[fieldIndex]; if (value == null) { continue; } stringBuilder.Append(value); } } } } else if (kind == 3) { using (System.IO.StringWriter stringWriter = new System.IO.StringWriter(stringBuilder)) { using (Newtonsoft.Json.JsonTextWriter jsonTextWriter = new Newtonsoft.Json.JsonTextWriter(stringWriter)) { jsonTextWriter.WriteStartArray(); foreach (var sqlReadResult in sqlReadResults) { jsonTextWriter.WriteStartArray(); foreach (var row in sqlReadResult.Rows) { jsonTextWriter.WriteStartObject(); for (int fieldIndex = 0; fieldIndex < sqlReadResult.FieldCount; fieldIndex++) { var fieldName = sqlReadResult.FieldNames[fieldIndex]; var value = row[fieldIndex]; jsonTextWriter.WritePropertyName(fieldName); jsonTextWriter.WriteValue(value); } jsonTextWriter.WriteEndObject(); } jsonTextWriter.WriteEndArray(); if ((sqlReadResult.MeassureMessage.Count > 0) && (sqlReadResult.MeassureError.Count > 0)) { if (sqlReadResult.MeassureMessage.Count > 0) { jsonTextWriter.WriteStartArray(); foreach (var meassureMessage in sqlReadResult.MeassureMessage) { jsonTextWriter.WriteStartObject(); jsonTextWriter.WritePropertyName("MeassureMessage"); jsonTextWriter.WriteValue(meassureMessage); jsonTextWriter.WriteEndObject(); } jsonTextWriter.WriteEndArray(); } if (sqlReadResult.MeassureError.Count > 0) { jsonTextWriter.WriteStartArray(); foreach (var meassureError in sqlReadResult.MeassureError) { jsonTextWriter.WriteStartObject(); jsonTextWriter.WritePropertyName("MeassureError"); jsonTextWriter.WriteValue(meassureError); jsonTextWriter.WriteEndObject(); } jsonTextWriter.WriteEndArray(); } } } jsonTextWriter.WriteEndArray(); } } } else if (kind == 4) { using (System.IO.StringWriter stringWriter = new System.IO.StringWriter(stringBuilder)) { using (var xmlWriter = new System.Xml.XmlTextWriter(stringWriter)) { xmlWriter.Formatting = System.Xml.Formatting.None; xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("data"); foreach (var sqlReadResult in sqlReadResults) { xmlWriter.WriteStartElement("result"); foreach (var row in sqlReadResult.Rows) { xmlWriter.WriteStartElement("row"); for (int fieldIndex = 0; fieldIndex < sqlReadResult.FieldCount; fieldIndex++) { var fieldName = sqlReadResult.FieldNames[fieldIndex]; var value = row[fieldIndex]; xmlWriter.WriteStartElement(fieldName); if (value == null) { // ignore } else if (value == DBNull.Value) { // ignore } else if (value is string) { xmlWriter.WriteValue((string)value); } else if (value is bool) { xmlWriter.WriteValue((bool)value); } else if (value is DateTime) { xmlWriter.WriteValue((DateTime)value); } else if (value is decimal) { xmlWriter.WriteValue((decimal)value); } else if (value is float) { xmlWriter.WriteValue((float)value); } else if (value is double) { xmlWriter.WriteValue((double)value); } else if (value is int) { xmlWriter.WriteValue((int)value); } else if (value is long) { xmlWriter.WriteValue((long)value); } else { xmlWriter.WriteElementString(fieldName, value.ToString()); } xmlWriter.WriteEndElement(/*fieldName*/); } xmlWriter.WriteEndElement(/*row*/); } xmlWriter.WriteEndElement(/*result*/); } xmlWriter.WriteEndElement(/*data*/); xmlWriter.WriteEndDocument(); } using (Newtonsoft.Json.JsonTextWriter jsonTextWriter = new Newtonsoft.Json.JsonTextWriter(stringWriter)) { jsonTextWriter.WriteStartArray(); foreach (var sqlReadResult in sqlReadResults) { jsonTextWriter.WriteStartArray(); foreach (var row in sqlReadResult.Rows) { jsonTextWriter.WriteStartObject(); for (int fieldIndex = 0; fieldIndex < sqlReadResult.FieldCount; fieldIndex++) { var fieldName = sqlReadResult.FieldNames[fieldIndex]; var value = row[fieldIndex]; jsonTextWriter.WritePropertyName(fieldName); jsonTextWriter.WriteValue(value); } jsonTextWriter.WriteEndObject(); } jsonTextWriter.WriteEndArray(); } jsonTextWriter.WriteEndArray(); } } } result.Value = stringBuilder.ToString(); }
public void Run() { var resultsFile = Path.Combine(Params.TestFileRoot, string.Format("XbimRegression_{0:yyyyMMdd-hhmmss}.csv", DateTime.Now)); var di = new DirectoryInfo(Params.TestFileRoot); using (var writer = new StreamWriter(resultsFile)) { writer.WriteLine(ProcessResult.CsvHeader); // ParallelOptions opts = new ParallelOptions() { MaxDegreeOfParallelism = 12 }; var toProcess = di.GetFiles("*.IFC", SearchOption.AllDirectories); // Parallel.ForEach<FileInfo>(toProcess, opts, file => foreach (var file in toProcess) { //set up a log file for this file run var logFile = Path.ChangeExtension(file.FullName, "log"); ProcessResult result; using (var loggerFactory = new LoggerFactory()) { XbimLogging.LoggerFactory = loggerFactory; loggerFactory.AddConsole(LogLevel.Error); loggerFactory.AddProvider(new NReco.Logging.File.FileLoggerProvider(logFile, false) { FormatLogEntry = (msg) => { var sb = new System.Text.StringBuilder(); StringWriter sw = new StringWriter(sb); var jsonWriter = new Newtonsoft.Json.JsonTextWriter(sw); jsonWriter.WriteStartArray(); jsonWriter.WriteValue(DateTime.Now.ToString("o")); jsonWriter.WriteValue(msg.LogLevel.ToString()); jsonWriter.WriteValue(msg.EventId.Id); jsonWriter.WriteValue(msg.Message); jsonWriter.WriteValue(msg.Exception?.ToString()); jsonWriter.WriteEndArray(); return(sb.ToString()); } }); var logger = loggerFactory.CreateLogger <BatchProcessor>(); Console.WriteLine($"Processing {file}"); result = ProcessFile(file.FullName, writer, logger); } XbimLogging.LoggerFactory = null; // uses a default loggerFactory var txt = File.ReadAllText(logFile); if (string.IsNullOrEmpty(txt)) { File.Delete(logFile); result.Errors = 0; result.Warnings = 0; result.Information = 0; } else { var tokens = txt.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); result.Errors = tokens.Count(t => t == "\"Error\""); result.Warnings = tokens.Count(t => t == "\"Warning\""); result.Information = Math.Max(0, tokens.Count(t => t == "\"Information\"") - 2); //we always get 2 } if (result != null && !result.Failed) { Console.WriteLine($"Processed {file} : {result.Errors} Errors, {result.Warnings} Warnings, {result.Information} Informational in {result.TotalTime}ms. {result.Entities} IFC Elements & {result.GeometryEntries} Geometry Nodes."); } else { Console.WriteLine("Processing failed for {0} after {1}ms.", file, result.TotalTime); } result.FileName = file.Name; writer.WriteLine(result.ToCsv()); writer.Flush(); } writer.Close(); } Console.WriteLine("Finished. Press Enter to continue..."); Console.ReadLine(); }
/// <summary> /// For the specified response processes any associated tracking table documents, converting from csv to json array. /// The json array is set on the ResponseData property of the response, save is _not_ called. /// </summary> /// <param name="response"></param> /// <returns></returns> public async Task Process(Response response) { Guid[] trackingTableDocuments = await _db.Documents.AsNoTracking().Where(d => d.ItemID == response.ID && d.Kind == TrackingTableDocumentKind).Select(d => d.ID).ToArrayAsync(); if (trackingTableDocuments.Length == 0) { return; } StringBuilder buffer = new StringBuilder(); string[] tableHeader; string[] currentLine; using (var writer = new Newtonsoft.Json.JsonTextWriter(new StringWriter(buffer))) { writer.QuoteName = true; writer.WriteStartArray(); foreach (Guid trackingTableDocumentID in trackingTableDocuments) { //read the tracking table csv into a dictionary, each dictionary represents a row in the csv document using (var dsDataContext = new DataContext()) using (var reader = new StreamReader(new Data.Documents.DocumentStream(dsDataContext, trackingTableDocumentID))) using (var csv = new Microsoft.VisualBasic.FileIO.TextFieldParser(reader)) { csv.SetDelimiters(","); csv.TrimWhiteSpace = true; tableHeader = csv.ReadFields(); while (csv.EndOfData == false) { currentLine = csv.ReadFields(); if (currentLine.Length == 0) { continue; } writer.WriteStartObject(); for (int i = 0; i < currentLine.Length; i++) { writer.WritePropertyName(tableHeader[i]); writer.WriteValue(currentLine[i]); } writer.WriteEndObject(); } reader.Close(); } } writer.WriteEndArray(); writer.Flush(); response.ResponseData = buffer.ToString(); } }