Example #1
0
        public async Task CreateSession_RedirectsToDashboard(string url)
        {
            // Arrange
            var client  = _factory.CreateClient();
            var payload = new LoginBindingModel {
                UserName = "******",
                Password = "******"
            };
            var options = new JsonSerializerOptions {
                PropertyNameCaseInsensitive = true,
                PropertyNamingPolicy        = JsonNamingPolicy.CamelCase,
                DictionaryKeyPolicy         = JsonNamingPolicy.CamelCase
            };

            options = options.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
            var ms = new MemoryStream();
            await JsonSerializer.SerializeAsync <LoginBindingModel>(ms, payload, options);

            var httpContent = new StringContent(ms.ToString(), Encoding.UTF8, "application/json");

            // Act
            var response = await client.PostAsync(url, httpContent);

            // Assert
            response.EnsureSuccessStatusCode();
            Assert.Equal("application/json", response.Content.Headers.ContentType.ToString());
        }
Example #2
0
            public void ShouldThrowOnNullProvider()
            {
                // Arrange
                var options = new JsonSerializerOptions();

                // Act
                options.ConfigureForNodaTime(null);
            }
        public static JsonSerializerOptions Configure(this JsonSerializerOptions options)
        {
            options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;

            options.Converters.Add(new JsonStringEnumConverter());
            options.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);

            return(options);
        }
Example #4
0
        public static JsonSerializerOptions ConfigureJsonOptions(this JsonSerializerOptions options, Action <MetadataJsonSerializationOptions>?configureSerialization = null)
        {
            options.ConfigureJsonForPropertyContainers(configureSerialization);
            options.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);

            options.Encoder       = JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
            options.WriteIndented = true;

            return(options);
        }
Example #5
0
        public static void ConfigureSystemTextJson(JsonSerializerOptions serializerOptions)
        {
            // Configures JsonSerializer to properly serialize NodaTime types.
            serializerOptions.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
            serializerOptions.Converters.Add(new JsonStringEnumConverter());
            serializerOptions.Converters.Add(new SmartEnumNameConverter <UnitOfMeasure, int>());
            serializerOptions.NumberHandling =
                JsonNumberHandling.WriteAsString | JsonNumberHandling.AllowReadingFromString;

            //serializerOptions.Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
        }
Example #6
0
    /// <summary>
    /// Configures an instance of <see cref="JsonSerializerOptions"/>.
    /// </summary>
    /// <param name="options">Options to configure.</param>
    public static JsonSerializerOptions ConfigureDefaultOptions(this JsonSerializerOptions options)
    {
        options.Encoder                     = JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
        options.NumberHandling              = JsonNumberHandling.AllowReadingFromString;
        options.AllowTrailingCommas         = true;
        options.PropertyNameCaseInsensitive = true;
        options.PropertyNamingPolicy        = JsonNamingPolicy.CamelCase;
        options.DictionaryKeyPolicy         = JsonNamingPolicy.CamelCase;
        options.DefaultIgnoreCondition      = JsonIgnoreCondition.WhenWritingNull;
        options.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));
        options.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);

        return(options);
    }
        public void SystemTextJsonSettingsTest()
        {
            IDateTimeZoneProvider dateTimeZoneProvider = DateTimeZoneProviders.Tzdb;
            DateTime dateTimeUtc = new DateTime(2020, 05, 23, 10, 30, 50, DateTimeKind.Utc);

            var schemaExamples        = new SchemaExamples(dateTimeZoneProvider, dateTimeUtc, "Europe/Moscow");
            var jsonSerializerOptions = new JsonSerializerOptions {
                Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            };
            var nodaTimeSchemaSettings = jsonSerializerOptions
                                         .ConfigureForNodaTime(dateTimeZoneProvider)
                                         .CreateNodaTimeSchemaSettingsForSystemTextJson(schemaExamples: schemaExamples);

            CheckGeneratedSchema(nodaTimeSchemaSettings);
        }
Example #8
0
        /// <summary>
        /// Create an implementation of <see cref="IBankMasterClient"/> wit Refit configured to use System.Text.Json for JSON deserialization.
        /// </summary>
        /// <param name="httpMessageHandlerFactory">Optionally supply a custom inner <see cref="HttpMessageHandler"/>.</param>
        /// <returns>An implementation of <see cref="IBankMasterClient"/> using System.Text.Json.</returns>
        public static IBankMasterClient CreateSystemTextJsonClient(Func <HttpMessageHandler>?httpMessageHandlerFactory = null)
        {
            var jsonSerializerOptions = new JsonSerializerOptions
            {
                Converters           = { new JsonStringEnumMemberConverter() },
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            };

            jsonSerializerOptions.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
            var contentSerializer = new SystemTextJsonContentSerializer(jsonSerializerOptions);
            var settings          = new RefitSettings(contentSerializer)
            {
                HttpMessageHandlerFactory = httpMessageHandlerFactory
            };

            return(RestService.For <IBankMasterClient>(BaseUri.ToString(), settings));
        }
Example #9
0
        public static JsonSerializerOptions Configure(this JsonSerializerOptions options, Action <JsonSerializerOptions> configure)
        {
            options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;

            options.Converters.Add(new JsonActivityContextConverter());
            options.Converters.Add(new JsonActivitySpanIdConverter());
            options.Converters.Add(new JsonActivityTraceIdConverter());
            options.Converters.Add(new JsonInstantConverter());
            options.Converters.Add(new JsonReadonlyDictionaryConverterFactory());
            options.Converters.Add(new JsonReadonlyListConverterFactory());
            options.Converters.Add(new JsonStringEnumConverter());
            options.Converters.Add(new JsonTimeSpanConverter());
            options.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);

            configure(options);

            return(options);
        }
Example #10
0
        public static SwaggerGenOptions ConfigureForNodaTime(this SwaggerGenOptions c)
        {
            var settings = new JsonSerializerOptions();

            settings.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);

            IEnumerable <(Type type, Func <OpenApiSchema> schema)> createStringSchema(
                Type type,
                object value,
                string?format = null
                )
            {
                yield return(type,
                             () => new OpenApiSchema()
                {
                    Type = "string",
                    Format = format,
                    Example = new OpenApiString(JsonSerializer.Serialize(value, settings).Trim('"'))
                });

                if (type.IsValueType)
                {
                    yield return(typeof(Nullable <>).MakeGenericType(type),
                                 () => new OpenApiSchema()
                    {
                        Type = "string",
                        Format = format,
                        Example = new OpenApiString(
                            JsonSerializer.Serialize(value, settings).Trim('"')
                            )
                    });
                }
            }

            var instant  = Instant.FromUnixTimeSeconds(1573000000);
            var interval = new Interval(
                instant,
                instant
                .PlusTicks(TimeSpan.TicksPerDay)
                .PlusTicks(TimeSpan.TicksPerHour)
                .PlusTicks(TimeSpan.TicksPerMinute)
                .PlusTicks(TimeSpan.TicksPerSecond)
                .PlusTicks(TimeSpan.TicksPerMillisecond)
                );
            var dateTimeZone   = DateTimeZoneProviders.Tzdb["America/New_York"];
            var zonedDateTime  = instant.InZone(dateTimeZone);
            var instantSchemas =
                createStringSchema(typeof(Instant), Instant.FromUnixTimeSeconds(1573000000), "date-time").ToArray();
            var period = Period.Between(
                zonedDateTime.LocalDateTime,
                interval.End.InZone(dateTimeZone).LocalDateTime,
                PeriodUnits.AllUnits
                );

            foreach (var(type, schema) in instantSchemas)
            {
                c.MapType(type, schema);
            }
            foreach (var(type, schema) in createStringSchema(
                         typeof(LocalDate),
                         LocalDate.FromDateTime(instant.ToDateTimeUtc()),
                         "date"
                         ))
            {
                c.MapType(type, schema);
            }

            foreach (var(type, schema) in createStringSchema(
                         typeof(LocalTime),
                         LocalTime.FromSecondsSinceMidnight(86400 - 12300),
                         "time"
                         ))
            {
                c.MapType(type, schema);
            }

            foreach (var(type, schema) in createStringSchema(
                         typeof(LocalDateTime),
                         LocalDateTime.FromDateTime(instant.ToDateTimeUtc()),
                         "date-time"
                         ))
            {
                c.MapType(type, schema);
            }

            foreach (var(type, schema) in createStringSchema(
                         typeof(OffsetDateTime),
                         OffsetDateTime.FromDateTimeOffset(instant.ToDateTimeOffset()),
                         "date-time"
                         ))
            {
                c.MapType(type, schema);
            }

            foreach (var(type, schema) in createStringSchema(typeof(ZonedDateTime), zonedDateTime, "date-time"))
            {
                c.MapType(type, schema);
            }
            foreach (var(type, schema) in createStringSchema(typeof(Offset), zonedDateTime.Offset))
            {
                c.MapType(type, schema);
            }
            foreach (var(type, schema) in createStringSchema(typeof(Period), period))
            {
                c.MapType(type, schema);
            }
            foreach (var(type, schema) in createStringSchema(typeof(Duration), interval.Duration))
            {
                c.MapType(type, schema);
            }
            foreach (var(type, schema) in createStringSchema(typeof(DateTimeZone), dateTimeZone))
            {
                c.MapType(type, schema);
            }
            c.MapType <Interval>(
                () =>
            {
                var instantSchema = instantSchemas[0].schema();
                return(new OpenApiSchema()
                {
                    Type = "object",
                    Nullable = false,
                    Properties = { ["start"] = instantSchemas[0].schema(), ["end"] = instantSchemas[0].schema(), }
                });
            });
            c.MapType <Interval?>(
                () => new OpenApiSchema()
            {
                Type       = "object",
                Nullable   = true,
                Properties = { ["start"] = instantSchemas[0].schema(), ["end"] = instantSchemas[0].schema(), }
            }
                );

            return(c);
        }
Example #11
0
    /// <summary>
    ///     Configure System.Text.Json with defaults for launchpad
    /// </summary>
    /// <param name="options"></param>
    /// <param name="dateTimeZoneProvider"></param>
    /// <returns></returns>
    public static JsonSerializerOptions ConfigureNodaTimeForLaunchPad(this JsonSerializerOptions options, IDateTimeZoneProvider dateTimeZoneProvider)
    {
        options.ConfigureForNodaTime(dateTimeZoneProvider);
        ReplaceConverter(
            options.Converters,
            new SystemTextJsonCompositeNodaPatternConverter <Instant>(
                InstantPattern.General,
                InstantPattern.ExtendedIso,
                new InstantDateTimeOffsetPattern()
                )
            );
        ReplaceConverter(
            options.Converters,
            new SystemTextJsonCompositeNodaPatternConverter <LocalDate>(
                LocalDatePattern.Iso,
                LocalDatePattern.FullRoundtrip
                )
            );
        ReplaceConverter(
            options.Converters,
            new SystemTextJsonCompositeNodaPatternConverter <LocalDateTime>(
                LocalDateTimePattern.GeneralIso,
                LocalDateTimePattern.ExtendedIso,
                LocalDateTimePattern.BclRoundtrip
                )
            );
        ReplaceConverter(
            options.Converters,
            new SystemTextJsonCompositeNodaPatternConverter <LocalTime>(
                LocalTimePattern.ExtendedIso,
                LocalTimePattern.GeneralIso
                )
            );
        ReplaceConverter(
            options.Converters,
            new SystemTextJsonCompositeNodaPatternConverter <Offset>(
                OffsetPattern.GeneralInvariant,
                OffsetPattern.GeneralInvariantWithZ
                )
            );
        ReplaceConverter(
            options.Converters,
            new SystemTextJsonCompositeNodaPatternConverter <Duration>(
                DurationPattern.JsonRoundtrip,
                DurationPattern.Roundtrip
                )
            );
        ReplaceConverter(
            options.Converters,
            new SystemTextJsonCompositeNodaPatternConverter <Period>(
                PeriodPattern.Roundtrip,
                PeriodPattern.NormalizingIso
                )
            );
        ReplaceConverter(
            options.Converters,
            new SystemTextJsonCompositeNodaPatternConverter <OffsetDateTime>(
                OffsetDateTimePattern.GeneralIso,
                OffsetDateTimePattern.FullRoundtrip
                )
            );
        ReplaceConverter(
            options.Converters,
            new SystemTextJsonCompositeNodaPatternConverter <OffsetDate>(
                OffsetDatePattern.GeneralIso,
                OffsetDatePattern.FullRoundtrip
                )
            );
        ReplaceConverter(
            options.Converters,
            new SystemTextJsonCompositeNodaPatternConverter <OffsetTime>(
                OffsetTimePattern.Rfc3339,
                OffsetTimePattern.GeneralIso,
                OffsetTimePattern.ExtendedIso
                )
            );
        ReplaceConverter(
            options.Converters,
            new SystemTextJsonCompositeNodaPatternConverter <ZonedDateTime>(
                ZonedDateTimePattern.CreateWithInvariantCulture("uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo<G> z", dateTimeZoneProvider)
                )
            );

        return(options);
    }
Example #12
0
 static RedisCacheService()
 {
     SerializeOptions.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
 }
        public void Output_format_must_comply_with_expected_streaming_input_format()
        {
            // Arrange
            // IMPORTANT: Please do not move this JSON away from this unit test despite that it would improve readability.
            // Reason is that the farther away it is being moving the more likely it becomes that someone changes
            // the format without realizing the consequences.
            var expectedTimeSeriesJson = @"{
  ""mRID"": ""tId2020-12-01T13:16:29.330Z"",
  ""MessageReference"": ""mId2020-12-01T13:16:29.330Z"",
  ""MarketDocument"": {
    ""mRID"": ""hId2020-12-01T13:16:29.330Z"",
    ""Type"": ""E66"",
    ""CreatedDateTime"": ""2020-12-01T13:16:29.33Z"",
    ""SenderMarketParticipant"": {
      ""mRID"": ""8100000000030"",
      ""name"": null,
      ""qualifier"": ""VA"",
      ""Type"": ""MDR""
    },
    ""RecipientMarketParticipant"": {
      ""mRID"": ""5790001330552"",
      ""name"": null,
      ""qualifier"": ""VA"",
      ""Type"": null
    },
    ""ProcessType"": ""D42"",
    ""MarketServiceCategory_Kind"": ""23""
  },
  ""MktActivityRecord_Status"": ""9"",
  ""Product"": ""8716867000030"",
  ""QuantityMeasurementUnit_Name"": ""KWH"",
  ""MarketEvaluationPointType"": ""E17"",
  ""SettlementMethod"": ""D01"",
  ""MarketEvaluationPoint_mRID"": ""571313180000000005"",
  ""CorrelationId"": ""66a28f7f-a8bc-4091-a870-0f54fccc6087"",
  ""Period"": {
    ""Resolution"": ""PT1H"",
    ""TimeInterval"": {
      ""Start"": ""2020-11-20T23:00:00Z"",
      ""End"": ""2020-11-21T23:00:00Z""
    },
    ""Points"": [
      {
        ""Position"": 1,
        ""Quantity"": 1.337,
        ""Quality"": ""E01"",
        ""Time"": ""2020-11-20T23:00:00Z""
      }
    ]
  },
  ""Transaction"": {
    ""mRID"": ""fc13ba2cf048432a951f260ecafb60d4""
  },
  ""RequestDate"": ""2020-12-15T13:15:11.8349163Z""
}";

            var prettyPrintOptions = new JsonSerializerOptions {
                WriteIndented = true
            };

            prettyPrintOptions.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
            var nodaTimeOptions = new JsonSerializerOptions();

            nodaTimeOptions.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
            var timeSeriesMessage = JsonSerializer.Deserialize <TimeSeriesMessage>(expectedTimeSeriesJson, nodaTimeOptions);

            // Act
            var actual = JsonSerializer.Serialize(timeSeriesMessage, prettyPrintOptions);

            // Assert
            Assert.Equal(expectedTimeSeriesJson.Replace("\r", string.Empty), actual.Replace("\r", string.Empty));
        }
Example #14
0
 public static void ConfigureSerializerSettings(JsonSerializerOptions jsonSerializerOptions)
 {
     jsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
     jsonSerializerOptions.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
 }