Skip to content

Commit

Permalink
Code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
emonney committed Jun 9, 2023
1 parent 9b54fcf commit 6ce5a54
Show file tree
Hide file tree
Showing 55 changed files with 188 additions and 544 deletions.
33 changes: 10 additions & 23 deletions DAL/ApplicationDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,13 @@
// ======================================

using DAL.Models;
using DAL.Models.Interfaces;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using DAL.Models.Interfaces;
using System.Threading.Tasks;

namespace DAL
{
Expand All @@ -27,12 +25,9 @@ public class ApplicationDbContext : IdentityDbContext<ApplicationUser, Applicati
public DbSet<Order> Orders { get; set; }
public DbSet<OrderDetail> OrderDetails { get; set; }



public ApplicationDbContext(DbContextOptions options) : base(options)
{ }


protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
Expand All @@ -49,71 +44,63 @@ protected override void OnModelCreating(ModelBuilder builder)
builder.Entity<Customer>().Property(c => c.Email).HasMaxLength(100);
builder.Entity<Customer>().Property(c => c.PhoneNumber).IsUnicode(false).HasMaxLength(30);
builder.Entity<Customer>().Property(c => c.City).HasMaxLength(50);
builder.Entity<Customer>().ToTable($"App{nameof(this.Customers)}");
builder.Entity<Customer>().ToTable($"App{nameof(Customers)}");

builder.Entity<ProductCategory>().Property(p => p.Name).IsRequired().HasMaxLength(100);
builder.Entity<ProductCategory>().Property(p => p.Description).HasMaxLength(500);
builder.Entity<ProductCategory>().ToTable($"App{nameof(this.ProductCategories)}");
builder.Entity<ProductCategory>().ToTable($"App{nameof(ProductCategories)}");

builder.Entity<Product>().Property(p => p.Name).IsRequired().HasMaxLength(100);
builder.Entity<Product>().HasIndex(p => p.Name);
builder.Entity<Product>().Property(p => p.Description).HasMaxLength(500);
builder.Entity<Product>().Property(p => p.Icon).IsUnicode(false).HasMaxLength(256);
builder.Entity<Product>().HasOne(p => p.Parent).WithMany(p => p.Children).OnDelete(DeleteBehavior.Restrict);
builder.Entity<Product>().ToTable($"App{nameof(this.Products)}");
builder.Entity<Product>().ToTable($"App{nameof(Products)}");
builder.Entity<Product>().Property(p => p.BuyingPrice).HasColumnType(priceDecimalType);
builder.Entity<Product>().Property(p => p.SellingPrice).HasColumnType(priceDecimalType);

builder.Entity<Order>().Property(o => o.Comments).HasMaxLength(500);
builder.Entity<Order>().ToTable($"App{nameof(this.Orders)}");
builder.Entity<Order>().ToTable($"App{nameof(Orders)}");
builder.Entity<Order>().Property(p => p.Discount).HasColumnType(priceDecimalType);

builder.Entity<OrderDetail>().ToTable($"App{nameof(this.OrderDetails)}");
builder.Entity<OrderDetail>().ToTable($"App{nameof(OrderDetails)}");
builder.Entity<OrderDetail>().Property(p => p.UnitPrice).HasColumnType(priceDecimalType);
builder.Entity<OrderDetail>().Property(p => p.Discount).HasColumnType(priceDecimalType);
}




public override int SaveChanges()
{
UpdateAuditEntities();
return base.SaveChanges();
}


public override int SaveChanges(bool acceptAllChangesOnSuccess)
{
UpdateAuditEntities();
return base.SaveChanges(acceptAllChangesOnSuccess);
}


public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
UpdateAuditEntities();
return base.SaveChangesAsync(cancellationToken);
}


public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default)
{
UpdateAuditEntities();
return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
}


private void UpdateAuditEntities()
{
var modifiedEntries = ChangeTracker.Entries()
.Where(x => x.Entity is IAuditableEntity && (x.State == EntityState.Added || x.State == EntityState.Modified));


foreach (var entry in modifiedEntries)
{
var entity = (IAuditableEntity)entry.Entity;
DateTime now = DateTime.UtcNow;
var now = DateTime.UtcNow;

if (entry.State == EntityState.Added)
{
Expand Down
55 changes: 11 additions & 44 deletions DAL/Core/AccountManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace DAL.Core
Expand All @@ -25,7 +24,6 @@ public class AccountManager : IAccountManager
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<ApplicationRole> _roleManager;


public AccountManager(
ApplicationDbContext context,
UserManager<ApplicationUser> userManager,
Expand All @@ -39,9 +37,6 @@ public AccountManager(

}




public async Task<ApplicationUser> GetUserByIdAsync(string userId)
{
return await _userManager.FindByIdAsync(userId);
Expand All @@ -62,7 +57,6 @@ public async Task<IList<string>> GetUserRolesAsync(ApplicationUser user)
return await _userManager.GetRolesAsync(user);
}


public async Task<(ApplicationUser User, string[] Roles)?> GetUserAndRolesAsync(string userId)
{
var user = await _context.Users
Expand All @@ -83,7 +77,6 @@ public async Task<IList<string>> GetUserRolesAsync(ApplicationUser user)
return (user, roles);
}


public async Task<List<(ApplicationUser User, string[] Roles)>> GetUsersAndRolesAsync(int page, int pageSize)
{
IQueryable<ApplicationUser> usersQuery = _context.Users
Expand All @@ -109,19 +102,17 @@ public async Task<IList<string>> GetUserRolesAsync(ApplicationUser user)
.ToList();
}


public async Task<(bool Succeeded, string[] Errors)> CreateUserAsync(ApplicationUser user, IEnumerable<string> roles, string password)
{
var result = await _userManager.CreateAsync(user, password);
if (!result.Succeeded)
return (false, result.Errors.Select(e => e.Description).ToArray());


user = await _userManager.FindByNameAsync(user.UserName);

try
{
result = await this._userManager.AddToRolesAsync(user, roles.Distinct());
result = await _userManager.AddToRolesAsync(user, roles.Distinct());
}
catch
{
Expand All @@ -138,20 +129,17 @@ public async Task<IList<string>> GetUserRolesAsync(ApplicationUser user)
return (true, new string[] { });
}


public async Task<(bool Succeeded, string[] Errors)> UpdateUserAsync(ApplicationUser user)
{
return await UpdateUserAsync(user, null);
}


public async Task<(bool Succeeded, string[] Errors)> UpdateUserAsync(ApplicationUser user, IEnumerable<string> roles)
{
var result = await _userManager.UpdateAsync(user);
if (!result.Succeeded)
return (false, result.Errors.Select(e => e.Description).ToArray());


if (roles != null)
{
var userRoles = await _userManager.GetRolesAsync(user);
Expand All @@ -177,10 +165,9 @@ public async Task<IList<string>> GetUserRolesAsync(ApplicationUser user)
return (true, new string[] { });
}


public async Task<(bool Succeeded, string[] Errors)> ResetPasswordAsync(ApplicationUser user, string newPassword)
{
string resetToken = await _userManager.GeneratePasswordResetTokenAsync(user);
var resetToken = await _userManager.GeneratePasswordResetTokenAsync(user);

var result = await _userManager.ResetPasswordAsync(user, resetToken, newPassword);
if (!result.Succeeded)
Expand Down Expand Up @@ -211,7 +198,6 @@ public async Task<bool> CheckPasswordAsync(ApplicationUser user, string password
return true;
}


public async Task<bool> TestCanDeleteUserAsync(string userId)
{
if (await _context.Orders.Where(o => o.CashierId == userId).AnyAsync())
Expand All @@ -222,7 +208,6 @@ public async Task<bool> TestCanDeleteUserAsync(string userId)
return true;
}


public async Task<(bool Succeeded, string[] Errors)> DeleteUserAsync(string userId)
{
var user = await _userManager.FindByIdAsync(userId);
Expand All @@ -233,30 +218,22 @@ public async Task<bool> TestCanDeleteUserAsync(string userId)
return (true, new string[] { });
}


public async Task<(bool Succeeded, string[] Errors)> DeleteUserAsync(ApplicationUser user)
{
var result = await _userManager.DeleteAsync(user);
return (result.Succeeded, result.Errors.Select(e => e.Description).ToArray());
}






public async Task<ApplicationRole> GetRoleByIdAsync(string roleId)
{
return await _roleManager.FindByIdAsync(roleId);
}


public async Task<ApplicationRole> GetRoleByNameAsync(string roleName)
{
return await _roleManager.FindByNameAsync(roleName);
}


public async Task<ApplicationRole> GetRoleLoadRelatedAsync(string roleName)
{
var role = await _context.Roles
Expand All @@ -269,7 +246,6 @@ public async Task<ApplicationRole> GetRoleLoadRelatedAsync(string roleName)
return role;
}


public async Task<List<ApplicationRole>> GetRolesLoadRelatedAsync(int page, int pageSize)
{
IQueryable<ApplicationRole> rolesQuery = _context.Roles
Expand All @@ -289,27 +265,23 @@ public async Task<List<ApplicationRole>> GetRolesLoadRelatedAsync(int page, int
return roles;
}


public async Task<(bool Succeeded, string[] Errors)> CreateRoleAsync(ApplicationRole role, IEnumerable<string> claims)
{
if (claims == null)
claims = new string[] { };
claims ??= new string[] { };

string[] invalidClaims = claims.Where(c => ApplicationPermissions.GetPermissionByValue(c) == null).ToArray();
var invalidClaims = claims.Where(c => ApplicationPermissions.GetPermissionByValue(c) == null).ToArray();
if (invalidClaims.Any())
return (false, new[] { "The following claim types are invalid: " + string.Join(", ", invalidClaims) });

return (false, new[] { $"The following claim types are invalid: {string.Join(", ", invalidClaims)}" });

var result = await _roleManager.CreateAsync(role);
if (!result.Succeeded)
return (false, result.Errors.Select(e => e.Description).ToArray());


role = await _roleManager.FindByNameAsync(role.Name);

foreach (string claim in claims.Distinct())
foreach (var claim in claims.Distinct())
{
result = await this._roleManager.AddClaimAsync(role, new Claim(ClaimConstants.Permission, ApplicationPermissions.GetPermissionByValue(claim)));
result = await _roleManager.AddClaimAsync(role, new Claim(ClaimConstants.Permission, ApplicationPermissions.GetPermissionByValue(claim)));

if (!result.Succeeded)
{
Expand All @@ -325,17 +297,15 @@ public async Task<List<ApplicationRole>> GetRolesLoadRelatedAsync(int page, int
{
if (claims != null)
{
string[] invalidClaims = claims.Where(c => ApplicationPermissions.GetPermissionByValue(c) == null).ToArray();
var invalidClaims = claims.Where(c => ApplicationPermissions.GetPermissionByValue(c) == null).ToArray();
if (invalidClaims.Any())
return (false, new[] { "The following claim types are invalid: " + string.Join(", ", invalidClaims) });
return (false, new[] { $"The following claim types are invalid: {string.Join(", ", invalidClaims)}" });
}


var result = await _roleManager.UpdateAsync(role);
if (!result.Succeeded)
return (false, result.Errors.Select(e => e.Description).ToArray());


if (claims != null)
{
var roleClaims = (await _roleManager.GetClaimsAsync(role)).Where(c => c.Type == ClaimConstants.Permission);
Expand All @@ -346,7 +316,7 @@ public async Task<List<ApplicationRole>> GetRolesLoadRelatedAsync(int page, int

if (claimsToRemove.Any())
{
foreach (string claim in claimsToRemove)
foreach (var claim in claimsToRemove)
{
result = await _roleManager.RemoveClaimAsync(role, roleClaims.Where(c => c.Value == claim).FirstOrDefault());
if (!result.Succeeded)
Expand All @@ -356,7 +326,7 @@ public async Task<List<ApplicationRole>> GetRolesLoadRelatedAsync(int page, int

if (claimsToAdd.Any())
{
foreach (string claim in claimsToAdd)
foreach (var claim in claimsToAdd)
{
result = await _roleManager.AddClaimAsync(role, new Claim(ClaimConstants.Permission, ApplicationPermissions.GetPermissionByValue(claim)));
if (!result.Succeeded)
Expand All @@ -368,13 +338,11 @@ public async Task<List<ApplicationRole>> GetRolesLoadRelatedAsync(int page, int
return (true, new string[] { });
}


public async Task<bool> TestCanDeleteRoleAsync(string roleId)
{
return !await _context.UserRoles.Where(r => r.RoleId == roleId).AnyAsync();
}


public async Task<(bool Succeeded, string[] Errors)> DeleteRoleAsync(string roleName)
{
var role = await _roleManager.FindByNameAsync(roleName);
Expand All @@ -385,7 +353,6 @@ public async Task<bool> TestCanDeleteRoleAsync(string roleId)
return (true, new string[] { });
}


public async Task<(bool Succeeded, string[] Errors)> DeleteRoleAsync(ApplicationRole role)
{
var result = await _roleManager.DeleteAsync(role);
Expand Down
Loading

0 comments on commit 6ce5a54

Please sign in to comment.