private async Task <IActionResult> PrivateCreateUser(User newUser) { try { newUser.PasswordHash = newUser.Password; if (newUser.RegistrationMethod.Type != RegistrationTypes.Application) { newUser.PasswordHash = CoreFunc.StringGenerator(40, 10, 10, 10, 10); newUser.EmailConfirmed = true; } ModelState.Clear(); if (!TryValidateModel(newUser)) { CoreFunc.ExtractErrors(ModelState, ref ErrorsList); return(UnprocessableEntity(ErrorsList)); } if (await _DbContext.Users.AnyAsync(u => u.NormalizedEmail == newUser.Email.ToUpper()).ConfigureAwait(false)) { CoreFunc.Error(ref ErrorsList, "This email is already registered."); return(StatusCode(412, ErrorsList)); } newUser.Id = 0; IdentityResult newUserResult = await _UserManager.CreateAsync(newUser, newUser.PasswordHash) .ConfigureAwait(false); if (!newUserResult.Succeeded) { foreach (var error in newUserResult.Errors) { CoreFunc.Error(ref ErrorsList, error.Description, error.Code); } return(StatusCode(417, ErrorsList)); } IdentityResult addedClaimResult = await _UserManager.AddClaimAsync( newUser, new Claim(AppConst.AccessClaims.Type, newUser.Role.AccessClaim) ).ConfigureAwait(false); if (!addedClaimResult.Succeeded) { _DbContext.Users.Remove(newUser); await _DbContext.SaveChangesAsync().ConfigureAwait(false); CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, null, User)); return(StatusCode(417, ErrorsList)); } await _UserManager.SetLockoutEnabledAsync(newUser, false); IsUserCreated = true; return(Created("Success", newUser)); } catch (Exception ex) { CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User)); return(StatusCode(417, ErrorsList)); } }
public async Task <IActionResult> CreateUser([FromBody] User newUser) { try { if (string.IsNullOrWhiteSpace(newUser.Password)) { newUser.Password = CoreFunc.StringGenerator(10, 3, 3, 2, 2); } if (newUser.Role.Id == 0) { newUser.Role = null; } TryValidateModel(newUser); ModelState.Remove("Role.Name"); ModelState.Remove("Role.AccessClaim"); ModelState.Remove("PasswordHash"); if (!ModelState.IsValid) { CoreFunc.ExtractErrors(ModelState, ref ErrorsList); return(UnprocessableEntity(ErrorsList)); } newUser.Role = await _DbContext.Roles.AsTracking() .FirstOrDefaultAsync(r => r.Id == newUser.Role.Id).ConfigureAwait(false); IActionResult result = await PrivateCreateUser(newUser).ConfigureAwait(false); if (IsUserCreated) { Request.Headers.TryGetValue("Origin", out StringValues OriginValue); await _EmailService .WelcomeNewEmployeeAsync(newUser, OriginValue) .ConfigureAwait(false); } newUser.Password = string.Empty; return(result); } catch (Exception ex) { CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User)); if (IsUserCreated) { _DbContext.Remove(newUser); await _DbContext.SaveChangesAsync().ConfigureAwait(false); } return(StatusCode(417, ErrorsList)); } }
public async Task <IActionResult> Post([FromBody] Category newCategory) { try { TryValidateModel(newCategory); if (ModelState.ContainsKey("ImageBase64")) { ModelState.Remove("OriginalImageBase64"); } if (!ModelState.IsValid) { CoreFunc.ExtractErrors(ModelState, ref ErrorsList); return(UnprocessableEntity(ErrorsList)); } /// check the database to see if a Category with the same name exists if (await _DbContext.Categories .AnyAsync(d => d.Name.Equals(newCategory.Name)).ConfigureAwait(false)) { /// extract the errors and return bad request containing the errors CoreFunc.Error(ref ErrorsList, "Category already exists."); return(StatusCode(412, ErrorsList)); } try { string folderName = CoreFunc.StringGenerator(10, 3, 3, 4); newCategory.ImagePath = CoreFunc.SaveImageToWWWRoot(CoreFunc.StringGenerator(10, 3, 3, 4), _WebHost.WebRootPath, newCategory.ImageBase64, $"Images\\Categories\\{folderName}"); newCategory.OriginalImagePath = CoreFunc.SaveImageToWWWRoot(CoreFunc.StringGenerator(10, 3, 3, 4), _WebHost.WebRootPath, newCategory.OriginalImageBase64, $"Images\\Categories\\{folderName}"); } catch (Exception ex) { CoreFunc.Error(ref ErrorsList, "Image cannot be saved."); _LoggingService.LogException(Request.Path, ex, User, AppLogType.FileModification); return(StatusCode(412, ErrorsList)); } try { /// else Category object is made without any errors /// Add the new Category to the EF context await _DbContext.Categories.AddAsync(newCategory).ConfigureAwait(false); /// save the changes to the database await _DbContext.SaveChangesAsync().ConfigureAwait(false); } catch (Exception ex) { CoreFunc.DeleteFromWWWRoot(newCategory.ImagePath, _WebHost.WebRootPath); CoreFunc.DeleteFromWWWRoot(newCategory.OriginalImagePath, _WebHost.WebRootPath); CoreFunc.ClearEmptyImageFolders(_WebHost.WebRootPath); CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User, AppLogType.FileModification)); } /// return 201 created status with the new object /// and success message return(Created("", newCategory)); } catch (Exception ex) { CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User)); return(StatusCode(417, ErrorsList)); } }
[Authorize(AppConst.AccessPolicies.Secret)] /// Done public async Task <IActionResult> Put([FromBody] Category modifiedCategory) { try { bool containsNewImages = true; TryValidateModel(modifiedCategory); /// if new image is not provided do not check for new images if (string.IsNullOrWhiteSpace(modifiedCategory.ImageBase64) && string.IsNullOrWhiteSpace(modifiedCategory.OriginalImageBase64)) { containsNewImages = false; ModelState.Remove("ImageBase64"); ModelState.Remove("OriginalImageBase64"); } if (ModelState.ContainsKey("ImageBase64")) { ModelState.Remove("OriginalImageBase64"); } /// if model validation failed if (!ModelState.IsValid) { CoreFunc.ExtractErrors(ModelState, ref ErrorsList); /// return Unprocessable Entity with all the errors return(UnprocessableEntity(ErrorsList)); } /// check the database to see if a Category with the same name exists if (await _DbContext.Categories .AnyAsync(c => c.Name == modifiedCategory.Name && c.Id != modifiedCategory.Id) .ConfigureAwait(false)) { /// extract the errors and return bad request containing the errors CoreFunc.Error(ref ErrorsList, "Category with the given name already exists."); return(StatusCode(412, ErrorsList)); } /// get the current category Category currentCatogory = await _DbContext.Categories .SingleOrDefaultAsync(c => c.Id == modifiedCategory.Id) .ConfigureAwait(false); // if the current category does not exists if (currentCatogory == null) { CoreFunc.Error(ref ErrorsList, "Category Not Found"); return(NotFound(ErrorsList)); } string oldImagePath = modifiedCategory.ImagePath.Clone().ToString(); string oldOriginalImagePath = modifiedCategory.OriginalImagePath.Clone().ToString(); /// if new image is provided save the new image if (containsNewImages) { try { string folderName = CoreFunc.StringGenerator(10, 3, 3, 4); modifiedCategory.ImagePath = CoreFunc.SaveImageToWWWRoot(CoreFunc.StringGenerator(10, 3, 3, 4), _WebHost.WebRootPath, modifiedCategory.ImageBase64, $"Images\\Categories\\{folderName}"); modifiedCategory.OriginalImagePath = CoreFunc.SaveImageToWWWRoot(CoreFunc.StringGenerator(10, 3, 3, 4), _WebHost.WebRootPath, modifiedCategory.OriginalImageBase64, $"Images\\Categories\\{folderName}"); } catch (Exception ex) { CoreFunc.Error(ref ErrorsList, "Image cannot be saved."); _LoggingService.LogException(Request.Path, ex, User, AppLogType.FileModification); return(StatusCode(412, ErrorsList)); } } try { /// else Category object is made without any errors _DbContext.Categories.Update(modifiedCategory); await _DbContext.SaveChangesAsync().ConfigureAwait(false); } catch (Exception ex) { if (containsNewImages) { CoreFunc.DeleteFromWWWRoot(modifiedCategory.ImagePath, _WebHost.WebRootPath); CoreFunc.DeleteFromWWWRoot(modifiedCategory.OriginalImagePath, _WebHost.WebRootPath); CoreFunc.ClearEmptyImageFolders(_WebHost.WebRootPath); } _LoggingService.LogException(Request.Path, ex, User, AppLogType.FileModification); } if (containsNewImages) { CoreFunc.DeleteFromWWWRoot(oldImagePath, _WebHost.WebRootPath); CoreFunc.DeleteFromWWWRoot(oldOriginalImagePath, _WebHost.WebRootPath); CoreFunc.ClearEmptyImageFolders(_WebHost.WebRootPath); } return(Ok(modifiedCategory)); } catch (Exception ex) { CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User)); return(StatusCode(417, ErrorsList)); } }
/// Done public async Task <IActionResult> Post([FromBody] Product newProduct) { try { if (newProduct.Category.Id == 0) { newProduct.Category = null; } TryValidateModel(newProduct); ModelState.Remove("Category.Name"); ModelState.Remove("Category.ImageBase64"); ModelState.Remove("NutritionalInfo.Product"); ModelState.Remove("Category.OriginalImageBase64"); if (ModelState.ContainsKey("ImageBase64")) { ModelState.Remove("OriginalImageBase64"); } if (!ModelState.IsValid) { CoreFunc.ExtractErrors(ModelState, ref ErrorsList); return(UnprocessableEntity(ErrorsList)); } /// check the database to see if a Product with the same name exists if (await _DbContext.Products.AnyAsync(d => d.Name == newProduct.Name && d.Category.Id == newProduct.Category.Id).ConfigureAwait(false)) { CoreFunc.Error(ref ErrorsList, "Product already exists."); return(StatusCode(412, ErrorsList)); } try { string folderName = CoreFunc.StringGenerator(10, 3, 3, 4); newProduct.ImagePath = CoreFunc.SaveImageToWWWRoot(CoreFunc.StringGenerator(10, 3, 3, 4), _WebHost.WebRootPath, newProduct.ImageBase64, $"Images\\Products\\{folderName}"); newProduct.OriginalImagePath = CoreFunc.SaveImageToWWWRoot(CoreFunc.StringGenerator(10, 3, 3, 4), _WebHost.WebRootPath, newProduct.OriginalImageBase64, $"Images\\Products\\{folderName}"); } catch (Exception ex) { CoreFunc.Error(ref ErrorsList, "Image cannot be saved."); _LoggingService.LogException(Request.Path, ex, User, AppLogType.FileModification); return(StatusCode(412, ErrorsList)); } try { await _DbContext.Products.AddAsync(newProduct).ConfigureAwait(false); _DbContext.Entry(newProduct.Category).State = EntityState.Unchanged; await _DbContext.SaveChangesAsync().ConfigureAwait(false); } catch (Exception) { CoreFunc.DeleteFromWWWRoot(newProduct.ImagePath, _WebHost.WebRootPath); CoreFunc.DeleteFromWWWRoot(newProduct.OriginalImagePath, _WebHost.WebRootPath); CoreFunc.ClearEmptyImageFolders(_WebHost.WebRootPath); throw; } return(Created("", newProduct)); } catch (Exception ex) { CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User)); return(StatusCode(417, ErrorsList)); } }
[Authorize(AppConst.AccessPolicies.Secret)] /// Done public async Task <IActionResult> Put([FromBody] Product modifiedProduct) { try { bool containsNewImages = true; if (modifiedProduct.Category.Id == 0) { modifiedProduct.Category = null; } ModelState.Remove("Category.Name"); ModelState.Remove("Category.ImageBase64"); ModelState.Remove("Category.OriginalImageBase64"); ModelState.Remove("NutritionalInfo.Product"); /// if new image is not provided do not check for new images if (string.IsNullOrWhiteSpace(modifiedProduct.ImageBase64) && string.IsNullOrWhiteSpace(modifiedProduct.OriginalImageBase64)) { containsNewImages = false; ModelState.Remove("ImageBase64"); ModelState.Remove("OriginalImageBase64"); } if (ModelState.ContainsKey("ImageBase64")) { ModelState.Remove("OriginalImageBase64"); } if (!ModelState.IsValid) { CoreFunc.ExtractErrors(ModelState, ref ErrorsList); return(UnprocessableEntity(ErrorsList)); } /// check the database to see if a Product with the same name exists if (await _DbContext.Products.AnyAsync(d => d.Id != modifiedProduct.Id && d.Name == modifiedProduct.Name && d.Category.Id == modifiedProduct.Category.Id).ConfigureAwait(false)) { CoreFunc.Error(ref ErrorsList, "Duplicated product name in selected category."); return(StatusCode(412, ErrorsList)); } string oldImagePath = modifiedProduct.ImagePath.Clone().ToString(); string oldOriginalImagePath = modifiedProduct.OriginalImagePath.Clone().ToString(); /// if new image is provided save the new image if (containsNewImages) { try { string folderName = CoreFunc.StringGenerator(10, 3, 3, 4); modifiedProduct.ImagePath = CoreFunc.SaveImageToWWWRoot(CoreFunc.StringGenerator(10, 3, 3, 4), _WebHost.WebRootPath, modifiedProduct.ImageBase64, $"Images\\Products\\{folderName}"); modifiedProduct.OriginalImagePath = CoreFunc.SaveImageToWWWRoot(CoreFunc.StringGenerator(10, 3, 3, 4), _WebHost.WebRootPath, modifiedProduct.OriginalImageBase64, $"Images\\Products\\{folderName}"); } catch (Exception ex) { CoreFunc.Error(ref ErrorsList, "Image cannot be saved."); _LoggingService.LogException(Request.Path, ex, User, AppLogType.FileModification); return(StatusCode(412, ErrorsList)); } } try { _DbContext.Products.Update(modifiedProduct); await _DbContext.SaveChangesAsync().ConfigureAwait(false); } catch (Exception) { if (containsNewImages) { CoreFunc.DeleteFromWWWRoot(modifiedProduct.ImagePath, _WebHost.WebRootPath); CoreFunc.DeleteFromWWWRoot(modifiedProduct.OriginalImagePath, _WebHost.WebRootPath); CoreFunc.ClearEmptyImageFolders(_WebHost.WebRootPath); } throw; } if (containsNewImages) { CoreFunc.DeleteFromWWWRoot(oldImagePath, _WebHost.WebRootPath); CoreFunc.DeleteFromWWWRoot(oldOriginalImagePath, _WebHost.WebRootPath); CoreFunc.ClearEmptyImageFolders(_WebHost.WebRootPath); } return(Ok(modifiedProduct)); } catch (Exception ex) { CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User)); return(StatusCode(417, ErrorsList)); } }
public async Task <IActionResult> Post(string paypalId, [FromBody] Order orderData) { async Task <Order> TryToSave(Order orderData, int tryCount) { try { orderData.Id = $"{CoreFunc.StringGenerator(3, 4, 0, 4, 0)}-{CoreFunc.StringGenerator(3, 4, 0, 4, 0)}"; await _DbContext.Orders.AddAsync(orderData).ConfigureAwait(false); if (orderData.User != null) { foreach (Address address in orderData.User.Addresses) { _DbContext.Entry(address).State = EntityState.Unchanged; } _DbContext.Entry(orderData.User).State = EntityState.Unchanged; } await _DbContext.SaveChangesAsync().ConfigureAwait(false); return(orderData); } catch (Exception ex) { _LoggingService.Log(Request.Path, AppLogType.OrderException, new { orderData, exception = ex }, User); if (tryCount > 4) { throw; } return(await TryToSave(orderData, tryCount ++)); } } try { if (string.IsNullOrEmpty(paypalId)) { CoreFunc.Error(ref ErrorsList, "Cannot find your payment order."); return(UnprocessableEntity(ErrorsList)); } orderData = await CheckOrderDetail(orderData).ConfigureAwait(false); if (orderData == null) { return(UnprocessableEntity(ErrorsList)); } if (!await orderData.CapturePaypalPayment(paypalId)) { await _DbContext.SaveChangesAsync().ConfigureAwait(false); CoreFunc.Error(ref ErrorsList, "Payment cannot be verified."); return(UnprocessableEntity(ErrorsList)); } orderData = await TryToSave(orderData, 1); await _EmailService.OrderReceiptAsync(orderData).ConfigureAwait(false); return(Created("Success", orderData)); } catch (Exception ex) { CoreFunc.Error(ref ErrorsList, _LoggingService.LogException(Request.Path, ex, User)); return(StatusCode(417, ErrorsList)); } }