Mike Phares 83789cdd91 Added ControllerExtensions to be used instead of HtmlViewRenderer for net8
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-19 13:29:54 -07:00

459 lines
14 KiB
C#

using System;
using System.Collections.Generic;
#if !NET8
using System.Web;
using System.Web.Mvc;
#endif
#if NET8
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
#endif
using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Misc;
using Fab2ApprovalSystem.Models;
#if !NET8
using System.Linq;
using Fab2ApprovalSystem.ViewModels;
#endif
#if !NET8
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
#endif
namespace Fab2ApprovalSystem.Controllers;
[Authorize]
#if !NET8
[SessionExpireFilter]
#endif
#if NET8
[Route("[controller]")]
#endif
public class AdminController : Controller {
// GET: /Admin/
private readonly UserAccountDMO userDMO = new();
private readonly AdminDMO adminDMO = new();
private readonly TrainingDMO trainingDMO = new();
private readonly LotDispositionDMO ldDMO = new();
private readonly AppSettings? _AppSettings = GlobalVars.AppSettings;
public ActionResult Index() {
if (GlobalVars.IsAdmin(GetSession())) {
var model = userDMO.GetAllUsers();
ViewBag.AllActiveUsers = userDMO.GetAllActiveUsers();
return View(model);
} else
return Content("Not Autthorized");
}
#if !NET8
public ActionResult AssignRoles() {
if (GlobalVars.IsAdmin(GetSession())) {
ViewBag.ToplevelNode = GetRoles_SubRolesList();
return View();
} else
return Content("Not Autthorized");
}
public ActionResult GetAllUserList([DataSourceRequest] DataSourceRequest request) {
IEnumerable<LoginModel> userlist = userDMO.GetAllActiveUsers();
return GetJsonResult(userlist);
}
public ActionResult GetGridUserList([DataSourceRequest] DataSourceRequest request) {
return GetJsonResult(userDMO.GetAllUsers().ToDataSourceResult(request));
}
#endif
public JsonResult GetAllUserListBySubRole(int subRole) {
IEnumerable<LoginModel> userlist = adminDMO.GetAllUsersBySubRole(subRole);
return GetJsonResult(userlist);
}
public JsonResult AllSubRoles(string showInactiveRoles = "") {
List<ParentChildModel> newRoles = adminDMO.GetAllSubRoles(showInactiveRoles);
return GetJsonResult(newRoles);
}
#if !NET8
public ActionResult GetSubRoleListByUserId([DataSourceRequest] DataSourceRequest request, string userId) {
int userIdInt = Convert.ToInt32(userId);
return Json(adminDMO.GetUserSubRoles(userIdInt).ToDataSourceResult(request));
}
private IEnumerable<TreeViewItemModel> GetRoles_SubRolesList() {
List<Role> roles = adminDMO.GetSubRoles();
List<TreeViewItemModel> ToplevelNode = new List<TreeViewItemModel>();
List<TreeViewItemModel> parentList = new List<TreeViewItemModel>();
List<TreeViewItemModel> childList = new List<TreeViewItemModel>();
TreeViewItemModel parent = new TreeViewItemModel();
TreeViewItemModel child = new TreeViewItemModel();
foreach (Role r in roles) {
parent = new TreeViewItemModel();
parent.HasChildren = true;
parent.Text = r.RoleName;
parent.Id = r.RoleID.ToString();
foreach (SubRole sr in r.SubRoles) {
child = new TreeViewItemModel();
child.Text = sr.SubRoleCategoryItem;
child.Id = sr.SubRoleID.ToString();
parent.Items.Add(child);
}
ToplevelNode.Add(parent);
};
return ToplevelNode;
}
#endif
public ActionResult AddUserRoles(int subRole, string users) {
adminDMO.AddUserRoles(subRole, users);
return View();
}
public ActionResult ReplaceUserRoles(int subRole, string users) {
adminDMO.AddUserRoles(subRole, users);
return Content("Success");
}
public ActionResult DeleteUserRoles(int subRole, string users) {
adminDMO.DeleteUserRoles(subRole, users);
return Content("");
}
// GET: /Workflow/Details/5
public ActionResult Details(int id) {
return View();
}
// GET: /Workflow/Create
public ActionResult Create() {
return View();
}
#if !NET8
// POST: /Workflow/Create
[HttpPost]
public ActionResult Create(FormCollection collection) {
try {
// TODO: Add insert logic here
return RedirectToAction("Index");
} catch {
return View();
}
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult BatchUpdateUser([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")] IEnumerable<LoginModel> model) {
return Json(new[] { model }.ToDataSourceResult(request, ModelState));
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UpdateUser([DataSourceRequest] DataSourceRequest request, LoginModel model) {
if (model != null && ModelState.IsValid) {
userDMO.UpdateUser(model);
}
return Json(new[] { model }.ToDataSourceResult(request, ModelState));
}
#endif
public ActionResult DeleteUser(string userId) {
LoginModel loginModel = userDMO.GetUserByID(Convert.ToInt32(userId));
adminDMO.DeleteUser(userDMO, trainingDMO, loginModel);
return Content("Success");
}
#if !NET8
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult InsertUser([DataSourceRequest] DataSourceRequest request, LoginModel model) {
try {
if (model != null && ModelState.IsValid) {
userDMO.InsertUser(model);
}
} catch (Exception ex) {
// TODO
throw new Exception(ex.Message);
}
return Json(new[] { model }.ToDataSourceResult(request, ModelState));
}
#endif
public ActionResult EnableOOOStatus(int oooUserID, int delegatedTo, DateTime startDate, DateTime endDate) {
int returnValue = MiscDMO.EnableOOOStatus(oooUserID, delegatedTo, startDate, endDate);
if (returnValue == 3) // the delegator is already a delegator to someone else
{
return Content("3");
} else
return Content("");
// TODO - Send an email to the OOO person and to the Delegated person
}
public void ExpireOOOStatus(int oooUserID) {
MiscDMO.ExpireOOOStatus(oooUserID);
// TODO - Does it need to send an email
}
public ActionResult ManageTrainingGroups() {
if (GlobalVars.IsAdmin(GetSession())) {
ViewBag.AllGroups = GetTrainingGroups();
return View();
} else
return Content("Not Autthorized");
}
public void RefreshGroups() {
ViewBag.AllGroups = GetTrainingGroups();
}
public ActionResult TrainingGroups() {
List<TrainingGroup> trainingGroups = adminDMO.GetTrainingGroups();
return PartialView(trainingGroups);
}
public List<TrainingGroup> GetTrainingGroups() {
List<TrainingGroup> TrainingGroups = adminDMO.GetTrainingGroups();
return TrainingGroups;
}
#if !NET8
public ActionResult GetTaskListByUser([DataSourceRequest] DataSourceRequest request, string userId) {
IEnumerable<IssuesViewModel> data = ldDMO.GetTaskList(Convert.ToInt32(userId));
data = from a in data where a.PendingApprovers != null select a;
return GetJsonResult(data.ToDataSourceResult(request));
}
public ActionResult GetOpenActionItemsByUser([DataSourceRequest] DataSourceRequest request, string userId) {
IEnumerable<OpenActionItemViewModel> data = ldDMO.GetMyOpenActionItems(Convert.ToInt32(userId));
return GetJsonResult(data.ToDataSourceResult(request));
}
public ActionResult AddNewTrainingGroup(string groupName) {
try {
adminDMO.AddNewTrainingGroup(groupName);
return Json(new { test = "Succesfully saved" });
} catch {
return Content("Unable to Save Group", "application/json");
}
}
#endif
public ActionResult DeleteTrainingGroup(int groupID) {
try {
adminDMO.DeleteTrainingGroup(groupID);
return Json(new { response = "Successfully Deleted" });
} catch {
return Json(new { response = "Unsuccessfully Deleted" });
}
}
public ActionResult ViewTrainingGroup(int TrainingGroupID) {
ViewBag.GroupID = TrainingGroupID;
return View();
}
#if !NET8
public ActionResult TrainingGroupPartial(int TrainingGroupID) {
ViewBag.AllUsers = userDMO.GetAllActiveUsers();
ViewBag.TrainingGroupId = TrainingGroupID;
List<TrainingGroupMember> trainingGroupMembers = adminDMO.GetTrainingGroupMembers(TrainingGroupID);
return PartialView(trainingGroupMembers);
}
public ActionResult AddToGroup(int userId, int groupId) {
try {
adminDMO.AddUserToGroup(userId, groupId);
} catch (Exception e) {
return Json(new { test = e.Message });
}
return Json(new { test = "Succesfully saved" });
}
#endif
public ActionResult DeleteFromGroup(int userId, int groupId) {
try {
adminDMO.DeleteFromGroup(userId, groupId);
} catch (Exception e) {
return Json(new { test = e.Message });
}
return Json(new { test = "Succesfully removed" });
}
public ActionResult JobSchedulerConfiguration() {
if (GlobalVars.IsAdmin(GetSession())) {
return View();
} else
return Content("Not Autthorized");
}
public ActionResult TrainingReportConfig() {
ViewBag.AllUsers = userDMO.GetAllActiveUsers();
List<TrainingReportUser> currentTrainingReportUsersIds = adminDMO.GetTrainingReportUsers();
List<LoginModel> currentTrainingReportUsers = new();
foreach (TrainingReportUser id in currentTrainingReportUsersIds) {
currentTrainingReportUsers.Add(userDMO.GetUserByID(id.UserId));
}
ViewBag.CurrentReportUsers = currentTrainingReportUsers;
return PartialView();
}
#if !NET8
public ActionResult TECNNotificationConfig() {
ViewBag.AllUsers = userDMO.GetAllActiveUsers();
List<TECNNotificationsUser> currentTECNNotificationUsersIds = adminDMO.GetTECNNotificationUsers();
List<LoginModel> currentTECNNotificationUsers = new();
foreach (TECNNotificationsUser id in currentTECNNotificationUsersIds) {
currentTECNNotificationUsers.Add(userDMO.GetUserByID(id.UserId));
}
ViewBag.CurrentReportUsers = currentTECNNotificationUsers;
return PartialView();
}
#endif
public ActionResult AddToTrainingReport(int userId) {
if (GlobalVars.IsAdmin(GetSession())) {
// Check to make sure user is not apart of the group already
bool userExists = false;
List<TrainingReportUser> existingUsers = adminDMO.GetTrainingReportUsers();
foreach (var item in existingUsers) {
if (item.UserId == userId) {
userExists = true;
}
}
// Check if user is valid
var validUser = userDMO.GetUserByID(userId);
// Add to group
if (!userExists && validUser != null) {
adminDMO.TrainingReportAddUser(userId);
return Json("Success Added");
} else {
return Content("User either doesn't exist OR is already added");
}
} else {
return Content("Not Autthorized");
}
}
#if !NET8
public ActionResult AddToTECNNotification(int userId) {
if (GlobalVars.IsAdmin(GetSession())) {
// Check to make sure user is not apart of the group already
bool userExists = false;
List<TECNNotificationsUser> existingUsers = adminDMO.GetTECNNotificationUsers();
foreach (var item in existingUsers) {
if (item.UserId == userId) {
userExists = true;
}
}
// Check if user is valid
var validUser = userDMO.GetUserByID(userId);
// Add to group
if (!userExists && validUser != null) {
try {
adminDMO.TECNExpirationAddUser(userId);
} catch (Exception e) {
string exception = e.Message;
return Content(exception);
}
return Json("Success Added");
} else {
return Content("User either doesn't exist OR is already added");
}
} else {
return Content("Not Autthorized");
}
}
#endif
public ActionResult DeleteFromTrainingReport(int userId) {
if (GlobalVars.IsAdmin(GetSession())) {
try {
adminDMO.TrainingReportDeleteUser(userId);
return Content("Successfully Deleted");
} catch {
return Content("Error while trying to delete");
}
} else {
return Content("Not Autthorized");
}
}
public ActionResult DeleteFromTECNNotification(int userId) {
if (GlobalVars.IsAdmin(GetSession())) {
try {
adminDMO.TECNExpirationDeleteUser(userId);
return Content("Successfully Deleted");
} catch {
return Content("Error while trying to delete");
}
} else {
return Content("Not Autthorized");
}
}
#if !NET8
private System.Web.HttpSessionStateBase GetSession() =>
Session;
private JsonResult GetJsonResult(object? data) =>
Json(data, JsonRequestBehavior.AllowGet);
private bool IsAjaxRequest() =>
Request.IsAjaxRequest();
#endif
#if NET8
private Microsoft.AspNetCore.Http.ISession GetSession() =>
HttpContext.Session;
private JsonResult GetJsonResult(object? data) =>
Json(data);
private bool IsAjaxRequest() =>
Request.Headers.TryGetValue("X-Requested-With", out Microsoft.Extensions.Primitives.StringValues strings) && strings[0] == "XMLHttpRequest";
#endif
private string GetUserIdentityName() =>
@User.Identity.Name;
}