/// <summary>
        /// (Serialize)JSON 序列化
        /// </summary>
        /// <param name="implType"></param>
        /// <param name="value"></param>
        /// <param name="inputType"></param>
        /// <param name="writeIndented"></param>
        /// <param name="ignoreNullValues"></param>
        /// <returns></returns>
        public static string SJSON(JsonImplType implType, object?value, Type?inputType = null, bool writeIndented = false, bool ignoreNullValues = false)
        {
            switch (implType)
            {
            case JsonImplType.SystemTextJson:
                var options = new SJsonSerializerOptions
                {
                    Encoder       = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
                    WriteIndented = writeIndented,
                    //IgnoreNullValues = ignoreNullValues
                };
                if (ignoreNullValues)
                {
                    options.DefaultIgnoreCondition = SJsonIgnoreCondition.WhenWritingNull;
                }
                return(SJsonSerializer.Serialize(value, inputType ?? value?.GetType() ?? typeof(object), options));

            default:
#if NOT_NJSON
                throw new NotSupportedException();
#else
                var formatting = writeIndented ? Formatting.Indented : Formatting.None;
                var settings   = ignoreNullValues ? new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                } : null;
                return(SerializeObject(value, inputType, formatting, settings));
#endif
            }
        }
Example #2
0
        public BeaconBlock SignBlock(BeaconBlock block, BlsPublicKey blsPublicKey)
        {
            var fork  = _beaconChain.Fork;
            var epoch = ComputeEpochAtSlot(block.Slot);

            ForkVersion forkVersion;

            if (epoch < fork.Epoch)
            {
                forkVersion = fork.PreviousVersion;
            }
            else
            {
                forkVersion = fork.CurrentVersion;
            }

            var domainType     = _signatureDomainOptions.CurrentValue.BeaconProposer;
            var proposerDomain = ComputeDomain(domainType, forkVersion);

            JsonSerializerOptions options = new System.Text.Json.JsonSerializerOptions {
                WriteIndented = true
            };

            options.ConfigureNethermindCore2();
            string blockJson = System.Text.Json.JsonSerializer.Serialize(block, options);

            var signingRoot = _cryptographyService.SigningRoot(block);

            var signature = _validatorKeyProvider.SignHashWithDomain(blsPublicKey, signingRoot, proposerDomain);

            block.SetSignature(signature);

            return(block);
        }
Example #3
0
        public async Task GenesisHead()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true);
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

            MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value;
            TimeParameters          timeParameters          = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;
            StateListLengths        stateListLengths        = testServiceProvider.GetService <IOptions <StateListLengths> >().Value;
            MaxOperationsPerBlock   maxOperationsPerBlock   = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value;

            JsonSerializerOptions options = new System.Text.Json.JsonSerializerOptions {
                WriteIndented = true
            };

            options.ConfigureNethermindCore2();
            string debugState = System.Text.Json.JsonSerializer.Serialize(state, options);

            // Initialization
            ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>();
            ForkChoice           forkChoice          = testServiceProvider.GetService <ForkChoice>();
            IStore store = forkChoice.GetGenesisStore(state);

            // Act
            Hash32 headRoot = await forkChoice.GetHeadAsync(store);

            // Assert
            Hash32      stateRoot    = cryptographyService.HashTreeRoot(state);
            BeaconBlock genesisBlock = new BeaconBlock(stateRoot);
            Hash32      expectedRoot = cryptographyService.SigningRoot(genesisBlock);

            headRoot.ShouldBe(expectedRoot);
        }
Example #4
0
        public async Task GenesisHead()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true);
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

            JsonSerializerOptions options = new System.Text.Json.JsonSerializerOptions {
                WriteIndented = true
            };

            options.ConfigureNethermindCore2();
            string debugState = System.Text.Json.JsonSerializer.Serialize(state, options);

            // Initialization
            IBeaconChainUtility  beaconChainUtility  = testServiceProvider.GetService <IBeaconChainUtility>();
            ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>();
            IForkChoice          forkChoice          = testServiceProvider.GetService <IForkChoice>();

            IStore store = testServiceProvider.GetService <IStore>();
            await forkChoice.InitializeForkChoiceStoreAsync(store, state);

            // Act
            Root headRoot = await forkChoice.GetHeadAsync(store);

            // Assert
            Root stateRoot = cryptographyService.HashTreeRoot(state);

            BeaconBlock genesisBlock = new BeaconBlock(Slot.Zero, Root.Zero, stateRoot, BeaconBlockBody.Zero);
            Root        expectedRoot = cryptographyService.HashTreeRoot(genesisBlock);

            headRoot.ShouldBe(expectedRoot);
        }
        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                context.Response.ContentType = "application/json";
                context.Response.StatusCode  = (int)HttpStatusCode.InternalServerError;

                var response = _env.IsDevelopment()
                ? new ApiException(context.Response.StatusCode, ex.Message, ex.StackTrace?.ToString())
                : new ApiException(context.Response.StatusCode, "Internal Server Error");

                var options = new System.Text.Json.JsonSerializerOptions {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                };

                var json = JsonSerializer.Serialize(response, options);

                await context.Response.WriteAsync(json);
            }
        }
        public GeneralLedgerModule(EventStoreClient eventStore,
                                   IMessageTypeMapper messageTypeMapper, JsonSerializerOptions serializerOptions)
        {
            Build <OpenGeneralLedger>()
            .Log()
            .UnitOfWork(eventStore, messageTypeMapper, serializerOptions)
            .Handle((_, ct) => {
                var(unitOfWork, command) = _;
                var handlers             =
                    new GeneralLedgerHandlers(
                        new GeneralLedgerEventStoreRepository(eventStore, messageTypeMapper, unitOfWork),
                        new GeneralLedgerEntryEventStoreRepository(eventStore, messageTypeMapper, unitOfWork),
                        new ChartOfAccountsEventStoreRepository(eventStore, messageTypeMapper, unitOfWork));

                return(handlers.Handle(command, ct));
            });
            Build <BeginClosingAccountingPeriod>()
            .Log()
            .UnitOfWork(eventStore, messageTypeMapper, serializerOptions)
            .Handle((_, ct) => {
                var(unitOfWork, command) = _;
                var handlers             =
                    new GeneralLedgerHandlers(
                        new GeneralLedgerEventStoreRepository(eventStore, messageTypeMapper, unitOfWork),
                        new GeneralLedgerEntryEventStoreRepository(eventStore, messageTypeMapper, unitOfWork),
                        new ChartOfAccountsEventStoreRepository(eventStore, messageTypeMapper, unitOfWork));

                return(handlers.Handle(command, ct));
            });
        }
Example #7
0
        /// <inheritdoc cref="ToJson{TEntity}(TEntity, JsonNet.JsonSerializerSettings)"/>
        public static string ToJson <TEntity>(this TEntity entity, TextJson.JsonSerializerOptions options)
            where TEntity : class
        {
            _ = entity ?? throw new ArgumentNullException(nameof(entity));
            _ = options ?? throw new ArgumentNullException(nameof(options));

            return(TextJson.JsonSerializer.Serialize(entity, options));
        }
Example #8
0
        /// <inheritdoc cref="JsonEquals{TEntity}(TEntity, TEntity, JsonNet.JsonSerializerSettings)"/>
        public static bool JsonEquals <TEntity>(this TEntity left, TEntity right, TextJson.JsonSerializerOptions options)
            where TEntity : class
        {
            _ = options ?? throw new ArgumentNullException(nameof(options));

            var equalityComparer = new JsonEqualityComparer <TEntity>(options);

            return(equalityComparer.Equals(left, right));
        }
Example #9
0
        public static System.Text.Json.JsonSerializerOptions GetSimpleOptions()
        {
            var options = new System.Text.Json.JsonSerializerOptions
            {
                Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
            };

            return(options);
        }
        private JsonSerializerOptions GetJsonSerializerSettings()
        {
            var settings = new System.Text.Json.JsonSerializerOptions();

            settings.Converters.Add(new PlayerCardJsonConverter());
            settings.Converters.Add(new PlayingCardJsonConverter());
            settings.PropertyNameCaseInsensitive = true;

            return(settings);
        }
Example #11
0
        /// <inheritdoc cref="JsonClone{TEntity}(TEntity, JsonNet.JsonSerializerSettings)"/>
        public static TEntity JsonClone <TEntity>(this TEntity item, TextJson.JsonSerializerOptions options)
            where TEntity : class
        {
            _ = item ?? throw new ArgumentNullException(nameof(item));
            _ = options ?? throw new ArgumentNullException(nameof(options));

            var json = TextJson.JsonSerializer.Serialize(item, options);

            return(TextJson.JsonSerializer.Deserialize <TEntity>(json, options));
        }
Example #12
0
        public static void SaveSettings()
        {
            var options = new JsonSerializerOptions
            {
                WriteIndented = true
            };
            var jsonUtf8Bytes = JsonSerializer.SerializeToUtf8Bytes(AppData.settings, options);

            File.WriteAllBytes(pathToSettings, jsonUtf8Bytes);
        }
Example #13
0
        public static System.Text.Json.JsonSerializerOptions GetOptions()
        {
            var options = new System.Text.Json.JsonSerializerOptions
            {
                Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
            };

            options.Converters.Add(new DateTimeConverter());
            options.Converters.Add(new UserIdConverter());
            return(options);
        }
Example #14
0
        private string ToDebuggerDisplay()
        {
            if (_Content == null)
            {
                return(null);
            }

            var options = new JSONOPTIONS();

            options.WriteIndented = true;
            return(ToJson(options));
        }
Example #15
0
        /// <summary>
        /// 数据对象 To Json CoreWebView2WebResourceResponse
        /// </summary>
        /// <param name="data">返回数据对象</param>
        /// <param name="statusCode">HttpStatusCode</param>
        /// <param name="jsonSerializerOptions">jsonSerializerOptions</param>
        /// <returns>CoreWebView2WebResourceResponse</returns>
        protected CoreWebView2WebResourceResponse Json(object data, HttpStatusCode statusCode = HttpStatusCode.OK,
                                                       System.Text.Json.JsonSerializerOptions jsonSerializerOptions = null)
        {
            var json     = System.Text.Json.JsonSerializer.Serialize(data, jsonSerializerOptions);
            var buffer   = Encoding.UTF8.GetBytes(json);
            var stream   = new MemoryStream(buffer);
            var response = AppRuntime.RunTime.WebView2Environment.CreateWebResourceResponse(stream, (int)statusCode, nameof(statusCode), null);

            response.Headers.AppendHeader("Content-Type", "application/json");
            response.Headers.AppendHeader("access-control-allow-origin", "*");
            return(response);
        }
Example #16
0
        public BaseServices(System.Net.Http.HttpClient http) : base()
        {
            JsonOptions = new System.Text.Json.JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true,
            };

            Http = http;
            //Client.DefaultRequestHeaders

            BaseUrl    = "https://localhost:44380";
            RequestUri = $"{ BaseUrl }/{ GetApiUrl() }";
        }
        public override ObjectId Read(ref Utf8JsonReader reader, Type typeToConvert, System.Text.Json.JsonSerializerOptions options)
        {
            var objectIdString = reader.GetString();

            if (ObjectId.TryParse(objectIdString, out var objectId))
            {
                return(objectId);
            }

            return(ObjectId.Empty);

            throw new FormatException($"Read string cannot be converted to type '{typeof(ObjectId)}'.");
        }
Example #18
0
        /// <summary>
        /// 数据对象 To Json CoreWebView2WebResourceResponse
        /// </summary>
        /// <param name="data">返回数据对象</param>
        /// <param name="statusCode">HttpStatusCode</param>
        /// <param name="jsonSerializerOptions">jsonSerializerOptions</param>
        /// <returns>CoreWebView2WebResourceResponse</returns>
        protected WebResponse Json(object data, HttpStatusCode statusCode = HttpStatusCode.OK,
                                   System.Text.Json.JsonSerializerOptions jsonSerializerOptions = null)
        {
            var json        = System.Text.Json.JsonSerializer.Serialize(data, jsonSerializerOptions);
            var buffer      = Encoding.UTF8.GetBytes(json);
            var stream      = new MemoryStream(buffer);
            var contentType = CONTENT_TYPE_APPLICATION_JSON;
            var response    = new WebResponse {
                ContentStream = stream, HttpStatus = statusCode, MimeType = contentType
            };

            response.Headers.Add("Content-Type", contentType);
            response.Headers.Add("access-control-allow-origin", "*");
            return(response);
        }
        /// <summary>
        /// Creates the default json configuration for Caravel applications.
        /// </summary>
        /// <returns></returns>
        public static System.Text.Json.JsonSerializerOptions CamelCase()
        {
            {
                var options = new System.Text.Json.JsonSerializerOptions()
                {
                    IgnoreNullValues     = true,
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                };

                options.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));
                options.Converters.Add(new JsonDateTimeConverter());

                return(options);
            }
        }
Example #20
0
        /// <inheritdoc cref="ToJsonStreamAsync{TEntity}(TEntity, JsonNet.JsonSerializerSettings, CancellationToken)"/>
        public static async Task <Stream> ToJsonStreamAsync <TEntity>(
            this TEntity entity,
            TextJson.JsonSerializerOptions options,
            CancellationToken cancellationToken = default)
            where TEntity : class
        {
            _ = entity ?? throw new ArgumentNullException(nameof(entity));
            _ = options ?? throw new ArgumentNullException(nameof(options));

            var stream = new MemoryStream();
            await TextJson.JsonSerializer.SerializeAsync(stream, entity, options, cancellationToken);

            stream.Position = 0;
            return(stream);
        }
Example #21
0
        private string ToDebuggerDisplay()
        {
            if (_Content == null)
            {
                return(null);
            }

            var options = new JSONOPTIONS();

            options.WriteIndented = true;
            #pragma warning disable IL2026 // Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code
            return(ToJson(options));

            #pragma warning restore IL2026 // Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code
        }
        /// <summary>
        /// Gets the json for a <see cref="UserBar"/>, so it can be loaded with a better deserialiser.
        /// </summary>
        /// <param name="userBar">Bar data object from Morphic.Core</param>
        private string GetUserBarJson(UserBar userBar)
        {
            // Serialise the bar data so it can be loaded with a better deserialiser.
            SystemJson.JsonSerializerOptions serializerOptions = new SystemJson.JsonSerializerOptions();
            serializerOptions.Converters.Add(new JsonElementInferredTypeConverter());
            serializerOptions.Converters.Add(
                new SystemJson.Serialization.JsonStringEnumConverter(SystemJson.JsonNamingPolicy.CamelCase));
            string barJson = SystemJson.JsonSerializer.Serialize(userBar, serializerOptions);

            // Dump to a file, for debugging.
            string barFile = AppPaths.GetConfigFile("last-bar.json5");

            File.WriteAllText(barFile, barJson);

            return(barJson);
        }
Example #23
0
        public static Object Deserialize(Object obj, Type type, JSONOPTIONS options = null)
        {
            if (options == null)
            {
                options = new JSONOPTIONS
                {
                    PropertyNamingPolicy   = JsonNamingPolicy.CamelCase,
                    DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull,
                    WriteIndented          = true
                };
            }

            var json = ToJson(obj, options);

            return(JsonSerializer.Deserialize(json, type, options));
        }
Example #24
0
        public static Object Deserialize(Object obj, Type type, JSONOPTIONS options = null)
        {
            if (options == null)
            {
                options = new JSONOPTIONS
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                    IgnoreNullValues     = true,
                    WriteIndented        = true
                };
            }

            var json = ToJson(obj, options);

            return(JsonSerializer.Deserialize(json, type, options));
        }
        public static void SaveEscola()
        {
            string escolaFile = DataLocationFolder + "Escolas.json";

            System.Text.Json.JsonSerializerOptions options = new System.Text.Json.JsonSerializerOptions()
            {
                WriteIndented = true
            };
            string json       = System.Text.Json.JsonSerializer.Serialize(Escolas.ToArray(), options);
            string serverPath = @"srvmm";

            using (Network.NetworkShareAccesser.Access(serverPath, "meiomundo", "meiomundo"))
            {
                System.IO.File.WriteAllText(escolaFile, json);
            }
        }
Example #26
0
        public IActionResult getNoteContent(string noteId)
        {
            string a       = System.IO.File.ReadAllText("TextFile.txt");
            var    options = new System.Text.Json.JsonSerializerOptions
            {
                Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            };
            //NoteContent noteContent1 = JsonSerializer.Deserialize<NoteContent>(a, options);
            //NoteService.InsertNoteContent(noteContent1);
            NoteContent noteContent = NoteContentService.SelectNoteContent(123123);
            string      json        = JsonSerializer.Serialize(noteContent, options);

            // return Content(a);

            return(Content(json));
        }
Example #27
0
        public static IJournalEvent ParseJournalEvent(string logLine)
        {
            var journalEvent = System.Text.Json.JsonSerializer.Deserialize <JournalEvent>(logLine);

            var allTypes = Assembly.GetExecutingAssembly().GetTypes();

            allTypes = typeof(JournalEvent).Assembly.GetTypes();
            List <System.Type> eventTypes = new List <System.Type>();

            foreach (var t in allTypes)
            {
                string eventName = $"{journalEvent.Event}Event";
                if (t.Name == eventName)
                {
                    var methods = typeof(System.Text.Json.JsonSerializer).GetMethods();
                    foreach (var method in methods)
                    {
                        if (method.IsGenericMethod &&
                            method.Name == "Deserialize")
                        {
                            var parameters = method.GetParameters();
                            if (parameters.Length == 2)
                            {
                                var param1      = parameters[0];
                                var param2      = parameters[1];
                                var param1Match = typeof(System.String);
                                var param1Name  = param1.Name;
                                var param1Type  = param1.ParameterType;
                                if (param1Type == typeof(System.String) &&
                                    param1Name == "json")
                                {
                                    MethodInfo generic = method.MakeGenericMethod(t);
                                    var        options = new System.Text.Json.JsonSerializerOptions();
                                    return((IJournalEvent)generic.Invoke(null, new object [] { logLine, null }));
                                }
                            }
                        }
                    }
                }
            }

            return(new DeserializeExceptionEvent
            {
                Message = $"No type definition found for {journalEvent.Event}"
            });
        }
        public void TestConnectionStatesConverter_SystemText_InvalidReturnEmpty()
        {
            var jsonOption = new SystemJson.JsonSerializerOptions();

            jsonOption.Converters.Add(new ConnectionStatesConverter());
            var input = new Dictionary <string, string>
            {
                { "aKey", "aValue" },
                { "bKey", "123" },
                { "cKey", DateTime.Now.ToString() }
            };
            var serialized   = SystemJson.JsonSerializer.Serialize(input);
            var deserialized = SystemJson.JsonSerializer.Deserialize <IReadOnlyDictionary <string, BinaryData> >(serialized, jsonOption);

            Assert.NotNull(deserialized);
            Assert.AreEqual(0, deserialized.Count);
        }
Example #29
0
        public async Task <IActionResult> RegisterCredentials(string token, string keyName, string data)
        {
            try
            {
                var tokenVerify = tokenSerivce.VerifyToken(token);
                if (!tokenVerify)
                {
                    var apiRe = new ApiRe()
                    {
                        Ok  = false,
                        Msg = "注册失败,token无效"
                    };
                    return(Json(apiRe, MyJsonConvert.GetSimpleOptions()));
                }
                JsonSerializerOptions options = new System.Text.Json.JsonSerializerOptions
                {
                    Encoder    = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
                    Converters =
                    {
                        new JsonStringEnumMemberConverter(),
                        new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)
                    },
                    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
                };
                options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;

                options.Converters.Add(new Base64UrlConverter());

                var attestationResponse = JsonSerializer.Deserialize <AuthenticatorAttestationRawResponse>(data, options);

                var user = userService.GetUserByToken(token);
                if (string.IsNullOrEmpty(keyName) || !MyStringUtil.IsNumAndEnCh(keyName))
                {
                    keyName = "key";
                }
                var success = await fido2Service.RegisterCredentials(user, keyName, attestationResponse);

                // 4. return "ok" to the client
                return(Json(success));
            }
            catch (Exception e)
            {
                return(Json(new CredentialMakeResult(status: "error", errorMessage: FormatException(e), result: null)));
            }
        }
Example #30
0
        public static string ToJson(Object obj, JSONOPTIONS options)
        {
            if (obj == null)
            {
                return(String.Empty);
            }

            if (options == null)
            {
                options = new JSONOPTIONS
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                    IgnoreNullValues     = true,
                    WriteIndented        = true
                };
            }

            return(JsonSerializer.Serialize(obj, obj.GetType(), options));
        }