/// <summary> /// Creates a new instance of an ErrorHandlingMiddleware class, and initializes it with the specified arguments. /// </summary> /// <param name="next"></param> /// <param name="env"></param> /// <param name="logger"></param> /// <param name="options"></param> public ErrorHandlingMiddleware(RequestDelegate next, IWebHostEnvironment env, ILogger <ErrorHandlingMiddleware> logger, IOptions <JsonOptions> options) { _next = next; _env = env; _logger = logger; _options = options.Value; }
private static async Task Run(JsonOptions options) { var serviceProvider = ServiceRegistration.Register(); var logger = serviceProvider.GetService <ILoggerFactory>() .CreateLogger <Program>(); logger.LogDebug("Starting building metrics service"); try { var service = serviceProvider.GetService <IBuildingMetricsService>(); var response = await service.Execute(options); var responseDisplay = JsonConvert.SerializeObject(response); Console.WriteLine($"Output: {responseDisplay}"); } catch (Exception e) { Console.WriteLine(e); } logger.LogDebug("Calculation completed"); Console.ReadKey(); }
public SystemTextJsonResultExecutor( IOptions <JsonOptions> options, ILogger <SystemTextJsonResultExecutor> logger) { _options = options.Value; _logger = logger; }
/// <summary> /// Handles the exception. /// </summary> public static async Task HandleException( HttpContext context, JsonOptions jsonOptions, IHostEnvironment env, ILogger logger) { var operationContext = context.RequestServices.GetService <IOperationContext>(); var helpDeskIdGenerator = context.RequestServices.GetService <IHelpDeskIdGenerator>(); var operationId = operationContext?.Id ?? Activity.Current?.Id; var exceptionHandlerFeature = context.Features.Get <IExceptionHandlerFeature>(); var responseModel = CreateErrorModel(exceptionHandlerFeature?.Error); responseModel.Extensions[OperationIdProperty] = operationId; var helpDeskId = helpDeskIdGenerator?.GenerateReadableId(CultureInfo.InvariantCulture); if (!string.IsNullOrEmpty(helpDeskId)) { responseModel.Extensions[HelpDeskIdProperty] = helpDeskId; logger.LogError("HelpDeskId: {helpDeskId} - Error: {Error}", helpDeskId, exceptionHandlerFeature?.Error?.ToStringDemystified()); } if (env.IsDevelopment()) { responseModel.Extensions["exceptionType"] = exceptionHandlerFeature?.Error?.GetType()?.ToString(); responseModel.Extensions["stackTrace"] = exceptionHandlerFeature?.Error?.ToStringDemystified()?.Split(Environment.NewLine); } context.Response.ContentType = "application/problem+json"; context.Response.StatusCode = responseModel.Status ?? StatusCodes.Status500InternalServerError; await context.Response.WriteAsync(JsonSerializer.Serialize(responseModel, jsonOptions.JsonSerializerOptions), Encoding.UTF8); }
public void Serialize_UsesOptionsConfiguredInTheProvider() { // Arrange // This should use property-casing and indentation, but the result should be HTML-safe var options = new JsonOptions { JsonSerializerOptions = { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, PropertyNamingPolicy = null, WriteIndented = true, } }; var helper = GetJsonHelper(options); var obj = new { HTML = "<b>John</b>" }; var expectedOutput = @"{ ""HTML"": ""\u003Cb\u003EJohn\u003C/b\u003E"" }"; // Act var result = helper.Serialize(obj); // Assert var htmlString = Assert.IsType <HtmlString>(result); Assert.Equal(expectedOutput, htmlString.ToString(), ignoreLineEndingDifferences: true); }
/// <summary> /// Format an object as a json string /// </summary> /// <param name="o">The value to be formatted</param> /// <param name="options">Options controlling output</param> /// <returns>The formatted string</returns> public static string Format(object o, JsonOptions options = JsonOptions.None) { var sw = new StringWriter(); var writer = new JsonWriter(sw, ResolveOptions(options)); writer.WriteValue(o); return(sw.ToString()); }
public Tokenizer(TextReader r, JsonOptions options) { _underlying = r; _options = options; FillBuffer(); NextChar(); NextToken(); }
protected SerialManager(Type type, JsonOptions op, bool get) { options = op; BindingFlags flags = BindingFlags.Instance | BindingFlags.Public; fields = type.GetFields(flags).Where(f => f.FieldType != type).ToArray(); properties = type.GetProperties(flags).Where(p => ValidProperty(p, type, get)).ToArray(); }
public static ChainedJsonOptions Use(this JsonOptions options, Func <JsonSerializerSettings> settingsFactory) { return(new ChainedJsonOptions(options, target => { var source = settingsFactory(); source.CopyTo(target); })); }
public ApiControllerBase(ControllerServicesContext context) { Mapper = context.Mapper; EmailService = context.EmailService; LinkGenerator = context.LinkGenerator; AppSettings = context.AppSettings; JsonOptions = context.JsonOptions; }
public void ODataJsonOptionsSetup_DoesNotSetup_ODataJsonConverters() { // Arrange & Act JsonOptions options = GetJsonOptions(false); // Assert Assert.Empty(options.JsonSerializerOptions.Converters); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddTransient <IInquiryRepository, InquireRepository>(provider => new InquireRepository(Configuration.GetConnectionString("Inquirydbms"))); services.AddTransient <IDbConnection, SqlConnection>(); services.AddMvc(option => option.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Version_2_1); JsonOptions opt = new JsonOptions(); }
private void TryParseSubTrees(string stringText, JsonOptions options) { // Trim the input from the right and make sure tree invariants hold var current = stringText; while (current != "@\"\"" && current != "\"\"") { current = current[0..^ 2] + "\"";
public IntegrationEventBusInMemory(ILogger <IntegrationEventBusInMemory> logger, IServiceProvider serviceProvider, IIntegrationEventBusSubscriptionsManager subsManager, IOptions <JsonOptions> jsonOptions) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _subsManager = subsManager ?? new IntegrationEventBusInMemorySubscriptionsManager(); _jsonOptions = jsonOptions.Value; _serviceProvider = serviceProvider; }
public void CreateJsonOptionsTest() { var options = JsonOptions.Create(); options.PropertyNamingPolicy.Should().Be(JsonNamingPolicy.CamelCase); options.WriteIndented.Should().BeTrue(); options.Converters.Should().ContainEquivalentOf(new JsonStringEnumConverter()); }
public static void SetDefaultJsonOptions(this JsonOptions options) { options.JsonSerializerOptions.Converters.Add(new NumericValueJsonConverter()); options.JsonSerializerOptions.Converters.Add(new AppKeyJsonConverter()); options.JsonSerializerOptions.Converters.Add(new AppVersionKeyJsonConverter()); options.JsonSerializerOptions.PropertyNameCaseInsensitive = true; options.JsonSerializerOptions.PropertyNamingPolicy = null; options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; }
public DomainEventBusInMemory( IServiceProvider serviceProvider, IDomainEventBusSubscriptionsManager domainEventSubscriptionsManager, IOptions <JsonOptions> jsonOptions) { _serviceProvider = serviceProvider; DomainEventSubscriptionsManager = domainEventSubscriptionsManager; _jsonOptions = jsonOptions.Value; }
public DownloadPersonalDataModel( UserManager <User> userManager, ILogger <DownloadPersonalDataModel> logger, IOptions <JsonOptions> jsonOptions) { _userManager = userManager; _logger = logger; _jsonOptions = jsonOptions.Value; }
public ControllerServicesContext(IWebHostEnvironment hostingEnvironment, IMapper mapper, IEmailService emailService, LinkGenerator linkGenerator, AppSettings appSettings, IOptions <JsonOptions> jsonOptions) { HostingEnvironment = hostingEnvironment; Mapper = mapper; EmailService = emailService; LinkGenerator = linkGenerator; AppSettings = appSettings; JsonOptions = jsonOptions.Value; }
public SystemTextJsonResultExecutor( IOptions <JsonOptions> options, ILogger <SystemTextJsonResultExecutor> logger, IOptions <MvcOptions> mvcOptions) { _options = options.Value; _logger = logger; _asyncEnumerableReader = new AsyncEnumerableReader(mvcOptions.Value); }
protected override IJsonHelper GetJsonHelper() { var options = new JsonOptions() { JsonSerializerOptions = { PropertyNamingPolicy = JsonNamingPolicy.CamelCase } }; return(new SystemTextJsonHelper(Options.Create(options))); }
public SerializationContext() { DateTimeOptions = new DateTimeOptions(); EnumOptions = new EnumOptions(); ArrayOptions = new ArrayOptions(); MapOptions = new MapOptions(); JsonOptions = new JsonOptions(); TypeHandlers = new TypeHandlers(this); }
public JsonInputFormatter(JsonOptions options, ILogger <SystemTextJsonInputFormatter> logger) { SerializerOptions = options.JsonSerializerOptions; _logger = logger; SupportedEncodings.Add(UTF8EncodingWithoutBOM); SupportedMediaTypes.Add(ApplicationJson); SupportedMediaTypes.Add(TextJson); }
private void UpdateJsonOptions(JsonOptions options) { options.JsonSerializerOptions.AllowTrailingCommas = JsonOptions.AllowTrailingCommas; options.JsonSerializerOptions.PropertyNamingPolicy = JsonOptions.PropertyNamingPolicy; foreach (var converter in JsonOptions.Converters) { options.JsonSerializerOptions.Converters.Add(converter); } }
public static IOptions <JsonOptions> JsonOptions(Action <JsonOptions> configuration = null) { var options = new JsonOptions() { JsonSerializerOptions = { PropertyNamingPolicy = JsonNamingPolicy.CamelCase } }; configuration?.Invoke(options); return(Options.Create(options)); }
public static void ConfigureJsonOptions(JsonOptions jsonOptions) { jsonOptions.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)); jsonOptions.JsonSerializerOptions.NumberHandling = JsonNumberHandling.AllowReadingFromString; jsonOptions.JsonSerializerOptions.PropertyNameCaseInsensitive = true; jsonOptions.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; // Use the same serialization settings globally 🌐 Common.JsonSerializerOptions = jsonOptions.JsonSerializerOptions; }
/// <summary> /// Serializes the class to JSON. /// </summary> /// <param name="jsonOptions">JSON formatting options.</param> /// <returns>A JSON string representing the class instance.</returns> public virtual string ToJson(JsonOptions jsonOptions) { var json = JsonConvert.SerializeObject( this, (jsonOptions == JsonOptions.Indented) ? Formatting.Indented : Formatting.None, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Serialize, DefaultValueHandling = DefaultValueHandling.Ignore }); return(json); }
public JsonNavigationService(IWebHostEnvironment hostingEnvironment, IOptions <JsonNavigationServiceOptions> options, IOptions <JsonOptions> jsonOptions) { _hostingEnvironment = hostingEnvironment; _jsonOptions = jsonOptions.Value; foreach (var file in options.Value.FileNames) { _navigations.Add(file, JsonSerializer.Deserialize <List <NavigationItem> >(File.ReadAllText(Path.Combine(_hostingEnvironment.ContentRootPath, file)), _jsonOptions.JsonSerializerOptions)); } }
public ApplicationServiceClient(ApplicationServiceCacheEntryResolver serviceEntryResolver, IEnumerable <IApplicationServiceComponent> components, IOptions <JsonOptions> jsonOptions, ILogger <ApplicationServiceClient> logger) { _serviceEntryResolver = serviceEntryResolver ?? throw new ArgumentNullException(nameof(serviceEntryResolver)); _components = components ?? throw new ArgumentNullException(nameof(components)); _jsonOptions = jsonOptions?.Value ?? throw new ArgumentNullException(nameof(jsonOptions)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); }
/// <summary> /// Initializes a new <see cref="SystemTextJsonOutputFormatter"/> instance. /// </summary> /// <param name="options">The <see cref="JsonOptions"/>.</param> public SystemTextJsonOutputFormatter(JsonOptions options) { SerializerOptions = options.JsonSerializerOptions; SupportedEncodings.Add(Encoding.UTF8); SupportedEncodings.Add(Encoding.Unicode); SupportedMediaTypes.Add(MediaTypeHeaderValues.ApplicationJson); SupportedMediaTypes.Add(MediaTypeHeaderValues.TextJson); SupportedMediaTypes.Add(MediaTypeHeaderValues.ApplicationAnyJsonSyntax); }
internal void BaseSerialize(TextWriter w, object obj, JsonOptions options, string format) { BaseSerialize(w, obj, options, format, 0); }
/// <summary> /// Serializes the class to JSON. /// </summary> /// <param name="jsonOptions">JSON formatting options.</param> /// <returns>A JSON string representing the class instance.</returns> public virtual string ToJson(JsonOptions jsonOptions) { var json = JsonConvert.SerializeObject(this, (jsonOptions == JsonOptions.Indented) ? Formatting.Indented : Formatting.None, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Serialize, DefaultValueHandling = DefaultValueHandling.Ignore, //NullValueHandling = NullValueHandling.Ignore, }); return json; }
internal override void BaseSerialize(TextWriter w, object obj, JsonOptions options, string format, int tabDepth) { w.Write(Convert.ToBoolean(obj).ToString().ToLower()); }
internal void BaseSerialize(TextWriter w, object obj, JsonOptions options) { BaseSerialize(w, obj, JsonOptions.None, null, 0); }
internal abstract void BaseSerialize(TextWriter w, object obj, JsonOptions options, string format, int tabDepth);