public Stream GenerateManifest(IEnumerable <FileReleaseData> filesProcessed)
        {
            var stream = new MemoryStream();

            var jro = new JsonWriterOptions
            {
                Indented = true,
                Encoder  = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            };

            using (var writer = new Utf8JsonWriter(stream, jro))
            {
                writer.WriteStartObject();

                WriteMetadata(writer);

                WritePublishingInstructions(writer, filesProcessed);
                WriteBundledTools(writer, filesProcessed);
                WriteNugetShippingPackages(writer, filesProcessed);

                writer.WriteEndObject();
            }
            stream.Position = 0;
            return(stream);
        }
Exemplo n.º 2
0
        public static Task WriteResponse(HttpContext context, HealthReport result)
        {
            context.Response.ContentType = "application/json; charset=utf-8";

            var options = new JsonWriterOptions
            {
                Indented = true
            };

            using (var stream = new MemoryStream())
            {
                using (var writer = new Utf8JsonWriter(stream, options))
                {
                    writer.WriteStartObject();
                    writer.WriteString("status", result.Status.ToString());
                    foreach (KeyValuePair <string, HealthReportEntry> entry in result.Entries)
                    {
                        writer.WriteString(entry.Key, entry.Value.Description);
                    }

                    writer.WriteEndObject();
                }

                stream.Position = 0;

                return(stream.CopyToAsync(context.Response.Body));
            }
        }
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object can be used to retrieve data from input parameters and
        /// to store data in output parameters.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Guid> guidList = new List <Guid>();

            var options = new JsonWriterOptions
            {
                Indented = true
            };


            using (var stream = new MemoryStream())
            {
                using (var writer = new Utf8JsonWriter(stream, options))
                {
                    writer.WriteStartObject();
                    writer.WriteString("action", "mnml:parameters");
                    writer.WritePropertyName("data");

                    writer.WriteStartArray();
                    foreach (var input in Params.Input)
                    {
                        if (!input.Sources.Any())
                        {
                            continue;
                        }
                        foreach (var source in input.Sources)
                        {
                            if (source is GH_NumberSlider)
                            {
                                var slider = source as GH_NumberSlider;

                                var min  = slider.Slider.Minimum;
                                var max  = slider.Slider.Maximum;
                                var step = slider.Slider.SnapDistance;
                                var name = slider.NickName == "" ? slider.Name : slider.NickName;
                                var guid = source.InstanceGuid;
                                writer.WriteStartObject();
                                writer.WriteNumber("step", step);
                                writer.WriteNumber("min", min);
                                writer.WriteNumber("max", max);
                                writer.WriteString("name", name);
                                writer.WriteNumber("value", slider.Slider.Value);
                                writer.WriteString("guid", guid.ToString());
                                writer.WriteEndObject();
                                guidList.Add(guid);
                            }
                        }
                    }
                    writer.WriteEndArray();
                    writer.WriteEndObject();
                }
                string json = Encoding.UTF8.GetString(stream.ToArray());
                DA.SetData(1, json);
            }

            if (!Hidden)
            {
                DA.SetDataList(0, guidList);
            }
        }
Exemplo n.º 4
0
        private static void WriteComplexValue(
            bool indented,
            string jsonIn,
            string expectedIndent,
            string expectedMinimal)
        {
            var buffer = new ArrayBufferWriter <byte>(1024);

            using (JsonDocument doc = JsonDocument.Parse($" [  {jsonIn}  ]", s_readerOptions))
            {
                JsonElement target = doc.RootElement[0];

                var options = new JsonWriterOptions
                {
                    Indented = indented,
                };

                var writer = new Utf8JsonWriter(buffer, options);

                target.WriteAsValue(writer);
                writer.Flush();

                if (indented && s_replaceNewlines)
                {
                    AssertContents(
                        expectedIndent.Replace(CompiledNewline, Environment.NewLine),
                        buffer);
                }

                AssertContents(indented ? expectedIndent : expectedMinimal, buffer);
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Creates a mocked http context that can be passed through a query processor for testing with the given
        /// query data on the request.
        /// </summary>
        /// <param name="requestData">The request data.</param>
        /// <returns>HttpContext.</returns>
        public HttpContext CreateHttpContext(GraphQueryData requestData = null)
        {
            var requestStream  = new MemoryStream();
            var responseStream = new MemoryStream();

            var httpContext = new DefaultHttpContext();

            httpContext.User            = _userAccount;
            httpContext.RequestServices = this.ServiceProvider;
            httpContext.Response.Body   = responseStream;
            httpContext.Request.Method  = HttpMethods.Post.ToUpper();
            httpContext.Request.Body    = requestStream;

            if (requestData != null)
            {
                var writerOptions = new JsonWriterOptions()
                {
                    Indented = this.Schema.Configuration.ResponseOptions.IndentDocument,
                };

                var serializerSettings = new JsonSerializerOptions();
                serializerSettings.Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping;

                using (var writer = new Utf8JsonWriter(requestStream, writerOptions))
                {
                    JsonSerializer.Serialize(writer, requestData, serializerSettings);
                    requestStream.Seek(0, SeekOrigin.Begin);
                }
            }

            return(httpContext);
        }
Exemplo n.º 6
0
 public byte[] AnalyzeJsonBuffer <T>(ReadOnlySpan <byte> bytes, JsonWriterOptions options = default, int minBufferSize = 8096)
 {
     byte[] buffer = JT809ArrayPool.Rent(minBufferSize);
     try
     {
         JT809MessagePackReader jT809MessagePackReader = new JT809MessagePackReader(bytes);
         if (CheckPackageType(typeof(T)))
         {
             jT809MessagePackReader.Decode(buffer);
         }
         var analyze = jT809Config.GetAnalyze <T>();
         using (MemoryStream memoryStream = new MemoryStream())
             using (Utf8JsonWriter utf8JsonWriter = new Utf8JsonWriter(memoryStream, options))
             {
                 if (!CheckPackageType(typeof(T)))
                 {
                     utf8JsonWriter.WriteStartObject();
                 }
                 analyze.Analyze(ref jT809MessagePackReader, utf8JsonWriter, jT809Config);
                 if (!CheckPackageType(typeof(T)))
                 {
                     utf8JsonWriter.WriteEndObject();
                 }
                 utf8JsonWriter.Flush();
                 return(memoryStream.ToArray());
             }
     }
     finally
     {
         JT809ArrayPool.Return(buffer);
     }
 }
Exemplo n.º 7
0
        private static void WritePropertyValue(
            bool indented,
            JsonEncodedText propertyName,
            string jsonIn,
            string expectedIndent,
            string expectedMinimal)
        {
            var buffer = new ArrayBufferWriter <byte>(1024);

            using (JsonDocument doc = JsonDocument.Parse($" [  {jsonIn}  ]", s_options))
            {
                JsonElement target = doc.RootElement[0];

                var options = new JsonWriterOptions
                {
                    Indented = indented,
                };

                using var writer = new Utf8JsonWriter(buffer, options);

                writer.WriteStartObject();
                writer.WritePropertyName(propertyName);
                target.WriteTo(writer);
                writer.WriteEndObject();
                writer.Flush();

                JsonTestHelper.AssertContents(indented ? expectedIndent : expectedMinimal, buffer);
            }
        }
Exemplo n.º 8
0
        public string Serialize(KeyValues values)
        {
            if (values == null)
            {
                return(null);
            }
            var options = new JsonWriterOptions {
                Indented = JsonWriterIndented
            };

            using (var stream = new MemoryStream())
            {
                using (var writer = new Utf8JsonWriter(stream, options))
                {
                    var dvalues = values.GroupKeys();
                    writer.WriteStartObject();
                    foreach (var item in dvalues)
                    {
                        writer.WritePropertyName(item.Key);
                        WriteValue(writer, item.Value);
                    }
                    writer.WriteEndObject();
                }
                string json = Encoding.UTF8.GetString(stream.ToArray());
                return(json);
            }
        }
        public async Task WithdrawalAsync_WithContractStatusAsString_ReturnsResponse()
        {
            // Arrange
            var options = new JsonWriterOptions
            {
                Indented = true
            };
            string json = null;

            using (var stream = new MemoryStream())
            {
                using (var writer = new Utf8JsonWriter(stream, options))
                {
                    writer.WriteStartObject();
                    writer.WriteNumber("id", 10);
                    writer.WriteString("contractNumber", "Test-Contract-High");
                    writer.WriteNumber("contractVersion", 1);
                    writer.WriteString("withdrawalType", "WithdrawnByAgency");
                    writer.WriteString("fileName", _blobName);
                    writer.WriteEndObject();
                }

                json = Encoding.UTF8.GetString(stream.ToArray());
                Console.WriteLine(json);
            }

            StringContent content = new StringContent(json, Encoding.Default, "application/json");

            // Act
            var response = await _testClient.PatchAsync(_withdrawUrl, content);

            // Assert
            response.StatusCode.Should().Be(HttpStatusCode.OK);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Executes the query and returns a JSON string from data set returned by the query.
        /// </summary>
        /// <param name="dataCommand">The data command.</param>
        /// <param name="options">The <see cref="JsonWriterOptions"/> options.</param>
        /// <returns>A JSON string representing the <see cref="IDataReader"/> result of the command.</returns>
        public static string QueryJson(this IDataCommand dataCommand, JsonWriterOptions options = default)
        {
            using var stream = new MemoryStream();
            using var writer = new Utf8JsonWriter(stream, options);

            writer.WriteStartArray();

            dataCommand.Read(reader =>
            {
                while (reader.Read())
                {
                    writer.WriteStartObject();

                    for (int index = 0; index < reader.FieldCount; index++)
                    {
                        var name = reader.GetName(index);
                        writer.WritePropertyName(name);

                        WriteValue(reader, writer, index);
                    }

                    writer.WriteEndObject();
                }
            });

            writer.WriteEndArray();

            writer.Flush();

            return(Encoding.UTF8.GetString(stream.ToArray()));
        }
Exemplo n.º 11
0
        public static string ToString(this object @object)
        {
            if (@object == null)
            {
                return(null);
            }

            //TODO:  Finish Implementation

            JsonWriterOptions jsonWriterOptions = new JsonWriterOptions
            {
                Indented = true
            };

            string result = null;

            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (Utf8JsonWriter utf8JsonWriter = new Utf8JsonWriter(memoryStream, jsonWriterOptions))
                {
                    Modify.Write(utf8JsonWriter, @object);

                    utf8JsonWriter.Flush();
                }

                result = Encoding.UTF8.GetString(memoryStream.ToArray());
            }

            return(result);
        }
Exemplo n.º 12
0
    private static void Convert(string toeeDir, string outputDir)
    {
        Directory.CreateDirectory(outputDir);
        using var fs = TroikaVfs.CreateFromInstallationDir(toeeDir);

        // Loads the map list
        var maps = MapListParser.Parse(fs);

        var entries = fs.ReadMesFile("rules/townmap_ui_placed_flag_locations.mes");

        var mapCount = int.Parse(entries[1]);

        for (var mapIndex = 0; mapIndex < mapCount; mapIndex++)
        {
            var mapKey = 100 * (mapIndex + 1);
            var mapId  = int.Parse(entries[mapKey]);
            // See MapSystem.GetDataDir
            var mapDataDir = Path.Join(outputDir, $"maps/{maps[mapId].name}");
            Directory.CreateDirectory(mapDataDir);

            using var stream = new FileStream($"{mapDataDir}/map_markers.json", FileMode.Create);
            var options = new JsonWriterOptions {
                Indented = true
            };
            using var writer = new Utf8JsonWriter(stream, options);

            writer.WriteStartObject();
            writer.WriteString("$schema", "https://schemas.opentemple.de/townMapMarkers.json");
            writer.WritePropertyName("markers");
            writer.WriteStartArray();

            var markerCount = int.Parse(entries[mapKey + 1]);
            for (var markerIndex = 0; markerIndex < markerCount; markerIndex++)
            {
                var markerKey     = mapKey + 20 + markerIndex;
                var locationParts = entries[markerKey].Split(",");
                var x             = int.Parse(locationParts[0].Trim());
                var y             = int.Parse(locationParts[1].Trim());

                // Interestingly, ToEE applied a hard coded offset
                x -= 4;
                y -= 8;

                writer.WriteStartObject();
                writer.WriteNumber("id", markerIndex);
                writer.WriteBoolean("initiallyVisible", false);
                // For the text, we reference the translation file
                // It however uses a different numbering scheme since ToEE itself will read it sequentially
                // rather than by key, but our translation system must reference it by key.
                var translationKey = markerKey - 110;
                writer.WriteString("text", $"#{{townmap_markers:{translationKey}}}");
                writer.WriteNumber("x", x);
                writer.WriteNumber("y", y);
                writer.WriteEndObject();
            }

            writer.WriteEndArray(); // markers
            writer.WriteEndObject();
        }
    }
 /// <summary>
 /// Writing data from an array to a file in JSON format
 /// </summary>
 /// <remarks>If the specified file does not exist, a new file is created.
 /// If it exists, the old information is erased and a new one is written.</remarks>
 /// <param name="array">Array of products to record</param>
 /// <param name="path">File path</param>
 /// <exception cref="FileNotFoundException">Throw if the specified file is not found</exception>
 public static void WriteDataToFile(Product[] array, string path)
 {
     if (path == null || array == null)
     {
         throw new NullReferenceException();
     }
     if (File.Exists(path))
     {
         JsonWriterOptions options = new JsonWriterOptions
         {
             Indented = true
         };
         using (FileStream filesStream = new FileStream(path, FileMode.Create))
         {
             using (Utf8JsonWriter writer = new Utf8JsonWriter(filesStream, options))
             {
                 JsonSerializer.Serialize(writer, array);
             }
         }
     }
     else
     {
         throw new FileNotFoundException();
     }
 }
Exemplo n.º 14
0
        /// <summary>
        ///   Gets a string representation for the current value appropriate to the node type.
        /// </summary>
        /// <returns>A string representation for the current value appropriate to the node type.</returns>
        public override string ToString()
        {
            // Special case for string; don't quote it.
            if (this is JsonValue)
            {
                if (this is JsonValue <string> jsonString)
                {
                    return(jsonString.Value);
                }

                if (this is JsonValue <JsonElement> jsonElement &&
                    jsonElement.Value.ValueKind == JsonValueKind.String)
                {
                    return(jsonElement.Value.GetString() !);
                }
            }

            var options = new JsonWriterOptions {
                Indented = true
            };
            var output = new ArrayBufferWriter <byte>();

            using (var writer = new Utf8JsonWriter(output, options))
            {
                WriteTo(writer);
            }

            return(JsonHelpers.Utf8GetString(output.WrittenSpan));
        }
Exemplo n.º 15
0
        /// <summary>
        /// Publishes the results to text files in the specified folder.
        /// Throws an IOException if the specified output folder is a file path.
        /// Throws a NotSupportedException if the path to the output folder is malformed.
        /// </summary>
        public static void PublishResults(string outputFolder)
        {
            var compilationProcessesForest = BuildCompilationTasksHierarchy();
            var outputPath = Path.GetFullPath(outputFolder);

            Directory.CreateDirectory(outputPath);
            using (var file = File.CreateText(Path.Combine(outputPath, CompilationPerfDataFileName)))
            {
                var jsonWriterOptions = new JsonWriterOptions()
                {
                    Indented = true
                };

                var jsonWriter = new Utf8JsonWriter(file.BaseStream, jsonWriterOptions);
                jsonWriter.WriteStartObject();
                foreach (var tree in compilationProcessesForest.OrderBy(t => t.Task.Name))
                {
                    tree.WriteToJson(jsonWriter, null);
                }

                jsonWriter.WriteEndObject();
                jsonWriter.Flush();
            }

            if (Warnings.Count > 0)
            {
                using (var file = File.CreateText(Path.Combine(outputPath, CompilationPerfWarningsFileName)))
                {
                    JsonSerializer.SerializeAsync(file.BaseStream, Warnings).Wait();
                }
            }
        }
Exemplo n.º 16
0
        public static string SerializeAsJson(this IEdmModel model, bool indented = true, bool isIeee754Compatible = false)
        {
            using (MemoryStream memStream = new MemoryStream())
            {
                JsonWriterOptions options = new JsonWriterOptions
                {
                    Encoder        = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
                    Indented       = indented,
                    SkipValidation = false
                };

                using (Utf8JsonWriter jsonWriter = new Utf8JsonWriter(memStream, options))
                {
                    CsdlJsonWriterSettings settings = new CsdlJsonWriterSettings();
                    settings.IsIeee754Compatible = isIeee754Compatible;
                    IEnumerable <EdmError> errors;
                    bool ok = CsdlWriter.TryWriteCsdl(model, jsonWriter, settings, out errors);
                    jsonWriter.Flush();
                    Assert.True(ok);
                }

                memStream.Seek(0, SeekOrigin.Begin);
                return(new StreamReader(memStream).ReadToEnd());
            }
        }
Exemplo n.º 17
0
        public static async Task <Stream> StringsToJson(Stream input)
        {
            var bytes = new byte[input.Length];
            //var readcount = await input.ReadAsync(bytes, 0, (int)input.Length);
            //if (readcount != input.Length) throw new Exception("Couldn't read entire thing");

            var ims        = new MemoryStream(bytes);
            var parsedfile = new DieselEngineFormats.StringsFile(input);
            var oms        = new MemoryStream((int)input.Length);
            var jwo        = new JsonWriterOptions {
                Indented = true
            };
            var jw = new Utf8JsonWriter(oms, jwo);

            jw.WriteStartObject();
            foreach (var entry in parsedfile.LocalizationStrings)
            {
                if (entry.ID.ToString() == "" && entry.Text == "")
                {
                    continue;
                }
                jw.WriteString(entry.ID.ToString(), entry.Text);
            }
            jw.WriteEndObject();
            jw.Flush();
            oms.Seek(0, SeekOrigin.Begin);
            return(oms);
        }
Exemplo n.º 18
0
        public static void WriteFile(RookDB database, string filename, bool allowOverwrite = false)
        {
            if (File.Exists(filename) && !allowOverwrite)
            {
                Logger.Critical?.WriteLine("[RookDB] Could not write file, file exists and allowOverwrite was not enabled. Aborting write operation.");
                return;
            }

            JsonWriterOptions writerOptions = new JsonWriterOptions()
            {
                Indented       = true,
                SkipValidation = false
            };

            using (FileStream fs = new FileStream(filename, FileMode.Create))
            {
                using (Utf8JsonWriter writer = new Utf8JsonWriter(fs, writerOptions))
                {
                    writer.WriteStartObject();
                    writer.WriteStartArray("sheets");
                    foreach (DBTable table in database.tables.Values)
                    {
                        WriteTable(table, writer);
                    }
                    writer.WriteEndArray();
                    writer.WriteEndObject();
                }
            }
        }
Exemplo n.º 19
0
        public void Write(DependencyContext context, Stream stream)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            // Custom encoder is required to fix https://github.com/dotnet/core-setup/issues/7137
            // Since the JSON is only written to a file that is read by the SDK (and not transmitted over the wire),
            // it is safe to skip escaping certain characters in this scenario
            // (that would otherwise be escaped, by default, as part of defense-in-depth, such as +).
            var options = new JsonWriterOptions {
                Indented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            };

            using (var jsonWriter = new Utf8JsonWriter(stream, options))
            {
                jsonWriter.WriteStartObject();
                WriteRuntimeTargetInfo(context, jsonWriter);
                WriteCompilationOptions(context.CompilationOptions, jsonWriter);
                WriteTargets(context, jsonWriter);
                WriteLibraries(context, jsonWriter);
                if (context.RuntimeGraph.Any())
                {
                    WriteRuntimeGraph(context, jsonWriter);
                }
                jsonWriter.WriteEndObject();
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// Use SOURCE CODE FILE PARSING to locate all recipes in the project and store their information in a JSON file
        /// </summary>
        /// <returns>array of recipes found using source code file parsing</returns>
        public static RecipeSource[] Generate(string cookbookFolder, string saveFilePath, int width = 600, int height = 400)
        {
            RecipeSource[] recipes = SourceParsing.GetRecipeSources(cookbookFolder, width, height);

            using var stream = File.OpenWrite(saveFilePath);
            var options = new JsonWriterOptions()
            {
                Indented = true
            };

            using var writer = new Utf8JsonWriter(stream, options);

            writer.WriteStartObject();
            writer.WriteString("version", ScottPlot.Plot.Version);
            writer.WriteString("generated", DateTime.UtcNow);

            writer.WriteStartArray("recipes");
            foreach (RecipeSource recipe in recipes)
            {
                writer.WriteStartObject();
                writer.WriteString("id", recipe.ID);
                writer.WriteString("category", recipe.Category);
                writer.WriteString("title", recipe.Title);
                writer.WriteString("description", recipe.Description);
                writer.WriteString("code", recipe.Code.Replace("\r", ""));
                writer.WriteEndObject();
            }
            writer.WriteEndArray();
            writer.WriteEndObject();

            return(recipes);
        }
Exemplo n.º 21
0
        internal JsonLogWriter(JsonWriterOptions formatting, bool formatLine)
        {
            this.formatLine = formatLine;
            this.formatting = formatting;

            streamReader = new StreamReader(stream, Encoding.UTF8);
        }
Exemplo n.º 22
0
        public static void WriteObjectValidations(bool skipValidation)
        {
            var buffer = new ArrayBufferWriter <byte>(1024);

            using (JsonDocument doc = JsonDocument.Parse("{\"First\":1}", default))
            {
                JsonElement root    = doc.RootElement;
                var         options = new JsonWriterOptions
                {
                    SkipValidation = skipValidation,
                };
                using var writer = new Utf8JsonWriter(buffer, options);
                if (skipValidation)
                {
                    foreach (JsonProperty property in root.EnumerateObject())
                    {
                        property.WriteTo(writer);
                    }
                    writer.Flush();
                    AssertContents("\"First\":1", buffer);
                }
                else
                {
                    foreach (JsonProperty property in root.EnumerateObject())
                    {
                        Assert.Throws <InvalidOperationException>(() =>
                        {
                            property.WriteTo(writer);
                        });
                    }
                    writer.Flush();
                    AssertContents("", buffer);
                }
            }
        }
 public JsonStreamActionResult()
 {
     JsonWriterOptions = new JsonWriterOptions()
     {
         Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
     };
 }
Exemplo n.º 24
0
        public static void WritePropertyOutsideObject(bool skipValidation)
        {
            var buffer = new ArrayBufferWriter <byte>(1024);

            using (var doc = JsonDocument.Parse("[ null, false, true, \"hi\", 5, {}, [] ]", s_readerOptions))
            {
                JsonElement root    = doc.RootElement;
                var         options = new JsonWriterOptions
                {
                    SkipValidation = skipValidation,
                };

                const string CharLabel = "char";
                byte[]       byteUtf8  = Encoding.UTF8.GetBytes("byte");
                var          writer    = new Utf8JsonWriter(buffer, options);

                if (skipValidation)
                {
                    foreach (JsonElement val in root.EnumerateArray())
                    {
                        val.WriteAsProperty(CharLabel, writer);
                        val.WriteAsProperty(CharLabel.AsSpan(), writer);
                        val.WriteAsProperty(byteUtf8, writer);
                    }

                    writer.Flush();

                    AssertContents(
                        "\"char\":null,\"char\":null,\"byte\":null," +
                        "\"char\":false,\"char\":false,\"byte\":false," +
                        "\"char\":true,\"char\":true,\"byte\":true," +
                        "\"char\":\"hi\",\"char\":\"hi\",\"byte\":\"hi\"," +
                        "\"char\":5,\"char\":5,\"byte\":5," +
                        "\"char\":{},\"char\":{},\"byte\":{}," +
                        "\"char\":[],\"char\":[],\"byte\":[]",
                        buffer);
                }
                else
                {
                    foreach (JsonElement val in root.EnumerateArray())
                    {
                        JsonTestHelper.AssertThrows <InvalidOperationException>(
                            ref writer,
                            (ref Utf8JsonWriter w) => val.WriteAsProperty(CharLabel, w));

                        JsonTestHelper.AssertThrows <InvalidOperationException>(
                            ref writer,
                            (ref Utf8JsonWriter w) => val.WriteAsProperty(CharLabel.AsSpan(), w));

                        JsonTestHelper.AssertThrows <InvalidOperationException>(
                            ref writer,
                            (ref Utf8JsonWriter w) => val.WriteAsProperty(byteUtf8, w));
                    }

                    writer.Flush();

                    AssertContents("", buffer);
                }
            }
        }
Exemplo n.º 25
0
        static FormUrlEncodedObjectSerializer()
        {
            writerOptions = new JsonWriterOptions
            {
                Indented       = false,
                SkipValidation = false
            };

            readerOptions = new JsonSerializerOptions
            {
                AllowTrailingCommas         = false,
                DefaultIgnoreCondition      = JsonIgnoreCondition.WhenWritingDefault,
                IgnoreReadOnlyFields        = true,
                IgnoreReadOnlyProperties    = true,
                IncludeFields               = false,
                NumberHandling              = JsonNumberHandling.AllowReadingFromString,
                PropertyNameCaseInsensitive = true,
                ReadCommentHandling         = JsonCommentHandling.Skip
            };

            readerOptions.Converters.Add(new NullableBooleanConverter());
            readerOptions.Converters.Add(new BooleanConverter());
            readerOptions.Converters.Add(new JsonStringEnumConverter(allowIntegerValues: true));
            readerOptions.Converters.Add(new NullableTimeSpanConverter());
            readerOptions.Converters.Add(new TimeSpanConverter());
            readerOptions.Converters.Add(new NullableDateTimeConverter());
            readerOptions.Converters.Add(new DateTimeConverter());
            readerOptions.Converters.Add(new NullableDateTimeOffsetConverter());
            readerOptions.Converters.Add(new DateTimeOffsetConverter());
            readerOptions.Converters.Add(new ObjectConverter());
            readerOptions.Converters.Add(new ContentDispositionConverter());
            readerOptions.Converters.Add(new ContentTypeConverter());
        }
Exemplo n.º 26
0
        static void JSONArrayAnidado()
        {
            JsonWriterOptions jsonWOpt = new JsonWriterOptions {
                Indented = true
            };

            using (var ms = new MemoryStream()) {
                using (var writer = new Utf8JsonWriter(ms, jsonWOpt)) {
                    writer.WriteStartObject();
                    writer.WriteString("nombre", "scrapywar.com");
                    writer.WriteStartArray("admins");

                    writer.WriteStartObject();
                    writer.WriteString("usuario", "nosoyadmin");
                    writer.WriteString("contrasena", "NoMeAcuerdo");
                    writer.WriteEndObject();

                    writer.WriteStartObject();
                    writer.WriteString("usuario", "nosoyadmin2");
                    writer.WriteString("contrasena", "TampocoMeAcuerdo");
                    writer.WriteEndObject();

                    writer.WriteEndArray();
                    writer.WriteEndObject();
                }
                string jsonstr = Encoding.UTF8.GetString(ms.ToArray());
                Console.WriteLine("JSON Anidado con Array: " + jsonstr);
                File.WriteAllText("yo3.json", jsonstr);
            }
        }
        private void WritePropertyValue(
            bool indented,
            JsonEncodedText propertyName,
            string jsonIn,
            string expectedIndent,
            string expectedMinimal)
        {
            var buffer = new ArrayBufferWriter <byte>(1024);

            using (JsonDocument doc = PrepareDocument(jsonIn))
            {
                var options = new JsonWriterOptions
                {
                    Indented = indented,
                };

                using (var writer = new Utf8JsonWriter(buffer, options))
                {
                    writer.WriteStartObject();
                    writer.WritePropertyName(propertyName);
                    WriteSingleValue(doc, writer);
                    writer.WriteEndObject();
                }

                JsonTestHelper.AssertContents(indented ? expectedIndent : expectedMinimal, buffer);
            }
        }
Exemplo n.º 28
0
    private static Task WriteResponse(HttpContext context, HealthReport result)
    {
        context.Response.ContentType = "application/json; charset=utf-8";

        var options = new JsonWriterOptions
        {
            Indented = true
        };

        using var stream = new MemoryStream();
        using (var writer = new Utf8JsonWriter(stream, options))
        {
            writer.WriteStartObject();
            writer.WriteString("status", result.Status.ToString());
            writer.WriteStartObject("results");
            foreach (var entry in result.Entries)
            {
                writer.WriteStartObject(entry.Key);
                writer.WriteString("status", entry.Value.Status.ToString());
                writer.WriteEndObject();
            }
            writer.WriteEndObject();
            writer.WriteEndObject();
        }

        var json = Encoding.UTF8.GetString(stream.ToArray());

        return(context.Response.WriteAsync(json));
    }
Exemplo n.º 29
0
        public static void AssertJsonWrite(
            JToken expectedValue,
            EventBean eventBean)
        {
            var expectedMinimalJson = expectedValue.ToString(Formatting.None);
            var expectedPrettyJson  = expectedValue.ToString(Formatting.Indented);

            var optionsMinimal = new JsonWriterOptions();
            var optionsIndent  = new JsonWriterOptions()
            {
                Indented = true
            };

            var und = (JsonEventObject)eventBean.Underlying;

            Assert.AreEqual(expectedMinimalJson, und.ToString(optionsMinimal));
            Assert.AreEqual(expectedPrettyJson, und.ToString(optionsIndent));

            var stream  = new MemoryStream();
            var writer  = new Utf8JsonWriter(stream, optionsMinimal);
            var context = new JsonSerializationContext(writer);

            und.WriteTo(context);

            Assert.AreEqual(expectedMinimalJson, Encoding.UTF8.GetString(stream.ToArray()));
        }
Exemplo n.º 30
0
        public static void DemoJsonWriter()
        {
            Console.WriteLine("================= Utf8JsonWriter Sample ================= ");

            var options = new JsonWriterOptions
            {
                Indented = true
            };

            var buffer = new ArrayBufferWriter <byte>();

            using var json = new Utf8JsonWriter(buffer, options);

            json.WriteStartObject();
            json.WritePropertyName("company");
            json.WriteStringValue("Acme");

            json.WriteString("language", "C#");

            json.WriteStartObject("author");

            json.WriteString("firstName", "Bugs");
            json.WriteString("lastName", "Bunny");

            json.WriteEndObject();
            json.WriteEndObject();

            json.Flush();

            var output  = buffer.WrittenSpan.ToArray();
            var ourJson = Encoding.UTF8.GetString(output);

            Console.WriteLine(ourJson);
            Console.WriteLine("================= ================= ================= ");
        }