barcode
barcode
CC#
Created by barcode on 7/12/2023 in #help
❔ Issues with model state validation
Hello, I'm trying to disable model state validation so I can return responses without the standard msdn response
builder.Services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
options.InvalidModelStateResponseFactory = actionContext =>
throw new BadRequestException(string.Join(
Environment.NewLine,
actionContext.ModelState.Values.SelectMany(v => v.Errors.Select(x => x.ErrorMessage))
.ToArray()
));
});
builder.Services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
options.InvalidModelStateResponseFactory = actionContext =>
throw new BadRequestException(string.Join(
Environment.NewLine,
actionContext.ModelState.Values.SelectMany(v => v.Errors.Select(x => x.ErrorMessage))
.ToArray()
));
});
BadRequestException is my exception which is supposed to be caught inside an api filter, this works fine. The main issue is that I can't trigger the invalidmodelstatefactory, If i say suppressModel = false it just doesn't enter the factory and returns 500 internal error frombody is null, and if I say suppressModel = true then I just get the standard msdn response
2 replies
CC#
Created by barcode on 7/11/2023 in #help
✅ Issues with method not being available
39 replies
CC#
Created by barcode on 7/11/2023 in #help
ASP.NET JSON conversion issues
3 replies
CC#
Created by barcode on 7/2/2023 in #help
❔ EFCore One-To-One
Hello, I am trying to save working hours as an entry in the database for each business. One approach is to store 14(7 days * 2 from,to) columns, other approach I thought of is to move this to a separate entity WorkingHour which contains from and to and have 7 of them. How would I make the entity convertible to db since it is not normal int, string and it is not a separate entity with a separate table?
7 replies
CC#
Created by barcode on 5/31/2023 in #help
❔ avalonia datagrid dynamic columns
16 replies
CC#
Created by barcode on 5/6/2023 in #help
✅ validation question
Should I be checking if a entity for a given id exists in my validator or should this be done in the requesthandler of mediator? I'm using fluent validation ex:
public CreateReviewCommandValidator()
{
RuleFor(x => x.CenterId)
.NotEmpty().WithMessage("{PropertyName} must be provided.")
.MustAsync(CenterExist).WithMessage("Center with that id doesn't exist.");

}

private async Task<bool> CenterExist(int centerId, CancellationToken cancellationToken)
{
return await _dbContext.Centers
.AnyAsync(x => x.Id == centerId, cancellationToken: cancellationToken);
}
public CreateReviewCommandValidator()
{
RuleFor(x => x.CenterId)
.NotEmpty().WithMessage("{PropertyName} must be provided.")
.MustAsync(CenterExist).WithMessage("Center with that id doesn't exist.");

}

private async Task<bool> CenterExist(int centerId, CancellationToken cancellationToken)
{
return await _dbContext.Centers
.AnyAsync(x => x.Id == centerId, cancellationToken: cancellationToken);
}
7 replies
CC#
Created by barcode on 5/3/2023 in #help
✅ Dependency Injection Exception
I'm having issues accessing dbcontext in my dependency injection project. I get an exception
Unhandled exception. System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: GymRadar.Application.Contracts.Identity.IIdentityService Lifetime: Singleton ImplementationType: GymRadar.Infrastructure.Identity.IdentityService': Cannot consume scoped service 'GymRadar.Application.Contracts.Persistence.IGymRadarDbContext' from singleton 'GymRadar.Application.Contracts.Identity.IIdentityService'.)
Unhandled exception. System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: GymRadar.Application.Contracts.Identity.IIdentityService Lifetime: Singleton ImplementationType: GymRadar.Infrastructure.Identity.IdentityService': Cannot consume scoped service 'GymRadar.Application.Contracts.Persistence.IGymRadarDbContext' from singleton 'GymRadar.Application.Contracts.Identity.IIdentityService'.)
public static WebApplication ConfigureServices(this WebApplicationBuilder builder)
{
builder.Services.AddApplicationServices();
builder.Services.AddInfrastructureServices();
builder.Services.AddPersistenceServices(builder.Configuration);
...
}
public static WebApplication ConfigureServices(this WebApplicationBuilder builder)
{
builder.Services.AddApplicationServices();
builder.Services.AddInfrastructureServices();
builder.Services.AddPersistenceServices(builder.Configuration);
...
}
public static IServiceCollection AddInfrastructureServices(this IServiceCollection services)
{
services.AddSingleton<IIdentityService, IdentityService>();
services.AddTransient<IIdentityContext, IdentityContext>();
return services;
}
public static IServiceCollection AddInfrastructureServices(this IServiceCollection services)
{
services.AddSingleton<IIdentityService, IdentityService>();
services.AddTransient<IIdentityContext, IdentityContext>();
return services;
}
Everything works fine in the application layer, problem occurs when I try to access dbcontext in identity service
private readonly IGymRadarDbContext _dbContext;
private readonly IConfiguration _configuration;

public IdentityService(IGymRadarDbContext dbContext, IConfiguration configuration)
{
_dbContext = dbContext;
_configuration = configuration;
}
private readonly IGymRadarDbContext _dbContext;
private readonly IConfiguration _configuration;

public IdentityService(IGymRadarDbContext dbContext, IConfiguration configuration)
{
_dbContext = dbContext;
_configuration = configuration;
}
53 replies
CC#
Created by barcode on 5/3/2023 in #help
❔ IQueryable implementation
I have a query that I want to order by location
.OrderBy(x => (x as ILocatable).DistanceTo(request.Longitude, request.Latitude))
.OrderBy(x => (x as ILocatable).DistanceTo(request.Longitude, request.Latitude))
however I get an error
System.InvalidOperationException: The LINQ expression 'DbSet<City>()
.OrderBy(c => ((c as ILocatable)).DistanceTo(
longitude: __request_Longitude_0,
latitude: __request_Latitude_1))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
System.InvalidOperationException: The LINQ expression 'DbSet<City>()
.OrderBy(c => ((c as ILocatable)).DistanceTo(
longitude: __request_Longitude_0,
latitude: __request_Latitude_1))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
which is expected, the function:
public double DistanceTo(double longitude, double latitude)
{
const double R = 6371; // Earth radius in kilometers

var dLat = (latitude - Latitude) * Math.PI / 180;
var dLon = (longitude - Longitude) * Math.PI / 180;
var lat1 = Latitude * Math.PI / 180;
var lat2 = latitude * Math.PI / 180;

var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
Math.Sin(dLon / 2) * Math.Sin(dLon / 2) * Math.Cos(lat1) * Math.Cos(lat2);
var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));

return R * c;
}
public double DistanceTo(double longitude, double latitude)
{
const double R = 6371; // Earth radius in kilometers

var dLat = (latitude - Latitude) * Math.PI / 180;
var dLon = (longitude - Longitude) * Math.PI / 180;
var lat1 = Latitude * Math.PI / 180;
var lat2 = latitude * Math.PI / 180;

var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
Math.Sin(dLon / 2) * Math.Sin(dLon / 2) * Math.Cos(lat1) * Math.Cos(lat2);
var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));

return R * c;
}
is it feasible to implement the translation or should I just do AsEnumerable?
5 replies
CC#
Created by barcode on 5/2/2023 in #help
❔ Question about abstraction
public interface ILocatable
{
public double Longitude { get; set; }
public double Latitude { get; set; }

public double DistanceTo(double longitude, double latitude)
{
const double R = 6371; // Earth radius in kilometers

double dLat = (latitude - Latitude) * Math.PI / 180;
double dLon = (longitude - Longitude) * Math.PI / 180;
double lat1 = Latitude * Math.PI / 180;
double lat2 = latitude * Math.PI / 180;

double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
Math.Sin(dLon / 2) * Math.Sin(dLon / 2) * Math.Cos(lat1) * Math.Cos(lat2);
double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));

return R * c;
}
}
public interface ILocatable
{
public double Longitude { get; set; }
public double Latitude { get; set; }

public double DistanceTo(double longitude, double latitude)
{
const double R = 6371; // Earth radius in kilometers

double dLat = (latitude - Latitude) * Math.PI / 180;
double dLon = (longitude - Longitude) * Math.PI / 180;
double lat1 = Latitude * Math.PI / 180;
double lat2 = latitude * Math.PI / 180;

double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
Math.Sin(dLon / 2) * Math.Sin(dLon / 2) * Math.Cos(lat1) * Math.Cos(lat2);
double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));

return R * c;
}
}
Is this a correct usage of interfaces? then having
public class Center : BaseEntity, ILocatable
public class Center : BaseEntity, ILocatable
implement an abstract class an and interface
12 replies
CC#
Created by barcode on 4/30/2023 in #help
✅ LINQ / EFCore
var centers = await _dbContext.Centers
.Include(x => x.Categories)
.Where(x => x.CityId == request.CityId && (request.CategoryIds.Count == 0 ||
x.Categories.All(y => request.CategoryIds.Contains(y.Id))))
.Include(x => x.Reviews)
.DoThis(x.Rating = x.Reviews.Average(y=>y.Rating))
.Skip(request.Page * request.Count)
.Take(request.Count)
.ToListAsync(cancellationToken: cancellationToken);
var centers = await _dbContext.Centers
.Include(x => x.Categories)
.Where(x => x.CityId == request.CityId && (request.CategoryIds.Count == 0 ||
x.Categories.All(y => request.CategoryIds.Contains(y.Id))))
.Include(x => x.Reviews)
.DoThis(x.Rating = x.Reviews.Average(y=>y.Rating))
.Skip(request.Page * request.Count)
.Take(request.Count)
.ToListAsync(cancellationToken: cancellationToken);
is this possible? I'm not sure how DoThis function is called
18 replies
CC#
Created by barcode on 4/30/2023 in #help
✅ MediatR exceptions
I am building an API having business logic in another layer and when validation error occurs I catch it, where should I handle this exception, should I handle it in the API like
// try
var dtos = await _mediator.Send(getCentersQuery);
return Ok(dtos);

// catch (validationException)
// ....
// try
var dtos = await _mediator.Send(getCentersQuery);
return Ok(dtos);

// catch (validationException)
// ....
or is there a better way?
9 replies
CC#
Created by barcode on 4/30/2023 in #help
❔ FluentValidation DTO
Hello, lets say I have a dto like this:
public uint CenterId { get; set; }

public int Page { get; set; } = 0;
public int Count { get; set; } = 10;
public uint CenterId { get; set; }

public int Page { get; set; } = 0;
public int Count { get; set; } = 10;
When the user supplies a request, if he doesn't supply center id it will be auto initialized to 0, making it impossible to detect if he even supplied that property The solution is making the property nullable and checking if .NotNull()
public uint? CenterId { get; set; }

public int Page { get; set; } = 0;
public int Count { get; set; } = 10;
public uint? CenterId { get; set; }

public int Page { get; set; } = 0;
public int Count { get; set; } = 10;
however then IDE cries for nullables so we come to this:
public uint CenterId { get; set; } = null!;

public int Page { get; set; } = 0;
public int Count { get; set; } = 10;
public uint CenterId { get; set; } = null!;

public int Page { get; set; } = 0;
public int Count { get; set; } = 10;
Is this the correct way to setup DTOs?
4 replies
CC#
Created by barcode on 4/30/2023 in #help
❔ Reducing commands
Currently to migrate I have to run
dotnet ef migrations add {ProjectName} --project Project.Persistence --startup-project Project.Api
dotnet ef migrations add {ProjectName} --project Project.Persistence --startup-project Project.Api
is there a defined way to create "scripts" in visual studio solutions?
5 replies
CC#
Created by barcode on 4/30/2023 in #help
❔ EFCore migrations
Hello, I'm having issues applying configurations with ApplyConfigurationsFromAssembly and have to manually apply configurations // automatic
modelBuilder.ApplyConfigurationsFromAssembly(typeof(MyDbContext).Assembly);
modelBuilder.ApplyConfigurationsFromAssembly(typeof(MyDbContext).Assembly);
//manual
new CategoryConfiguration().Configure(modelBuilder.Entity<Category>());
...
new CenterConfiguration().Configure(modelBuilder.Entity<Center>());
new CategoryConfiguration().Configure(modelBuilder.Entity<Category>());
...
new CenterConfiguration().Configure(modelBuilder.Entity<Center>());
This occurs due to having a CenterCategory many to many table that I handle inside center configuration
3 replies
CC#
Created by barcode on 4/29/2023 in #help
✅ EFCore LINQ methods
I have this function
public async Task<IReadOnlyList<Review>> GetByCenterId(uint id, uint page, uint count)
{
return await _dbContext.Reviews
.Where(x => x.CenterId == id)
.OrderBy(x => x.CreatedAt)
.Skip((int)(page * count))
.Take((int)count)
.ToListAsync();
}
public async Task<IReadOnlyList<Review>> GetByCenterId(uint id, uint page, uint count)
{
return await _dbContext.Reviews
.Where(x => x.CenterId == id)
.OrderBy(x => x.CreatedAt)
.Skip((int)(page * count))
.Take((int)count)
.ToListAsync();
}
and naturally pages and count cannot be negative so I use uint, however I must cast it as no Skip or Take method exists for uint, is this the way it should be done or should I use int as parameters?
22 replies
CC#
Created by barcode on 4/29/2023 in #help
✅ Dependency Injection question
Should Repositories be Scoped or Transient? They are injected into MediatR request handlers
105 replies
CC#
Created by barcode on 2/27/2023 in #help
Static files asp.net
Hello, in my app I have 2 middlewares that are ran before any request but I want to disable them for static files. These middlewares check for a token but i don't want to force the user to be authorized to access some images.
app.UseStaticFiles();
app.UseMiddleware<AuthMiddleware>();
app.UseMiddleware<AccessMiddleware>();
app.UseStaticFiles();
app.UseMiddleware<AuthMiddleware>();
app.UseMiddleware<AccessMiddleware>();
I can't find anything on documentation nor google how to do this. What is the correct way?
2 replies
CC#
Created by barcode on 2/15/2023 in #help
❔ EF Core question
public class User : BaseEntity
{
public ulong OAuthId { get; set; }
public Role Role { get; set; }
public ICollection<UserClient> UserClients { get; set; } = null!;
public ICollection<Client> Clients { get; set; } = null!;
}
public class User : BaseEntity
{
public ulong OAuthId { get; set; }
public Role Role { get; set; }
public ICollection<UserClient> UserClients { get; set; } = null!;
public ICollection<Client> Clients { get; set; } = null!;
}
Currently I define my models like this, should these collections be defined as null! or should I do new List<Client>() in the class?
var clients = _clients.GetClients()
.Where(x => createUserDto.ClientIds!.Contains(x.Id));
// TODO: add clients
user.Clients = new List<Client>();
clients.ToList().ForEach(x=> user.Clients.Add(x));

await _users.CreateUser(user);
var clients = _clients.GetClients()
.Where(x => createUserDto.ClientIds!.Contains(x.Id));
// TODO: add clients
user.Clients = new List<Client>();
clients.ToList().ForEach(x=> user.Clients.Add(x));

await _users.CreateUser(user);
currently I add clients when I create an user like this
8 replies
CC#
Created by barcode on 2/13/2023 in #help
✅ EF Core Seeders
How do I handle seeders in EF Core? Is there a way to split seeders away from migrations? Currently .HasData creates the insert in the migration
19 replies
CC#
Created by barcode on 2/9/2023 in #help
❔ EF Core question
Data annotations vs fluent api? What are pros and cons? a pro for fluent api I see is that I can decouple models away from db definitions and for data annotations the simplicity, however data annotations seem to be lacking some things that fluent api has
6 replies