pyrodistic
pyrodistic
CC#
Created by pyrodistic on 4/19/2024 in #help
Entity Framework - Circular References
Hey everyone. I'm stuck on this issue since yesterday. I'm using Entity Framework (repository & unit of work), AutoMapper and Blazor. I have a endpoint that retrieves, for example, Teams and that allows me to choose which properties to include. The issue is that I am unable prevent circular references from the entities, even when using mapping, for example, Teams references Persons, Person has a Team, so it references Teams, and so on. I have tried MaxDepth, PreserveReferences on mapping, as well as ignoring cycles on JSON and what seems like dozen other suggestions, ironically I think I'm going in circles. This seems to me like it's something that MUST have a easy solution, but I'm not being able to find anything on it. https://paste.mod.gg/nfujgutykvga/0
32 replies
CC#
Created by pyrodistic on 12/26/2023 in #help
FileWatcher Mutex - Object synchronization method was called from an unsynchronized block of code.
The following code is an attempt at handling when multiple files are modified in the same folder. Since I'm doing database transactions on importer.DoImporterActionAsync, I need to make sure that it's handling files like a queue. I'm getting the error: 'Object synchronization method was called from an unsynchronized block of code.'. Even when copying a single file, and I'm not understanding why.
public async Task OnModifiedAsync(FileSystemEventArgs e)
{
if (e.FullPath.ToLower().EndsWith(extension_to_read))
{
string text = await CalculateSha256Async(e.FullPath);
if (file_hash != text)
{
file_hash = text;
Log.Information("File " + e.FullPath + " has been modified.");
Log.Information("Watching folder: " + folder);
await importer.DoImporterActionAsync(e.FullPath);
}
}
}

public async void OnModifiedAsyncHandler(object sender, FileSystemEventArgs e)
{
try
{
mutex.WaitOne();
await OnModifiedAsync(e);
}
finally
{
mutex.ReleaseMutex();
}
}
public async Task OnModifiedAsync(FileSystemEventArgs e)
{
if (e.FullPath.ToLower().EndsWith(extension_to_read))
{
string text = await CalculateSha256Async(e.FullPath);
if (file_hash != text)
{
file_hash = text;
Log.Information("File " + e.FullPath + " has been modified.");
Log.Information("Watching folder: " + folder);
await importer.DoImporterActionAsync(e.FullPath);
}
}
}

public async void OnModifiedAsyncHandler(object sender, FileSystemEventArgs e)
{
try
{
mutex.WaitOne();
await OnModifiedAsync(e);
}
finally
{
mutex.ReleaseMutex();
}
}
System.ApplicationException HResult=0x80131600 Message=Object synchronization method was called from an unsynchronized block of code. Source=System.Private.CoreLib StackTrace: at System.Threading.Mutex.ReleaseMutex() in /_/src/libraries/System.Private.CoreLib/src/System/Threading/Mutex.Windows.cs:line 92 at FileWatcherBase.<OnModifiedAsyncHandler>d__10.MoveNext() //...cut due to character limit.
2 replies
CC#
Created by pyrodistic on 2/19/2023 in #help
❔ Access Resources File
Hey, sorry to bother - quick question. I created a EmailResources.resx file inside a "Resources" folder, where I have the Name-Value pair of "ConfirmationEmailSubject" - "Verify Your Email Address". On Program.cs I have:
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
builder.Services.AddSingleton<IStringLocalizerFactory, ResourceManagerStringLocalizerFactory>();
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
builder.Services.AddSingleton<IStringLocalizerFactory, ResourceManagerStringLocalizerFactory>();
On the controller I have instantiated the _localizer (private readonly IStringLocalizer<AuthController> _localizer), I have tried to do:
_localizer["EmailResources:ConfirmationEmailSubject"];
_localizer["EmailResources:ConfirmationEmailSubject"].Value;
_localizer["ConfirmationEmailSubject"];
_localizer["ConfirmationEmailSubject"].Value;
_localizer.GetString("ConfirmationEmailSubject");
_localizer.GetString("ConfirmationEmailSubject").Value;
_localizer["EmailResources.EmailResources:ConfirmationEmailSubject"];
_localizer["EmailResources.EmailResources:ConfirmationEmailSubject"].Value;
_localizer["EmailResources:ConfirmationEmailSubject"];
_localizer["EmailResources:ConfirmationEmailSubject"].Value;
_localizer["ConfirmationEmailSubject"];
_localizer["ConfirmationEmailSubject"].Value;
_localizer.GetString("ConfirmationEmailSubject");
_localizer.GetString("ConfirmationEmailSubject").Value;
_localizer["EmailResources.EmailResources:ConfirmationEmailSubject"];
_localizer["EmailResources.EmailResources:ConfirmationEmailSubject"].Value;
All of these are returning "ConfirmationEmailSubject" instead of "Verify Your Email Address". What am I doing wrong? There's a lot of things I've tried on Program.cs. Still cannot do it.
4 replies
CC#
Created by pyrodistic on 12/5/2022 in #help
❔ Xamarin Authentication
Hello everyone. I currently have a MVC project that uses the IdentityUser base class to register/login users. I'm not manually using any kind of token. Using the same database I wanted to Authenticate the user in Xamarin. How can I say to the Xamarin app that the User/IdentityUser logged is the one the app should keep? Sorry if it appears too broad of a question, but would appreciate any help!
15 replies
CC#
Created by pyrodistic on 11/13/2022 in #help
❔ AJAX MVC Table DatePick
Could someone help me manipulating table results with ajax? I'm using MVC. I was using it before to manipulate results on a combo box, but my front-end is really bad... On Controller/Repository:
//Controller
[HttpPost]
[Route("Appointments/GetVetsAsync")]
public async Task<JsonResult> GetAppointmentsAsync(DateTime date)
{
var dateResult = await _appointmentRepository.GetAppointmentFromDate(date);

return Json(dateResult.OrderBy(s => s.TimeslotId));
}
//REPO
public async Task<List<Appointment>> GetAppointmentFromDate(DateTime date)
{
var appointments = _context.Appointments.Where(appt => (appt.Date == date.Date));

return await appointments.ToListAsync();
}
//Controller
[HttpPost]
[Route("Appointments/GetVetsAsync")]
public async Task<JsonResult> GetAppointmentsAsync(DateTime date)
{
var dateResult = await _appointmentRepository.GetAppointmentFromDate(date);

return Json(dateResult.OrderBy(s => s.TimeslotId));
}
//REPO
public async Task<List<Appointment>> GetAppointmentFromDate(DateTime date)
{
var appointments = _context.Appointments.Where(appt => (appt.Date == date.Date));

return await appointments.ToListAsync();
}
On the View I have the table with a foreach(var item in Model). I want for ajax to replace the model or filter the item in it when the date picker changes. So I have:
$(document).ready(function () {
$("#Date").change(function () {
$("#table_appointments").empty();
$.ajax({
url: '@Url.Action("GetAppointmentsAsync","Appointments")',
type: 'POST',
dataType: 'json',
data: { date: $("#Date").val() },
success: function (appointments) {
$(document).ready(function () {
$("#Date").change(function () {
$("#table_appointments").empty();
$.ajax({
url: '@Url.Action("GetAppointmentsAsync","Appointments")',
type: 'POST',
dataType: 'json',
data: { date: $("#Date").val() },
success: function (appointments) {
I think I'm just missing the syntax for the ajax function, the Model is a IEnumerable so I'm not sure if json is the right dataType in this case. Would appreciate any help!
2 replies
CC#
Created by pyrodistic on 10/9/2022 in #help
Cascading DropDown
I'm using MVC (.NET5) with EF and had this code to select a species on a View (to Create/Edit):
<b><label asp-for="Species" class="control-label"></label></b>
@Html.DropDownList("SpeciesId", new SelectList((System.Collections.IEnumerable) ViewData["Species"], "Id", "Name"), "Select Species", new { @class="form-control" })
<span asp-validation-for="SpeciesId" class="text-danger"></span>
<b><label asp-for="Species" class="control-label"></label></b>
@Html.DropDownList("SpeciesId", new SelectList((System.Collections.IEnumerable) ViewData["Species"], "Id", "Name"), "Select Species", new { @class="form-control" })
<span asp-validation-for="SpeciesId" class="text-danger"></span>
It displayed every species but I wanted to have another drop down list that displays the taxonomy or class of a species, for example Mammal, and then filters what the species drop down displays. For example if Mammal is selected (id/index == 1, for example) in the taxonomy list, then the species list will only display the options that have that matching foreign key. After spending pretty much all day trying to find a good explanation I'm a bit defeated. I was trying to follow https://stackoverflow.com/questions/46954959/how-to-create-cascading-drop-down-list , but unfortunately it doesn't seem to convey a deep enough explanation to me. I have only a basic understanding of JS, and this is the first time using jQuery/AJAX. I have on the PetViewModel class:
public PetViewModel()
{
ListTaxonomy = new List<SelectListItem>();
ListSpecies = new List<SelectListItem>();
}

public List<SelectListItem> ListTaxonomy { get; set; }
public List<SelectListItem> ListSpecies { get; set; }

public int SelectedTaxonomyId { get; set; }
public int SelectedSpeciesId { get; set; }
public PetViewModel()
{
ListTaxonomy = new List<SelectListItem>();
ListSpecies = new List<SelectListItem>();
}

public List<SelectListItem> ListTaxonomy { get; set; }
public List<SelectListItem> ListSpecies { get; set; }

public int SelectedTaxonomyId { get; set; }
public int SelectedSpeciesId { get; set; }
(...)
22 replies
CC#
Created by pyrodistic on 10/1/2022 in #help
InvalidOperationException - EF Instance - Identity Resolution
I'm getting:
InvalidOperationException: The instance of entity type 'Vet' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
InvalidOperationException: The instance of entity type 'Vet' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
public async Task<IActionResult> Create(RoomViewModel model)
{
if (ModelState.IsValid)
{
// Converts the model to a Room object.
var room = _converterHelper.ToRoom(model, true);

// Before creating the Room check if there's a room with the same VetId, nulls it if exists.
var previousRoom = _roomRepository.GetByVet((int)model.VetId).AsNoTracking().FirstOrDefault();
if (previousRoom != null)
{
previousRoom.VetId = null;
await _roomRepository.UpdateAsync(previousRoom);
}

// Creates Room
await _roomRepository.CreateAsync(room);

// Changes the room on the related Vet object if provided.
if(room.VetId != null)
{
Vet vet = await _vetRepository.GetByIdAsync((int)room.VetId);

await _vetRepository.UpdateAsync(vet); //Error occurs at this point.
}

return RedirectToAction(nameof(Index));
}
return View(model);
}
public async Task<IActionResult> Create(RoomViewModel model)
{
if (ModelState.IsValid)
{
// Converts the model to a Room object.
var room = _converterHelper.ToRoom(model, true);

// Before creating the Room check if there's a room with the same VetId, nulls it if exists.
var previousRoom = _roomRepository.GetByVet((int)model.VetId).AsNoTracking().FirstOrDefault();
if (previousRoom != null)
{
previousRoom.VetId = null;
await _roomRepository.UpdateAsync(previousRoom);
}

// Creates Room
await _roomRepository.CreateAsync(room);

// Changes the room on the related Vet object if provided.
if(room.VetId != null)
{
Vet vet = await _vetRepository.GetByIdAsync((int)room.VetId);

await _vetRepository.UpdateAsync(vet); //Error occurs at this point.
}

return RedirectToAction(nameof(Index));
}
return View(model);
}
After restarting the application everything seems to be correctly updated despite the error. I've read a couple of stackoverflow posts, but I couldn't figure out what to do in order to fix this. Would appreciate any help.
5 replies
CC#
Created by pyrodistic on 9/22/2022 in #help
Xamarin - Displaying JSON
4 replies
CC#
Created by pyrodistic on 9/16/2022 in #help
Get Parameter From URL (MVC)
If I have an a Action parameter I can pass a value to it from the View like " asp-route-origin="Owner" ". However, how can I retrieve the value that's already set in the URL for that parameter? I know I can retrieve the default route id in the controller from the view (1?origin=Owner) like:
var foo = Url.ActionContext.RouteData.Values["id"]; //==1 (considering the parenthesis above)
var foo = Url.ActionContext.RouteData.Values["id"]; //==1 (considering the parenthesis above)
But replacing id by the desired parameter name ("origin") doesn't seem to work. What should I be doing here? I thought that the same way I do:
<a asp-action="Create" asp-route-id="@Url.ActionContext.RouteData.Values["id"]" class="btn btn-primary btn-lg mb-1">Create New</a>
<a asp-action="Create" asp-route-id="@Url.ActionContext.RouteData.Values["id"]" class="btn btn-primary btn-lg mb-1">Create New</a>
I could do:
<a asp-action="Create" asp-route-origin="@Url.ActionContext.RouteData.Values["origin"]" asp-route-id="@Url.ActionContext.RouteData.Values["id"]" class="btn btn-primary btn-lg mb-1">Create New</a>
<a asp-action="Create" asp-route-origin="@Url.ActionContext.RouteData.Values["origin"]" asp-route-id="@Url.ActionContext.RouteData.Values["id"]" class="btn btn-primary btn-lg mb-1">Create New</a>
But origin seems to be null. Thanks for the help.
2 replies
CC#
Created by pyrodistic on 9/14/2022 in #help
MVC EF 5 - How to reference Model FK Properties?
Hello, I'm having some trouble figuring out the logic to reference FK table properties from a model. I'm currently using the same model for index and details views for an entity. On the index I have:
@foreach (var item in Model)
{
<tr>
<td>@Html.DisplayFor(modelItem => item.Species.Name)</td>
...
@foreach (var item in Model)
{
<tr>
<td>@Html.DisplayFor(modelItem => item.Species.Name)</td>
...
This displays the Species.Name corretly in the column (Dog/Cat/...), where Species is a FK in the Pet class (public virtual Species Species { get; set; }). On the details view I have:
<dt>@Html.DisplayNameFor(model => model.Species)</dt>
<dd>@Html.DisplayFor(model => model.Species)</dd>
<dt>@Html.DisplayNameFor(model => model.Species)</dt>
<dd>@Html.DisplayFor(model => model.Species)</dd>
For the index on the controller I do:
public async Task<IActionResult> Index(int id)
{
var dataContext = _petRepository.GetByOwner(id).Include("Species.Taxonomy");
return View(await dataContext.ToListAsync());
}
public async Task<IActionResult> Index(int id)
{
var dataContext = _petRepository.GetByOwner(id).Include("Species.Taxonomy");
return View(await dataContext.ToListAsync());
}
However on the details I'm unable to use Include:
public async Task<IActionResult> Details(int? id)
{
var pet = await _petRepository.GetByIdAsync(id.Value); // Cannot use .Include("Species.Taxonomy") here.

return View(pet);
}
public async Task<IActionResult> Details(int? id)
{
var pet = await _petRepository.GetByIdAsync(id.Value); // Cannot use .Include("Species.Taxonomy") here.

return View(pet);
}
The error I get is:
Error CS1061 'Task<Pet>' does not contain a definition for 'Include' and no accessible extension method 'Include' accepting a first argument of type 'Task<Pet>' could be found (are you missing a using directive or an assembly reference?)
Error CS1061 'Task<Pet>' does not contain a definition for 'Include' and no accessible extension method 'Include' accepting a first argument of type 'Task<Pet>' could be found (are you missing a using directive or an assembly reference?)
I'm using repository pattern and dependency injection. So the GetByIdAsync() is implemented on a general repository for all entities.
public async Task<T> GetByIdAsync(int id)
{
return await _context.Set<T>().AsNoTracking().FirstOrDefaultAsync(e => e.Id == id);
}
public async Task<T> GetByIdAsync(int id)
{
return await _context.Set<T>().AsNoTracking().FirstOrDefaultAsync(e => e.Id == id);
}
While the GetByOwner() is specific to the Pets repository and returns a IQueryable<Pet>. Both repositories have the same references, tried to use .AsQueryable(), but have the same error. What am I doing wrong and how can I fix it? Thanks in advance.
17 replies
CC#
Created by pyrodistic on 8/27/2022 in #help
Enum or SQL Table?
Hello, I'm doing a CRUD system for animals using MCV (.NET 5). So I thought to have AnimalClass, AnimalSpecies, and AnimalSex as properties. AnimalSpecies is going to be a SQL Table since I might want to allow the user to add species, it's going to have to depend on AnimalClass as a FK so I think the easiest way is to make AnimalClass a table as well (though the values are not supposed to change). The 3 values on the AnimalSex are fixed aswell, so I'm thinking it might make more sense as a enum? Does this make sense? I've never used enum, how would I go about using the enum in this case? Thanks in advance.
18 replies
CC#
Created by pyrodistic on 8/17/2022 in #help
Entity Framework One-To-One [Answered]
Code at: https://paste.mod.gg/rccwzntafwoj/0 When attempting to change the database I'm getting: The dependent side could not be determined for the one-to-one relationship between 'Room.Vet' and 'Vet.Room'. To identify the dependent side of the relationship, configure the foreign key property. If these navigations should not be part of the same relationship, configure them independently via separate method chains in 'OnModelCreating'. See http://go.microsoft.com/fwlink/?LinkId=724062 for more details. OR The property 'Room.Vet' is of type 'Vet' which is not supported by the current database provider. Either change the property CLR type, or ignore the property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'. I wanted to be able to create a Room that can have 0 or 1 Vets, and create a Vet that has 0 or 1 Rooms. What am I doing incorrectly? Thanks in advance.
19 replies