Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,57 @@
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using Microsoft.Extensions.Logging;
using Volo.Abp.Timing;

namespace Volo.Abp.AspNetCore.Mvc.ModelBinding;

public class AbpDateTimeModelBinder : IModelBinder
{
private readonly ILogger<AbpDateTimeModelBinder> _logger;
private readonly DateTimeModelBinder _dateTimeModelBinder;
private readonly IClock _clock;
private readonly ICurrentTimezoneProvider _currentTimezoneProvider;
private readonly ITimezoneProvider _timezoneProvider;

public AbpDateTimeModelBinder(IClock clock, DateTimeModelBinder dateTimeModelBinder)
public AbpDateTimeModelBinder(
ILogger<AbpDateTimeModelBinder> logger,
DateTimeModelBinder dateTimeModelBinder,
IClock clock,
ICurrentTimezoneProvider currentTimezoneProvider,
ITimezoneProvider timezoneProvider)
{
_clock = clock;
_logger = logger;
_dateTimeModelBinder = dateTimeModelBinder;
_clock = clock;
_currentTimezoneProvider = currentTimezoneProvider;
_timezoneProvider = timezoneProvider;
}

public async Task BindModelAsync(ModelBindingContext bindingContext)
{
await _dateTimeModelBinder.BindModelAsync(bindingContext);
if (bindingContext.Result.IsModelSet && bindingContext.Result.Model is DateTime dateTime)

if (!bindingContext.Result.IsModelSet || bindingContext.Result.Model is not DateTime dateTime)
{
bindingContext.Result = ModelBindingResult.Success(_clock.Normalize(dateTime));
return;
}

if (dateTime.Kind == DateTimeKind.Unspecified &&
_clock.SupportsMultipleTimezone &&
!_currentTimezoneProvider.TimeZone.IsNullOrWhiteSpace())
{
try
{
var timezoneInfo = _timezoneProvider.GetTimeZoneInfo(_currentTimezoneProvider.TimeZone);
dateTime = new DateTimeOffset(dateTime, timezoneInfo.GetUtcOffset(dateTime)).UtcDateTime;
}
catch
{
_logger.LogWarning("Could not convert DateTime with unspecified Kind using timezone '{TimeZone}'.", _currentTimezoneProvider.TimeZone);
}
Comment thread
maliming marked this conversation as resolved.
Resolved
Comment thread
maliming marked this conversation as resolved.
Resolved
}

bindingContext.Result = ModelBindingResult.Success(_clock.Normalize(dateTime));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,6 @@ protected virtual AbpDateTimeModelBinder CreateAbpDateTimeModelBinder(ModelBinde
{
const DateTimeStyles supportedStyles = DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AdjustToUniversal;
var dateTimeModelBinder = new DateTimeModelBinder(supportedStyles, context.Services.GetRequiredService<ILoggerFactory>());
return new AbpDateTimeModelBinder(context.Services.GetRequiredService<IClock>(), dateTimeModelBinder);
return ActivatorUtilities.CreateInstance<AbpDateTimeModelBinder>(context.Services, dateTimeModelBinder);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
using System.Globalization;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
Expand All @@ -15,15 +17,24 @@ namespace Volo.Abp.Json.Newtonsoft;
public class AbpDateTimeConverter : DateTimeConverterBase, ITransientDependency
{
private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";

public ILogger<AbpDateTimeConverter> Logger { get; set; }

private readonly DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind;
private readonly CultureInfo _culture = CultureInfo.InvariantCulture;
private readonly IClock _clock;
private readonly AbpJsonOptions _options;
private readonly ICurrentTimezoneProvider _currentTimezoneProvider;
private readonly ITimezoneProvider _timezoneProvider;
private bool _skipDateTimeNormalization;

public AbpDateTimeConverter(IClock clock, IOptions<AbpJsonOptions> options)
public AbpDateTimeConverter(IClock clock, IOptions<AbpJsonOptions> options, ICurrentTimezoneProvider currentTimezoneProvider, ITimezoneProvider timezoneProvider)
{
Logger = NullLogger<AbpDateTimeConverter>.Instance;

_clock = clock;
_currentTimezoneProvider = currentTimezoneProvider;
_timezoneProvider = timezoneProvider;
_options = options.Value;
}

Expand All @@ -41,19 +52,14 @@ public override bool CanConvert(Type objectType)
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
var nullable = Nullable.GetUnderlyingType(objectType) != null;
if (reader.TokenType == JsonToken.Null)
switch (reader.TokenType)
{
if (!nullable)
{
case JsonToken.Null when !nullable:
throw new JsonSerializationException($"Cannot convert null value to {objectType.FullName}.");
}

return null;
}

if (reader.TokenType == JsonToken.Date)
{
return Normalize(reader.Value!.To<DateTime>());
case JsonToken.Null:
return null;
case JsonToken.Date:
return Normalize(reader.Value!.To<DateTime>());
}

if (reader.TokenType != JsonToken.String)
Expand Down Expand Up @@ -108,7 +114,7 @@ public override void WriteJson(JsonWriter writer, object? value, JsonSerializer
}
}

static internal bool ShouldNormalize(MemberInfo member, JsonProperty property)
internal static bool ShouldNormalize(MemberInfo member, JsonProperty property)
{
if (property.PropertyType != typeof(DateTime) &&
property.PropertyType != typeof(DateTime?))
Expand All @@ -121,6 +127,23 @@ static internal bool ShouldNormalize(MemberInfo member, JsonProperty property)

protected virtual DateTime Normalize(DateTime dateTime)
{
if (dateTime.Kind != DateTimeKind.Unspecified ||
!_clock.SupportsMultipleTimezone ||
_currentTimezoneProvider.TimeZone.IsNullOrWhiteSpace())
{
return _skipDateTimeNormalization ? dateTime : _clock.Normalize(dateTime);
}

try
{
var timezoneInfo = _timezoneProvider.GetTimeZoneInfo(_currentTimezoneProvider.TimeZone);
dateTime = new DateTimeOffset(dateTime, timezoneInfo.GetUtcOffset(dateTime)).UtcDateTime;
}
catch
{
Logger.LogWarning("Could not convert DateTime with unspecified Kind using timezone '{TimeZone}'.", _currentTimezoneProvider.TimeZone);
}
Comment thread
maliming marked this conversation as resolved.
Resolved

return _skipDateTimeNormalization
? dateTime
: _clock.Normalize(dateTime);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,84 +1,43 @@
using System;
using System.Globalization;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Options;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Timing;

namespace Volo.Abp.Json.SystemTextJson.JsonConverters;

public class AbpDateTimeConverter : JsonConverter<DateTime>, ITransientDependency
public class AbpDateTimeConverter : AbpDateTimeConverterBase<DateTime>, ITransientDependency
{
private readonly IClock _clock;
private readonly AbpJsonOptions _options;
private bool _skipDateTimeNormalization;

public AbpDateTimeConverter(IClock clock, IOptions<AbpJsonOptions> abpJsonOptions)
public AbpDateTimeConverter(
IClock clock,
IOptions<AbpJsonOptions> abpJsonOptions,
ICurrentTimezoneProvider currentTimezoneProvider,
ITimezoneProvider timezoneProvider)
: base(clock, abpJsonOptions, currentTimezoneProvider, timezoneProvider)
{
_clock = clock;
_options = abpJsonOptions.Value;
}

public virtual AbpDateTimeConverter SkipDateTimeNormalization()
{
_skipDateTimeNormalization = true;
IsSkipDateTimeNormalization = true;
return this;
}

public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (_options.InputDateTimeFormats.Any())
{
if (reader.TokenType == JsonTokenType.String)
{
foreach (var format in _options.InputDateTimeFormats)
{
var s = reader.GetString();
if (DateTime.TryParseExact(s, format, CultureInfo.CurrentUICulture, DateTimeStyles.None, out var d1))
{
return Normalize(d1);
}
}
}
else
{
throw new JsonException("Reader's TokenType is not String!");
}
}

if (reader.TryGetDateTime(out var d3))
{
return Normalize(d3);
}

var dateText = reader.GetString();
if (!dateText.IsNullOrWhiteSpace())
if (Options.InputDateTimeFormats.Any() && reader.TokenType != JsonTokenType.String)
{
if (DateTime.TryParse(dateText, CultureInfo.CurrentUICulture, DateTimeStyles.None, out var d4))
{
return Normalize(d4);
}
throw new JsonException("Reader's TokenType is not String!");
}

throw new JsonException("Can't get datetime from the reader!");
return TryReadDateTime(ref reader, out var result)
? result
: throw new JsonException("Can't get datetime from the reader!");
}

public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
if (_options.OutputDateTimeFormat.IsNullOrWhiteSpace())
{
writer.WriteStringValue(Normalize(value));
}
else
{
writer.WriteStringValue(Normalize(value).ToString(_options.OutputDateTimeFormat, CultureInfo.CurrentUICulture));
}
}

protected virtual DateTime Normalize(DateTime dateTime)
{
return _skipDateTimeNormalization ? dateTime : _clock.Normalize(dateTime);
WriteDateTime(writer, value);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
using System;
using System.Globalization;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Volo.Abp.Timing;

namespace Volo.Abp.Json.SystemTextJson.JsonConverters;

public abstract class AbpDateTimeConverterBase<T> : JsonConverter<T>
{
public ILogger<AbpDateTimeConverterBase<T>> Logger { get; set; }

protected IClock Clock { get; }
protected AbpJsonOptions Options { get; }
protected ICurrentTimezoneProvider CurrentTimezoneProvider { get; }
protected ITimezoneProvider TimezoneProvider { get; }
protected bool IsSkipDateTimeNormalization { get; set; }

protected AbpDateTimeConverterBase(
IClock clock,
IOptions<AbpJsonOptions> abpJsonOptions,
ICurrentTimezoneProvider currentTimezoneProvider,
ITimezoneProvider timezoneProvider)
{
Logger = NullLogger<AbpDateTimeConverterBase<T>>.Instance;

Clock = clock;
CurrentTimezoneProvider = currentTimezoneProvider;
TimezoneProvider = timezoneProvider;
Options = abpJsonOptions.Value;
}

protected bool TryReadDateTime(ref Utf8JsonReader reader, out DateTime value)
{
value = default;

if (Options.InputDateTimeFormats.Any())
{
if (reader.TokenType != JsonTokenType.String)
{
return false;
}

var s = reader.GetString();
foreach (var format in Options.InputDateTimeFormats)
{
if (!DateTime.TryParseExact(s, format, CultureInfo.CurrentUICulture, DateTimeStyles.None, out var d1))
{
continue;
}

value = Normalize(d1);
return true;
}
}

if (reader.TryGetDateTime(out var d2))
{
value = Normalize(d2);
return true;
}

var dateText = reader.GetString();
if (dateText.IsNullOrWhiteSpace())
{
return false;
}

if (!DateTime.TryParse(dateText, CultureInfo.CurrentUICulture, DateTimeStyles.None, out var d3))
{
return false;
}

value = Normalize(d3);
return true;

}

protected void WriteDateTime(Utf8JsonWriter writer, DateTime value)
{
if (Options.OutputDateTimeFormat.IsNullOrWhiteSpace())
{
writer.WriteStringValue(Normalize(value));
}
else
{
writer.WriteStringValue(Normalize(value).ToString(Options.OutputDateTimeFormat, CultureInfo.CurrentUICulture));
}
}

protected virtual DateTime Normalize(DateTime dateTime)
{
if (dateTime.Kind != DateTimeKind.Unspecified ||
!Clock.SupportsMultipleTimezone ||
CurrentTimezoneProvider.TimeZone.IsNullOrWhiteSpace())
{
return IsSkipDateTimeNormalization ? dateTime : Clock.Normalize(dateTime);
}

try
{
var timezoneInfo = TimezoneProvider.GetTimeZoneInfo(CurrentTimezoneProvider.TimeZone);
dateTime = new DateTimeOffset(dateTime, timezoneInfo.GetUtcOffset(dateTime)).UtcDateTime;
}
catch
{
Logger.LogWarning("Could not convert DateTime with unspecified Kind using timezone '{TimeZone}'.", CurrentTimezoneProvider.TimeZone);
}
Comment thread
maliming marked this conversation as resolved.
Resolved

return IsSkipDateTimeNormalization ? dateTime : Clock.Normalize(dateTime);
}
}
Loading
Loading