nobody
nobody
Explore posts from servers
CC#
Created by nobody on 9/1/2023 in #help
❔ Runtime reflection on Asp .net core 7.0 missing
Hi, I am writing a generator which is used to generated api endpoints in a highly unified way. For that I need to be able to add data annotations to specific parameters. The Generator works fine, but when I add e.g the [FromBody] data annotation, it crashes with the following error: Could not load file or assembly 'Microsoft.AspNetCore.Mvc.Core, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the file specified. And this is the code:
private static (string parameterWithTypes, string parametersWithoutTypes) GetMethodParameters(MethodInfo method)
{
var parametersWithTypes = method.GetParameters()
.Select(param =>
{
// Get all attributes for the parameter
var attributes = param.GetCustomAttributes(false)
.Select(attr => $"[{attr.GetType().FullName}]")
.Aggregate(string.Empty, (current, attrName) => current + attrName + " ");

return $"{attributes}{TypeHelper.GetFriendlyName(param.ParameterType)} {param.Name}";
});

var parametersWithoutTypes = method.GetParameters()
.Select(param => $"{param.Name}");

return (string.Join(", ", parametersWithTypes), string.Join(", ", parametersWithoutTypes));
}
private static (string parameterWithTypes, string parametersWithoutTypes) GetMethodParameters(MethodInfo method)
{
var parametersWithTypes = method.GetParameters()
.Select(param =>
{
// Get all attributes for the parameter
var attributes = param.GetCustomAttributes(false)
.Select(attr => $"[{attr.GetType().FullName}]")
.Aggregate(string.Empty, (current, attrName) => current + attrName + " ");

return $"{attributes}{TypeHelper.GetFriendlyName(param.ParameterType)} {param.Name}";
});

var parametersWithoutTypes = method.GetParameters()
.Select(param => $"{param.Name}");

return (string.Join(", ", parametersWithTypes), string.Join(", ", parametersWithoutTypes));
}
` This occurs when I retrieve the type of a AspNetCore data annotation. There is no nuget packaged which I could include in order to make the types known in my generator project. Any suggestions?
2 replies
CC#
Created by nobody on 6/21/2023 in #help
❔ Why does the JsonSerializer.Deserialize return a nullable object
I found this following example in the docs about the deserializer:
WeatherForecast? weatherForecast =
JsonSerializer.Deserialize<WeatherForecast>(jsonString);

Console.WriteLine($"Date: {weatherForecast?.Date}");
Console.WriteLine($"TemperatureCelsius: {weatherForecast?.TemperatureCelsius}");
Console.WriteLine($"Summary: {weatherForecast?.Summary}");
WeatherForecast? weatherForecast =
JsonSerializer.Deserialize<WeatherForecast>(jsonString);

Console.WriteLine($"Date: {weatherForecast?.Date}");
Console.WriteLine($"TemperatureCelsius: {weatherForecast?.TemperatureCelsius}");
Console.WriteLine($"Summary: {weatherForecast?.Summary}");
based on the docs it looks like it would throw an exception if the json can't be deserialized. The type, for deserialization, in this case is WeatherForecase not WeatherForecast? . Why does it return nullable<..>? Is there a way to make it return the acutal instance or just throw an error? I want to avoid many (maybe unnecessary) null checks? Thx!
6 replies
CC#
Created by nobody on 6/8/2023 in #help
❔ Source generator for creating REST Api
I want to create a REST endpoint for my entity classes. Structure: Backend.Api (contains asp net core logic, endpoints etc.) Backend.Database (DB-Layer using EF Core, Entity classes) Now I want to annotate my entity classes with a specific annotation (lets say [HasEndpoint]) and create the specific endpoint in the Backend.Api project. But the source generator will create the endpoints in the Backend.Database project.. How would it be possible to create the endpoints in Backend.Api using the entities in Backend.Database ?
10 replies
CC#
Created by nobody on 11/14/2022 in #help
Named tuple on delegate return type [Answered]
I've defined a delegate like this:
public delegate Task<Tuple<TEntity, bool>> AddUpdateCallbackDelegate(TEntity entity, IEnumerable<TEntity> dataSource);
public AddUpdateCallbackDelegate OnAddCallback { get; set; }

...
public async Task Test()
{
var res = await OnAddCallback(...);
res.Item1...
res.Item2...
}
public delegate Task<Tuple<TEntity, bool>> AddUpdateCallbackDelegate(TEntity entity, IEnumerable<TEntity> dataSource);
public AddUpdateCallbackDelegate OnAddCallback { get; set; }

...
public async Task Test()
{
var res = await OnAddCallback(...);
res.Item1...
res.Item2...
}
the return type etc. works just fine, but I want to name the tuple parameters instead of the default Item1/2. How could I do that?
5 replies
CC#
Created by nobody on 11/7/2022 in #help
Are exceptions really that slow? - with .NET gRPC
I am building a server base on gRPC. In all docs about gRPC + C# there is the suggested method for error handling to simply throw a RpcException to expose information to the client. But I always thought throwing an exception is extremely bad performance wise? I mean throwing an exception for a simple validation failure on the clients input data (REST eq: return BadRequest()) seems a bit too much, right? Or is that not really a big deal?
14 replies
CC#
Created by nobody on 11/5/2022 in #help
Will this service will be disposed using DependencyInjection?
I have the following class which is added to the default DI-container (Blazor WASM)
public class ClientGrpcService<TService> : IClientGrpcService<TService>, IDisposable where TService : class
{
private readonly GrpcChannel _channel;
private readonly TService _service;

public ClientGrpcService()
{
_channel = GrpcChannel.ForAddress("https://localhost:7046");
_service = _channel.CreateGrpcService<TService>();
}

public TService Service => _service;

public void Dispose()
{
_channel.Dispose();
}
}
public class ClientGrpcService<TService> : IClientGrpcService<TService>, IDisposable where TService : class
{
private readonly GrpcChannel _channel;
private readonly TService _service;

public ClientGrpcService()
{
_channel = GrpcChannel.ForAddress("https://localhost:7046");
_service = _channel.CreateGrpcService<TService>();
}

public TService Service => _service;

public void Dispose()
{
_channel.Dispose();
}
}
and In my classes I simply do
public TestClass(IClientGrpcService<Example> service)
{
...
}
public TestClass(IClientGrpcService<Example> service)
{
...
}
the TestClass itself will be instantiated by the DI as well. Will the disposed method of the GrpcService will be called?
3 replies
CC#
Created by nobody on 10/27/2022 in #help
Source Generator only annotate method instead of class
Is it possible to annotate only a method with a custom attribute instead of the class itself?
public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
switch (syntaxNode)
{
case ClassDeclarationSyntax classDeclarationSyntax when
classDeclarationSyntax.HasAttribute<TAttribute>():
//Process...
break;
case MethodDeclarationSyntax methodDeclarationSyntax when
methodDeclarationSyntax.HasAttribute<TAttribute>():
//Process...
break;
}
}
public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
switch (syntaxNode)
{
case ClassDeclarationSyntax classDeclarationSyntax when
classDeclarationSyntax.HasAttribute<TAttribute>():
//Process...
break;
case MethodDeclarationSyntax methodDeclarationSyntax when
methodDeclarationSyntax.HasAttribute<TAttribute>():
//Process...
break;
}
}
HasAttribute is a custom method which simply checks for the attribute, for classes it works just fine - for method it does not.. Would that be the right way? Assuming that HasAttribute works fine for methods too
20 replies
CC#
Created by nobody on 9/29/2022 in #help
How to use .NET 7 preview?
I am trying to use .NET7 (Version: 7.0.100-preview.7.22377.5) and I am using VS 2022 (latest preview), but when I set my project to .net7 it uses the .NET7 RC1 as version? I wanna test the IRouteHandlerFilter which got merged past preview 3.
11 replies
CC#
Created by nobody on 9/28/2022 in #help
Generics and type inference
public TDest MapTo<TSource, TDest>(TSource src)
{
var res = _mapper.Map<TSource, TDest>(src);
return res;
}
public TDest MapTo<TSource, TDest>(TSource src)
{
var res = _mapper.Map<TSource, TDest>(src);
return res;
}
Why can't the compiler infer my type of TSource? If I call that mehod I always have to specify it like this
Mapper.MapTo<ObjectA, ObjectB>(instance of ObjectA);
Mapper.MapTo<ObjectA, ObjectB>(instance of ObjectA);
It should be possible to call it just like this
Mapper.MapTo<ObjectB>(instance of ObjectA);
Mapper.MapTo<ObjectB>(instance of ObjectA);
I am just starting with .NET
14 replies
CC#
Created by nobody on 9/27/2022 in #help
PartialType from Nest.js in Csharp
Is there is a possibility to recreate a behaviour like the partialType from Nestjs (=> https://docs.nestjs.com/openapi/mapped-types#partial )? This is used to create a DTO from an existing DTO which has the same properties but all are optional. Perfect for a PostCustomerDto where all properties have to be provided, and the UpdateCustomerDto has the same but nullable. I am a nodejs dev starting with .NET
1 replies