Alizer
Alizer
CC#
Created by Alizer on 7/30/2024 in #help
asp core form tag helpers but the router has dynamic route
i have this form
<form id="chequeForm" asp-route-payrollHistoryId="@(payrollHistory?.Id)" asp-action="GenerateCheque" asp-controller="DocumentGenerations" method="post">
<form id="chequeForm" asp-route-payrollHistoryId="@(payrollHistory?.Id)" asp-action="GenerateCheque" asp-controller="DocumentGenerations" method="post">
now the endpoint it points to is below
c#
[ApiController]
[Route("/api/documents")]
[Authorize(Roles = $"{Roles.Administrator},{Roles.Authority}")]
public class DocumentGenerations : Controller
{
private readonly PayrollHistories _payrollHistories;
private readonly BankOrderGenerator _bankOrderGenerator;

public DocumentGenerations(PayrollHistories payrollHistories, BankOrderGenerator bankOrderGenerator)
{
_payrollHistories = payrollHistories;
_bankOrderGenerator = bankOrderGenerator;
}

// below is my target form i want to submit the form to
[HttpPost("{payrollHistoryId}/cheque")]
public async Task<IActionResult> GenerateCheque([FromForm] ChequeGeneration chequeGeneration,
[FromRoute] string? payrollHistoryId)
{
var payrollHistories = await _payrollHistories.GetPayrollHistoryByIdAsync(payrollHistoryId);

return Ok();
}
c#
[ApiController]
[Route("/api/documents")]
[Authorize(Roles = $"{Roles.Administrator},{Roles.Authority}")]
public class DocumentGenerations : Controller
{
private readonly PayrollHistories _payrollHistories;
private readonly BankOrderGenerator _bankOrderGenerator;

public DocumentGenerations(PayrollHistories payrollHistories, BankOrderGenerator bankOrderGenerator)
{
_payrollHistories = payrollHistories;
_bankOrderGenerator = bankOrderGenerator;
}

// below is my target form i want to submit the form to
[HttpPost("{payrollHistoryId}/cheque")]
public async Task<IActionResult> GenerateCheque([FromForm] ChequeGeneration chequeGeneration,
[FromRoute] string? payrollHistoryId)
{
var payrollHistories = await _payrollHistories.GetPayrollHistoryByIdAsync(payrollHistoryId);

return Ok();
}
but for some reason it points to the wrong route, the generated html is
<form id="chequeForm" method="post" action="/DocumentGenerations/GenerateCheque">
<form id="chequeForm" method="post" action="/DocumentGenerations/GenerateCheque">
as you can see it points to /DocumentGenerations/GenerateCheque which is wrong, but this is probably becaus of the {payrollHistoryId} in the route, how would i fix this?
8 replies
CC#
Created by Alizer on 6/20/2024 in #help
mapping a dynamic object to an existing object and only map properties that exist in the source obj
I need help with patching an object in ASP Core, on my api i only send a partial data of the object i want to update, i looked into JsonPatchDocument<T> but the syntax is too complicated compared to what my competitors do with their API, what i want here is just for my customers to send a json with the properties and values they want to change and that's it, let's say i have an object like
public class Car
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
[MaxLength(Constants.MaxStringLength)]
public string? Id { get; set; }

public string? Model { get; set; }

public string? CompanyName { get; set; }

// omitted 10+ properties
}
public class Car
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
[MaxLength(Constants.MaxStringLength)]
public string? Id { get; set; }

public string? Model { get; set; }

public string? CompanyName { get; set; }

// omitted 10+ properties
}
and in my API I only want to update specific properties, so I decided to take a dynamic object in my action
[HttpPatch]
[Route("{id}")]
public async Task<IActionResult> UpdateCarByIdAsync(string id, [FromBody] dynamic car)
{

var tenants = await _tenants.UpdateCarFromDynamic(id, car);
// omitted code
[HttpPatch]
[Route("{id}")]
public async Task<IActionResult> UpdateCarByIdAsync(string id, [FromBody] dynamic car)
{

var tenants = await _tenants.UpdateCarFromDynamic(id, car);
// omitted code
in my update method i have this code
public async Task<Car?> UpdateCarFromDynamic(string id, dynamic car)
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<dynamic, Car>().ForAllMembers(x =>
{
x.Condition((src, dest, srcMember) => { return srcMember != null; });
});

});

var mapper = _personUserConfiguration.CreateMapper();

var existingUser =
await _applicationDbContext.Cars.FirstOrDefaultAsync(x => x.IsActive && x.Id == id);

mapper.Map(car, existingCar);

// omitted code
public async Task<Car?> UpdateCarFromDynamic(string id, dynamic car)
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<dynamic, Car>().ForAllMembers(x =>
{
x.Condition((src, dest, srcMember) => { return srcMember != null; });
});

});

var mapper = _personUserConfiguration.CreateMapper();

var existingUser =
await _applicationDbContext.Cars.FirstOrDefaultAsync(x => x.IsActive && x.Id == id);

mapper.Map(car, existingCar);

// omitted code
now, for some reason existingCar has all properties turned to their default or null values, how should i fix this? is there an alternative library for doing this
11 replies
CC#
Created by Alizer on 1/15/2024 in #help
advanced inheritance in arguments
No description
3 replies
CC#
Created by Alizer on 1/10/2024 in #help
Scaffold Not Working because `dotnet-aspnet-codegenerator.exe` uses old C# version
I need help with scaffolding identity my C# project, I get this error whenever I scaffold D:\ProjectFolder\ClientAction(81,37): error CS1002: ; expected and I look into the line that causes this and I found it it's caued by the new required keyword
public class ClientAction
{
public required string Description { get; set; } // the required keyword causes this!
}
public class ClientAction
{
public required string Description { get; set; } // the required keyword causes this!
}
The project builds successfully in dotnet rider, no problems at all, however when it runs dotnet-aspnet-codegenerator.exe to scaffold I get a lot of errors, I'm thinking it's caued by dotnet-aspnet-codegenerator.exe using an old c# version, currently I use .net 7.0 Now my problem is that I have around 100+ properties using required and I needed to scaffold the Identity to edit the register and login pages, how do I get around this?
5 replies
CC#
Created by Alizer on 8/6/2023 in #help
❔ I need help making a `diff` of 2 objects of the same class
I have a complex class like below
public class Person {
public string Name { get; set; }

public byte Age { get; set; }

public List<Person>? Children { get; set; }

// many other properties omitted
}
public class Person {
public string Name { get; set; }

public byte Age { get; set; }

public List<Person>? Children { get; set; }

// many other properties omitted
}
Now, I have 2 instances of this class Person and I want to get the differences between both, my problem is the Person class is a really complex class, it has around 20+ properties, some properties are collections, I made a class like below to record the differences
public class Difference {
public string PropertyPath { get; set; }

public object OriginalValue { get; set; }

public object NewValue { get; set; }
}
public class Difference {
public string PropertyPath { get; set; }

public object OriginalValue { get; set; }

public object NewValue { get; set; }
}
my question is, how do I start with this? if there is a library that does this automatically I would use it
4 replies
CC#
Created by Alizer on 7/31/2023 in #help
❔ Return PartialView with ``for`` attribute
I have a complex <form> in my .cshtml file and I want to simplify it more, now I have this original code, this is inside the <form>
<div class="container-fluid mx-0 px-0">
@foreach (var assistanceData in i.Assistances)
{
var assistanceDataIndex = i.Assistances.IndexOf(assistanceData);
<p class="mb-1 fw-normal">@assistanceData.Name</p>
<partial for="Assistances[assistanceIndex].Assistances[assistanceDataIndex]" name="Encoder/AssistanceDataForm"/>
}
</div>
<div class="container-fluid mx-0 px-0">
@foreach (var assistanceData in i.Assistances)
{
var assistanceDataIndex = i.Assistances.IndexOf(assistanceData);
<p class="mb-1 fw-normal">@assistanceData.Name</p>
<partial for="Assistances[assistanceIndex].Assistances[assistanceDataIndex]" name="Encoder/AssistanceDataForm"/>
}
</div>
now instead of doing a foreach loop I want to add these <partial/> views with the click of a button, I plan on doing this by making a controller return the partial view and I'll just append it to the parent div via an ajax call using jquery, I have the following action in the controller below
c#
public async Task<IActionResult> AssistanceDataForm(Assistance parentAssistance, int assistanceIndex, int assistanceDataIndex)
{
return PartialView("Encoder/AssistanceDataForm", assistanceData);
}
c#
public async Task<IActionResult> AssistanceDataForm(Assistance parentAssistance, int assistanceIndex, int assistanceDataIndex)
{
return PartialView("Encoder/AssistanceDataForm", assistanceData);
}
this returns the partial view but how do I add for="parentAssistance[assistanceIndex].Assistances[assistanceDataIndex]" in the PartialView? Is this even possible? If not could there be another way around it?
7 replies
CC#
Created by Alizer on 7/30/2023 in #help
✅ Retain form tag helper names inside partial view
I want to retain a form tag helper's name inside a partial view, I have a massive form model with lots of nested objects, below is just a simplified version of what I wanted to do I have a form below, this works because Name.FirstName is being handled correctly by ASP automatically setting the name of the <input/> tag, my controller parses this correct into a Member object
@model Member
<form>
<div class="form-floating flex-grow-1">
<input asp-for="Name.FirstName" class="form-control border-0 bg-subtle" placeholder="[email protected]">
<label asp-for="Name.FirstName">
<i class="fa-solid fa-person me-2"></i>First Name
</label>
<span asp-validation-for="Name.FirstName" class="text-danger fw-normal"></span>
</div>
</form>
@model Member
<form>
<div class="form-floating flex-grow-1">
<input asp-for="Name.FirstName" class="form-control border-0 bg-subtle" placeholder="[email protected]">
<label asp-for="Name.FirstName">
<i class="fa-solid fa-person me-2"></i>First Name
</label>
<span asp-validation-for="Name.FirstName" class="text-danger fw-normal"></span>
</div>
</form>
but since my form is massive, I wanted to split it to multiple sections, now I put the Name property inside another partial view like below
// _NameSection.cshtml partial view
@model Name
<div class="form-floating flex-grow-1">
<input asp-for="FirstName" class="form-control border-0 bg-subtle" placeholder="[email protected]">
<label asp-for="FirstName">
<i class="fa-solid fa-person me-2"></i>First Name
</label>
<span asp-validation-for="FirstName" class="text-danger fw-normal"></span>
</div>
// _NameSection.cshtml partial view
@model Name
<div class="form-floating flex-grow-1">
<input asp-for="FirstName" class="form-control border-0 bg-subtle" placeholder="[email protected]">
<label asp-for="FirstName">
<i class="fa-solid fa-person me-2"></i>First Name
</label>
<span asp-validation-for="FirstName" class="text-danger fw-normal"></span>
</div>
and below is the main form's .cshtml file
// Main form .cshtml page view
@model Member
<form>
<partial name="_NameSection"/>
</form>
// Main form .cshtml page view
@model Member
<form>
<partial name="_NameSection"/>
</form>
and for some reason this breaks ASP's automatically set name for the <input/> tag, it just sets the input's name to FirstName when it should be Name.FirstName, how do I fix this?
3 replies
CC#
Created by Alizer on 6/5/2023 in #help
How do I pass data from my partial view to my main layout in ASP Core?
I have this code in my partial view:
// Partial View Lesson.html
@{
ViewData["LessonTitle"] = "Lesson 1";
}
// Partial View Lesson.html
@{
ViewData["LessonTitle"] = "Lesson 1";
}
Now I want to pass this data to my main layout.
// Main _Layout.cshtml
<html>
<body>
<partial name="Lesson"/>
<h1>@ViewData["LessonTitle"]</h1>
</body>
</html>
// Main _Layout.cshtml
<html>
<body>
<partial name="Lesson"/>
<h1>@ViewData["LessonTitle"]</h1>
</body>
</html>
What I want to do here is to set ViewData["LessonTitle"] in my partial layout and get that data in my _Layout.cshtml but I get the error NullReferenceException: Object reference not set to an instance. specifically on the <h1>@ViewData["LessonTitle"]</h1> line, if I remove that line I don't get any error at all so I believe I can't pass data from partial view to layout via ViewData....? If I can't, how do I pass data from my partial to my main layout?
1 replies
CC#
Created by Alizer on 4/28/2023 in #help
❔ what the proper way to check if ``dynamic`` has a specific property?
I have this code below
dynamic modelObject = new { Count = 0 };
dynamic modelObject = new { Count = 0 };
now I'm passing this as a @model to a partial view
@model dynamic

<div class="container-fluid">
<p>
<!-- Check if @@Model has a property named ``Count`` -->
</p>
</div>
@model dynamic

<div class="container-fluid">
<p>
<!-- Check if @@Model has a property named ``Count`` -->
</p>
</div>
how do i properly check if modelObject has a property named Count? I searched for solutions online and most require me to turn it into a Dictionary BUT I DONT WANT TO DO THAT!! casting it to dictionary is just....redundant and doesn't feel right, anyways, is there a proper way to do it?
16 replies
CC#
Created by Alizer on 4/1/2023 in #help
❔ How do I use a .cshtml (or Razor View) from a class library?
I wanted to make a modular ASP Core project, I wanted to make some kind of 'plugin system' for me project, basically some Razor views will be stored in class libraries, but currently I don't know how to do it, I followed the instruction at the Microsoft docs and Controllers work, I was able to add a controller class to my library and make it return a 200 OK on a specific route, however Razor views don't work, the following below is my code for importing .dll files
var pluginAssemblies =
Directory.GetFiles(Path.Combine(AppContext.BaseDirectory), "plugin/*.dll", SearchOption.AllDirectories);

// Load DLL plugins.
foreach (var pluginAssembly in pluginAssemblies)
{
try
{
var assemblyLoadContext = new AssemblyLoadContext(Path.GetFileName(pluginAssembly));
var assembly = assemblyLoadContext.LoadFromAssemblyPath(pluginAssembly);
var pluginTypes = assembly.GetTypes().Where(type => typeof(PluginBase).IsAssignableFrom(type));

foreach (var pluginType in pluginTypes)
{
builder.Services.AddScoped(typeof(IPlugin), pluginType);
builder.Services.AddControllersWithViews()
.AddApplicationPart(pluginType.Assembly)
.AddRazorRuntimeCompilation();

builder.Services.Configure<MvcRazorRuntimeCompilationOptions>(o =>
{
o.FileProviders.Add(new EmbeddedFileProvider(pluginType.Assembly));
});

builder.Services.AddRazorPages().AddApplicationPart(pluginType.Assembly)
.AddRazorRuntimeCompilation();
}
}
catch (Exception ex)
{
}
}
var pluginAssemblies =
Directory.GetFiles(Path.Combine(AppContext.BaseDirectory), "plugin/*.dll", SearchOption.AllDirectories);

// Load DLL plugins.
foreach (var pluginAssembly in pluginAssemblies)
{
try
{
var assemblyLoadContext = new AssemblyLoadContext(Path.GetFileName(pluginAssembly));
var assembly = assemblyLoadContext.LoadFromAssemblyPath(pluginAssembly);
var pluginTypes = assembly.GetTypes().Where(type => typeof(PluginBase).IsAssignableFrom(type));

foreach (var pluginType in pluginTypes)
{
builder.Services.AddScoped(typeof(IPlugin), pluginType);
builder.Services.AddControllersWithViews()
.AddApplicationPart(pluginType.Assembly)
.AddRazorRuntimeCompilation();

builder.Services.Configure<MvcRazorRuntimeCompilationOptions>(o =>
{
o.FileProviders.Add(new EmbeddedFileProvider(pluginType.Assembly));
});

builder.Services.AddRazorPages().AddApplicationPart(pluginType.Assembly)
.AddRazorRuntimeCompilation();
}
}
catch (Exception ex)
{
}
}
2 replies
CC#
Created by Alizer on 2/10/2023 in #help
❔ Any good persistent data solution for .net core 6 c#?
Back in .NET framework I use settings and the Properties.Settings.Default namespace to store data in just about a line of code but looks like I cannot use it with the new .net core 6, is there like a library or just a good way of storing persistent user data in .net core? something that doesnt require me to use a database
12 replies
CC#
Created by Alizer on 12/17/2022 in #help
❔ how do I get the mouse position in MacOS
I can do it in Windows via the Cursor class but how do I do it in MacOS? every google search results points to Unity but I need to do it in .NET 6
3 replies
CC#
Created by Alizer on 12/14/2022 in #help
❔ how to get the current selected text from any window just like how clipboard does it?
I want to simulate Ctrl + C without pressing Ctrl + C, basically able to read any selected text from any window be it a browser, notepad or word, most solutions I found online requires me to call SendKeys to do Ctrl + C every mouse release but some programs (such as VLC media player) performs a different action if Ctrl + C is pressed, and hell, I have no idea if text is even being selected in the first place, so currently my question is, how do I simulate clipboard copy without pressing Ctrl + C?
6 replies
CC#
Created by Alizer on 10/31/2022 in #help
how to add a table to an existing ef core database created using EnsureCreated()?
I have an existing SQLite database (30GB in size) which was created using EnsureCreated(), now I need to add a table which I tried using migrations (I passed dotnet ef database update) on the command line but it causes Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 1: 'table "AspNetRoles" already exists'. error, I did a lot of research and it seems like I needed to create the database via migrations. How do I add a table when the ef core database is created via EnsureCreated()? Do I have to create the db via migrations and fill it with data from the existing db? can there be a way in which I can add the table be it via code?
4 replies
CC#
Created by Alizer on 10/1/2022 in #help
Does DbSet.FirstOrDefaultAsync return a tracked entity?
I have the following code below
var existingCreator = await _dbContext.ContentCreators.FirstOrDefaultAsync(x => x.Name == creator.Name);
var existingCreator = await _dbContext.ContentCreators.FirstOrDefaultAsync(x => x.Name == creator.Name);
is changing properties inside existingCreator going to also change the record inside the sql server?
5 replies
CC#
Created by Alizer on 9/16/2022 in #help
where does the default ASP Core with Identity put the registration and login form?
3 replies