/// <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(); }
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 { } }
public override void Structure(IReadWritable value, string name) { writer.WritePropertyName(name); writer.WriteStartObject(); value.WriteData(this); writer.WriteEndObject(); }
} // GetAssemblyQualifiedNoVersionName private static void WriteAssociativeColumnsArray(Newtonsoft.Json.JsonTextWriter jsonWriter , System.Data.Common.DbDataReader dr, RenderType_t renderType) { //jsonWriter.WriteStartObject(); jsonWriter.WriteStartObject(); for (int i = 0; i <= dr.FieldCount - 1; i++) { jsonWriter.WritePropertyName(dr.GetName(i)); jsonWriter.WriteStartObject(); 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(); } // WriteAssociativeArray
} // 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 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 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 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()); }
/// <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(); }
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(); } }
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); }
/// <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(); }
public Message SerializeRequest(MessageVersion messageVersion, object[] parameters) { byte[] body; Newtonsoft.Json.JsonSerializer serializer = endpoint.NewtonsoftSettings().JsonSerializer; using (MemoryStream ms = new MemoryStream()) { using (StreamWriter sw = new StreamWriter(ms, Encoding.UTF8)) { using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw)) { if (parameters.Length == 1) { // Single parameter, assuming bare serializer.Serialize(sw, parameters[0]); } else { writer.WriteStartObject(); for (int i = 0; i < this.operation.Messages[0].Body.Parts.Count; i++) { writer.WritePropertyName(this.operation.Messages[0].Body.Parts[i].Name); serializer.Serialize(writer, parameters[i]); } writer.WriteEndObject(); } writer.Flush(); sw.Flush(); body = ms.ToArray(); } } } if (traceSource.Switch.ShouldTrace(TraceEventType.Information)) { traceSource.TraceEvent(TraceEventType.Information, 1004, System.Text.Encoding.UTF8.GetString(body)); } Message requestMessage = Message.CreateMessage(messageVersion, operation.Messages[0].Action, new RawBodyWriter(body)); requestMessage.Headers.To = operationUri; requestMessage.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Raw)); HttpRequestMessageProperty reqProp = new HttpRequestMessageProperty(); reqProp.Headers[HttpRequestHeader.ContentType] = "application/json"; requestMessage.Properties.Add(HttpRequestMessageProperty.Name, reqProp); return(requestMessage); }
//[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 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 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(); } }
public Message SerializeRequest(MessageVersion messageVersion, object[] parameters) { byte[] body; var serializer = NewtonsoftJsonSettings.GetSerializer(); using (var ms = new MemoryStream()) { using (var sw = new StreamWriter(ms)) { using (Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw)) { writer.Formatting = NewtonsoftJsonSettings.GetFormatting(); if (parameters.Length == 1) { // Single parameter, assuming bare serializer.Serialize(sw, parameters[0]); } else { writer.WriteStartObject(); foreach (MessagePartDescription t in this.m_operation.Messages[0].Body.Parts) { writer.WritePropertyName(t.Name); serializer.Serialize(writer, parameters[0]); } writer.WriteEndObject(); } writer.Flush(); sw.Flush(); body = ms.ToArray(); } } } Message requestMessage = Message.CreateMessage(messageVersion, m_operation.Messages[0].Action, new RawBodyWriter(body)); requestMessage.Headers.To = m_operationUri; requestMessage.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Raw)); HttpRequestMessageProperty reqProp = new HttpRequestMessageProperty(); reqProp.Headers[HttpRequestHeader.ContentType] = "application/json"; requestMessage.Properties.Add(HttpRequestMessageProperty.Name, reqProp); return(requestMessage); }
public 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(); }
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 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; }
/// <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()); }
} // 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> /// 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 ActionResult OpenNBG(string fname, bool antrag, bool sign, bool do_xtraData) { string err = null; string rawHtml = null; string StartID = null; if (string.IsNullOrWhiteSpace(fname)) { err = "Der übergebene Parameter fname darf n icht leer sein. Starten Sie am besten die Anwendung über die Index.cshtml."; } else { var stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(fname); byte[] BT4allFile = null; if (fname.EndsWith(".xml", StringComparison.CurrentCultureIgnoreCase)) { var biproString = new System.IO.StreamReader(stream).ReadToEnd(); using (var mem = new System.IO.MemoryStream()) { var writer = new Newtonsoft.Json.JsonTextWriter( new System.IO.StreamWriter(mem)); writer.WriteStartObject(); writer.WritePropertyName("module"); writer.WriteValue("YA"); writer.WritePropertyName("data"); writer.WriteValue(biproString); writer.WritePropertyName("callBackURL"); writer.WriteValue("https://nuernberger.de"); writer.WriteEndObject(); writer.Flush(); BT4allFile = mem.GetBuffer().Take((int)mem.Length).ToArray(); } } else if (fname.EndsWith(".txt", StringComparison.CurrentCultureIgnoreCase)) { var biproString = new System.IO.StreamReader(stream).ReadToEnd(); using (var mem = new System.IO.MemoryStream()) { var writer = new Newtonsoft.Json.JsonTextWriter( new System.IO.StreamWriter(mem)); writer.WriteStartObject(); writer.WritePropertyName("module"); writer.WriteValue("LVLebenPrivat_6"); writer.WritePropertyName("data"); writer.WriteValue(biproString); writer.WritePropertyName("callBackURL"); writer.WriteValue("https://nuernberger.de"); writer.WriteEndObject(); writer.Flush(); BT4allFile = mem.GetBuffer().Take((int)mem.Length).ToArray(); } } else //PDF auspacken { iTextSharp.text.pdf.PdfReader reader; try { reader = new iTextSharp.text.pdf.PdfReader(stream); iTextSharp.text.pdf.PdfDictionary root = reader.Catalog; iTextSharp.text.pdf.PdfDictionary names = root.GetAsDict(iTextSharp.text.pdf.PdfName.NAMES); if (names != null) { iTextSharp.text.pdf.PdfDictionary embeddedFiles = names.GetAsDict(iTextSharp.text.pdf.PdfName.EMBEDDEDFILES); if (embeddedFiles != null) { var en = embeddedFiles.Keys.GetEnumerator(); while (en.MoveNext()) { var obj = embeddedFiles.GetAsArray(en.Current as iTextSharp.text.pdf.PdfName); iTextSharp.text.pdf.PdfDictionary fileSpec = obj.GetAsDict(1); iTextSharp.text.pdf.PdfDictionary file = fileSpec.GetAsDict(iTextSharp.text.pdf.PdfName.EF); foreach (iTextSharp.text.pdf.PdfName key in file.Keys) { iTextSharp.text.pdf.PRStream innerstream = (iTextSharp.text.pdf.PRStream) iTextSharp.text.pdf.PdfReader.GetPdfObject(file.GetAsIndirectObject(key)); if (innerstream != null) { BT4allFile = iTextSharp.text.pdf.PdfReader.GetStreamBytes(innerstream); break; } } } } } } catch (Exception ex) { err = ex.ToString(); } } //Request mit Post des Falls und Response mit der ID if (BT4allFile != null) { try { //var Req = System.Net.WebRequest.Create("http://localhost/BT4All/SV/d.svc/m?i=getStartID_SLS_NoSign"); var Req = System.Net.WebRequest.Create("https://test.nuernberger-bt4all.de/BT4All/SV/d.svc/m?i=getStartID_SLS_NoSign"); Req.Method = "POST"; //Req.UseDefaultCredentials = true; var xtraData = new byte[0]; if (do_xtraData) { var xstream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream( "AufrufVergleicher.170728_NuernbergerVorschlag.xml"); var bList = new List <byte>(); int b = xstream.ReadByte(); while (b != -1) { bList.Add((byte)b); b = xstream.ReadByte(); } } Req.ContentLength = BT4allFile.Length + xtraData.Length; if (xtraData.Length > 0) { Req.Headers.Add("xtraDataLen", xtraData.Length.ToString()); } var reqS = Req.GetRequestStream(); reqS.Write(BT4allFile, 0, BT4allFile.Length); reqS.Write(xtraData, 0, xtraData.Length); var resp = Req.GetResponse(); var respStream = resp.GetResponseStream(); var respData = new byte[resp.ContentLength]; respStream.Read(respData, 0, respData.Length); try { using (var mem = new System.IO.MemoryStream(respData)) { Newtonsoft.Json.JsonTextReader jReader = new Newtonsoft.Json.JsonTextReader( new System.IO.StreamReader(mem)); while (jReader.Read()) { var tp = jReader.TokenType; var val = jReader.Value; if (tp == Newtonsoft.Json.JsonToken.PropertyName && (val as string) == "sid") { StartID = jReader.ReadAsString(); break; } } } } catch { using (var strReader = new System.IO.StreamReader(new System.IO.MemoryStream(respData))) { err = "Fehler beim Parsen des JSON Objekts. Serverresponse: "; rawHtml = strReader.ReadToEnd(); } } } catch (Exception ex) { err = ex.ToString(); } } } //=>iframe wird in der Views/Home/INDEX.cshtml aufgebaut ViewBag.err = err; ViewBag.rawHtml = rawHtml; ViewBag.StartID = StartID; ViewBag.antrag = antrag; ViewBag.sign = sign; return(View()); }
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(); } }
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(); } }
/// <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(); } }
public override void ExecuteResult(System.Web.Mvc.ControllerContext context) { context.HttpContext.Response.ContentType = "application/json"; context.HttpContext.Response.ContentEncoding = System.Text.Encoding.UTF8; using (Newtonsoft.Json.JsonTextWriter jsonWriter = new Newtonsoft.Json.JsonTextWriter(context.HttpContext.Response.Output)) { jsonWriter.Formatting = Newtonsoft.Json.Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("Tables"); jsonWriter.WriteStartArray(); using (System.Data.Common.DbConnection con = SQL.CreateConnection()) { if (con.State != System.Data.ConnectionState.Open) { con.Open(); } using (System.Data.Common.DbCommand cmd = this.GetCommand(con)) { using (System.Data.Common.DbDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.SequentialAccess | System.Data.CommandBehavior.CloseConnection )) { do { jsonWriter.WriteStartObject(); // tbl = new Table(); jsonWriter.WritePropertyName("Columns"); jsonWriter.WriteStartArray(); for (int i = 0; i < dr.FieldCount; ++i) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("ColumnName"); jsonWriter.WriteValue(dr.GetName(i)); jsonWriter.WritePropertyName("FieldType"); jsonWriter.WriteValue(SQL.GetAssemblyQualifiedNoVersionName(dr.GetFieldType(i))); jsonWriter.WriteEndObject(); } // Next i jsonWriter.WriteEndArray(); jsonWriter.WritePropertyName("Rows"); jsonWriter.WriteStartArray(); if (dr.HasRows) { while (dr.Read()) { object[] thisRow = new object[dr.FieldCount]; jsonWriter.WriteStartArray(); // object[] thisRow = new object[dr.FieldCount]; for (int i = 0; i < dr.FieldCount; ++i) { jsonWriter.WriteValue(dr.GetValue(i)); } // Next i jsonWriter.WriteEndArray(); // tbl.Rows.Add(thisRow); } // Whend } // End if (dr.HasRows) jsonWriter.WriteEndArray(); jsonWriter.WriteEndObject(); // ser.Tables.Add(tbl); } while (dr.NextResult()); } // End using dr } // End using cmd if (con.State != System.Data.ConnectionState.Closed) { con.Close(); } } // End using con jsonWriter.WriteEndArray(); jsonWriter.WriteEndObject(); jsonWriter.Flush(); } // End Using jsonWriter context.HttpContext.Response.Output.Flush(); context.HttpContext.Response.OutputStream.Flush(); context.HttpContext.Response.Flush(); } // End Sub SerializeLargeDataset
public static void ToJson(this Method method, System.IO.Stream target) { using (var sw = new System.IO.StreamWriter(target, System.Text.Encoding.UTF8, 4 * 1024, true)) using (var jw = new Newtonsoft.Json.JsonTextWriter(sw)) { jw.Formatting = Newtonsoft.Json.Formatting.Indented; foreach (var _ in method.All((item, action) => { if (item == method) { if (action == VisitorState.Enter) { jw.WriteStartArray(); } else if (action == VisitorState.Leave) { jw.WriteEndArray(); } return(true); } else if (item is Statement) { if (action == VisitorState.Enter) { var stm = item as Statement; jw.WriteStartObject(); jw.WritePropertyName("type"); jw.WriteValue(stm.GetType().FullName); if (!string.IsNullOrWhiteSpace(stm.Name)) { jw.WritePropertyName("name"); jw.WriteValue(stm.Name); } jw.WritePropertyName("children"); jw.WriteStartArray(); } else if (action == VisitorState.Leave) { jw.WriteEndArray(); jw.WriteEndObject(); } return(true); } else if (item is Expression) { if (action == VisitorState.Enter) { var expr = item as Expression; jw.WriteStartObject(); jw.WritePropertyName("type"); jw.WriteValue(expr.GetType().FullName); if (!string.IsNullOrWhiteSpace(expr.Name)) { jw.WritePropertyName("name"); jw.WriteValue(expr.Name); } if (expr.SourceExpression != null) { jw.WritePropertyName("source"); jw.WriteValue(expr.SourceExpression.ToString()); } jw.WritePropertyName("children"); jw.WriteStartArray(); } else if (action == VisitorState.Leave) { jw.WriteEndArray(); jw.WriteEndObject(); } return(true); } else { return(false); } })) { } } }
private static ArraySegment <byte> GenerateEvents(ref long sequence, int eventCount) { using (MemoryStream buffer = new MemoryStream()) { using (StreamWriter writer = new StreamWriter(buffer, new UTF8Encoding(false), 4096, true)) using (Newtonsoft.Json.JsonTextWriter w = new Newtonsoft.Json.JsonTextWriter(writer)) { w.WriteStartArray(); for (int i = 0; i < eventCount; i++) { var sequenceNo = Interlocked.Increment(ref sequence); w.WriteStartObject(); w.WritePropertyName("@timestamp"); w.WriteValue(DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fff'Z'")); w.WritePropertyName("logger"); w.WriteValue("Program.GridLogger"); w.WritePropertyName("level"); w.WriteValue("INFO"); w.WritePropertyName("hostname"); w.WriteValue(Environment.MachineName); w.WritePropertyName("taskId"); w.WriteValue(1); w.WritePropertyName("jobId"); w.WriteValue(3); w.WritePropertyName("thread"); w.WriteValue("4"); w.WritePropertyName("message"); w.WriteValue($"log message sequence {sequenceNo}"); w.WritePropertyName("eventSequence"); w.WriteValue(sequenceNo); w.WritePropertyName("metrics"); w.WriteStartObject(); w.WritePropertyName("metric1"); w.WriteValue(4.3); w.WritePropertyName("metric2"); w.WriteValue(5.3); w.WritePropertyName("metric3"); w.WriteValue(0.3 * sequenceNo); w.WritePropertyName("seq"); w.WriteValue(sequenceNo); w.WriteEndObject(); w.WriteEndObject(); } w.WriteEndArray(); } buffer.TryGetBuffer(out var result); return(result); } }
}// End Sub public static void SerializeDataTableAsAssociativeJsonArray( System.Data.Common.DbCommand cmd , Microsoft.AspNetCore.Http.HttpContext context , bool pretty , System.Text.Encoding enc) { SqlService service = (SqlService)context.RequestServices.GetService(typeof(SqlService)); using (System.IO.TextWriter sw = new System.IO.StreamWriter(context.Response.Body, enc)) { using (Newtonsoft.Json.JsonTextWriter jsonWriter = new Newtonsoft.Json.JsonTextWriter(sw)) { if (pretty) { jsonWriter.Formatting = Newtonsoft.Json.Formatting.Indented; } // jsonWriter.WriteStartObject(); // jsonWriter.WritePropertyName("tables"); // jsonWriter.WriteStartArray(); using (System.Data.Common.DbConnection con = service.Connection) { cmd.Connection = con; if (con.State != System.Data.ConnectionState.Open) { con.Open(); } try { using (System.Data.Common.DbDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.SequentialAccess | System.Data.CommandBehavior.CloseConnection )) { do { // jsonWriter.WriteStartObject(); // tbl = new Table(); //jsonWriter.WritePropertyName("columns"); //// WriteArray(jsonWriter, dr); //WriteAssociativeArray(jsonWriter, dr); //jsonWriter.WritePropertyName("rows"); jsonWriter.WriteStartArray(); if (dr.HasRows) { string[] columns = new string[dr.FieldCount]; for (int i = 0; i < dr.FieldCount; i++) { columns[i] = dr.GetName(i); } // Next i while (dr.Read()) { // jsonWriter.WriteStartArray(); // object[] thisRow = new object[dr.FieldCount]; jsonWriter.WriteStartObject(); // tbl = new Table(); for (int i = 0; i < dr.FieldCount; ++i) { jsonWriter.WritePropertyName(columns[i]); object obj = dr.GetValue(i); if (obj == System.DBNull.Value) { obj = null; } jsonWriter.WriteValue(obj); } // Next i // jsonWriter.WriteEndArray(); // tbl.Rows.Add(thisRow); jsonWriter.WriteEndObject(); } // Whend } // End if (dr.HasRows) jsonWriter.WriteEndArray(); // jsonWriter.WriteEndObject(); // ser.Tables.Add(tbl); } while (dr.NextResult()); } // End using dr } catch (System.Exception ex) { System.Console.WriteLine(ex.Message); throw; } if (con.State != System.Data.ConnectionState.Closed) { con.Close(); } } // End using con // jsonWriter.WriteEndArray(); // jsonWriter.WriteEndObject(); jsonWriter.Flush(); } // End Using jsonWriter } // End Using sw } // End Sub SerializeDataTableAsAssociativeJsonArray
} // End Sub WriteArray public static void AnyDataReaderToAnyJson( string sql , SqlService service , System.Collections.Generic.Dictionary <string, object> pars , System.Web.HttpContext context , RenderType_t format) { using (System.Data.Common.DbConnection con = service.Connection) { using (System.Data.Common.DbCommand cmd = con.CreateCommand()) { cmd.CommandText = sql; service.AddParameterList(pars, cmd); // cmd.ExecuteNonQuery // cmd.ExecuteReader // cmd.ExecuteScalar using (System.Data.Common.DbDataReader dr = cmd.ExecuteReader( System.Data.CommandBehavior.SequentialAccess | System.Data.CommandBehavior.CloseConnection)) { using (System.IO.StreamWriter output = new System.IO.StreamWriter(context.Response.OutputStream)) { using (Newtonsoft.Json.JsonTextWriter jsonWriter = new Newtonsoft.Json.JsonTextWriter(output)) // context.Response.Output) { if (format.HasFlag(RenderType_t.Indented)) { jsonWriter.Formatting = Newtonsoft.Json.Formatting.Indented; } context.Response.StatusCode = (int)System.Net.HttpStatusCode.OK; context.Response.ContentType = "application/json"; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("tables"); jsonWriter.WriteStartArray(); do { if (!format.HasFlag(RenderType_t.Data_Only) && !format.HasFlag(RenderType_t.DataTable)) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("columns"); if (format.HasFlag(RenderType_t.Columns_Associative)) { WriteAssociativeColumnsArray(jsonWriter, dr, format); } else if (format.HasFlag(RenderType_t.Columns_ObjectArray)) { WriteComplexArray(jsonWriter, dr, format); } else // (format.HasFlag(RenderType_t.Array)) { WriteArray(jsonWriter, dr); } } // End if (!format.HasFlag(RenderType_t.Data_Only)) if (!format.HasFlag(RenderType_t.Data_Only) && !format.HasFlag(RenderType_t.DataTable)) { jsonWriter.WritePropertyName("rows"); } // End if (!format.HasFlag(RenderType_t.Data_Only)) jsonWriter.WriteStartArray(); if (dr.HasRows) { string[] columns = null; if (format.HasFlag(RenderType_t.DataTable)) { columns = new string[dr.FieldCount]; for (int i = 0; i < dr.FieldCount; i++) { columns[i] = dr.GetName(i); } // Next i } // End if (format.HasFlag(RenderType_t.DataTable)) while (dr.Read()) { if (format.HasFlag(RenderType_t.DataTable)) { jsonWriter.WriteStartObject(); } else { jsonWriter.WriteStartArray(); } for (int i = 0; i <= dr.FieldCount - 1; i++) { object obj = dr.GetValue(i); if (obj == System.DBNull.Value) { obj = null; } if (columns != null && format.HasFlag(RenderType_t.DataTable)) { jsonWriter.WritePropertyName(columns[i]); } jsonWriter.WriteValue(obj); } // Next i if (format.HasFlag(RenderType_t.DataTable)) { jsonWriter.WriteEndObject(); } else { jsonWriter.WriteEndArray(); } } // Whend } // End if (dr.HasRows) jsonWriter.WriteEndArray(); if (!format.HasFlag(RenderType_t.Data_Only) && !format.HasFlag(RenderType_t.DataTable)) { jsonWriter.WriteEndObject(); } // End if (!format.HasFlag(RenderType_t.Data_Only)) } while (dr.NextResult()); jsonWriter.WriteEndArray(); jsonWriter.WriteEndObject(); jsonWriter.Flush(); output.Flush(); } // jsonWriter } // output } // dr } // End Using cmd if (con.State != System.Data.ConnectionState.Closed) { con.Close(); } } // con } // End Sub WriteArray