public override void Write( System.Text.Json.Utf8JsonWriter writer, ElmTestRsReportJsonEntryFailureReasonData value, System.Text.Json.JsonSerializerOptions options) { throw new System.NotImplementedException(); }
/// <summary> /// Executes the result operation of the action method asynchronously. This method is called by the Controller to process the result of an action method. /// </summary> /// <param name="context"></param> /// <returns></returns> public override async Task ExecuteResultAsync(ActionContext context) { _context = context ?? throw new ArgumentNullException(nameof(context)); DisableBuffering(); if (StatusCode.HasValue) { context.HttpContext.Response.StatusCode = StatusCode.Value; } if (!string.IsNullOrWhiteSpace(ContentType)) { context.HttpContext.Response.ContentType = ContentType; } StreamToWrite = _context.HttpContext.Response.Body; if (writter == null) { writter = new System.Text.Json.Utf8JsonWriter(StreamToWrite, JsonWriterOptions); } readyTaskCompletionSource.SetResult(true); await completeTaskCompletionSource.Task; }
public void ForceReady() { if (writter == null) { writter = new System.Text.Json.Utf8JsonWriter(StreamToWrite, JsonWriterOptions); } readyTaskCompletionSource.TrySetResult(true); }
public static async Task WriteToStream(Stream StreamToWrite, DataSet DS, CancellationToken cancellationToken, JsonWriterOptions JsonWriterOptions) { using (System.Text.Json.Utf8JsonWriter writter = new System.Text.Json.Utf8JsonWriter(StreamToWrite, JsonWriterOptions)) { writter.WriteStartObject(); writter.WriteStartArray("Tables"); if (DS.Tables.Count > 0) { foreach (DataTable table in DS.Tables) { writter.WriteStartObject(); writter.WriteString("TableName", table.TableName); writter.WriteStartArray("Columns"); foreach (DataColumn column in table.Columns) { writter.WriteStartArray(); JsonSerializer.Serialize(writter, column.ColumnName); JsonSerializer.Serialize(writter, ColumnType(column)); writter.WriteEndArray(); } writter.WriteEndArray(); writter.WriteStartArray("Rows"); await writter.FlushAsync(cancellationToken); if (table.Rows.Count > 0) { foreach (DataRow row in table.Rows) { writter.WriteStartArray(); foreach (var item in row.ItemArray) { JsonSerializer.Serialize(writter, item); } writter.WriteEndArray();; } } writter.WriteEndArray(); writter.WriteEndObject(); } } writter.WriteEndArray(); writter.WriteEndObject(); } await StreamToWrite.FlushAsync(); }
public void ToJson(System.Text.Json.Utf8JsonWriter w) { w.WriteStartObject(); w.WriteString("id", Hid); w.WriteString("description", Description); w.WriteString("tag", Tag); w.WriteString("avatar_url", AvatarUrl); w.WriteString("created", Formats.TimestampExportFormat.Format(Created)); w.WriteString("tz", UiTz); w.WriteEndObject(); }
public static void WriteErrorDetailsResponseJson(this HttpContext Context, ErrorDetails errorDetails) { Context.Response.ContentType = "application/json"; using Utf8JsonWriter writer = new System.Text.Json.Utf8JsonWriter(Context.Response.BodyWriter); writer.WriteStartObject(); foreach (var item in errorDetails.GetType().GetProperties()) { writer.WritePropertyName(item.Name); if (item.PropertyType == typeof(int)) { writer.WriteNumberValue((int)item.GetValue(errorDetails)); } else if (item.PropertyType == typeof(string)) { writer.WriteStringValue(item.GetValue(errorDetails).ToString()); } } writer.WriteEndObject(); writer.Flush(); }
public string Serialize(MeetingModelRegular value) { var options = new JsonWriterOptions { Indented = true }; using (var stream = new System.IO.MemoryStream()) { using (var writer = new System.Text.Json.Utf8JsonWriter(stream, options)) { writer.WriteStartObject(); writer.WriteString("MeetingType", MeetingType); writer.WriteString("ID", ID); writer.WriteString("DayOfMeeting", DayOfMeeting); writer.WriteString("Toastmaster", Toastmaster); writer.WriteString("Speaker1", Speaker1); writer.WriteString("Speaker2", Speaker2); writer.WriteString("GeneralEvaluator", GeneralEvaluator); writer.WriteString("Evaluator1", Evaluator1); writer.WriteString("Evaluator2", Evaluator2); writer.WriteString("TableTopics", TableTopics); writer.WriteString("AhCounter", AhCounter); writer.WriteString("Grammarian", Grammarian); writer.WriteString("Timer", Timer); writer.WriteString("QuizMaster", QuizMaster); writer.WriteString("Video", Video); writer.WriteString("HotSeat", HotSeat); writer.WriteString("Attendees", Attendees?.ToString()); writer.WriteString("Resolved", Resolved); writer.WriteEndObject(); } return(Encoding.UTF8.GetString(stream.ToArray())); } // return JsonSerializer.ToString<MeetingModelRegular>(value, options); }
protected virtual void OnWriteDictionary(ref WriteStackFrame current, Utf8JsonWriter writer) { }
private static bool WriteCore <TValue>( JsonConverter jsonConverter, Utf8JsonWriter writer, in TValue value,
private static bool HandleEnumerable( JsonClassInfo elementClassInfo, JsonSerializerOptions options, Utf8JsonWriter writer, ref WriteStack state) { Debug.Assert(state.Current.JsonPropertyInfo !.ClassType == ClassType.Enumerable); if (state.Current.CollectionEnumerator == null) { IEnumerable?enumerable = (IEnumerable?)state.Current.JsonPropertyInfo.GetValueAsObject(state.Current.CurrentValue); if (enumerable == null) { // If applicable, we only want to ignore object properties. if (state.Current.JsonClassInfo !.ClassType != ClassType.Object || !state.Current.JsonPropertyInfo.IgnoreNullValues) { // Write a null object or enumerable. state.Current.WriteObjectOrArrayStart(ClassType.Enumerable, writer, options, writeNull: true); } if (state.Current.PopStackOnEndCollection) { state.Pop(); } return(true); } if (options.ReferenceHandling.ShouldWritePreservedReferences()) { if (WriteReference(ref state, writer, options, ClassType.Enumerable, enumerable)) { return(WriteEndArray(ref state)); } } else { state.Current.WriteObjectOrArrayStart(ClassType.Enumerable, writer, options); } state.Current.CollectionEnumerator = enumerable.GetEnumerator(); } if (state.Current.CollectionEnumerator.MoveNext()) { // Check for polymorphism. if (elementClassInfo.ClassType == ClassType.Unknown) { object?currentValue = state.Current.CollectionEnumerator.Current; GetRuntimeClassInfo(currentValue, ref elementClassInfo, options); } if (elementClassInfo.ClassType == ClassType.Value) { elementClassInfo.PolicyProperty !.WriteEnumerable(ref state, writer); } else if (state.Current.CollectionEnumerator.Current == null) { // Write a null object or enumerable. writer.WriteNullValue(); } else { // An object or another enumerator requires a new stack frame. object nextValue = state.Current.CollectionEnumerator.Current; state.Push(elementClassInfo, nextValue); } return(false); } // We are done enumerating. writer.WriteEndArray(); // Used for ReferenceHandling.Preserve if (state.Current.WriteWrappingBraceOnEndPreservedArray) { writer.WriteEndObject(); } return(WriteEndArray(ref state)); }
private static async Task WriteStreamAsync <TValue>( Stream utf8Json, TValue value, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken) { JsonSerializerOptions options = jsonTypeInfo.Options; JsonWriterOptions writerOptions = options.GetWriterOptions(); using (var bufferWriter = new PooledByteBufferWriter(options.DefaultBufferSize)) using (var writer = new Utf8JsonWriter(bufferWriter, writerOptions)) { WriteStack state = new WriteStack { CancellationToken = cancellationToken }; JsonConverter converter = state.Initialize(jsonTypeInfo, supportContinuation: true); bool isFinalBlock; try { do { state.FlushThreshold = (int)(bufferWriter.Capacity * FlushThreshold); try { isFinalBlock = WriteCore(converter, writer, value, options, ref state); if (state.SuppressFlush) { Debug.Assert(!isFinalBlock); Debug.Assert(state.PendingTask is not null); state.SuppressFlush = false; } else { await bufferWriter.WriteToStreamAsync(utf8Json, cancellationToken).ConfigureAwait(false); bufferWriter.Clear(); } } finally { // Await any pending resumable converter tasks (currently these can only be IAsyncEnumerator.MoveNextAsync() tasks). // Note that pending tasks are always awaited, even if an exception has been thrown or the cancellation token has fired. if (state.PendingTask is not null) { try { await state.PendingTask.ConfigureAwait(false); } catch { // Exceptions should only be propagated by the resuming converter // TODO https://github.com/dotnet/runtime/issues/22144 } } // Dispose any pending async disposables (currently these can only be completed IAsyncEnumerators). if (state.CompletedAsyncDisposables?.Count > 0) { await state.DisposeCompletedAsyncDisposables().ConfigureAwait(false); } } } while (!isFinalBlock); } catch { // On exception, walk the WriteStack for any orphaned disposables and try to dispose them. await state.DisposePendingDisposablesOnExceptionAsync().ConfigureAwait(false); throw; } } }
private static async Task Execute(string sql, HttpContext context) { context.Response.Headers.Add("Content-Type", "application/json"); var koraliumService = context.RequestServices.GetService <IKoraliumTransportService>(); var logger = context.RequestServices.GetService <ILogger <IKoraliumTransportService> >(); QueryResult result = null; try { result = await koraliumService.Execute(sql, new Shared.SqlParameters(), context); } catch (SqlErrorException error) { logger.LogWarning(error.Message); await WriteError(context, 400, error.Message); return; } catch (AuthorizationFailedException authFailed) { logger.LogWarning(authFailed.Message, authFailed); await WriteError(context, 401, authFailed.Message); return; } catch (Exception e) { logger.LogError(e, "Unexpected exception thrown"); await WriteError(context, 500, "Internal error"); return; } var responseStream = new System.Text.Json.Utf8JsonWriter(context.Response.Body); IJsonEncoder[] encoders = new IJsonEncoder[result.Columns.Count]; JsonEncodedText[] names = new JsonEncodedText[result.Columns.Count]; for (int i = 0; i < encoders.Length; i++) { encoders[i] = EncoderHelper.GetEncoder(result.Columns[i]); names[i] = JsonEncodedText.Encode(result.Columns[i].Name); } System.Diagnostics.Stopwatch encodingWatch = new System.Diagnostics.Stopwatch(); encodingWatch.Start(); responseStream.WriteStartObject(); responseStream.WriteStartArray(_valuesText); foreach (var row in result.Result) { responseStream.WriteStartObject(); for (int i = 0; i < encoders.Length; i++) { responseStream.WritePropertyName(names[i]); encoders[i].Encode(in responseStream, in row); } responseStream.WriteEndObject(); } responseStream.WriteEndArray(); responseStream.WriteEndObject(); encodingWatch.Stop(); await responseStream.FlushAsync(); }
public abstract bool GetMemberAndWriteJsonExtensionData(object obj, ref WriteStack state, Utf8JsonWriter writer);
private static bool HandleDictionary( JsonClassInfo elementClassInfo, JsonSerializerOptions options, Utf8JsonWriter writer, ref WriteStack state) { JsonPropertyInfo jsonPropertyInfo = state.Current.JsonPropertyInfo; if (state.Current.CollectionEnumerator == null) { IEnumerable enumerable; enumerable = (IEnumerable)jsonPropertyInfo.GetValueAsObject(state.Current.CurrentValue); if (enumerable == null) { if (!state.Current.JsonPropertyInfo.IgnoreNullValues) { // Write a null object or enumerable. state.Current.WriteObjectOrArrayStart(ClassType.Enumerable, writer, writeNull: true); } return(true); } if (enumerable is IDictionary dictionary) { state.Current.CollectionEnumerator = dictionary.GetEnumerator(); } else { state.Current.CollectionEnumerator = enumerable.GetEnumerator(); } if (state.Current.ExtensionDataStatus != ExtensionDataWriteStatus.Writing) { state.Current.WriteObjectOrArrayStart(ClassType.Dictionary, writer); } } if (state.Current.CollectionEnumerator.MoveNext()) { // Check for polymorphism. if (elementClassInfo.ClassType == ClassType.Unknown) { object currentValue = ((IDictionaryEnumerator)state.Current.CollectionEnumerator).Entry.Value; GetRuntimeClassInfo(currentValue, ref elementClassInfo, options); } if (elementClassInfo.ClassType == ClassType.Value) { elementClassInfo.PolicyProperty.WriteDictionary(ref state, writer); } else if (state.Current.CollectionEnumerator.Current == null) { writer.WriteNull(jsonPropertyInfo.Name); } else { // An object or another enumerator requires a new stack frame. var enumerator = (IDictionaryEnumerator)state.Current.CollectionEnumerator; object value = enumerator.Value; state.Push(elementClassInfo, value); state.Current.KeyName = (string)enumerator.Key; } return(false); } // We are done enumerating. if (state.Current.ExtensionDataStatus == ExtensionDataWriteStatus.Writing) { state.Current.ExtensionDataStatus = ExtensionDataWriteStatus.Finished; } else { writer.WriteEndObject(); } if (state.Current.PopStackOnEndCollection) { state.Pop(); } else { state.Current.EndDictionary(); } return(true); }
private static void Serialize <TValue>(Utf8JsonWriter writer, in TValue value, Type runtimeType, JsonSerializerOptions?options)
private static bool HandleEnumerable( JsonClassInfo elementClassInfo, JsonSerializerOptions options, Utf8JsonWriter writer, ref WriteStack state) { Debug.Assert(state.Current.JsonPropertyInfo.ClassType == ClassType.Enumerable); if (state.Current.Enumerator == null) { IEnumerable enumerable = (IEnumerable)state.Current.JsonPropertyInfo.GetValueAsObject(state.Current.CurrentValue); if (enumerable == null) { if (!state.Current.JsonPropertyInfo.IgnoreNullValues) { // Write a null object or enumerable. state.Current.WriteObjectOrArrayStart(ClassType.Enumerable, writer, writeNull: true); } return(true); } state.Current.Enumerator = enumerable.GetEnumerator(); state.Current.WriteObjectOrArrayStart(ClassType.Enumerable, writer); } if (state.Current.Enumerator.MoveNext()) { // Check for polymorphism. if (elementClassInfo.ClassType == ClassType.Unknown) { object currentValue = state.Current.Enumerator.Current; GetRuntimeClassInfo(currentValue, ref elementClassInfo, options); } if (elementClassInfo.ClassType == ClassType.Value) { elementClassInfo.GetPolicyProperty().WriteEnumerable(ref state.Current, writer); } else if (state.Current.Enumerator.Current == null) { // Write a null object or enumerable. writer.WriteNullValue(); } else { // An object or another enumerator requires a new stack frame. object nextValue = state.Current.Enumerator.Current; state.Push(elementClassInfo, nextValue); } return(false); } // We are done enumerating. writer.WriteEndArray(); if (state.Current.PopStackOnEnd) { state.Pop(); } else { state.Current.EndArray(); } return(true); }
protected override void OnWriteDictionary(ref WriteStackFrame current, Utf8JsonWriter writer) { JsonSerializer.WriteDictionary(Converter, Options, ref current, writer); }
// There are three conditions to consider for an object (primitive value, enumerable or object) being processed here: // 1) The object type was specified as the root-level return type to a Parse\Read method. // 2) The object is property on a parent object. // 3) The object is an element in an enumerable. private static bool Write( Utf8JsonWriter writer, int originalWriterDepth, int flushThreshold, JsonSerializerOptions options, ref WriteStack state) { bool finishedSerializing; try { do { WriteStackFrame current = state.Current; switch (current.JsonClassInfo.ClassType) { case ClassType.Enumerable: finishedSerializing = HandleEnumerable(current.JsonClassInfo.ElementClassInfo, options, writer, ref state); break; case ClassType.Value: Debug.Assert(current.JsonPropertyInfo.ClassType == ClassType.Value); current.JsonPropertyInfo.Write(ref state, writer); finishedSerializing = true; break; case ClassType.Object: finishedSerializing = WriteObject(options, writer, ref state); break; case ClassType.Dictionary: case ClassType.IDictionaryConstructible: finishedSerializing = HandleDictionary(current.JsonClassInfo.ElementClassInfo, options, writer, ref state); break; default: Debug.Assert(state.Current.JsonClassInfo.ClassType == ClassType.Unknown); // Treat typeof(object) as an empty object. finishedSerializing = WriteObject(options, writer, ref state); break; } if (finishedSerializing) { if (writer.CurrentDepth == 0 || writer.CurrentDepth == originalWriterDepth) { break; } } else if (writer.CurrentDepth >= options.EffectiveMaxDepth) { ThrowHelper.ThrowJsonException_DepthTooLarge(writer.CurrentDepth, state, options); } // If serialization is not yet end and we surpass beyond flush threshold return false and flush stream. if (flushThreshold >= 0 && writer.BytesPending > flushThreshold) { return(false); } } while (true); } catch (InvalidOperationException ex) when(ex.Source == ThrowHelper.ExceptionSourceValueToRethrowAsJsonException) { ThrowHelper.ReThrowWithPath(state, ex); } catch (JsonException ex) { ThrowHelper.AddExceptionInformation(state, ex); throw; } return(true); }
public override void WriteDictionary(ref WriteStackFrame current, Utf8JsonWriter writer) { Debug.Assert(ShouldSerialize); JsonSerializer.WriteDictionary(ValueConverter, Options, ref current, writer); }
protected abstract void OnWriteEnumerable(ref WriteStackFrame current, Utf8JsonWriter writer);
private static bool HandleObject( JsonPropertyInfo jsonPropertyInfo, JsonSerializerOptions options, Utf8JsonWriter writer, ref WriteStack state) { Debug.Assert( state.Current.JsonClassInfo.ClassType == ClassType.Object || state.Current.JsonClassInfo.ClassType == ClassType.Unknown); if (!jsonPropertyInfo.ShouldSerialize) { state.Current.MoveToNextProperty = true; return(true); } bool obtainedValue = false; object currentValue = null; // Check for polymorphism. if (jsonPropertyInfo.ClassType == ClassType.Unknown) { currentValue = jsonPropertyInfo.GetValueAsObject(state.Current.CurrentValue); obtainedValue = true; GetRuntimePropertyInfo(currentValue, state.Current.JsonClassInfo, ref jsonPropertyInfo, options); } state.Current.JsonPropertyInfo = jsonPropertyInfo; if (jsonPropertyInfo.ClassType == ClassType.Value) { jsonPropertyInfo.Write(ref state, writer); state.Current.MoveToNextProperty = true; return(true); } // A property that returns an enumerator keeps the same stack frame. if (jsonPropertyInfo.ClassType == ClassType.Enumerable) { bool endOfEnumerable = HandleEnumerable(jsonPropertyInfo.ElementClassInfo, options, writer, ref state); if (endOfEnumerable) { state.Current.MoveToNextProperty = true; } return(endOfEnumerable); } // A property that returns a dictionary keeps the same stack frame. if (jsonPropertyInfo.ClassType == ClassType.Dictionary) { bool endOfEnumerable = HandleDictionary(jsonPropertyInfo.ElementClassInfo, options, writer, ref state); if (endOfEnumerable) { state.Current.MoveToNextProperty = true; } return(endOfEnumerable); } // A property that returns a type that is deserialized by passing an // IDictionary to its constructor keeps the same stack frame. if (jsonPropertyInfo.ClassType == ClassType.IDictionaryConstructible) { state.Current.IsIDictionaryConstructibleProperty = true; bool endOfEnumerable = HandleDictionary(jsonPropertyInfo.ElementClassInfo, options, writer, ref state); if (endOfEnumerable) { state.Current.MoveToNextProperty = true; } return(endOfEnumerable); } // A property that returns an object. if (!obtainedValue) { currentValue = jsonPropertyInfo.GetValueAsObject(state.Current.CurrentValue); } if (currentValue != null) { // A new stack frame is required. JsonPropertyInfo previousPropertyInfo = state.Current.JsonPropertyInfo; state.Current.MoveToNextProperty = true; JsonClassInfo nextClassInfo = jsonPropertyInfo.RuntimeClassInfo; state.Push(nextClassInfo, currentValue); // Set the PropertyInfo so we can obtain the property name in order to write it. state.Current.JsonPropertyInfo = previousPropertyInfo; } else { if (!jsonPropertyInfo.IgnoreNullValues) { writer.WriteNull(jsonPropertyInfo.EscapedName.Value); } state.Current.MoveToNextProperty = true; } return(true); }