Maskoe
Maskoe
CC#
Created by Maskoe on 3/2/2024 in #help
minimal api DI magic
Why does the upper one work, but the lower one doesnt?
v1.MapGet("/lmao4", (HttpContext context) => // Executes and returns 4444.
{
Console.WriteLine("4");
return TypedResults.Ok("444");
});
v1.MapGet("/lmao3", GetAllTodos); // Executes, but doesnt return 333.

app.Run();

static async Task<IResult> GetAllTodos(HttpContext context)
{
Console.WriteLine("3");
return TypedResults.Ok("333");
}
v1.MapGet("/lmao4", (HttpContext context) => // Executes and returns 4444.
{
Console.WriteLine("4");
return TypedResults.Ok("444");
});
v1.MapGet("/lmao3", GetAllTodos); // Executes, but doesnt return 333.

app.Run();

static async Task<IResult> GetAllTodos(HttpContext context)
{
Console.WriteLine("3");
return TypedResults.Ok("333");
}
9 replies
CC#
Created by Maskoe on 2/18/2024 in #help
Does Hangfire create a new instance of my aspnetcore api?
Based on the documentation and some tests I did, it doesnt, but I'd like to be sure. I dont trust the docs and myself too much in this case. https://docs.hangfire.io/en/latest/index.html
These method invocations are performed in a background thread and called background jobs.
So it doesnt create a a new instance of my webapi every time it executes a job right? What I played with was this
BackgroundJob.Enqueue(() => DoSomething(DateTime.Now));

public async Task DoSomething(DateTime enqueuedAt)
{
coolSingletonService.Value++;
await Task.Delay(5000);
Console.WriteLine(coolSingletonService.Value);
}
BackgroundJob.Enqueue(() => DoSomething(DateTime.Now));

public async Task DoSomething(DateTime enqueuedAt)
{
coolSingletonService.Value++;
await Task.Delay(5000);
Console.WriteLine(coolSingletonService.Value);
}
So this actually does put out 1 2 3 4 ... So it IS the same instance of my webapi, which I can tell by the singleton service. If it was a different instance, it would start at 0 every single time. Now you should never do this, BUT that means hangfire jobs actually do work with application state somewhat. Obviously you cant guarantee your app hasnt restarted and hangfire executes a job right after. Even in FireAndForget scenarios. 🤔
3 replies
CC#
Created by Maskoe on 1/31/2024 in #help
Razor MVC UI reuse
I cant believe that I cannot figure this out, but how do I create the equivalent of a react or blazor component in MVC Razor? I have this code
<div class="form-group row">
<div class="col-md-3">
<nop-label asp-for="PimId" />
</div>
<div class="col-md-9">
<nop-editor asp-for="PimId" />
<span asp-validation-for="PimId" />
</div>
</div>
<div class="form-group row">
<div class="col-md-3">
<nop-label asp-for="PimId" />
</div>
<div class="col-md-9">
<nop-editor asp-for="PimId" />
<span asp-validation-for="PimId" />
</div>
</div>
That I want to turn into <SimpleEditor asp-for="PimId/> or something similiar. But I just cant find the right direction. ViewComponents? TagHelper? I think its more difficult because these are ModelExpressions. PimId comes from the Model of the original component. This has to be one of the most common reuse patterns to ever exist, but there is nothing online.
4 replies
CC#
Created by Maskoe on 1/25/2024 in #help
Manually execute default ModelBinding from AspNetCore
For reasons I am in an ActionFilter and want to transform the IFormCollection I have into a model class. This is basically ModelBinding, I want to avoid writing a bunch of reflection and typing stuff myself. Where is this logic? I found Microsoft.AspNetCore.Mvc.ModelBinding.ModelBindingHelper, but I dont have access to it somehow. I basically just want something like ModelBindingHelper.TryUpdateModel(myForm) or my HttpContext or my ActionExecutingContext. I know I have A model in my ActionExecutingContext, but its not the one I need. Basically I want a simple way to bind form data to a model and I know aspnetcore does this internally. Where is this code? Can I use it? Can I steal it?
1 replies
CC#
Created by Maskoe on 10/25/2023 in #help
❔ Coldstart issues?
I've been working on my own very small projects and MVPs and noticed something common to them. I seem to have insane cold start issues for the most mundane things. I'm talking sending a request to an endpoint, and creating a row in a database via ef core. This is especially noticable when the app is hosted in azure. My usual setup is an app service and a Azure Database for PostgreSQL flexible server using aspnetcore and ef core. Its only ever the first request that is slow. It happens locally too, just far less noticable. The first request to my endpoint is 225ms, the same call 2 minutes later is 16ms. Thats more than 10x faster. What could cause this? Especially hosted since im using an app service and a database server. There is nothing serverless here. I have a simple request taking 2 seconds. Its very noticeable. It will be <500ms after the first one is through. Eventually (hours? minutes?) it seems to reset back and the first request is back to taking 2 seconds. I got detailed ef core logging. The queries, locally, are executed in 1-7ms. So it doesnt seem to be the actual db. What is this? thinkingpepe
21 replies
CC#
Created by Maskoe on 10/18/2023 in #help
❔ EF Core optional where extension method
I have a lot of optional parameters for queries. Filter by this, filter by that etc. I can do it like this context.table.Where(x => projectId == null || x.ProjectId == projectId) (This actually doesnt even add a WHERE TRUE to the generated SQL Query Ok would like to avoid the null check or part every time and write something like .OptionalWhere(x => x.ProjectId, projectId) but I cant find the correct syntax for the extension method. Im trying stuff similiar to this
public static IQueryable<T> OptionalWhere<T, T2>(this IQueryable<T> source, Expression<Func<T, T2>> selector, T2 value)
{
if (value == null)
return source;

return source.Where(x => selector.Compile()(x).Equals(value));
}
public static IQueryable<T> OptionalWhere<T, T2>(this IQueryable<T> source, Expression<Func<T, T2>> selector, T2 value)
{
if (value == null)
return source;

return source.Where(x => selector.Compile()(x).Equals(value));
}
Func cant be translated. Expression cant be translated if I compile it. I guess because it turns into a func..
public static IQueryable<TSource> WhereNotNull<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate)
{
// somehow look into the predicate whether its an equals clause and check if the "right side" is null and return source back
return source.Where(predicate);
}
public static IQueryable<TSource> WhereNotNull<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate)
{
// somehow look into the predicate whether its an equals clause and check if the "right side" is null and return source back
return source.Where(predicate);
}
8 replies
CC#
Created by Maskoe on 3/28/2023 in #help
❔ Rapid prototyping
Do you feel there is such a thing as rapid prototyping or mvp development where you do things different than at work? I've been trying a couple of my own things lately and been cutting corners to just get the absolute minimum up and running. Stuff like returning ef core entities directly instead of dto's / response models. But I run into issues sooo fast, making me go back to dedicated response models within like the first 20 hours. Yea i can stop the serialization loops with a line of code. Yea I can ignore the silly swagger definitions it leads to, I know the models after all, i just made them up yesterday. I feel like it actually slowed me down overall. Yea I feel silly for 2 minutes literally copy pasting the entity class to new class, removing 3 properties and returning that one, but I know it wont stay that way. It never does. I also have a feeling that if there was actually something that would make development faster, no matter the tradeoffs. We would all be doing it at work...
2 replies
CC#
Created by Maskoe on 2/18/2023 in #help
❔ Trying to generify List Func Task
Im trying to generify the following code.
string? contract = null;

var contractsPrio1 = await GetContractsPrio1(client);
contract = contractsPrio1.FirstOrDefault();

if (contract is null)
{
var contractsPrio2 = await GetContractsPrio2(client);
contract = contractsPrio2.FirstOrDefault();
}

if (contract is null)
{
var contractsPrio3 = await GetContractsPrio3(client);
contract = contractsPrio3.FirstOrDefault();
}
string? contract = null;

var contractsPrio1 = await GetContractsPrio1(client);
contract = contractsPrio1.FirstOrDefault();

if (contract is null)
{
var contractsPrio2 = await GetContractsPrio2(client);
contract = contractsPrio2.FirstOrDefault();
}

if (contract is null)
{
var contractsPrio3 = await GetContractsPrio3(client);
contract = contractsPrio3.FirstOrDefault();
}
I think my intention is clear, I have several ways to query contracts that are prioritized a certain way. If i dont find anything in the first priority list, check the 2nd, if i dont find anything, check the 3rd and so on. I got this so far
async Task<T?> SetToFirstElement<T>(List<Func<Task<List<T>>>> getElementsFunctions) where T : class
{
foreach (var getElementsFunction in getElementsFunctions)
{
var elements = await getElementsFunction.Invoke();
if (elements.Any())
return elements.First();
}

return null;
}
async Task<T?> SetToFirstElement<T>(List<Func<Task<List<T>>>> getElementsFunctions) where T : class
{
foreach (var getElementsFunction in getElementsFunctions)
{
var elements = await getElementsFunction.Invoke();
if (elements.Any())
return elements.First();
}

return null;
}
I can call it like this
var contract = await SetToFirstElement<string>(new()
{
() => GetContractsPrio1(client),
() => GetContractsPrio2(client),
() => GetContractsPrio3(client)
});
var contract = await SetToFirstElement<string>(new()
{
() => GetContractsPrio1(client),
() => GetContractsPrio2(client),
() => GetContractsPrio3(client)
});
Are there any issues with this? Does this work simpler? Working with tasks and lists of tasks and async await is always kinda dangerous. But it seems to work. The GetContractsPrioX methods fire only if needed. If I have an exception in one of them, everything seems to behave normally, nothing gets swallowed. I would like to remove the () => part, but I dont think its possible. If I remove it and just work with the GetContractsPrioX methods directly, the tasks naturally start executing instantly.
4 replies
CC#
Created by Maskoe on 2/8/2023 in #help
❔ Manual route/template matching exactly like blazor
I want to take what blazors INavigationManager gives me, which is the ACTUAL uri like this: "/jobadmin/23" and find my @page route TEMPLATE based on it, which looks like this "/jobadmin/{JobNumber:int}". I found this post https://blog.markvincze.com/matching-route-templates-manually-in-asp-net-core/ and played around with the code, adjusted it a little and now I got the following:
var routeTemplate = "/jobadmin/{JobNumber:int}";
var requestPath = "/jobadmin/23";

var template = TemplateParser.Parse(routeTemplate);
var matcher = new TemplateMatcher(template, GetDefaults(template));
var doesMatch = matcher.TryMatch(requestPath, matcher.Defaults);

RouteValueDictionary GetDefaults(RouteTemplate parsedTemplate)
{
var result = new RouteValueDictionary();

foreach (var parameter in parsedTemplate.Parameters.Where(x => x.DefaultValue is not null))
result.Add(parameter.Name, parameter.DefaultValue);

return result;
}
var routeTemplate = "/jobadmin/{JobNumber:int}";
var requestPath = "/jobadmin/23";

var template = TemplateParser.Parse(routeTemplate);
var matcher = new TemplateMatcher(template, GetDefaults(template));
var doesMatch = matcher.TryMatch(requestPath, matcher.Defaults);

RouteValueDictionary GetDefaults(RouteTemplate parsedTemplate)
{
var result = new RouteValueDictionary();

foreach (var parameter in parsedTemplate.Parameters.Where(x => x.DefaultValue is not null))
result.Add(parameter.Name, parameter.DefaultValue);

return result;
}
This seems to generally work. I only found one "issue", when I set the requestPath = "/jobadmin/ff", it still matches. I dont know if it should. Its not an int, but it still matches... internally aspnetcore probably just handles that part later. Its fine for me that this is a "match", however it makes me think to make sure. My question is basically, does this work? Does this do what I think it does?
2 replies
CC#
Created by Maskoe on 1/14/2023 in #help
❔ Smart way to code an insurance pricing calculation with explanation?
I'm refactoring a ~60% correct pricing method. To give you an idea its currently like 1000 lines of c# code, 1000 lines of sql queries and maybe about 7 involved tables. The code and math is actually not heavily complicated. Its just a LOT of "if there is a contract for this item in that table, its prio1. Otherwise look for an old contract in the other table with column = true, thats prio2, column = flase is prio3..." "If there is a discount, apply the discount from that table, but only up to this total" The heaviest mathemathical operation is actually just percentages. Its important for users to see how the app ended up at the final number. All I can think of is basically doing it manually. For every line of math, i just add an explanation after like this: if(contract.AllowDiscount && discountTotal < allowedDiscount) price = price * (1-contract.Discount) Console.WriteLine("Discount is below {allowedDiscount}. Reducing price by {contract.Discount}%")
16 replies