/// <summary> /// Updates the specified Entity in the backing repository, as an asynchronous operation. /// </summary> /// <param name="entity">The Entity to update.</param> /// <param name="formDict">The form dictionary containing the new values for the specified Entity.</param> /// <returns> /// The System.Threading.Tasks.Task that represents the asynchronous operation, containing the KerykeionDbResult of the operation. /// </returns> public async Task <KerykeionDbResult> UpdateAsync(object entity, Dictionary <string, StringValues> formDict) { if (entity == null) { return(KerykeionDbResult.Fail(new KerykeionDbError { Message = $"{await _translationsService.TranslateAsync("Please provide a valid entity when calling this function")}." })); } if (formDict.ContainsKey(PropertyNameConstants.Name)) { var exists = await ExistsAsync(formDict[PropertyNameConstants.Name], FindTableNameByClrType(entity.GetType())); if (exists && entity.GetType().GetProperty(PropertyNameConstants.Name).GetValue(entity) != formDict[PropertyNameConstants.Name]) { return(KerykeionDbResult.Fail(new KerykeionDbError { Message = _translationsService.TranslateErrorByDescriber(ErrorDescriberConstants.NameDuplicate, $"The name '{formDict[PropertyNameConstants.Name]}' is already taken.", formDict[PropertyNameConstants.Name]) })); } } var result = await SetPropertiesAsync(entity, formDict); if (!result.Successfull) { return(result); } return(await UpdateAsync(entity)); }
public async Task <IActionResult> OnPostAsync() { var user = await _userService.GetUserAsync(User); if (user == null) { return(NotFound($"Het is niet gelukt om de gebruiker te laden met ID'{_userService.GetUserId(User)}'.")); } if (!ModelState.IsValid) { await LoadAsync(user); return(Page()); } var phoneNumber = await _userService.GetPhoneNumberAsync(user); if (Input.PhoneNumber != phoneNumber) { var setPhoneResult = await _userService.SetPhoneNumberAsync(user, Input.PhoneNumber); if (!setPhoneResult.Succeeded) { StatusMessage = "Onverwachte fout bij het proberen opslaan van de telefoonnummer."; return(RedirectToPage()); } } if (Input.ProfileImage != null) { KerykeionDbResult uploadProfileImageResult = await _userService.AddProfileImage(user, Input.ProfileImage); if (!uploadProfileImageResult.Successfull) { StatusMessage = "Onverwachte fout bij het proberen uploaden van de profielfoto."; return(RedirectToPage()); } } var language = await _userService.GetLanguageAsync(user); if (Input.Language != language) { KerykeionDbResult setLanguageResult = await _userService.SetLanguageAsync(user, Input.Language); if (!setLanguageResult.Successfull) { StatusMessage = "Onverwachte fout bij het proberen wijwigen van de taal."; return(RedirectToPage()); } } await _signInService.RefreshSignInAsync(user); StatusMessage = "Uw profiel is geupdatet."; return(RedirectToPage()); }
private async Task <KerykeionDbResult> SetForeignKeyAsync(object entity, string formValue, string propertyName) { var foreignKey = FindEntityTypeByClrType(entity.GetType()).GetForeignKeys().FirstOrDefault(fk => fk.GetDefaultName().Contains(propertyName, StringComparison.OrdinalIgnoreCase)); if (foreignKey == null) { return(null); } if (string.IsNullOrEmpty(formValue?.Trim())) { if (foreignKey.IsRequired) { return(KerykeionDbResult.Fail(new KerykeionDbError { Message = _translationsService.TranslateErrorByDescriber(ErrorDescriberConstants.RequiredField, $"The field '{propertyName}' is required.", propertyName) })); } Context.Entry(entity).Property(propertyName).CurrentValue = null; return(null); } if (!Guid.TryParse(formValue, out _)) { return(KerykeionDbResult.Fail(new KerykeionDbError { Message = _translationsService.TranslateErrorByDescriber(ErrorDescriberConstants.NotValidGuid, $"Please provide a valid GUID for the property '{propertyName}'.", propertyName) })); } var foreignPrincipalEntityType = foreignKey?.PrincipalEntityType?.ClrType; if (foreignPrincipalEntityType == null) { return(null); } var foreignEntity = await Context.FindAsync(foreignPrincipalEntityType, Guid.Parse(formValue)); if (foreignEntity == null) { return(KerykeionDbResult.Fail(new KerykeionDbError { Message = _translationsService.TranslateErrorByDescriber(ErrorDescriberConstants.EntityNotExistsWithSpecifiedPriKey, $"There is no '{foreignPrincipalEntityType?.Name}' found in the database with '{formValue}' as primary key.", foreignPrincipalEntityType?.Name, formValue) })); } Context.Entry(entity).Property(propertyName).CurrentValue = Guid.Parse(formValue); return(KerykeionDbResult.Success()); }
public async Task <JsonResult> OnPostDeleteViaAjaxAsync([FromBody] DeleteEntityFromSideNavDto dto) { var entity = await EntitiesService.FindByIdAndTableNameAsync(dto.Id, dto.Table); if (entity == null) { return(new JsonResult(KerykeionDbResult.Fail(new KerykeionDbError { Message = "The entity is not found." }))); } var result = await EntitiesService.DeleteAsync(entity); return(new JsonResult(result)); }
private async Task <KerykeionDbResult> TrySaveChangesAsync(object entity = null) { try { await Context.SaveChangesAsync(); return(KerykeionDbResult.Success(entity)); } catch (Exception ex) { return(KerykeionDbResult.Fail(new KerykeionDbError { Message = ex.InnerException.Message })); } }
/// <summary> /// Deletes the specified Entity from the backing repository, as an asynchronous operation. /// </summary> /// <param name="entity">The Entity to delete.</param> /// <returns> /// The System.Threading.Tasks.Task that represents the asynchronous operation, containing the KerykeionDbResult of the operation. /// </returns> public async Task <KerykeionDbResult> DeleteAsync(object entity) { if (entity is Image) { var removeImgResult = await _imagesService.DeleteImage(entity.GetType().GetProperty("Url").GetValue(entity)?.ToString()?.Split("/")?.Last()); if (!removeImgResult.Success) { return(KerykeionDbResult.Fail(new KerykeionDbError { Message = "Could not delete the image." })); } } Context.Remove(entity); return(await TrySaveChangesAsync()); }
/// <summary> /// Creates an Entity specified by its table with the form dictionary values, as an asynchronous operation. /// </summary> /// <param name="tableName">The name of the table the entity resides in.</param> /// <param name="formDict">The form dictionary containing the values to create the entity.</param> /// <returns> /// The System.Threading.Tasks.Task that represents the asynchronous operation, containing the KerykeionDbResult of the operation. /// </returns> public async Task <KerykeionDbResult> CreateAsync(string tableName, Dictionary <string, StringValues> formDict) { if (string.IsNullOrEmpty(tableName)) { return(KerykeionDbResult.Fail(new KerykeionDbError { Message = $"{await _translationsService.TranslateAsync("Please specify a valid table name")}." })); } var type = FindEntityTypeByTableName(tableName); if (type == null) { return(KerykeionDbResult.Fail(new KerykeionDbError { Message = _translationsService.TranslateErrorByDescriber(ErrorDescriberConstants.TableNotExists, $"There are no entities in a table called '{tableName}'.", tableName) })); } if (formDict.ContainsKey(PropertyNameConstants.Name)) { var exists = await ExistsAsync(formDict[PropertyNameConstants.Name], tableName); if (exists) { return(KerykeionDbResult.Fail(new KerykeionDbError { Message = _translationsService.TranslateErrorByDescriber(ErrorDescriberConstants.NameDuplicate, $"The name '{formDict[PropertyNameConstants.Name]}' is already taken.", formDict[PropertyNameConstants.Name]) })); } } var entity = Activator.CreateInstance(type.ClrType); var result = await SetPropertiesAsync(entity, formDict); if (!result.Successfull) { return(result); } return(await CreateAsync(entity)); }
/// <summary> /// Sets Foreign Key property values to the specified Entity. /// </summary> /// <param name="entity">The Entity to set the foreign keys value to.</param> /// <param name="formForeignKeys">The form dictionary foreign keys and values.</param> /// <returns> /// The System.Threading.Tasks.Task that represents the asynchronous operation, containing the KerykeionDbResult of the operation. /// </returns> public async Task <KerykeionDbResult> SetForeignKeysAsync(object entity, IEnumerable <KeyValuePair <string, StringValues> > formForeignKeys) { foreach (var key in formForeignKeys) { var foreignKeyName = key.Key.Split("-").Last(); var result = await SetForeignKeyAsync(entity, key.Value.ToString(), foreignKeyName); if (result == null) { continue; } if (!result.Successfull) { return(result); } } return(KerykeionDbResult.Success()); }
private async Task <KerykeionDbResult> SetPropertiesAsync(object entity, Dictionary <string, StringValues> formDict) { var entityType = FindEntityTypeByClrType(entity.GetType()); List <KerykeionDbError> errors = new List <KerykeionDbError>(); foreach (var prop in entityType.GetProperties()) { var property = entityType.ClrType.GetProperty(prop.Name); if (property == null) { if (formDict.ContainsKey(prop.Name)) { var result = await SetForeignKeyAsync(entity, formDict[prop.Name].ToString(), prop.Name); if (result == null) { continue; } if (!result.Successfull) { errors.Add(result.Errors.FirstOrDefault()); } } continue; } if (prop.Name.Equals(PropertyNameConstants.Id, StringComparison.OrdinalIgnoreCase) || prop.Name.Equals(PropertyNameConstants.DateTimeCreated, StringComparison.OrdinalIgnoreCase)) { continue; } if (formDict.ContainsKey(prop.Name)) { if (prop.IsPrimaryKey()) { if (Guid.TryParse(formDict[prop.Name], out _)) { var navigation = entityType.GetNavigations().FirstOrDefault(n => prop.Name.Contains(n.Name, StringComparison.OrdinalIgnoreCase)); var targetType = navigation?.GetTargetType()?.ClrType; if (targetType == null) { errors.Add(new KerykeionDbError { Message = _translationsService.TranslateErrorByDescriber(ErrorDescriberConstants.EntityNotExistsWithSpecifiedPriKey, $"There is no '{targetType?.Name}' found in the database with '{formDict[prop.Name]}' as primary key.", targetType?.Name, formDict[prop.Name]) }); continue; } var target = await Context.FindAsync(targetType, Guid.Parse(formDict[prop.Name])); if (target == null) { errors.Add(new KerykeionDbError { Message = _translationsService.TranslateErrorByDescriber(ErrorDescriberConstants.EntityNotExistsWithSpecifiedPriKey, $"There is no '{targetType?.Name}' found in the database with '{formDict[prop.Name]}' as primary key.", targetType?.Name, formDict[prop.Name]) }); continue; } property.SetValue(entity, Guid.Parse(formDict[prop.Name])); continue; } errors.Add(new KerykeionDbError { Message = _translationsService.TranslateErrorByDescriber(ErrorDescriberConstants.NotValidGuid, $"Please provide a valid GUID for the property '{prop.Name}'.", prop.Name) }); continue; } if (prop.IsForeignKey()) { var result = await SetForeignKeyAsync(entity, formDict[prop.Name].ToString(), prop.Name); if (result == null) { continue; } if (!result.Successfull) { errors.Add(result.Errors.FirstOrDefault()); } continue; } if (string.IsNullOrEmpty(formDict[prop.Name])) { continue; } if (int.TryParse(formDict[prop.Name], out _)) { property.SetValue(entity, int.Parse(formDict[prop.Name])); continue; } if (bool.TryParse(formDict[prop.Name], out _)) { property.SetValue(entity, bool.Parse(formDict[prop.Name])); continue; } if (DateTime.TryParse(formDict[prop.Name], out _)) { property.SetValue(entity, DateTime.Parse(formDict[prop.Name])); continue; } if (TimeSpan.TryParse(formDict[prop.Name], out _)) { property.SetValue(entity, TimeSpan.Parse(formDict[prop.Name])); continue; } if (float.TryParse(formDict[prop.Name], out _)) { property.SetValue(entity, float.Parse(formDict[prop.Name])); continue; } if (double.TryParse(formDict[prop.Name], out _)) { property.SetValue(entity, double.Parse(formDict[prop.Name])); continue; } if (decimal.TryParse(formDict[prop.Name], out _)) { property.SetValue(entity, decimal.Parse(formDict[prop.Name])); continue; } property.SetValue(entity, formDict[prop.Name].ToString()); } } if (errors.Count > 0) { return(KerykeionDbResult.Fail(errors.ToArray())); } return(KerykeionDbResult.Success()); }