Code Monkey home page Code Monkey logo

dateonlytimeonly.aspnet's People

Contributors

maxkoshevoi avatar stevedunn avatar tinohager avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

dateonlytimeonly.aspnet's Issues

Dateonly in Query Parameter is being rendered as DayOfWeek in swagger

A DateOnly query parameter is being displayed as a DayOfWeek parameter in swagger.

image

Env:
ASP .Net 6.
Nuget Package:
DateOnlyTimeOnly.AspNet Version="1.0.1"
Swashbuckle.AspNetCore Version="6.1.4"

The Controller Code:

[HttpGet]
[Route("UserAssigned/{userId}/{calendarDate}")]
public async Task<ApiResponse<UserDayCalendarBookingsResponse>> GetBookingsAUserIsAssignedTo(string userId, DateOnly calendarDate)

Swagger param

calendarDate": {
            "$ref": "#/components/schemas/DateOnly"
          },

Swagger Schema

"DateOnly": {
        "type": "object",
        "properties": {
          "year": {
            "type": "integer",
            "format": "int32",
            "readOnly": true
          },
          "month": {
            "type": "integer",
            "format": "int32",
            "readOnly": true
          },
          "day": {
            "type": "integer",
            "format": "int32",
            "readOnly": true
          },
          "dayOfWeek": {
            "$ref": "#/components/schemas/DayOfWeek"
          },
          "dayOfYear": {
            "type": "integer",
            "format": "int32",
            "readOnly": true
          },
          "dayNumber": {
            "type": "integer",
            "format": "int32",
            "readOnly": true
          }
        },
        "additionalProperties": false
      },
      "DayOfWeek": {
        "enum": [
          0,
          1,
          2,
          3,
          4,
          5,
          6
        ],
        "type": "integer",
        "format": "int32"
      }

Startup.cs Code

            services.AddControllers(mvcOptions =>
                {
                    mvcOptions.UseDateOnlyTimeOnlyStringConverters();
                })
                .ConfigureApiBehaviorOptions(behaviorOptions =>
                {
                    behaviorOptions.SuppressModelStateInvalidFilter = true;
                })
                .AddJsonOptions(jsonOptions =>
                {
                    jsonOptions.UseDateOnlyTimeOnlyStringConverters();
                    jsonOptions.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
                    jsonOptions.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
                });

            services.AddMvc(mvcOptions => {
                mvcOptions.UseDateOnlyTimeOnlyStringConverters();
            })
            .AddJsonOptions(jsonOptions => {
                jsonOptions.UseDateOnlyTimeOnlyStringConverters();
            }
            )

The package mutates runtime behavior

Description

At the moment this package messes with the TypeConverter attribute of DateOnly and TimeOnly:

TypeDescriptor.AddAttributes(typeof(DateOnly), new TypeConverterAttribute(typeof(DateOnlyTypeConverter)));
TypeDescriptor.AddAttributes(typeof(TimeOnly), new TypeConverterAttribute(typeof(TimeOnlyTypeConverter)));

Such approach should be avoided, because it unintentionally changes documented behavior of the runtime. For example,

var date = TypeDescriptor.GetConverter(typeof(DateOnly)).ConvertFromString("01.01.0001");

Expected behavior:

System.NotSupportedException: 'TypeConverter cannot convert from System.String.' should be thrown

Actual behavior:

Exception is not thrown

Proposal

The package should not mutate runtime (potentially breaking code, that relies on documented and therefore expected behavior). It's possible to add support of DateOnly and TimeOnly for AspNetCore via ModelBinders

Enable passing format to converters

Description

Library is using DateOnly.Parse method, which invokes default behavior from .Net itself. There are no additional signatures available to configure the behavior.

Example

When day is not passed as part of the string, value is set to 1 as default. This is from .Net, not library.

Proposal

Behavior can be avoided using DateOnly.ParseExact method with a format string but the library doesn't offer a signature to pass this value. More signatures needs to be added so user of this library can configure the behavior.

Bug: CultureInfo isn't passed when parsing

StringTypeConverterBase<> does not pass along the incoming culture to its abstract Parse method. It should, and derived types should pass it along to the DateOnly.Parse and TimeOnly.Parse methods.

Because of the current behavior, properties such as RangeAttribute.ConvertValueInInvariantCulture and RangeAttribute.ParseLimitsInInvariantCulture have no effect when using ASP.NET ModelState binding/validation. The parsing happens in the "current" culture, which is the OS-level regional settings of the web server that the application is running on. It should be possible to avoid that by parsing using the invariant culture. That way, the web application can be deployed to servers all over the world and behave the same.

[Request] License Information

Please:

Under what license do you make this code available?

I'd like to use/extend it but need to know what control you'd like to have over that.

Thanks

It's impossible to use DateOnly in the Dictionaries

The type 'System.DateOnly' is not a supported dictionary key using converter of type 'DateOnlyTimeOnly.AspNet.Converters.DateOnlyJsonConverter'.

[HttpGet]
[Route("date-foo")]
public async Task<Dictionary<DateOnly, Foo>> GetDatedFoos()
{
  return results.ToDictionary(x=> x.date, x=> x.foo);
}

How to use with top-lavel statements

Hi, Program.cs can be written differently with the latest C# version. Is it possible to use this package in a Program.cs written in top-level statements?

My Program.cs looks like below and I don't see where to insert the magic lines builder.Services .AddControllers(options => options.UseDateOnlyTimeOnlyStringConverters()).AddJsonOptions(options => options.UseDateOnlyTimeOnlyStringConverters());, since there is no call to a AddControllers method with this syntax.

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();

var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
// **********
// TODO: I want to be able to serialize DateOnly in my API endpoints requests/responses
    endpoints.MapControllers(); // Map attribute-routed API controllers
// **********
    endpoints.MapRazorPages();// Map razor pages
});

app.Run();

Thanks!

The property 'Tripstop.Birthdate' could not be mapped because it is of type 'DateOnly'

Hopefully not a newbie question however getting this error when attempting to generate a migration for the new DateOnly field I have added. This is dotnet core web api project, using sqlserver for the database. (or is saving DateOnly to SQLServer a different part of the puzzle I have to solve, with your DateOnlyTimeOnly nuget package handing getting it working through the Web API interface?)

Error:

$dotnet ef migrations add dateonlyfield
Build started...
Build succeeded.
System.InvalidOperationException: The property 'Tripstop.Birthdate' could not be mapped because it is of type 'DateOnly', which is not a supported primitive type or a valid entity type. Either explicitly map this property, or ignore it using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

Added in Program.cs:

.
.
.
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services
    .AddControllers(options => options.UseDateOnlyTimeOnlyStringConverters())
    .AddJsonOptions(options => options.UseDateOnlyTimeOnlyStringConverters());
var app = builder.Build();
.
.
.

Then added to my model class:

public DateOnly Birthdate { get; set; }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.