示例#1
0
        public static void WriteJsonusingUTF8Writer(string path)
        {
            var writeOptions = new JsonWriterOptions
            {
                Indented       = true,
                SkipValidation = false
            };
            var bufferwriter = new ArrayBufferWriter <byte>();

            using (Utf8JsonWriter writer = new Utf8JsonWriter(bufferwriter, writeOptions))
            {
                writer.WriteStartObject();
                writer.WriteNumber("ID", 1);
                writer.WriteNull("ID2");
                writer.WriteBoolean("IsValid", true);
                writer.WriteString("CreatedDate", DateTimeOffset.UtcNow);
                writer.WriteNumber("NumValue", 1.2345);
                //Example of a comment
                writer.WriteCommentValue("Example of a comment");
                writer.WriteStartArray("NumArray");
                writer.WriteNumberValue(1.23);
                writer.WriteNumberValue(4.56);
                writer.WriteCommentValue("Example of a comment");

                writer.WriteNumberValue(7.89);
                writer.WriteEndArray();
                writer.WriteStartObject("Object");
                writer.WriteNumber("ID", 1);
                writer.WriteString("Name", "InnerObject");
                writer.WriteBase64String("FileData", File.ReadAllBytes("StaticFiles/SampleText.txt"));
                writer.WriteEndObject();
                writer.WriteEndObject();
            }
            string json = Encoding.UTF8.GetString(bufferwriter.WrittenSpan);

            Console.WriteLine(json);
            File.WriteAllBytes(path, bufferwriter.WrittenSpan.ToArray());
        }
        public override StreamMetadata Read(ref Utf8JsonReader reader, Type typeToConvert,
                                            JsonSerializerOptions options)
        {
            int?           maxCount = null;
            TimeSpan?      maxAge = null, cacheControl = null;
            StreamRevision?truncateBefore = null;
            StreamAcl      acl            = null;

            using var stream = new MemoryStream();
            using var customMetadataWriter = new Utf8JsonWriter(stream);

            if (reader.TokenType != JsonTokenType.StartObject)
            {
                throw new InvalidOperationException();
            }

            customMetadataWriter.WriteStartObject();

            while (reader.Read())
            {
                if (reader.TokenType == JsonTokenType.EndObject)
                {
                    break;
                }

                if (reader.TokenType != JsonTokenType.PropertyName)
                {
                    throw new InvalidOperationException();
                }

                switch (reader.GetString())
                {
                case SystemMetadata.MaxCount:
                    if (!reader.Read())
                    {
                        throw new InvalidOperationException();
                    }

                    maxCount = reader.GetInt32();
                    break;

                case SystemMetadata.MaxAge:
                    if (!reader.Read())
                    {
                        throw new InvalidOperationException();
                    }

                    var int64 = reader.GetInt64();
                    maxAge = TimeSpan.FromSeconds(int64);
                    break;

                case SystemMetadata.CacheControl:
                    if (!reader.Read())
                    {
                        throw new InvalidOperationException();
                    }

                    cacheControl = TimeSpan.FromSeconds(reader.GetInt64());
                    break;

                case SystemMetadata.TruncateBefore:
                    if (!reader.Read())
                    {
                        throw new InvalidOperationException();
                    }

                    var value = reader.GetInt64();
                    truncateBefore = value == long.MaxValue
                                                        ? StreamRevision.End
                                                        : StreamRevision.FromInt64(value);
                    break;

                case SystemMetadata.Acl:
                    if (!reader.Read())
                    {
                        throw new InvalidOperationException();
                    }

                    acl = StreamAclJsonConverter.Instance.Read(ref reader, typeof(StreamAcl), options);
                    break;

                default:
                    customMetadataWriter.WritePropertyName(reader.GetString());
                    reader.Read();
                    switch (reader.TokenType)
                    {
                    case JsonTokenType.Comment:
                        customMetadataWriter.WriteCommentValue(reader.GetComment());
                        break;

                    case JsonTokenType.String:
                        customMetadataWriter.WriteStringValue(reader.GetString());
                        break;

                    case JsonTokenType.Number:
                        customMetadataWriter.WriteNumberValue(reader.GetDouble());
                        break;

                    case JsonTokenType.True:
                    case JsonTokenType.False:
                        customMetadataWriter.WriteBooleanValue(reader.GetBoolean());
                        break;

                    case JsonTokenType.Null:
                        reader.Read();
                        customMetadataWriter.WriteNullValue();
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }

                    break;
                }
            }

            customMetadataWriter.WriteEndObject();
            customMetadataWriter.Flush();

            stream.Position = 0;

            return(new StreamMetadata(maxCount, maxAge, truncateBefore, cacheControl, acl,
                                      JsonDocument.Parse(stream)));
        }
示例#3
0
        public static void CopyCurrentTokenTo(this Utf8JsonReader reader, Utf8JsonWriter writer)
        {
            switch (reader.TokenType)
            {
            case JsonTokenType.Comment:
                writer.WriteCommentValue(reader.GetComment());
                break;

            case JsonTokenType.EndArray:
                writer.WriteEndArray();
                break;

            case JsonTokenType.EndObject:
                writer.WriteEndObject();
                break;

            case JsonTokenType.False:
                writer.WriteBooleanValue(false);
                break;

            case JsonTokenType.None:
                break;

            case JsonTokenType.Null:
                writer.WriteNullValue();
                break;

            case JsonTokenType.Number:
                if (reader.TryGetDecimal(out decimal d))
                {
                    writer.WriteNumberValue(d);
                }
                else
                {
                    throw new OverflowException("Too large for decimal");                             // How can I copy over the number if it can't even be represented in C#?
                }
                break;

            case JsonTokenType.PropertyName:
                writer.WritePropertyName(reader.GetString());
                break;

            case JsonTokenType.StartArray:
                writer.WriteStartArray();
                break;

            case JsonTokenType.StartObject:
                writer.WriteStartObject();
                break;

            case JsonTokenType.String:
                writer.WriteStringValue(reader.GetString());
                break;

            case JsonTokenType.True:
                writer.WriteBooleanValue(true);
                break;

            default:
                throw new DefaultSwitchCaseUnreachableException();
            }
        }
示例#4
0
        private void OverwriteAppsettings()
        {
            const string APPSETTINGS = "appsettings.json";
            const string TEMP        = "appsettings.tmp";


            lock (_fileLock)
            {
                using (Stream ofStream = System.IO.File.OpenRead(APPSETTINGS))
                    using (Utf8JsonStreamReader.Utf8JsonStreamReader reader = new Utf8JsonStreamReader.Utf8JsonStreamReader(ofStream, BUFFERSIZE))
                        using (Stream nfStream = System.IO.File.Create(TEMP))
                            using (Utf8JsonWriter writer = new Utf8JsonWriter(nfStream, new JsonWriterOptions {
                                Indented = true
                            }))
                            {
                                while (reader.Read())
                                {
                                    switch (reader.TokenType)
                                    {
                                    case JsonTokenType.None:
                                        break;

                                    case JsonTokenType.StartObject:
                                        writer.WriteStartObject();
                                        break;

                                    case JsonTokenType.EndObject:
                                        writer.WriteEndObject();
                                        break;

                                    case JsonTokenType.StartArray:
                                        writer.WriteStartArray();
                                        break;

                                    case JsonTokenType.EndArray:
                                        writer.WriteEndArray();
                                        break;

                                    case JsonTokenType.Comment:
                                        writer.WriteCommentValue(reader.GetComment());
                                        break;

                                    case JsonTokenType.String:
                                        writer.WriteStringValue(reader.GetString());
                                        break;

                                    case JsonTokenType.Number:
                                        writer.WriteNumberValue(reader.GetDecimal());
                                        break;

                                    case JsonTokenType.True:
                                        writer.WriteBooleanValue(true);
                                        break;

                                    case JsonTokenType.False:
                                        writer.WriteBooleanValue(false);
                                        break;

                                    case JsonTokenType.Null:
                                        writer.WriteNullValue();
                                        break;

                                    case JsonTokenType.PropertyName:
                                        if (reader.HasValueSequence)
                                        {
                                            Span <byte> buffer;

                                            if (reader.ValueSequence.Length <= BUFFERSIZE)
                                            {
                                                buffer = new Span <byte>(_buffer, 0, (int)reader.ValueSequence.Length);
                                            }
                                            else
                                            {
                                                buffer = new Span <byte>(new byte[reader.ValueSequence.Length]);
                                            }

                                            reader.ValueSequence.CopyTo(buffer);

                                            if (!buffer.SequenceEqual(BOTSETTINGS))
                                            {
                                                writer.WritePropertyName(buffer);
                                                break;
                                            }
                                        }
                                        else
                                        {
                                            if (!reader.ValueSpan.SequenceEqual(BOTSETTINGS))
                                            {
                                                writer.WritePropertyName(reader.ValueSpan);
                                                break;
                                            }
                                        }

                                        writer.WritePropertyName(BOTSETTINGS);
                                        JsonSerializer.Serialize(writer, _settings);

                                        // skip botsettigns
                                        int startDepth = reader.CurrentDepth;
                                        while (reader.TokenType != JsonTokenType.EndObject && reader.CurrentDepth != startDepth)
                                        {
                                            reader.Read();
                                        }

                                        break;

                                    default:
                                        break;
                                    }
                                }
                            }

                System.IO.File.Move(TEMP, APPSETTINGS);
            }
        }
        private static void WriteTestUsersSection(Utf8JsonWriter jw, IEnumerable <TestUser> testUsers)
        {
            jw.WriteStartArray("TestUsers");
            {
                foreach (var user in testUsers)
                {
                    jw.WriteStartObject();
                    {
                        jw.WriteString("Email", user.Email);
                        if (user.EmailConfirmed != TestUser.EMAIL_CONFIRMED_DEFAULT)
                        {
                            jw.WriteBoolean("EmailConfirmed", user.EmailConfirmed);
                        }
                        if (user.PlainTextPassword != TestUser.PASSWORD_DEFAULT)
                        {
                            jw.WriteString("PlainTextPassword", user.PlainTextPassword);
                        }
                        if (user.PhoneNumber != TestUser.PHONE_NUMBER_DEFAULT)
                        {
                            jw.WriteString("PhoneNumber", user.PhoneNumber);
                        }
                        if (user.PhoneNumberConfirmed != TestUser.PHONE_CONFIRMED_DEFAULT)
                        {
                            jw.WriteBoolean("PhoneNumberConfirmed", user.PhoneNumberConfirmed);
                        }
                        if (user.Organization != default)
                        {
                            jw.WriteString("Organization", user.Organization);
                        }
                        if (user.OrganizationConfirmed != TestUser.ORGANIZATION_CONFIRMED_DEFAULT)
                        {
                            jw.WriteBoolean("OrganizationConfirmed", user.OrganizationConfirmed);
                        }
                        if (user.OrganizationAdmin != TestUser.ORGANIZATION_ADMIN_DEFAULT)
                        {
                            jw.WriteBoolean("OrganizationAdmin", user.OrganizationAdmin);
                        }
                        if (user.SuperAdmin != TestUser.SUPER_ADMIN_DEFAULT)
                        {
                            jw.WriteBoolean("SuperAdmin", user.SuperAdmin);
                        }
                        if (user.LockedOut != TestUser.LOCKED_OUT_DEFAULT)
                        {
                            jw.WriteBoolean("LockedOut", user.LockedOut);
                        }

                        if (user.Roles != null && user.Roles.Count > 0)
                        {
                            jw.WriteStartArray("Roles");
                            {
                                foreach (var role in user.Roles)
                                {
                                    jw.WriteStringValue(role);
                                }
                            }
                            jw.WriteEndArray();
                        }

                        if (user.Claims != null && user.Claims.Count > 0)
                        {
                            if (user.Claims.Count == 1 && user.Claims.Keys.First() == "someClaimType")
                            {
                                jw.WriteCommentValue("Sample Custom Claims");
                            }

                            jw.WriteStartObject("Claims");
                            {
                                foreach (var claimType in user.Claims.Keys)
                                {
                                    jw.WriteStartArray(claimType);
                                    {
                                        foreach (var claimValue in user.Claims[claimType])
                                        {
                                            jw.WriteStringValue(claimValue);
                                        }
                                    }
                                    jw.WriteEndArray();
                                }
                            }
                            jw.WriteEndObject();
                        }
                    }
                    jw.WriteEndObject();
                }
            }
            jw.WriteEndArray();
        }