Core
Core
Explore posts from servers
CC#
Created by Core on 1/16/2025 in #help
✅ Serialized enum starts with uppercase / camel case is ignored
Hello, I am using the newer source generated enum serializer (introduced in .NET 8), but for some reason the serialized string starts with uppercase instead of lowercase. https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/source-generation#source-generation-support-in-aspnet-core
c#
[JsonSourceGenerationOptions(UseStringEnumConverter = true, PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(RedirectType))]
public partial class EnumToStringJsonContext : JsonSerializerContext;
c#
[JsonSourceGenerationOptions(UseStringEnumConverter = true, PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(RedirectType))]
public partial class EnumToStringJsonContext : JsonSerializerContext;
I even tried another configuration, but it had the same outcome
c#
public class CamelCaseEnumConverter<TEnum>() :
JsonStringEnumConverter<TEnum>(JsonNamingPolicy.CamelCase) where TEnum : struct, Enum;

[JsonSourceGenerationOptions(
UseStringEnumConverter = true,
Converters =
[
typeof(CamelCaseEnumConverter<RedirectType>)
]),
JsonSerializable(typeof(RedirectType))
]
public partial class EnumToStringJsonContext : JsonSerializerContext;
c#
public class CamelCaseEnumConverter<TEnum>() :
JsonStringEnumConverter<TEnum>(JsonNamingPolicy.CamelCase) where TEnum : struct, Enum;

[JsonSourceGenerationOptions(
UseStringEnumConverter = true,
Converters =
[
typeof(CamelCaseEnumConverter<RedirectType>)
]),
JsonSerializable(typeof(RedirectType))
]
public partial class EnumToStringJsonContext : JsonSerializerContext;
4 replies
CC#
Created by Core on 1/7/2025 in #help
Static class or regular class with interface?
Hello, I've been building a QR code generator for a while. It's a simple method call QrCodeGenerator.Generate("data", options).
c#
var qrCode = QrCodeGenerator.Generate("data", new QrCodeOptions
{
MarkerLeft = new MarkerOptions
{
OuterStyle = markerStyle,
InnerStyle = markerStyle
},
MarkerRight = new MarkerOptions
{
OuterStyle = markerStyle,
InnerStyle = markerStyle
},
MarkerBottom = new MarkerOptions
{
OuterStyle = markerStyle,
InnerStyle = markerStyle
},
PatternStyle = PatternStyle.Circle,
Format = ImageFormat.Png,
});
c#
var qrCode = QrCodeGenerator.Generate("data", new QrCodeOptions
{
MarkerLeft = new MarkerOptions
{
OuterStyle = markerStyle,
InnerStyle = markerStyle
},
MarkerRight = new MarkerOptions
{
OuterStyle = markerStyle,
InnerStyle = markerStyle
},
MarkerBottom = new MarkerOptions
{
OuterStyle = markerStyle,
InnerStyle = markerStyle
},
PatternStyle = PatternStyle.Circle,
Format = ImageFormat.Png,
});
It is a static method/class, I was wondering if it would be better to supply the class trough an interface, making it available trough DI. Suppose it's going to be a nuget package, would it make a difference if it was supplied trough DI, instead of a static class?
25 replies
CC#
Created by Core on 12/14/2024 in #help
✅ Downloading file with HttpClient does not work
Hello, Everywhere it is advisable to use HttpClient for downloading larger files. For some reason it only downloads a little chunk of a larger file, and that's it. How should I even determine what the problem is? The url is fine, I am able to download the file trough the browser
c#
await using var stream = await httpClient.GetStreamAsync(_url);
await using var fileStream = new FileStream(filePath, FileMode.Create);
await stream.CopyToAsync(fileStream);
c#
await using var stream = await httpClient.GetStreamAsync(_url);
await using var fileStream = new FileStream(filePath, FileMode.Create);
await stream.CopyToAsync(fileStream);
11 replies
CC#
Created by Core on 12/13/2024 in #help
SemaphoreSlim wait without creating a critical section
Hello, I don't want to have a critical section, instead I should have a section where all threads are blocked until the semaphore is released. When it is released, all threads should start executing the section. For this semaphore.Wait() is not good, because threads will execute the section one by one. The outcome should be: No critical section, just blocking for all threads. Probably some other object is needed for this use case, but what is that?
3 replies
CC#
Created by Core on 12/12/2024 in #help
✅ Disposable class level property
Hello If there is a singleton service that uses a disposable class level property, should the service implement IDisposable as well? Also, wouldn't the property be disposed automatically upon application shutdown, only if it implements IDisposable?
c#
public class IpLookupService : IIpLookupService
{
private readonly Reader _reader; // This property can be disposed
}
c#
public class IpLookupService : IIpLookupService
{
private readonly Reader _reader; // This property can be disposed
}
8 replies
CC#
Created by Core on 11/30/2024 in #help
✅ SkiaSharp apply gradient on the whole canvas except to one color
No description
6 replies
CC#
Created by Core on 11/19/2024 in #help
✅ How is JsonConverter(typeof(JsonStringEnumConverter<MyEnum>)) evaluated?
Hello, This makes it possible that enum is serialized to string when the request comes in. Is this evaluated on each request, or only once at compile time?
c#
[JsonConverter(typeof(JsonStringEnumConverter<Precipitation>))]
public enum Precipitation
{
Drizzle, Rain, Sleet, Hail, Snow
}
c#
[JsonConverter(typeof(JsonStringEnumConverter<Precipitation>))]
public enum Precipitation
{
Drizzle, Rain, Sleet, Hail, Snow
}
10 replies
CC#
Created by Core on 11/18/2024 in #help
✅ .NET 8 enum to string serialization throws an exception
Hello, Following the docs, a custom JsonSerializerContext is applied on the controllers, yet an exception is thrown.
c#
public sealed record GetLinkMetricsRequest
{
[FromRoute]
public string Id { get; set; }

[FromQuery]
public TimePeriodUnit? TimeUnit { get; set; } = TimePeriodUnit.Day;

[FromQuery]
public int? Units { get; set; }
}

[JsonSourceGenerationOptions(UseStringEnumConverter = true)]
[JsonSerializable(typeof(GetLinkMetricsRequest))]
public partial class TimePeriodUnitJsonContext : JsonSerializerContext;


// applied to the Controllers
var options = new JsonSerializerOptions
{
TypeInfoResolver = JsonTypeInfoResolver.Combine(ContextA.Default, ContextB.Default, ContextC.Default);
};
c#
public sealed record GetLinkMetricsRequest
{
[FromRoute]
public string Id { get; set; }

[FromQuery]
public TimePeriodUnit? TimeUnit { get; set; } = TimePeriodUnit.Day;

[FromQuery]
public int? Units { get; set; }
}

[JsonSourceGenerationOptions(UseStringEnumConverter = true)]
[JsonSerializable(typeof(GetLinkMetricsRequest))]
public partial class TimePeriodUnitJsonContext : JsonSerializerContext;


// applied to the Controllers
var options = new JsonSerializerOptions
{
TypeInfoResolver = JsonTypeInfoResolver.Combine(ContextA.Default, ContextB.Default, ContextC.Default);
};
The exception:
An unexpected error occurred. See the inner exception for details. System.NotSupportedException: JsonTypeInfo metadata for type 'AnalyticsService.Api..' was not provided by TypeInfoResolver of type 'System.Text.Json.Serialization.Metadata.JsonTypeInfoResolverWithAddedModifiers'. If using source generation, ensure that all root types passed to the serializer have been annotated with 'JsonSerializableAttribute', along with any types that might be serialized polymorphically.
An unexpected error occurred. See the inner exception for details. System.NotSupportedException: JsonTypeInfo metadata for type 'AnalyticsService.Api..' was not provided by TypeInfoResolver of type 'System.Text.Json.Serialization.Metadata.JsonTypeInfoResolverWithAddedModifiers'. If using source generation, ensure that all root types passed to the serializer have been annotated with 'JsonSerializableAttribute', along with any types that might be serialized polymorphically.
I have followed the docs: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/source-generation#combine-source-generators https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/source-generation#blanket-policy
21 replies
CC#
Created by Core on 10/12/2024 in #help
✅ Azure Key vault - what is considered a transaction?
No description
2 replies
CC#
Created by Core on 10/10/2024 in #help
✅ Any practical use to have an endpoint accessing an entity trough a non ID path variable?
No description
3 replies
CC#
Created by Core on 10/5/2024 in #help
✅ Storing user related data when using an auth provider
Hello, When using an auth provider, all the user data, like ID, email, etc. is stored and managed by the provider. Regarding that, do I need to store the user data in my SQL database and make relation based on that? Or would it be better to simply add an extra userId column to tables where needed and leave it be? (without any relationship)
13 replies
CC#
Created by Core on 9/6/2024 in #help
✅ NodaTime JSON Serialization
Hello, .NET will parse any date format to DateTime or DateTimeOffset, but what happens if I give NodaTime control over the serialization? Assuming I accept an Instant in the DTO and a request comes in, but the format is not ISO-8601, will it be able to convert any type of date like .NET does, or will it only work with strict types? From the docs:
Between releases 4.0 and 4.5.11, Json.NET introduced automatic date parsing: by default, if the parser detects a value which looks like a date, it will automatically convert it to a DateTime or (optionally) to a DateTimeOffset. In order to give Noda Time control over the serialization, this must be disabled in JsonSerializerSettings or JsonSerializer
Between releases 4.0 and 4.5.11, Json.NET introduced automatic date parsing: by default, if the parser detects a value which looks like a date, it will automatically convert it to a DateTime or (optionally) to a DateTimeOffset. In order to give Noda Time control over the serialization, this must be disabled in JsonSerializerSettings or JsonSerializer
21 replies
CC#
Created by Core on 9/2/2024 in #help
✅ Background jobs, choosing the right library
Hello, I need to implement a scheduled job that will be periodically executed. Why are there so many libraries: Hangfire, Quartz, Coravel? Even .NET offeres the BackgroundService out of the box. How do I choose the right library? Literally every one of them gets the job done...
16 replies
CC#
Created by Core on 8/30/2024 in #help
✅ .NET Worker service doesn't load appsettings.json into a class
No description
20 replies
CC#
Created by Core on 8/27/2024 in #help
Is there a method that throws an exception if a config value is not present in appsettings?
Hello, Getting configuration values from appsettings.json is done via calling builder.Configuration["name"]. This way few of my services might get a null property, without throwing error before build. Is there an existing method that will throw an exception if the config value is null?
12 replies
CC#
Created by Core on 8/26/2024 in #help
✅ Azure key vault with microservices
Hello, Right now I have 2 microservice, they communicate with RabbitMq, so the credentials are the same. Would it be more reasonable to have 2 key vaults storing the same secrets, one vault per each microservice, or create an extra vault for shared secrets? 2 vault, 1 per each microservice or 3 vault, 1 per each microservice + a shared one?
19 replies
CC#
Created by Core on 8/24/2024 in #help
✅ EF: how to structure same EF select query with no tracking?
Hello, I need the exact same select query with and without tracking. Should I implement it in 2 separate methods or a single method with a bool parameter that would determine if the query will use tracking or not (e.g. SelectSomething(enableTracking = true))?
12 replies
CC#
Created by Core on 8/22/2024 in #help
✅ EF Best way to do UPDATE on entity
Hello, EF by default tracks entities. That means, if a property of an entity is modified, SaveChanges() will do the update. Now, I set new values for the properties in the business logic layer, and the repository layer is responsible for any DB operation. My current method looks like this.... Is there a clearer approach or leave this as it is?
c#
public async Task UpdateEntityAsync()
{
try
{
await _dbContext.SaveChangesAsync();
}
catch (Exception)
{
//
}
}
c#
public async Task UpdateEntityAsync()
{
try
{
await _dbContext.SaveChangesAsync();
}
catch (Exception)
{
//
}
}
24 replies
CC#
Created by Core on 8/21/2024 in #help
✅ Class library is not loaded with the Main solution
No description
8 replies
CC#
Created by Core on 8/21/2024 in #help
✅ EF SaveChanges in transactions
Hello, Does it make a difference if SaveChanges is called after each Add operation or only one time after the last Add operation? Multiple times
c#
await using var transaction = await _dbContext.Database.BeginTransactionAsync();

await _dbContext.Domains.AddAsync(domain);
await _dbContext.SaveChangesAsync();

await _dbContext.DomainVerifications.AddAsync(domainVerification);
await _dbContext.SaveChangesAsync();

await transaction.CommitAsync();
c#
await using var transaction = await _dbContext.Database.BeginTransactionAsync();

await _dbContext.Domains.AddAsync(domain);
await _dbContext.SaveChangesAsync();

await _dbContext.DomainVerifications.AddAsync(domainVerification);
await _dbContext.SaveChangesAsync();

await transaction.CommitAsync();
One time
c#
await using var transaction = await _dbContext.Database.BeginTransactionAsync();

await _dbContext.Domains.AddAsync(domain);
await _dbContext.DomainVerifications.AddAsync(domainVerification);

await _dbContext.SaveChangesAsync();
await transaction.CommitAsync();
c#
await using var transaction = await _dbContext.Database.BeginTransactionAsync();

await _dbContext.Domains.AddAsync(domain);
await _dbContext.DomainVerifications.AddAsync(domainVerification);

await _dbContext.SaveChangesAsync();
await transaction.CommitAsync();
31 replies