/// <summary> /// Constructor. /// </summary> /// <param name="jsonWriter">The underlying JSON writer.</param> /// <param name="odataSimplified">Whether OData Simplified is enabled.</param> public JsonLightODataAnnotationWriter(IJsonWriter jsonWriter, bool odataSimplified) { Debug.Assert(jsonWriter != null, "jsonWriter != null"); this.jsonWriter = jsonWriter; this.odataSimplified = odataSimplified; }
public virtual void TearDown() { stringWriter.Dispose(); jsonWriter.Dispose(); stringWriter = null; jsonWriter = null; }
void IJsonSerializable.Serialize(IJsonWriter writer) { writer.WriteStartObject(); writer.WriteProperty("sdkVersion", this.SdkVersion); writer.WriteProperty("agentVersion", this.AgentVersion); writer.WriteEndObject(); }
public AjaxAuthenticationRedirect(IRequestData data, IJsonWriter jsonWriter, IOutputWriter outputWriter, IUrlRegistry urls) { _data = data; _jsonWriter = jsonWriter; _outputWriter = outputWriter; _urls = urls; }
void IJsonSerializable.Serialize(IJsonWriter writer) { writer.WriteStartObject(); writer.WriteProperty("id", this.Id); writer.WriteProperty("firstSession", this.IsFirst); writer.WriteEndObject(); }
public static void WriteTo(this IEnumerable<IJsonNode> source, IJsonWriter writer) { foreach (var node in source) { writer.Node(node); } }
/// <summary> /// Constructs a <see cref="JsonLightInstanceAnnotationWriter"/> that can write a collection of <see cref="ODataInstanceAnnotation"/>. /// </summary> /// <param name="valueSerializer">The <see cref="IODataJsonLightValueSerializer"/> to use for writing values of instance annotations. /// The <see cref="IJsonWriter"/> that is also used internally will be acquired from the this instance.</param> /// <param name="typeNameOracle">The oracle to use to determine the type name to write for entries and values.</param> internal JsonLightInstanceAnnotationWriter(IODataJsonLightValueSerializer valueSerializer, JsonLightTypeNameOracle typeNameOracle) { Debug.Assert(valueSerializer != null, "valueSerializer should not be null"); this.valueSerializer = valueSerializer; this.typeNameOracle = typeNameOracle; this.jsonWriter = this.valueSerializer.JsonWriter; this.odataAnnotationWriter = new JsonLightODataAnnotationWriter(this.jsonWriter, valueSerializer.Settings.ODataSimplified); }
void IJsonSerializable.Serialize(IJsonWriter writer) { writer.WriteStartObject(); writer.WriteProperty("id", this.Id); writer.WriteProperty("name", this.Name); writer.WriteProperty("syntheticSource", this.SyntheticSource); writer.WriteEndObject(); }
public static void WriteTelemetryContext(IJsonWriter json, TelemetryContext context) { if (context != null) { json.WriteProperty("iKey", context.InstrumentationKey); json.WriteProperty("tags", context.Tags); } }
public AjaxExceptionWrapper(IFubuRequest request, IPartialFactory factory, IJsonWriter writer, HttpContext httpContext, IOutputWriter output) { _request = request; _writer = writer; _httpContext = httpContext; _output = output; }
/// <summary> /// Writes the odata.type instance annotation with the specified type name. /// </summary> /// <param name="jsonWriter">The JSON writer to write to.</param> /// <param name="typeName">The type name to write.</param> internal static void WriteODataTypeInstanceAnnotation(IJsonWriter jsonWriter, string typeName) { Debug.Assert(jsonWriter != null, "jsonWriter != null"); Debug.Assert(typeName != null, "typeName != null"); // "@odata.type": #"typename" jsonWriter.WriteInstanceAnnotationName(ODataAnnotationNames.ODataType); jsonWriter.WriteValue(PrefixTypeName(WriterUtils.RemoveEdmPrefixFromTypeName(typeName))); }
/// <summary> /// If we are writing a response and the given Json Padding function name is not null or empty /// this function will close the JSONP scope. /// </summary> /// <param name="jsonWriter">JsonWriter to write to.</param> /// <param name="settings">Writer settings.</param> internal static void EndJsonPaddingIfRequired(IJsonWriter jsonWriter, ODataMessageWriterSettings settings) { Debug.Assert(jsonWriter != null, "jsonWriter should not be null"); if (settings.HasJsonPaddingFunction()) { jsonWriter.EndPaddingFunctionScope(); } }
void IJsonSerializable.Serialize(IJsonWriter writer) { writer.WriteStartObject(); writer.WriteProperty("id", this.Id); writer.WriteProperty("userAgent", this.UserAgent); writer.WriteProperty("accountId", this.AccountId); writer.WriteProperty("anonUserAcquisitionDate", this.AcquisitionDate); writer.WriteProperty("storeRegion", this.StoreRegion); writer.WriteEndObject(); }
/// <summary> /// Writes the odata.type propert annotation for the specified property with the specified type name. /// </summary> /// <param name="jsonWriter">The JSON writer to write to.</param> /// <param name="propertyName">The name of the property for which to write the odata.type annotation.</param> /// <param name="typeName">The type name to write.</param> internal static void WriteODataTypePropertyAnnotation(IJsonWriter jsonWriter, string propertyName, string typeName) { Debug.Assert(jsonWriter != null, "jsonWriter != null"); Debug.Assert(!string.IsNullOrEmpty(propertyName), "!string.IsNullOrEmpty(propertyName)"); Debug.Assert(typeName != null, "typeName != null"); // "<propertyName>@odata.type": #"typename" WritePropertyAnnotationName(jsonWriter, propertyName, ODataAnnotationNames.ODataType); jsonWriter.WriteValue(PrefixTypeName(WriterUtils.RemoveEdmPrefixFromTypeName(typeName))); }
/// <summary> /// Will write the function's name and start the JSONP scope if we are writing a response and the /// JSONP function name is not null or empty. /// </summary> /// <param name="jsonWriter">JsonWriter to write to.</param> /// <param name="settings">Writer settings.</param> internal static void StartJsonPaddingIfRequired(IJsonWriter jsonWriter, ODataMessageWriterSettings settings) { Debug.Assert(jsonWriter != null, "jsonWriter should not be null"); if (settings.HasJsonPaddingFunction()) { jsonWriter.WritePaddingFunctionName(settings.JsonPCallback); jsonWriter.StartPaddingFunctionScope(); } }
/// <summary> /// Write an error message. /// </summary> /// <param name="jsonWriter">The JSON writer to write the error.</param> /// <param name="writeInstanceAnnotationsDelegate">Action to write the instance annotations.</param> /// <param name="error">The error instance to write.</param> /// <param name="includeDebugInformation">A flag indicating whether error details should be written (in debug mode only) or not.</param> /// <param name="maxInnerErrorDepth">The maximum number of nested inner errors to allow.</param> /// <param name="writingJsonLight">true if we're writing JSON lite, false if we're writing verbose JSON.</param> internal static void WriteError(IJsonWriter jsonWriter, Action<IEnumerable<ODataInstanceAnnotation>> writeInstanceAnnotationsDelegate, ODataError error, bool includeDebugInformation, int maxInnerErrorDepth, bool writingJsonLight) { Debug.Assert(jsonWriter != null, "jsonWriter != null"); Debug.Assert(error != null, "error != null"); string code, message; ErrorUtils.GetErrorDetails(error, out code, out message); ODataInnerError innerError = includeDebugInformation ? error.InnerError : null; WriteError(jsonWriter, code, message, innerError, error.GetInstanceAnnotations(), writeInstanceAnnotationsDelegate, maxInnerErrorDepth, writingJsonLight); }
/// <summary> /// Constructor. /// </summary> /// <param name="format">The format for this output context.</param> /// <param name="textWriter">The text writer to write to.</param> /// <param name="messageWriterSettings">Configuration settings of the OData writer.</param> /// <param name="model">The model to use.</param> protected internal ODataJsonOutputContextBase( ODataFormat format, TextWriter textWriter, ODataMessageWriterSettings messageWriterSettings, IEdmModel model) : base(format, messageWriterSettings, false /*writingResponse*/, true /*synchronous*/, model, null /*urlResolver*/) { Debug.Assert(textWriter != null, "textWriter != null"); this.textWriter = textWriter; this.jsonWriter = new JsonWriter(this.textWriter, messageWriterSettings.Indent, format, true /*isIeee754Compatible*/); }
public static void WriteEnvelopeProperties(this ITelemetry telemetry, IJsonWriter json) { json.WriteProperty("time", telemetry.Timestamp.UtcDateTime.ToString("o", CultureInfo.InvariantCulture)); var samplingSupportingTelemetry = telemetry as ISupportSampling; if ((samplingSupportingTelemetry != null) && (samplingSupportingTelemetry.SamplingPercentage > 0.0 + 1.0E-12) && (samplingSupportingTelemetry.SamplingPercentage < 100.0 - 1.0E-12)) { json.WriteProperty("sampleRate", samplingSupportingTelemetry.SamplingPercentage); } json.WriteProperty("seq", telemetry.Sequence); WriteTelemetryContext(json, telemetry.Context); }
public static void WriteEnvelopeProperties(this ITelemetry telemetry, IJsonWriter json) { json.WriteProperty("time", telemetry.Timestamp); var samplingSupportingTelemetry = telemetry as ISupportSampling; if ((samplingSupportingTelemetry != null) && (samplingSupportingTelemetry.SamplingPercentage > 0.0 + 1.0E-12) && (samplingSupportingTelemetry.SamplingPercentage < 100.0 - 1.0E-12)) { json.WriteProperty("sampleRate", samplingSupportingTelemetry.SamplingPercentage); } json.WriteProperty("seq", telemetry.Sequence); ((IJsonSerializable)telemetry.Context).Serialize(json); }
public void Write(IJsonWriter writer, ITypeWriterRegistry registry, object value) { if (value == null) { writer.WriteNull(); } else if (value.GetType() != typeof (object)) { registry.Write(writer, value); } else { writer.WriteObjectStart(); writer.WriteObjectEnd(0); } }
/// <summary> /// Constructor. /// </summary> /// <param name="jsonLightOutputContext">The output context to write to.</param> /// <param name="navigationSource">The navigation source we are going to write entities for.</param> /// <param name="entityType">The entity type for the entries in the feed to be written (or null if the entity set base type should be used).</param> /// <param name="writingFeed">true if the writer is created for writing a feed; false when it is created for writing an entry.</param> /// <param name="writingParameter">true if the writer is created for writing a parameter; false otherwise.</param> /// <param name="listener">If not null, the writer will notify the implementer of the interface of relevant state changes in the writer.</param> internal ODataJsonLightWriter( ODataJsonLightOutputContext jsonLightOutputContext, IEdmNavigationSource navigationSource, IEdmEntityType entityType, bool writingFeed, bool writingParameter = false, IODataReaderWriterListener listener = null) : base(jsonLightOutputContext, navigationSource, entityType, writingFeed, listener) { Debug.Assert(jsonLightOutputContext != null, "jsonLightOutputContext != null"); this.jsonLightOutputContext = jsonLightOutputContext; this.jsonLightEntryAndFeedSerializer = new ODataJsonLightEntryAndFeedSerializer(this.jsonLightOutputContext); this.writingParameter = writingParameter; this.jsonWriter = this.jsonLightOutputContext.JsonWriter; this.odataAnnotationWriter = new JsonLightODataAnnotationWriter(this.jsonWriter, jsonLightOutputContext.MessageWriterSettings.ODataSimplified); }
protected void SerializeRegion(IJsonWriter writer, RegionModel model, String discriminator, CalculationTicket ticket) { this.AddDiscriminatorIfAny(writer, discriminator); writer.Write(model.Name, JsonNames.Name); this.expressionWriter.SerializeOnceResolved(model.Benchmark, JsonNames.Benchmark, writer, ticket); this.expressionWriter.SerializeOnceResolved(model.Base, JsonNames.Base, writer, ticket); this.expressionWriter.SerializeOnceResolved(model.BaseActive, JsonNames.BaseActive, writer, ticket); this.expressionWriter.SerializeOnceResolved(model.Overlay, JsonNames.Overlay, writer, ticket); this.expressionWriter.SerializeOnceResolved(model.PortfolioAdjustment, JsonNames.PortfolioAdjustment, writer, ticket); this.expressionWriter.SerializeOnceResolved(model.PortfolioScaled, JsonNames.PortfolioScaled, writer, ticket); this.expressionWriter.SerializeOnceResolved(model.TrueExposure, JsonNames.TrueExposure, writer, ticket); this.expressionWriter.SerializeOnceResolved(model.TrueActive, JsonNames.TrueActive, writer, ticket); writer.WriteArray(model.Residents, JsonNames.Residents, resident => { writer.Write(delegate { resident.Accept(new IRegionModelResident_Resolver(this, writer, ticket)); }); }); }
public override void Serialize(IJsonWriter writer, object value) { if (writer == null) { throw new ArgumentNullException("writer"); } if (value == null) { throw new ArgumentNullException("value"); } var bounds = (Bounds)value; writer.WriteObjectBegin(2); writer.WriteMember("center"); writer.WriteValue(bounds.center, typeof(Vector3)); writer.WriteMember("extents"); writer.WriteValue(bounds.extents, typeof(Vector3)); writer.WriteObjectEnd(); }
public override void Serialize(IJsonWriter writer, object value) { if (writer == null) { throw new ArgumentNullException("writer"); } if (value == null) { throw new ArgumentNullException("value"); } if (value != null && value is byte[] == false) { throw new TypeContractViolation(this.GetType(), "be array of bytes"); } var base64String = Convert.ToBase64String(value as byte[]); writer.WriteString(base64String); }
protected void SerializeOverlay(Overlaying.RootModel overlay, IJsonWriter writer, CalculationTicket ticket) { writer.WriteArray(overlay.Items, JsonNames.Items, item => { writer.Write(delegate { #warning set up a special object for JSON property names in order not to confuse them with string values writer.Write(JsonNames.Portfolio, delegate { this.portfolioSerializer.SerializeBottomUpPortfolio(item.BottomUpPortfolio, writer); }); this.expressionWriter.SerializeOnceResolved( item.OverlayFactor, JsonNames.OverlayFactor, writer, ticket ); }); }); }
/// <summary> /// Writes the json object value to the <paramref name="jsonWriter"/>. /// </summary> /// <param name="jsonWriter">The <see cref="JsonWriter"/> to write to.</param> /// <param name="jsonObjectValue">Writes the given json object value to the underlying json writer.</param> /// <param name="injectPropertyAction">Called when the top-level object is started to possibly inject first property into the object.</param> internal static void WriteJsonObjectValue(this IJsonWriter jsonWriter, IDictionary <string, object> jsonObjectValue, Action <IJsonWriter> injectPropertyAction) { Debug.Assert(jsonWriter != null, "jsonWriter != null"); Debug.Assert(jsonObjectValue != null, "jsonObjectValue != null"); jsonWriter.StartObjectScope(); if (injectPropertyAction != null) { injectPropertyAction(jsonWriter); } foreach (KeyValuePair <string, object> property in jsonObjectValue) { jsonWriter.WriteName(property.Key); jsonWriter.WriteJsonValue(property.Value); } jsonWriter.EndObjectScope(); }
public override void Serialize(IJsonWriter writer, object value) { if (writer == null) { throw new ArgumentNullException("writer"); } if (value == null) { throw new ArgumentNullException("value"); } var vector2 = (Vector2)value; writer.WriteObjectBegin(2); writer.WriteMember("x"); writer.Write(vector2.x); writer.WriteMember("y"); writer.Write(vector2.y); writer.WriteObjectEnd(); }
/// <summary> /// Write an inner error property and message. /// </summary> /// <param name="jsonWriter">The JSON writer to write the error to.</param> /// <param name="innerError">Inner error details.</param> /// <param name="innerErrorPropertyName">The property name for the inner error property.</param> /// <param name="recursionDepth">The number of times this method has been called recursively.</param> /// <param name="maxInnerErrorDepth">The maximum number of nested inner errors to allow.</param> private static void WriteInnerError(IJsonWriter jsonWriter, ODataInnerError innerError, string innerErrorPropertyName, int recursionDepth, int maxInnerErrorDepth) { Debug.Assert(jsonWriter != null, "jsonWriter != null"); Debug.Assert(innerErrorPropertyName != null, "innerErrorPropertyName != null"); ValidationUtils.IncreaseAndValidateRecursionDepth(ref recursionDepth, maxInnerErrorDepth); // "innererror": jsonWriter.WriteName(innerErrorPropertyName); jsonWriter.StartObjectScope(); if (innerError.Properties != null) { foreach (KeyValuePair <string, ODataValue> pair in innerError.Properties) { jsonWriter.WriteName(pair.Key); if (pair.Value is ODataNullValue && (pair.Key == JsonConstants.ODataErrorInnerErrorMessageName || pair.Key == JsonConstants.ODataErrorInnerErrorStackTraceName || pair.Key == JsonConstants.ODataErrorInnerErrorTypeNameName)) { // Write empty string for null values in stacktrace, type and message properties of inner error. jsonWriter.WriteODataValue(new ODataPrimitiveValue(string.Empty)); } else { jsonWriter.WriteODataValue(pair.Value); } } } if (innerError.InnerError != null) { // "internalexception": { <nested inner error> } WriteInnerError(jsonWriter, innerError.InnerError, JsonConstants.ODataErrorInnerErrorInnerErrorName, recursionDepth, maxInnerErrorDepth); } // } jsonWriter.EndObjectScope(); }
public static void Serialize <T>(T objectToSerialize, IJsonWriter writer, SerializationContext context) { if (writer == null) { throw new ArgumentNullException("writer"); } if (context == null) { throw new ArgumentNullException("context"); } if (objectToSerialize == null) { writer.WriteNull(); writer.Flush(); return; } writer.WriteValue(objectToSerialize, typeof(T)); writer.Flush(); }
private static void ExecuteNavigatorBenchmark( CurratedDocsPayload payload, SerializationFormat sourceFormat, SerializationFormat destinationFormat) { IJsonNavigator navigator = sourceFormat switch { SerializationFormat.Text => JsonNavigator.Create(payload.Text), SerializationFormat.Binary => JsonNavigator.Create(payload.Binary), _ => throw new ArgumentException($"Unexpected {nameof(sourceFormat)} of type: '{sourceFormat}'"), }; IJsonWriter writer = destinationFormat switch { SerializationFormat.Text => JsonWriter.Create(JsonSerializationFormat.Text), SerializationFormat.Binary => JsonWriter.Create(JsonSerializationFormat.Binary), _ => throw new ArgumentException($"Unexpected {nameof(destinationFormat)} of type: {destinationFormat}"), }; writer.WriteJsonNode(navigator, navigator.GetRootNode()); }
public DeserializerBenchmark() { List <Person> people = new List <Person>(); for (int i = 0; i < 1000; i++) { people.Add(Person.GetRandomPerson()); } this.json = JsonConvert.SerializeObject(people); IJsonWriter jsonTextWriter = Microsoft.Azure.Cosmos.Json.JsonWriter.Create(JsonSerializationFormat.Text); CosmosElement.Parse(this.json).WriteTo(jsonTextWriter); this.textBuffer = jsonTextWriter.GetResult(); IJsonWriter jsonBinaryWriter = Microsoft.Azure.Cosmos.Json.JsonWriter.Create(JsonSerializationFormat.Binary); CosmosElement.Parse(this.json).WriteTo(jsonBinaryWriter); this.binaryBuffer = jsonBinaryWriter.GetResult(); }
/// <summary> /// Writes the specified value /// to the IJsonWriter. /// </summary> /// <param name="value">The value.</param> /// <param name="writer">The writer.</param> /// <exception cref="System.ArgumentNullException"> /// value /// or /// writer /// </exception> public static void Write(T value, IJsonWriter writer) { if (value == null) { throw new ArgumentNullException("value"); } if (writer == null) { throw new ArgumentNullException("writer"); } for (int i = 0; i < _serializePropertyActions.Length; i++) { var serializePropertyAction = _serializePropertyActions[i]; if (serializePropertyAction != null) { _serializePropertyActions[i](value, writer); } } }
public void ToJson(IJsonContext context, IJsonWriter writer, TList instance) { if (instance == null) { writer.WriteRaw(JsonLiterals.Null); } else { writer.WriteRaw(JsonLiterals.ArrayStart); if (instance.Count > 0) { ToJsonItem(context, writer, instance[0]); for (int i = 1; i < instance.Count; i++) { writer.WriteRaw(JsonLiterals.Comma); ToJsonItem(context, writer, instance[i]); } } writer.WriteRaw(JsonLiterals.ArrayEnd); } }
public void BinaryTest() { IJsonWriter jsonWriter = JsonWriter.Create(JsonSerializationFormat.Binary); byte[] binaryValue = new byte[] { 1, 2, 3 }; jsonWriter.WriteBinaryValue(binaryValue); ReadOnlyMemory <byte> buffer = jsonWriter.GetResult(); { // positive TryCatch <ReadOnlyMemory <byte> > tryDeserialize = JsonSerializer.Monadic.Deserialize <ReadOnlyMemory <byte> >(buffer); Assert.IsTrue(tryDeserialize.Succeeded); Assert.IsTrue(tryDeserialize.Result.ToArray().SequenceEqual(binaryValue)); } { // negative TryCatch <int> tryDeserialize = JsonSerializer.Monadic.Deserialize <int>(buffer); Assert.IsFalse(tryDeserialize.Succeeded); } }
public static void WriteTelemetryName(this ITelemetry telemetry, IJsonWriter json, string telemetryName) { // A different event name prefix is sent for normal mode and developer mode. bool isDevMode = false; string devModeProperty; var telemetryWithProperties = telemetry as ISupportProperties; if (telemetryWithProperties != null && telemetryWithProperties.Properties.TryGetValue("DeveloperMode", out devModeProperty)) { bool.TryParse(devModeProperty, out isDevMode); } // Format the event name using the following format: // Microsoft.[ProductName].[Dev].<normalized-instrumentation-key>.<event-type> var eventName = string.Format( System.Globalization.CultureInfo.InvariantCulture, "{0}{1}{2}", isDevMode ? DevModeTelemetryNamePrefix : TelemetryItemExtensions.TelemetryNamePrefix, NormalizeInstrumentationKey(telemetry.Context.InstrumentationKey), telemetryName); json.WriteProperty("name", eventName); }
public void Utf8VsUtf16StringWrite() { void RunPerf(string utf16String, JsonSerializationFormat jsonSerializationFormat, bool useUtf8) { ReadOnlySpan <byte> utf8String = Encoding.UTF8.GetBytes(utf16String); Stopwatch stopWatch = new Stopwatch(); for (int i = 0; i < 1000000; i++) { IJsonWriter writer = JsonWriter.Create(jsonSerializationFormat); stopWatch.Start(); if (useUtf8) { writer.WriteStringValue(utf8String); } else { writer.WriteStringValue(utf16String); } stopWatch.Stop(); } Console.WriteLine($"UTF {(useUtf8 ? 8 : 16)} {jsonSerializationFormat} writer + string length: {utf16String.Length} = {stopWatch.ElapsedMilliseconds} ms"); } foreach (int stringLength in new int[] { 8, 32, 256, 1024, 4096 }) { foreach (JsonSerializationFormat jsonSerializationFormat in new JsonSerializationFormat[] { JsonSerializationFormat.Text, JsonSerializationFormat.Binary }) { foreach (bool useUtf8 in new bool[] { false, true }) { RunPerf( utf16String: new string('a', stringLength), jsonSerializationFormat: jsonSerializationFormat, useUtf8: useUtf8); } } } }
private static void WriteErrorDetails( IJsonWriter jsonWriter, IEnumerable <ODataErrorDetail> details, string odataErrorDetailsName) { Debug.Assert(jsonWriter != null, "jsonWriter != null"); Debug.Assert(details != null, "details != null"); Debug.Assert(odataErrorDetailsName != null, "odataErrorDetailsName != null"); // "details": [ jsonWriter.WriteName(odataErrorDetailsName); jsonWriter.StartArrayScope(); foreach (var detail in details.Where(d => d != null)) { // { jsonWriter.StartObjectScope(); // "code": "301", jsonWriter.WriteName(JsonConstants.ODataErrorCodeName); jsonWriter.WriteValue(detail.ErrorCode ?? string.Empty); if (detail.Target != null) { // "target": "$search" jsonWriter.WriteName(JsonConstants.ODataErrorTargetName); jsonWriter.WriteValue(detail.Target); } // "message": "$search query option not supported", jsonWriter.WriteName(JsonConstants.ODataErrorMessageName); jsonWriter.WriteValue(detail.Message ?? string.Empty); // } jsonWriter.EndObjectScope(); } // ] jsonWriter.EndArrayScope(); }
public override void WriteNode(IJsonNavigatorNode jsonNavigatorNode, IJsonWriter jsonWriter) { if (!(jsonNavigatorNode is JsonTextNavigatorNode textNavigatorNode)) { throw new ArgumentOutOfRangeException($"Expected {nameof(jsonNavigatorNode)} to be a {nameof(JsonTextNavigatorNode)}."); } bool sameEncoding = this.SerializationFormat == jsonWriter.SerializationFormat; if (sameEncoding && jsonWriter is IJsonTextWriterExtensions jsonTextWriter) { bool isFieldName = textNavigatorNode.Type == JsonNodeType.FieldName; jsonTextWriter.WriteRawJsonValue( JsonTextNavigator.GetNodeBuffer(textNavigatorNode), isFieldName); } else { // TODO: we can optimize this to use private APIs in the future, but for now defaulting to public API. base.WriteNode(jsonNavigatorNode, jsonWriter); } }
public void ToJson(IJsonWriter writer) { writer.WriteStartObject(); if (this.ErrorCode.HasValue) { writer.WritePropertyName("errorCode"); writer.Write(this.ErrorCode); } if (this.ErrorMessage.IsPresent()) { writer.WritePropertyName("errorMessage"); writer.Write(this.ErrorMessage); } writer.WritePropertyName("item"); JSON.GetSerializer().Serialize(writer, this.Item); writer.WriteEndObject(); }
internal void WriteCheckLoop(object value, IJsonWriter writer) { if (value == null || value is DBNull) { WriterContainer.GetNullWriter().Write(null, this); return; } if (writer == null) { writer = WriterContainer.GetWriter(value.GetType()); } if (CheckLoopRef) { if (value is ValueType) { writer.Write(value, this); } else if (_loopObject.Contains(value) == false) { var index = _loopObject.Add(value); writer.Write(value, this); _loopObject.RemoveAt(index); } else { Writer?.Write("undefined"); } } else if (Depth > 64) { throw new NotSupportedException("对象过于复杂或存在循环引用"); } else { Depth++; writer.Write(value, this); Depth--; } }
public static void WriteValue(this IJsonWriter writer, object value, Type valueType) { if (writer == null) { throw new ArgumentNullException("writer"); } if (value == null) { writer.WriteNull(); return; } var actualValueType = value.GetType(); var serializer = writer.Context.GetSerializerForType(actualValueType); //var objectSerializer = serializer as ObjectSerializer; //if (objectSerializer != null && valueType == actualValueType) // objectSerializer.SuppressTypeInformation = true; // no need to write type information on when type is obvious serializer.Serialize(writer, value); }
private static void Value(this IJsonWriter writer, IJsonValue?value) { if (value == null) { writer.Value(null); } else if (value.Type == Json.Type.Object) { writer.Object((JsonObject)value); } else if (value.Type == Json.Type.Array) { writer.ArrayStart(); JsonValueCollection ArrayValue = (JsonValueCollection)value; foreach (IJsonValue ChildValue in ArrayValue) { writer.Value(ChildValue); } writer.ArrayEnd(); } else if (value.Type == Json.Type.String) { writer.Value(((JsonString)value).String); } else if (value.Type == Json.Type.Integer) { writer.Value(((JsonInteger)value).Number); } else if (value.Type == Json.Type.Float) { writer.Value(((JsonFloat)value).Number); } else if (value.Type == Json.Type.Boolean) { writer.Value(((JsonBool)value).Value); } }
private static void RunWriteBenchmark( Payload payload, bool useUtf8) { IJsonWriter jsonWriter = JsonWriter.Create(JsonSerializationFormat.Binary); jsonWriter.WriteArrayStart(); for (int i = 0; i < 100000; i++) { if (useUtf8) { jsonWriter.WriteStringValue(payload.Utf8StringToken.Span); } else { jsonWriter.WriteStringValue(payload.Utf16StringToken); } } jsonWriter.WriteArrayEnd(); }
public void NavigatorToWriter( CurratedDocsPayload payload, SerializationFormat sourceFormat, SerializationFormat destinationFormat) { IJsonNavigator navigator = sourceFormat switch { SerializationFormat.Text => JsonNavigator.Create(payload.Text), SerializationFormat.Binary => JsonNavigator.Create(payload.Binary), _ => throw new ArgumentException($"Unexpected {nameof(sourceFormat)} of type: '{sourceFormat}'"), }; IJsonWriter writer = destinationFormat switch { SerializationFormat.Text => JsonWriter.Create(JsonSerializationFormat.Text), SerializationFormat.Binary => JsonWriter.Create(JsonSerializationFormat.Binary), SerializationFormat.NewtonsoftText => NewtonsoftToCosmosDBWriter.CreateTextWriter(), _ => throw new ArgumentException($"Unexpected {nameof(destinationFormat)} of type: {destinationFormat}"), }; navigator.WriteNode(navigator.GetRootNode(), writer); }
public void SerializeRoot(IJsonWriter writer, RootModel model, CalculationTicket ticket) { writer.Write(model.TargetingType.Id, JsonNames.TargetingTypeId); writer.Write(model.Portfolio.Id, JsonNames.PortfolioId); writer.Write(model.BenchmarkDate, JsonNames.BenchmarkDate); writer.Write(JsonNames.LatestChangesets, delegate { writer.Write(JsonNames.TargetingTypeBasketBaseValue, delegate { this.SerializeTargetingTypeBasketBaseValueChangeset(model.LatestTtbbvChangeset, writer); }); writer.Write(JsonNames.TargetingTypeBasketPortfolioTarget, delegate { this.SerializeTargetingTypeBasketPortfolioTargetChangeset(model.LatestTtbptChangeset, writer); }); writer.Write(JsonNames.PortfolioSecurityTargetOverlay, delegate { this.SerializePortfolioSecurityTargetOverlayChangeset(model.LatestPstoChangeset, writer); }); writer.Write(JsonNames.PortfolioSecurityTarget, delegate { this.SerializePortfolioSecurityTargetChangeset(model.LatestPstChangeset, writer); }); }); writer.Write(JsonNames.Root, delegate { this.SerializeGlobe(writer, model.Globe, ticket); }); writer.Write(JsonNames.Cash, delegate { this.SerializeCash(writer, model.Cash, ticket); }); writer.Write(JsonNames.Overlay, delegate { this.SerializeOverlay(model.Factors, writer, ticket); }); this.expressionWriter.SerializeOnceResolved(model.PortfolioScaledGrandTotal, JsonNames.PortfolioScaledTotal, writer, ticket); }
protected void SerializeBasketRegion(IJsonWriter writer, BasketRegionModel model, String discriminator, CalculationTicket ticket) { this.AddDiscriminatorIfAny(writer, discriminator); writer.Write(model.Basket.Id, JsonNames.BasketId); writer.Write(model.Basket.Name, JsonNames.Name); this.expressionWriter.SerializeOnceResolved(model.Benchmark, JsonNames.Benchmark, writer, ticket); this.expressionWriter.SerializeOnceResolved(model.Base, JsonNames.Base, writer, ticket); this.expressionWriter.SerializeOnceResolved(model.BaseActive, JsonNames.BaseActive, writer, ticket); this.expressionWriter.SerializeOnceResolved(model.Overlay, JsonNames.Overlay, writer, ticket); this.expressionWriter.SerializeOnceResolved(model.PortfolioAdjustment, JsonNames.PortfolioAdjustment, writer, ticket); this.expressionWriter.SerializeOnceResolved(model.PortfolioScaled, JsonNames.PortfolioScaled, writer, ticket); this.expressionWriter.SerializeOnceResolved(model.TrueExposure, JsonNames.TrueExposure, writer, ticket); this.expressionWriter.SerializeOnceResolved(model.TrueActive, JsonNames.TrueActive, writer, ticket); writer.WriteArray(model.Countries, JsonNames.Countries, country => { writer.Write(delegate { this.SerializeCountry(writer, country.Country); this.expressionWriter.SerializeOnceResolved(country.Benchmark, JsonNames.Benchmark, writer, ticket); this.expressionWriter.SerializeOnceResolved(country.Overlay, JsonNames.Overlay, writer, ticket); }); }); }
public void Write(IJsonWriter writer, ITypeWriterRegistry registry, object value) { var enumerable = value as IEnumerable; if (enumerable == null) { writer.WriteNull(); } else { writer.WriteArrayStart(); var index = 0; foreach (var item in enumerable) { if (index++ > 0) { writer.WriteArrayElementDelimiter(); } registry.Write(writer, item); } writer.WriteArrayEnd(index); } }
public static void WriteTelemetryName(this ITelemetry telemetry, IJsonWriter json, string telemetryName) { // A different event name prefix is sent for normal mode and developer mode. bool isDevMode = false; string devModeProperty; var telemetryWithProperties = telemetry as ISupportProperties; if (telemetryWithProperties != null && telemetryWithProperties.Properties.TryGetValue("DeveloperMode", out devModeProperty)) { bool.TryParse(devModeProperty, out isDevMode); } // Format the event name using the following format: // Microsoft.ApplicationInsights[.Dev].<normalized-instrumentation-key>.<event-type> var eventName = string.Format( System.Globalization.CultureInfo.InvariantCulture, "{0}{1}{2}", isDevMode ? Constants.DevModeTelemetryNamePrefix : Constants.TelemetryNamePrefix, NormalizeInstrumentationKey(telemetry.Context.InstrumentationKey), telemetryName); json.WriteProperty("name", eventName); }
public void ReaderToWriter( CurratedDocsPayload payload, SerializationFormat sourceFormat, SerializationFormat destinationFormat) { IJsonReader reader = sourceFormat switch { SerializationFormat.Text => JsonReader.Create(payload.Text), SerializationFormat.Binary => JsonReader.Create(payload.Binary), SerializationFormat.NewtonsoftText => NewtonsoftToCosmosDBReader.CreateFromBuffer(payload.Text), _ => throw new ArgumentException($"Unexpected {nameof(sourceFormat)} of type: '{sourceFormat}'"), }; IJsonWriter writer = destinationFormat switch { SerializationFormat.Text => JsonWriter.Create(JsonSerializationFormat.Text), SerializationFormat.Binary => JsonWriter.Create(JsonSerializationFormat.Binary), SerializationFormat.NewtonsoftText => NewtonsoftToCosmosDBWriter.CreateTextWriter(), _ => throw new ArgumentException($"Unexpected {nameof(destinationFormat)} of type: {destinationFormat}"), }; writer.WriteAll(reader); }
protected override void Dispose(bool disposing) { try { if (this.messageOutputStream != null) { // JsonWriter.Flush will call the underlying TextWriter.Flush. // The TextWriter.Flush (Which is in fact StreamWriter.Flush) will call the underlying Stream.Flush. this.jsonWriter.Flush(); JsonWriter writer = this.jsonWriter as JsonWriter; if (writer != null) { writer.Dispose(); } // In the async case the underlying stream is the async buffered stream, so we have to flush that explicitly. if (this.asynchronousOutputStream != null) { this.asynchronousOutputStream.FlushSync(); this.asynchronousOutputStream.Dispose(); } // Dispose the message stream (note that we OWN this stream, so we always dispose it). this.messageOutputStream.Dispose(); } } finally { this.messageOutputStream = null; this.asynchronousOutputStream = null; this.textWriter = null; this.jsonWriter = null; } base.Dispose(disposing); }
private static void Value(this IJsonWriter writer, IJsonValue value) { if (value == null) { writer.Value(null); } else if (value.Type == Json.Type.Object) { writer.Object((JsonObject)value); } else if (value.Type == Json.Type.Array) { writer.ArrayStart(); var array = (JsonArray)value; foreach (var child in array) { writer.Value(child); } writer.ArrayEnd(); } else if (value.Type == Json.Type.String) { writer.Value(((JsonString)value).String); } else if (value.Type == Json.Type.Integer) { writer.Value(((JsonInteger)value).Number); } else if (value.Type == Json.Type.Float) { writer.Value(((JsonFloat)value).Number); } else if (value.Type == Json.Type.Boolean) { writer.Value(((JsonBool)value).Value); } }
private static ReadOnlyMemory <byte> GetPayload(string filename) { string path = string.Format("TestJsons/{0}", filename); string json = TextFileConcatenation.ReadMultipartFile(path); IEnumerable <object> documents = null; try { try { documents = JsonConvert.DeserializeObject <List <object> >(json); } catch (JsonSerializationException) { documents = new List <object> { JsonConvert.DeserializeObject <object>(json) }; } } catch (Exception ex) { Assert.Fail($"Failed to get JSON payload: {json.Substring(0, 128)} {ex}"); } documents = documents.OrderBy(x => Guid.NewGuid()).Take(100); json = JsonConvert.SerializeObject(documents); IJsonReader jsonReader = Microsoft.Azure.Cosmos.Json.JsonReader.Create(Encoding.UTF8.GetBytes(json)); IJsonWriter jsonWriter = Microsoft.Azure.Cosmos.Json.JsonWriter.Create(JsonSerializationFormat.Binary); jsonWriter.WriteAll(jsonReader); return(jsonWriter.GetResult()); }
public override void Serialize(IJsonWriter writer, object value) { if (writer == null) { throw new ArgumentNullException("writer"); } if (value == null) { throw new ArgumentNullException("value"); } var quaternion = (Quaternion)value; writer.WriteObjectBegin(4); writer.WriteMember("x"); writer.Write(quaternion.x); writer.WriteMember("y"); writer.Write(quaternion.y); writer.WriteMember("z"); writer.Write(quaternion.z); writer.WriteMember("w"); writer.Write(quaternion.w); writer.WriteObjectEnd(); }
/// <summary> /// Write an inner error property and message. /// </summary> /// <param name="jsonWriter">The JSON writer to write the error to.</param> /// <param name="innerError">Inner error details.</param> /// <param name="innerErrorPropertyName">The property name for the inner error property.</param> /// <param name="recursionDepth">The number of times this method has been called recursively.</param> /// <param name="maxInnerErrorDepth">The maximum number of nested inner errors to allow.</param> private static void WriteInnerError(IJsonWriter jsonWriter, ODataInnerError innerError, string innerErrorPropertyName, int recursionDepth, int maxInnerErrorDepth) { Debug.Assert(jsonWriter != null, "jsonWriter != null"); Debug.Assert(innerErrorPropertyName != null, "innerErrorPropertyName != null"); ValidationUtils.IncreaseAndValidateRecursionDepth(ref recursionDepth, maxInnerErrorDepth); // "innererror": { jsonWriter.WriteName(innerErrorPropertyName); jsonWriter.StartObjectScope(); //// NOTE: we add empty elements if no information is provided for the message, error type and stack trace //// to stay compatible with Astoria. // "message": "<message>" jsonWriter.WriteName(JsonConstants.ODataErrorInnerErrorMessageName); jsonWriter.WriteValue(innerError.Message ?? string.Empty); // "type": "<typename"> jsonWriter.WriteName(JsonConstants.ODataErrorInnerErrorTypeNameName); jsonWriter.WriteValue(innerError.TypeName ?? string.Empty); // "stacktrace": "<stacktrace>" jsonWriter.WriteName(JsonConstants.ODataErrorInnerErrorStackTraceName); jsonWriter.WriteValue(innerError.StackTrace ?? string.Empty); if (innerError.InnerError != null) { // "internalexception": { <nested inner error> } WriteInnerError(jsonWriter, innerError.InnerError, JsonConstants.ODataErrorInnerErrorInnerErrorName, recursionDepth, maxInnerErrorDepth); } // } jsonWriter.EndObjectScope(); }
private static void WriteErrorDetails(IJsonWriter jsonWriter, IEnumerable<ODataErrorDetail> details, string odataErrorDetailsName) { Debug.Assert(jsonWriter != null, "jsonWriter != null"); Debug.Assert(details != null, "details != null"); Debug.Assert(odataErrorDetailsName != null, "odataErrorDetailsName != null"); // "details": [ jsonWriter.WriteName(odataErrorDetailsName); jsonWriter.StartArrayScope(); foreach (var detail in details.Where(d => d != null)) { // { jsonWriter.StartObjectScope(); // "code": "301", jsonWriter.WriteName(JsonConstants.ODataErrorCodeName); jsonWriter.WriteValue(detail.ErrorCode ?? string.Empty); if (detail.Target != null) { // "target": "$search" jsonWriter.WriteName(JsonConstants.ODataErrorTargetName); jsonWriter.WriteValue(detail.Target); } // "message": "$search query option not supported", jsonWriter.WriteName(JsonConstants.ODataErrorMessageName); jsonWriter.WriteValue(detail.Message ?? string.Empty); // } jsonWriter.EndObjectScope(); } // ] jsonWriter.EndArrayScope(); }
/// <summary> /// Write an error message. /// </summary> /// <param name="jsonWriter">JSON writer.</param> /// <param name="code">The code of the error.</param> /// <param name="message">The message of the error.</param> /// <param name="target">The target of the error.</param> /// <param name="details">The details of the error.</param> /// <param name="innerError">Inner error details that will be included in debug mode (if present).</param> /// <param name="instanceAnnotations">Instance annotations for this error.</param> /// <param name="writeInstanceAnnotationsDelegate">Action to write the instance annotations.</param> /// <param name="maxInnerErrorDepth">The maximum number of nested inner errors to allow.</param> /// <param name="writingJsonLight">true if we're writing JSON lite, false if we're writing verbose JSON.</param> private static void WriteError(IJsonWriter jsonWriter, string code, string message, string target, IEnumerable<ODataErrorDetail> details, ODataInnerError innerError, IEnumerable<ODataInstanceAnnotation> instanceAnnotations, Action<IEnumerable<ODataInstanceAnnotation>> writeInstanceAnnotationsDelegate, int maxInnerErrorDepth, bool writingJsonLight) { Debug.Assert(jsonWriter != null, "jsonWriter != null"); Debug.Assert(code != null, "code != null"); Debug.Assert(message != null, "message != null"); Debug.Assert(instanceAnnotations != null, "instanceAnnotations != null"); // "error": { jsonWriter.StartObjectScope(); if (writingJsonLight) { jsonWriter.WriteName(JsonLightConstants.ODataErrorPropertyName); } else { jsonWriter.WriteName(JsonConstants.ODataErrorName); } jsonWriter.StartObjectScope(); // "code": "<code>" jsonWriter.WriteName(JsonConstants.ODataErrorCodeName); jsonWriter.WriteValue(code); // "message": "<message string>" jsonWriter.WriteName(JsonConstants.ODataErrorMessageName); jsonWriter.WriteValue(message); // For example, "target": "query", if (target != null) { jsonWriter.WriteName(JsonConstants.ODataErrorTargetName); jsonWriter.WriteValue(target); } // Such as, "details": [ // { // "code": "301", // "target": "$search", // "message": "$search query option not supported" // }] if (details != null) { WriteErrorDetails(jsonWriter, details, JsonConstants.ODataErrorDetailsName); } if (innerError != null) { WriteInnerError(jsonWriter, innerError, JsonConstants.ODataErrorInnerErrorName, /* recursionDepth */ 0, maxInnerErrorDepth); } if (writingJsonLight) { Debug.Assert(writeInstanceAnnotationsDelegate != null, "writeInstanceAnnotations != null"); writeInstanceAnnotationsDelegate(instanceAnnotations); } // } } jsonWriter.EndObjectScope(); jsonWriter.EndObjectScope(); }
protected internal ODataJsonOutputContextBase( ODataFormat format, Stream messageStream, Encoding encoding, ODataMessageWriterSettings messageWriterSettings, bool writingResponse, bool synchronous, bool isIeee754Compatible, IEdmModel model, IODataUrlResolver urlResolver) : base(format, messageWriterSettings, writingResponse, synchronous, model, urlResolver) { Debug.Assert(messageStream != null, "messageStream != null"); try { this.messageOutputStream = messageStream; Stream outputStream; if (synchronous) { outputStream = messageStream; } else { this.asynchronousOutputStream = new AsyncBufferedStream(messageStream); outputStream = this.asynchronousOutputStream; } this.textWriter = new StreamWriter(outputStream, encoding); // COMPAT 2: JSON indentation - WCFDS indents only partially, it inserts newlines but doesn't actually insert spaces for indentation // in here we allow the user to specify if true indentation should be used or if the limited functionality is enough. this.jsonWriter = new JsonWriter(this.textWriter, messageWriterSettings.Indent, format, isIeee754Compatible); } catch (Exception e) { // Dispose the message stream if we failed to create the input context. if (ExceptionUtils.IsCatchableExceptionType(e) && messageStream != null) { messageStream.Dispose(); } throw; } }
void IJsonSerializable.Serialize(IJsonWriter writer) { writer.WriteStartObject(); writer.WriteProperty("version", this.Version); writer.WriteEndObject(); }
/// <summary> /// Original implementation of writing a spatial instance. /// </summary> /// <param name="instance">The spatial instance to write.</param> /// <param name="jsonWriter">The Json writer.</param> private static void OriginalWriteJsonLight(object instance, IJsonWriter jsonWriter) { IDictionary<string, object> jsonObject = GeoJsonObjectFormatter.Create().Write((ISpatial)instance); jsonWriter.WriteJsonObjectValue(jsonObject, /*injectPropertyAction*/ null); }
public MockJsonLightValueSerializer(IJsonWriter jsonWriter, IEdmModel model) { this.JsonWriter = jsonWriter; this.Model = model; }