Mike Phares b586da5c82 Removed PdfViewController, HtmlViewRenderer and FakeView to be replaced with ViewEngineResult Render method
Added HttpException class for missing HttpException for net8

Wrapped HttpContext.Session, GetJsonResult, IsAjaxRequest and GetUserIdentityName in controllers for net8

Added AuthenticationService to test Fab2ApprovalMKLink code for net8

Compile conditionally flags to debug in dotnet core
2025-05-23 12:27:09 -07:00

150 lines
5.7 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Fab2ApprovalSystem.Models;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
namespace Fab2ApprovalSystem.Services;
public interface IUserService {
Task<IEnumerable<User>> GetAllActiveUsers();
Task<User> GetUserByLoginId(string loginId);
Task<User> GetUserByUserId(int userId);
Task<IEnumerable<int>> GetApproverUserIdsBySubRoleCategoryItem(string item);
}
public class UserService : IUserService {
private readonly ILogger<UserService> _logger;
private readonly IDalService _dalService;
private readonly IMemoryCache _cache;
public UserService(ILogger<UserService> logger, IDalService dalService, IMemoryCache cache) {
_logger = logger ??
throw new ArgumentNullException("ILogger not injected");
_dalService = dalService ??
throw new ArgumentNullException("IDalService not injected");
_cache = cache ??
throw new ArgumentNullException("IMemoryCache not injected");
}
public async Task<IEnumerable<User>> GetAllActiveUsers() {
try {
_logger.LogInformation("Attempting to get all active users");
IEnumerable<User>? allActiveUsers = _cache.Get<IEnumerable<User>>("allActiveUsers");
if (allActiveUsers is null) {
string sql = "select * from Users where IsActive = 1";
allActiveUsers = (await _dalService.QueryAsync<User>(sql)).ToList();
_cache.Set("allActiveUsers", allActiveUsers, DateTimeOffset.Now.AddHours(1));
}
if (allActiveUsers is null || allActiveUsers.Count() == 0) {
throw new Exception("No users found");
}
return allActiveUsers;
} catch (Exception ex) {
string errMsg = $"An exception occurred when attempting to get all users. Exception: {ex.Message}";
_logger.LogError(errMsg);
throw;
}
}
public async Task<User> GetUserByLoginId(string loginId) {
try {
_logger.LogInformation("Attempting to get user by LoginId");
if (string.IsNullOrWhiteSpace(loginId))
throw new ArgumentException("LoginId cannot be null or empty");
User? user = _cache.Get<User>($"userByLoginId{loginId}");
user ??= _cache.Get<IEnumerable<User>>("allActiveUsers")?.FirstOrDefault(u => u.LoginID == loginId);
if (user is null) {
string sql = $"select * from Users where LoginID = '{loginId}';";
user = (await _dalService.QueryAsync<User>(sql)).FirstOrDefault();
_cache.Set($"userByLoginId{loginId}", user, DateTimeOffset.Now.AddHours(1));
}
if (user is null) throw new Exception($"No user found with LoginID {loginId}");
return user;
} catch (Exception ex) {
string errMsg = $"An exception occurred when attempting to get user for LoginID {loginId}. Exception: {ex.Message}";
_logger.LogError(errMsg);
throw;
}
}
public async Task<User> GetUserByUserId(int userId) {
try {
_logger.LogInformation("Attempting to get user by user ID");
if (userId <= 0) throw new ArgumentException($"{userId} is not a valid user ID");
User? user = _cache.Get<User>($"userByUserId{userId}");
user ??= _cache.Get<IEnumerable<User>>("allActiveUsers")?.FirstOrDefault(u => u.UserID == userId);
if (user is null) {
string sql = $"select * from Users where UserID = '{userId}';";
user = (await _dalService.QueryAsync<User>(sql)).FirstOrDefault();
_cache.Set($"userByUserId{userId}", user, DateTimeOffset.Now.AddHours(1));
}
if (user is null) throw new Exception($"No user found with UserID {userId}");
return user;
} catch (Exception ex) {
string errMsg = $"An exception occurred when attempting to get user for UserID {userId}. Exception: {ex.Message}";
_logger.LogError(errMsg);
throw;
}
}
public async Task<IEnumerable<int>> GetApproverUserIdsBySubRoleCategoryItem(string item) {
try {
_logger.LogInformation("Attempting to get approver user IDs");
if (string.IsNullOrWhiteSpace(item)) throw new ArgumentException("SubRoleCategoryItem cannot be null or empty");
IEnumerable<int>? userIds = _cache.Get<IEnumerable<int>>($"approverUserIdsBySubRollCategory{item}");
if (userIds is null) {
StringBuilder queryBuilder = new();
queryBuilder.Append("select us.UserID ");
queryBuilder.Append("from SubRole as sr ");
queryBuilder.Append("join UserSubRole as us on sr.SubRoleID=us.SubRoleID ");
queryBuilder.Append("join SubRoleCategory as sc on sr.SubRoleCategoryID=sc.SubRoleCategoryID ");
queryBuilder.Append($"where sc.SubRoleCategoryItem='{item}'");
userIds = (await _dalService.QueryAsync<int>(queryBuilder.ToString())).ToList();
_cache.Set($"approverUserIdsBySubRollCategory{item}", userIds, DateTimeOffset.Now.AddHours(1));
}
if (userIds is null || userIds.Count() == 0) {
throw new Exception($"No users found for SubRoleCategoryItem {item}");
}
return userIds;
} catch (Exception ex) {
string errMsg = $"An exception occurred when attempting to get approver user IDs. Exception: {ex.Message}";
_logger.LogError(errMsg);
throw;
}
}
}