From 4f0102ca8ecd69cb6f96abad7eb769927400bd84 Mon Sep 17 00:00:00 2001 From: Mike Phares Date: Thu, 22 May 2025 13:35:27 -0700 Subject: [PATCH] dont --- .gitignore | 29 +- .vscode/launch.json | 42 ++ .vscode/tasks.json | 16 +- Fab2ApprovalMKLink/.vscode/mklink.md | 42 +- .../Extensions/ControllerExtensions.cs | 74 +++ Fab2ApprovalMKLink/Fab2ApprovalMKLink.csproj | 1 + Fab2ApprovalMKLink/Program.cs | 57 ++ .../Services/AuthenticationService.cs | 266 ++++++++ Fab2ApprovalMKLink/Services/DalService.cs | 168 +++++ .../Services/DbConnectionService.cs | 22 + Fab2ApprovalMKLink/Services/UserService.cs | 150 +++++ Fab2ApprovalMKLink/Views/_ViewImports.cshtml | 8 + Fab2ApprovalMKLink/Views/_ViewStart.cshtml | 3 + Fab2ApprovalSystem/App_Start/FilterConfig.cs | 2 + Fab2ApprovalSystem/App_Start/RouteConfig.cs | 4 + Fab2ApprovalSystem/App_Start/WebApiConfig.cs | 2 + .../Controllers/AccountController.cs | 136 +++- .../Controllers/AdminController.cs | 128 +++- .../Controllers/AuditController.cs | 123 +++- .../Controllers/ChangeControlController.cs | 186 ++++-- .../Controllers/CorrectiveActionController.cs | 317 +++++---- .../Controllers/ECNController.cs | 493 ++++++++------ .../Controllers/HomeController.cs | 208 +++--- .../Controllers/LotDispositionController.cs | 321 ++++++---- .../Controllers/LotTravelerController.cs | 604 +++++++++++------- .../Controllers/MRBController.cs | 242 ++++--- .../Controllers/ManagerController.cs | 62 +- .../Controllers/PCRBController.cs | 48 +- .../Controllers/PartsRequestController.cs | 185 ++++-- .../Controllers/ReportsController.cs | 101 ++- .../Controllers/TrainingController.cs | 100 ++- .../Controllers/WebAPIController.cs | 43 +- .../Controllers/WorkflowController.cs | 60 +- Fab2ApprovalSystem/DMO/AdminDMO.cs | 16 +- Fab2ApprovalSystem/DMO/TrainingDMO.cs | 127 +++- Fab2ApprovalSystem/Fab2ApprovalSystem.csproj | 1 + Fab2ApprovalSystem/Global.asax.cs | 21 +- Fab2ApprovalSystem/Misc/ExcelData.cs | 8 +- Fab2ApprovalSystem/Misc/GlobalVars.cs | 271 +++++++- .../Misc/SessionExpireFilterAttribute.cs | 4 +- Fab2ApprovalSystem/Models/AppSettings.cs | 15 + Fab2ApprovalSystem/Models/HttpException.cs | 37 ++ Fab2ApprovalSystem/Models/LoginResult.cs | 1 + Fab2ApprovalSystem/Models/User.cs | 30 + .../PdfGenerator/BinaryContentResult.cs | 70 +- Fab2ApprovalSystem/PdfGenerator/FakeView.cs | 48 +- .../PdfGenerator/HtmlViewRenderer.cs | 100 +-- .../PdfGenerator/PdfViewController.cs | 76 +-- .../PdfGenerator/PrintHeaderFooter.cs | 147 +++-- .../PdfGenerator/StandardPdfRenderer.cs | 3 - Fab2ApprovalSystem/Utilities/FileUtilities.cs | 13 +- .../Views/Admin/_AdminLayout.cshtml | 2 +- .../Views/ChangeControl/Edit.cshtml | 4 +- .../ChangeControl/EditMeetingUpdate.cshtml | 2 +- .../Views/ChangeControl/ReadOnlyCC.cshtml | 2 +- .../Views/CorrectiveAction/Edit.cshtml | 6 +- .../Views/CorrectiveAction/ReadOnlyCA.cshtml | 2 +- .../Views/ECN/Acknowledge.cshtml | 8 +- .../Views/ECN/ECNTrainingView.cshtml | 2 +- Fab2ApprovalSystem/Views/ECN/Edit.cshtml | 6 +- .../Views/ECN/EditApproval.cshtml | 10 +- Fab2ApprovalSystem/Views/ECN/ReadOnly.cshtml | 10 +- .../Views/Home/AllDocuments.cshtml | 2 +- .../Views/Home/CorrectiveActionList.cshtml | 2 +- Fab2ApprovalSystem/Views/Home/ECNList.cshtml | 2 +- Fab2ApprovalSystem/Views/Home/Index.cshtml | 10 +- .../Views/Home/LotDispositionList.cshtml | 2 +- Fab2ApprovalSystem/Views/Home/MRBList.cshtml | 6 +- Fab2ApprovalSystem/Views/Home/MyTasks.cshtml | 2 +- .../Views/Home/_HomeLayout.cshtml | 22 +- .../Views/LotDisposition/Create.cshtml | 4 +- .../Views/LotDisposition/Edit.cshtml | 4 +- .../Views/LotDisposition/EditStep.cshtml | 2 +- .../Views/LotTraveler/Edit.cshtml | 6 +- .../LotTraveler/LotTravelerExecute.cshtml | 2 +- .../LotTraveler/LotTravelerReadOnly.cshtml | 2 +- .../LotTraveler/LotTravelerUpdate.cshtml | 2 +- .../LotTraveler/WorkRequestApproval.cshtml | 8 +- .../LotTraveler/WorkRequestReadOnly.cshtml | 2 +- .../LotTraveler/WorkRequestRevision.cshtml | 26 +- .../_HoldStepAttachmentsRevision.cshtml | 2 +- Fab2ApprovalSystem/Views/MRB/Edit.cshtml | 2 +- .../Views/Manager/_ManagerLayout.cshtml | 2 +- .../Views/Shared/_Layout.cshtml | 4 +- .../Training/ViewTrainingAssignments.cshtml | 10 +- .../Views/Training/ViewTrainingPartial.cshtml | 2 +- .../Views/Training/ViewTrainings.cshtml | 2 +- Fab2ApprovalSystem/pipelines-manual.yml | 2 + Fab2ApprovalSystem/pipelines.yml | 2 + .../DMO/EngChangeNoticeDMOTests.cs | 10 +- 90 files changed, 3971 insertions(+), 1458 deletions(-) create mode 100644 Fab2ApprovalMKLink/Extensions/ControllerExtensions.cs create mode 100644 Fab2ApprovalMKLink/Services/AuthenticationService.cs create mode 100644 Fab2ApprovalMKLink/Services/DalService.cs create mode 100644 Fab2ApprovalMKLink/Services/DbConnectionService.cs create mode 100644 Fab2ApprovalMKLink/Services/UserService.cs create mode 100644 Fab2ApprovalMKLink/Views/_ViewImports.cshtml create mode 100644 Fab2ApprovalMKLink/Views/_ViewStart.cshtml create mode 100644 Fab2ApprovalSystem/Models/HttpException.cs create mode 100644 Fab2ApprovalSystem/Models/User.cs diff --git a/.gitignore b/.gitignore index a460c74..8a36456 100644 --- a/.gitignore +++ b/.gitignore @@ -351,9 +351,36 @@ ASALocalRun/ /Fab2ApprovalMKLink/Utilities /Fab2ApprovalMKLink/ViewModels +/Fab2ApprovalMKLink/Views/Account +/Fab2ApprovalMKLink/Views/Admin +/Fab2ApprovalMKLink/Views/Audit +/Fab2ApprovalMKLink/Views/ChangeControl +/Fab2ApprovalMKLink/Views/CorrectiveAction +/Fab2ApprovalMKLink/Views/ECN +/Fab2ApprovalMKLink/Views/Home +/Fab2ApprovalMKLink/Views/LotDisposition +/Fab2ApprovalMKLink/Views/LotTraveler +/Fab2ApprovalMKLink/Views/Manager +/Fab2ApprovalMKLink/Views/MRB +/Fab2ApprovalMKLink/Views/PartsRequest +/Fab2ApprovalMKLink/Views/Reports +/Fab2ApprovalMKLink/Views/Shared +/Fab2ApprovalMKLink/Views/Training +/Fab2ApprovalMKLink/Views/Workflow + /Fab2ApprovalMKLink/.vscode/.UserSecrets /Fab2ApprovalSystem/.vscode/.UserSecrets /Fab2ApprovalTests/.vscode/.UserSecrets /MesaFabApproval.API/.vscode/.UserSecrets /MesaFabApproval.Client/.vscode/.UserSecrets -/MesaFabApproval.Shared/.vscode/.UserSecrets \ No newline at end of file +/MesaFabApproval.Shared/.vscode/.UserSecrets + +fab-001 +fab-002 +fab-004 +fab-004 +fab-005 +fab-006 +fab-007 +fab-008 +fab-009 \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json index 7249802..a8097f9 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -15,6 +15,48 @@ "console": "integratedTerminal", "stopAtEntry": false }, + { + "name": ".NET Core Launch (web) - Fab2ApprovalMKLink", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "Fab2ApprovalMKLink-build", + "program": "${workspaceFolder}/Fab2ApprovalMKLink/bin/Debug/net8.0/Fab2ApprovalMKLink.dll", + "args": [], + "cwd": "${workspaceFolder}", + "stopAtEntry": false, + "serverReadyAction": { + "action": "openExternally", + "pattern": "\\bNow listening on:\\s+(https?://\\S+)", + "uriFormat": "%s/swagger/index.html" + }, + "env": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "sourceFileMap": { + "/Views": "${workspaceFolder}/Views" + } + }, + { + "name": ".NET Core Launch (web) - fab-004", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "fab-004-build", + "program": "${workspaceFolder}/fab-004/bin/net8.0/fab-004.dll", + "args": [], + "cwd": "${workspaceFolder}", + "stopAtEntry": false, + "serverReadyAction": { + "action": "openExternally", + "pattern": "\\bNow listening on:\\s+(https?://\\S+)", + "uriFormat": "%s/swagger/index.html" + }, + "env": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "sourceFileMap": { + "/Views": "${workspaceFolder}/Views" + } + }, { "name": ".NET Core Launch (console) - MesaFabApproval.API", "type": "coreclr", diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 1f0acfb..e582a29 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -63,6 +63,7 @@ "type": "process", "args": [ "format", + "${workspaceFolder}/Fab2ApprovalMKLink/Fab2ApprovalMKLink.csproj", "--report", ".vscode", "--verbosity", @@ -78,7 +79,8 @@ "type": "process", "args": [ "format", - "whitespace" + "whitespace", + "${workspaceFolder}/Fab2ApprovalMKLink/Fab2ApprovalMKLink.csproj" ], "problemMatcher": "$msCompile" }, @@ -94,6 +96,18 @@ ], "problemMatcher": "$msCompile" }, + { + "label": "fab-004-build", + "command": "dotnet", + "type": "process", + "args": [ + "build", + "${workspaceFolder}/fab-004/fab-004.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, { "label": "Fab2ApprovalMKLink-publish", "command": "dotnet", diff --git a/Fab2ApprovalMKLink/.vscode/mklink.md b/Fab2ApprovalMKLink/.vscode/mklink.md index 4d88833..188097c 100644 --- a/Fab2ApprovalMKLink/.vscode/mklink.md +++ b/Fab2ApprovalMKLink/.vscode/mklink.md @@ -36,14 +36,36 @@ mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\Jobs" "L:\DevOps mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\JobSchedules" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\JobSchedules" ``` -```bash 1734015544321 = 638696123443210000 = Thu Dec 12 2024 07:59:03 GMT-0700 (Mountain Standard Time) -mklink /J ".vscode\.UserSecrets" "%AppData%\Microsoft\UserSecrets\f2da5035-aba9-4676-9f8d-d6689f84663d" -mklink /J "DMO" "..\Fab2ApprovalSystem\DMO" -mklink /J "Jobs" "..\Fab2ApprovalSystem\Jobs" -mklink /J "JobSchedules" "..\Fab2ApprovalSystem\JobSchedules" -mklink /J "Misc" "..\Fab2ApprovalSystem\Misc" -mklink /J "Models" "..\Fab2ApprovalSystem\Models" -mklink /J "PdfGenerator" "..\Fab2ApprovalSystem\PdfGenerator" -mklink /J "Utilities" "..\Fab2ApprovalSystem\Utilities" -mklink /J "ViewModels" "..\Fab2ApprovalSystem\ViewModels" +```bash 1747242128286 = 638828389282860000 = 2025-2.Spring = Wed May 14 2025 10:02:07 GMT-0700 (Mountain Standard Time) +mklink /J "Fab2ApprovalMKLink\.vscode\.UserSecrets" "%AppData%\Microsoft\UserSecrets\f2da5035-aba9-4676-9f8d-d6689f84663d" +mklink /J "Fab2ApprovalMKLink\Controllers" "Fab2ApprovalSystem\Controllers" +mklink /J "Fab2ApprovalMKLink\DMO" "Fab2ApprovalSystem\DMO" +mklink /J "Fab2ApprovalMKLink\Jobs" "Fab2ApprovalSystem\Jobs" +mklink /J "Fab2ApprovalMKLink\JobSchedules" "Fab2ApprovalSystem\JobSchedules" +mklink /J "Fab2ApprovalMKLink\Misc" "Fab2ApprovalSystem\Misc" +mklink /J "Fab2ApprovalMKLink\Models" "Fab2ApprovalSystem\Models" +mklink /J "Fab2ApprovalMKLink\PdfGenerator" "Fab2ApprovalSystem\PdfGenerator" +mklink /J "Fab2ApprovalMKLink\Utilities" "Fab2ApprovalSystem\Utilities" +mklink /J "Fab2ApprovalMKLink\ViewModels" "Fab2ApprovalSystem\ViewModels" +mklink /J "Fab2ApprovalMKLink\ViewModels" "Fab2ApprovalSystem\ViewModels" +``` + +```bash 1747249935803 = 638828467358030000 = 2025-2.Spring = Wed May 14 2025 12:12:15 GMT-0700 (Mountain Standard Time) +mkdir "Fab2ApprovalMKLink\Views" +mklink /J "Fab2ApprovalMKLink\Views\Account" "Fab2ApprovalSystem\Views\Account" +mklink /J "Fab2ApprovalMKLink\Views\Admin" "Fab2ApprovalSystem\Views\Admin" +mklink /J "Fab2ApprovalMKLink\Views\Audit" "Fab2ApprovalSystem\Views\Audit" +mklink /J "Fab2ApprovalMKLink\Views\ChangeControl" "Fab2ApprovalSystem\Views\ChangeControl" +mklink /J "Fab2ApprovalMKLink\Views\CorrectiveAction" "Fab2ApprovalSystem\Views\CorrectiveAction" +mklink /J "Fab2ApprovalMKLink\Views\ECN" "Fab2ApprovalSystem\Views\ECN" +mklink /J "Fab2ApprovalMKLink\Views\Home" "Fab2ApprovalSystem\Views\Home" +mklink /J "Fab2ApprovalMKLink\Views\LotDisposition" "Fab2ApprovalSystem\Views\LotDisposition" +mklink /J "Fab2ApprovalMKLink\Views\LotTraveler" "Fab2ApprovalSystem\Views\LotTraveler" +mklink /J "Fab2ApprovalMKLink\Views\Manager" "Fab2ApprovalSystem\Views\Manager" +mklink /J "Fab2ApprovalMKLink\Views\MRB" "Fab2ApprovalSystem\Views\MRB" +mklink /J "Fab2ApprovalMKLink\Views\PartsRequest" "Fab2ApprovalSystem\Views\PartsRequest" +mklink /J "Fab2ApprovalMKLink\Views\Reports" "Fab2ApprovalSystem\Views\Reports" +mklink /J "Fab2ApprovalMKLink\Views\Shared" "Fab2ApprovalSystem\Views\Shared" +mklink /J "Fab2ApprovalMKLink\Views\Training" "Fab2ApprovalSystem\Views\Training" +mklink /J "Fab2ApprovalMKLink\Views\Workflow" "Fab2ApprovalSystem\Views\Workflow" ``` diff --git a/Fab2ApprovalMKLink/Extensions/ControllerExtensions.cs b/Fab2ApprovalMKLink/Extensions/ControllerExtensions.cs new file mode 100644 index 0000000..f0c8ac7 --- /dev/null +++ b/Fab2ApprovalMKLink/Extensions/ControllerExtensions.cs @@ -0,0 +1,74 @@ +#if NET8 + +using System; +using System.IO; +using System.Threading.Tasks; + +using Fab2ApprovalSystem.PdfGenerator; + +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Rendering; +using Microsoft.AspNetCore.Mvc.ViewEngines; +using Microsoft.AspNetCore.Mvc.ViewFeatures; +using Microsoft.Extensions.DependencyInjection; + +namespace Fab2ApprovalSystem.Extensions; + +public static class ControllerExtensions { + + public static ActionResult GetBinaryContentResult(this Controller controller, string viewName, string contentType, TModel model) { + string pageTitle = string.Empty; + + string htmlText = RenderViewToString(controller, viewName, model); + + StandardPdfRenderer standardPdfRenderer = new(); + // Let the html be rendered into a PDF document through iTextSharp. + byte[] buffer = standardPdfRenderer.Render(htmlText, pageTitle); + + // Return the PDF as a binary stream to the client. + return new BinaryContentResult(buffer, contentType); + } + + public static string RenderViewToString(this Controller controller, string viewName, TModel model) { + if (string.IsNullOrEmpty(viewName)) + viewName = controller.ControllerContext.ActionDescriptor.ActionName; + + controller.ViewData.Model = model; + + using (StringWriter writer = new()) { + try { + CompositeViewEngine compositeViewEngine = controller.HttpContext.RequestServices.GetRequiredService(typeof(ICompositeViewEngine)) as CompositeViewEngine; + if (compositeViewEngine is null || compositeViewEngine.ViewEngines.Count == 0) { } + + ViewEngineResult viewResult = null; + + if (viewName.EndsWith(".cshtml")) + viewResult = compositeViewEngine.GetView(viewName, viewName, false); + else + viewResult = compositeViewEngine.FindView(controller.ControllerContext, viewName, false); + + if (!viewResult.Success) + return $"A view with the name '{viewName}' could not be found"; + + ViewContext viewContext = new( + controller.ControllerContext, + viewResult.View, + controller.ViewData, + controller.TempData, + writer, + new HtmlHelperOptions() + ); + + Task task = viewResult.View.RenderAsync(viewContext); + task.Wait(); + + return writer.GetStringBuilder().ToString(); + } catch (Exception ex) { + return $"Failed - {ex.Message}"; + } + } + } + +} + +#endif \ No newline at end of file diff --git a/Fab2ApprovalMKLink/Fab2ApprovalMKLink.csproj b/Fab2ApprovalMKLink/Fab2ApprovalMKLink.csproj index c054aa7..bb8ff55 100644 --- a/Fab2ApprovalMKLink/Fab2ApprovalMKLink.csproj +++ b/Fab2ApprovalMKLink/Fab2ApprovalMKLink.csproj @@ -30,6 +30,7 @@ + diff --git a/Fab2ApprovalMKLink/Program.cs b/Fab2ApprovalMKLink/Program.cs index 381e519..7f60280 100644 --- a/Fab2ApprovalMKLink/Program.cs +++ b/Fab2ApprovalMKLink/Program.cs @@ -1,15 +1,23 @@ using System; using System.Diagnostics; +using System.Text; +using Fab2ApprovalSystem.Misc; using Fab2ApprovalSystem.Models; +using Fab2ApprovalSystem.Services; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.ViewEngines; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting.WindowsServices; using Microsoft.Extensions.Logging; +using Microsoft.IdentityModel.Tokens; namespace Fab2ApprovalMKLink; @@ -24,12 +32,36 @@ public class Program { throw new Exception("Company name must have a value!"); if (string.IsNullOrEmpty(appSettings.WorkingDirectoryName)) throw new Exception("Working directory name must have a value!"); + GlobalVars.AppSettings = appSettings; + GlobalVars.AttachmentUrl = appSettings.AttachmentUrl is null ? string.Empty : appSettings.AttachmentUrl; + GlobalVars.CA_BlankFormsLocation = appSettings.CABlankFormsLocation; + GlobalVars.DBConnection = appSettings.DBConnection; + GlobalVars.DB_CONNECTION_STRING = appSettings.DBConnectionString; + GlobalVars.hostURL = appSettings.HostURL; + GlobalVars.IS_INFINEON_DOMAIN = appSettings.IsInfineonDomain; + GlobalVars.MesaTemplateFiles = appSettings.MesaTemplateFiles; + GlobalVars.NDriveURL = appSettings.NDriveURL; + GlobalVars.SENDER_EMAIL = appSettings.SenderEmail; + GlobalVars.USER_ID = appSettings.UserId; + GlobalVars.USER_ISADMIN = appSettings.UserIsAdmin; + GlobalVars.WSR_URL = appSettings.WSR_URL; try { _ = webApplicationBuilder.Services.Configure(options => options.SuppressModelStateInvalidFilter = true); _ = webApplicationBuilder.Services.AddControllers(); + _ = webApplicationBuilder.Services.AddControllersWithViews(); _ = webApplicationBuilder.Services.AddDistributedMemoryCache(); _ = webApplicationBuilder.Services.AddHttpClient(); + _ = webApplicationBuilder.Services.AddMemoryCache(); _ = webApplicationBuilder.Services.AddSingleton(_ => appSettings); + _ = webApplicationBuilder.Services.AddSingleton(); + // _ = webApplicationBuilder.Services.AddTransient(); + // _ = webApplicationBuilder.Services.AddScoped(); + // _ = webApplicationBuilder.Services.AddSingleton(); + _ = webApplicationBuilder.Services.AddSingleton(); + _ = webApplicationBuilder.Services.AddScoped(); + _ = webApplicationBuilder.Services.AddScoped(); + _ = webApplicationBuilder.Services.AddScoped(); + _ = webApplicationBuilder.Services.AddScoped(); _ = webApplicationBuilder.Services.AddSwaggerGen(); _ = webApplicationBuilder.Services.AddSession(sessionOptions => { sessionOptions.IdleTimeout = TimeSpan.FromSeconds(2000); @@ -37,6 +69,29 @@ public class Program { sessionOptions.Cookie.IsEssential = true; } ); + + _ = webApplicationBuilder.Services.AddAuthentication(options => { + options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + }) + .AddJwtBearer(options => { + options.RequireHttpsMetadata = false; + options.SaveToken = true; + options.TokenValidationParameters = new TokenValidationParameters { + ValidateIssuerSigningKey = true, + ValidIssuer = appSettings.JwtIssuer, + ValidateAudience = false, + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(appSettings.JwtKey)), + ClockSkew = TimeSpan.Zero + }; + }); + + _ = webApplicationBuilder.Services.AddAuthorization(options => { + options.DefaultPolicy = new AuthorizationPolicyBuilder() + .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) + .RequireAuthenticatedUser() + .Build(); + }); if (WindowsServiceHelpers.IsWindowsService()) { _ = webApplicationBuilder.Services.AddSingleton(); _ = webApplicationBuilder.Logging.AddEventLog(settings => { @@ -65,6 +120,8 @@ public class Program { } _ = webApplication.UseSession(); _ = webApplication.MapControllers(); + _ = webApplication.UseAuthentication(); + _ = webApplication.UseAuthorization(); logger.LogInformation("Starting Web Application"); webApplication.Run(); return 0; diff --git a/Fab2ApprovalMKLink/Services/AuthenticationService.cs b/Fab2ApprovalMKLink/Services/AuthenticationService.cs new file mode 100644 index 0000000..8c98f0d --- /dev/null +++ b/Fab2ApprovalMKLink/Services/AuthenticationService.cs @@ -0,0 +1,266 @@ +using System; +using System.Collections.Generic; +using System.DirectoryServices.AccountManagement; +using System.IdentityModel.Tokens.Jwt; +using System.Security.Authentication; +using System.Security.Claims; +using System.Security.Cryptography; +using System.Security.Principal; +using System.Text; +using System.Threading.Tasks; + +using Fab2ApprovalSystem.Models; + +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Logging; +using Microsoft.IdentityModel.Tokens; + +namespace Fab2ApprovalSystem.Services; + +public interface IAuthenticationService { + public Task AuthenticateUser(AuthAttempt login); + public Task AttemptLocalUserAuth(WindowsIdentity identity); + public AuthTokens GenerateAuthTokens(AuthAttempt authAttempt, IEnumerable roles); + public Task RefreshAuthTokens(AuthAttempt authAttempt); +} + +public class AuthenticationService : IAuthenticationService { + private readonly ILogger _logger; + private readonly IMemoryCache _cache; + private readonly IUserService _userService; + + private readonly string? _jwtIssuer; + private readonly string? _jwtAudience; + private readonly string? _jwtKey; + + public AuthenticationService(ILogger logger, IMemoryCache cache, IUserService userService, AppSettings appSettings) { + _logger = logger ?? throw new ArgumentNullException("ILogger not injected"); + _cache = cache ?? throw new ArgumentNullException("IMemoryCache not injected"); + _userService = userService ?? throw new ArgumentNullException("IUserService not injected"); + _jwtKey = appSettings.JwtKey; + _jwtIssuer = appSettings.JwtIssuer; + _jwtAudience = appSettings.JwtAudience; + } + + public async Task AuthenticateUser(AuthAttempt login) { + try { + _logger.LogInformation("Attempting to authenticate user"); + + if (login is null) + throw new ArgumentNullException("Login cannot be null"); + + string domain = "infineon.com"; + + using (PrincipalContext pc = new(ContextType.Domain, domain)) { + bool isValid = pc.ValidateCredentials(login.LoginID, login.Password); + + if (isValid) { + User? user = _cache.Get($"user{login.LoginID}"); + + if (user is null) { + user = await _userService.GetUserByLoginId(login.LoginID); + + _cache.Set($"user{login.LoginID}", user, DateTimeOffset.Now.AddDays(1)); + } + + List roles = new(); + + if (user.IsManager) + roles.Add("manager"); + if (user.IsAdmin) + roles.Add("admin"); + + AuthTokens tokens = GenerateAuthTokens(login, roles); + + return new LoginResult { + IsAuthenticated = true, + AuthTokens = tokens, + User = user + }; + } else { + return new LoginResult() { + IsAuthenticated = false, + AuthTokens = new() { + JwtToken = "", + RefreshToken = "" + }, + User = null + }; + } + } + } catch (Exception ex) { + _logger.LogError($"An exception occurred when attempting to authenticate user. Exception: {ex.Message}"); + throw; + } + } + + public async Task AttemptLocalUserAuth(WindowsIdentity identity) { + try { + _logger.LogInformation("Attempting to authenticate local Windows system user"); + + if (identity is null) + throw new ArgumentNullException("WindowsIdentity cannot be null"); + + User user = await _userService.GetUserByLoginId(identity.Name); + + List roles = new(); + + if (user.IsManager) + roles.Add("manager"); + if (user.IsAdmin) + roles.Add("admin"); + + AuthAttempt authAttempt = new() { + LoginID = user.LoginID, + }; + + AuthTokens tokens = GenerateAuthTokens(authAttempt, roles); + + return new LoginResult { + IsAuthenticated = true, + AuthTokens = tokens, + User = user + }; + } catch (Exception ex) { + _logger.LogError($"Unable to authenticate local Windows system user, because {ex.Message}"); + throw; + } + } + + public AuthTokens GenerateAuthTokens(AuthAttempt authAttempt, IEnumerable roles) { + try { + _logger.LogInformation("Attempting to generate JWT"); + + if (authAttempt is null) + throw new ArgumentNullException("AuthAttempt cannot be null"); + if (string.IsNullOrWhiteSpace(authAttempt.LoginID)) + throw new ArgumentException("UserName cannot be null or empty"); + if (roles is null) + throw new ArgumentNullException("roles cannot be null"); + + byte[] key = Encoding.ASCII.GetBytes(_jwtKey); + + List claims = new() { + new Claim(nameof(authAttempt.LoginID), authAttempt.LoginID) + }; + + foreach (string role in roles) { + claims.Add(new Claim(ClaimTypes.Role, role)); + } + + ClaimsIdentity identity = new(claims); + + SecurityTokenDescriptor tokenDescriptor = new() { + Issuer = _jwtIssuer, + Audience = _jwtAudience, + Subject = identity, + NotBefore = DateTime.Now, + Expires = DateTime.Now.AddHours(8), + SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) + }; + + JwtSecurityTokenHandler tokenHandler = new(); + + JwtSecurityToken token = tokenHandler.CreateJwtSecurityToken(tokenDescriptor); + + string jwt = tokenHandler.WriteToken(token); + + string refreshToken = GenerateRefreshToken(); + + List? refreshTokensForUser = _cache.Get>(authAttempt.LoginID); + + refreshTokensForUser ??= new List(); + + if (refreshTokensForUser.Count > 9) + refreshTokensForUser.RemoveRange(9, refreshTokensForUser.Count - 9); + + refreshTokensForUser.Insert(0, refreshToken); + + _cache.Set(authAttempt.LoginID, refreshTokensForUser, DateTimeOffset.Now.AddHours(4)); + + return new AuthTokens { + JwtToken = jwt, + RefreshToken = refreshToken + }; + } catch (Exception ex) { + _logger.LogError($"An exception occurred when attempting to generate JWT. Exception: {ex.Message}"); + throw; + } + } + + public async Task RefreshAuthTokens(AuthAttempt authAttempt) { + try { + _logger.LogInformation("Attempting to refresh auth tokens"); + + if (authAttempt is null) + throw new ArgumentNullException("AuthAttempt cannot be null"); + if (authAttempt.AuthTokens is null) + throw new ArgumentNullException("AuthTokens cannot be null"); + + bool refreshTokenIsValid = IsRefreshTokenValid(authAttempt.LoginID, authAttempt.AuthTokens.RefreshToken); + + if (refreshTokenIsValid) { + User? user = _cache.Get($"user{authAttempt.LoginID}"); + + if (user is null) { + user = await _userService.GetUserByLoginId(authAttempt.LoginID); + + _cache.Set($"user{authAttempt.LoginID}", user, DateTimeOffset.Now.AddDays(1)); + } + + List roles = new(); + + if (user.IsManager) + roles.Add("manager"); + if (user.IsAdmin) + roles.Add("admin"); + + AuthTokens refreshedTokens = GenerateAuthTokens(authAttempt, roles); + + LoginResult loginResult = new() { + IsAuthenticated = true, + AuthTokens = refreshedTokens, + User = user + }; + + return loginResult; + } else { + throw new AuthenticationException("Invalid refresh token"); + } + } catch (Exception ex) { + _logger.LogError($"An exception occurred when attempting to refresh auth tokens. Exception: {ex.Message}"); + throw; + } + } + + private string GenerateRefreshToken() { + byte[] randomNumber = new byte[32]; + using (RandomNumberGenerator rng = RandomNumberGenerator.Create()) { + rng.GetBytes(randomNumber); + return Convert.ToBase64String(randomNumber); + } + } + + private bool IsRefreshTokenValid(string loginId, string refreshToken) { + try { + _logger.LogInformation("Attempting to determine if refresh token is valid"); + + if (string.IsNullOrWhiteSpace(loginId)) + throw new ArgumentNullException("LoginID cannot be null or empty"); + if (string.IsNullOrWhiteSpace(refreshToken)) + throw new ArgumentNullException("Refresh token cannot be null or empty"); + + List? cachedRefreshTokensForUser = _cache.Get>(loginId); + + if (cachedRefreshTokensForUser is null || !cachedRefreshTokensForUser.Contains(refreshToken)) { + _logger.LogInformation($"Could not find cached refresh tokens for user {loginId}"); + return false; + } + + return true; + } catch (Exception ex) { + _logger.LogError($"An exception occurred when attempting to validate refresh token. Exception: {ex.Message}"); + throw; + } + } +} \ No newline at end of file diff --git a/Fab2ApprovalMKLink/Services/DalService.cs b/Fab2ApprovalMKLink/Services/DalService.cs new file mode 100644 index 0000000..052ea6e --- /dev/null +++ b/Fab2ApprovalMKLink/Services/DalService.cs @@ -0,0 +1,168 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Text; +using System.Threading.Tasks; + +using Dapper; + +using Microsoft.Extensions.Logging; + +namespace Fab2ApprovalSystem.Services; + +public interface IDalService { + Task> QueryAsync(string sql); + Task> QueryAsync(string sql, object parameters); + Task ExecuteAsync(string sql); + Task ExecuteAsync(string sql, T parameters); +} + +public class DalService : IDalService { + private static readonly int RETRIES = 3; + private static readonly int BACKOFF_SECONDS_INTERVAL = 30; + + private readonly ILogger _logger; + private readonly IDbConnectionService _dbConnectionService; + + public DalService(IDbConnectionService dbConnectionService, ILogger logger) { + _dbConnectionService = dbConnectionService ?? + throw new ArgumentNullException("IDbConnectionService not injected"); + _logger = logger ?? + throw new ArgumentNullException("ILogger not injected"); + } + + public async Task> QueryAsync(string sql) { + if (sql is null) throw new ArgumentNullException("sql cannot be null"); + + int remainingRetries = RETRIES; + bool queryWasSuccessful = false; + Exception exception = null; + IEnumerable result = new List(); + while (!queryWasSuccessful && remainingRetries > 0) { + int backoffSeconds = (RETRIES - remainingRetries--) * BACKOFF_SECONDS_INTERVAL; + Task.Delay(backoffSeconds * 1000).Wait(); + + try { + _logger.LogInformation($"Attempting to perform query with {sql}. Remaining retries: {remainingRetries}"); + + using (IDbConnection conn = _dbConnectionService.GetConnection()) { + result = await conn.QueryAsync(sql); + } + + queryWasSuccessful = true; + } catch (Exception ex) { + _logger.LogError($"An exception occurred while attempting to perform a query. Exception: {ex.Message}"); + exception = ex; + } + } + + if (!queryWasSuccessful && exception is not null) { + throw exception; + } + + return result; + } + + public async Task> QueryAsync(string sql, object parameters) { + if (sql is null) throw new ArgumentNullException("sql cannot be null"); + if (parameters is null) throw new ArgumentNullException("parameters cannot be null"); + + StringBuilder logBuilder = new(); + + int remainingRetries = RETRIES; + bool queryWasSuccessful = false; + Exception exception = null; + IEnumerable result = new List(); + while (!queryWasSuccessful && remainingRetries > 0) { + int backoffSeconds = (RETRIES - remainingRetries--) * BACKOFF_SECONDS_INTERVAL; + Task.Delay(backoffSeconds * 1000).Wait(); + + try { + logBuilder.Clear(); + logBuilder.Append($"Attempting to perform query with {sql} "); + logBuilder.Append($"and parameters {parameters.ToString()}. "); + logBuilder.Append($"Remaining retries: {remainingRetries}"); + _logger.LogInformation(logBuilder.ToString()); + + using (IDbConnection conn = _dbConnectionService.GetConnection()) { + result = await conn.QueryAsync(sql, parameters); + } + + queryWasSuccessful = true; + } catch (Exception ex) { + _logger.LogError($"An exception occurred while attempting to perform a query. Exception: {ex.Message}"); + exception = ex; + } + } + + if (!queryWasSuccessful && exception is not null) { + throw exception; + } + + return result; + } + + public async Task ExecuteAsync(string sql) { + if (sql is null) throw new ArgumentNullException("sql cannot be null"); + + int remainingRetries = RETRIES; + bool queryWasSuccessful = false; + Exception exception = null; + int rowsAffected = 0; + while (!queryWasSuccessful && remainingRetries > 0) { + int backoffSeconds = (RETRIES - remainingRetries--) * BACKOFF_SECONDS_INTERVAL; + Task.Delay(backoffSeconds * 1000).Wait(); + + try { + _logger.LogInformation($"Attempting to execute {sql}. Remaining retries: {remainingRetries}"); + + using (IDbConnection conn = _dbConnectionService.GetConnection()) { + rowsAffected = await conn.ExecuteAsync(sql); + } + + queryWasSuccessful = true; + } catch (Exception ex) { + _logger.LogError($"An exception occurred while attempting to execute a query. Exception: {ex.Message}"); + exception = ex; + } + } + + if (!queryWasSuccessful && exception is not null) { + throw exception; + } + + return rowsAffected; + } + + public async Task ExecuteAsync(string sql, T parameters) { + if (sql is null) throw new ArgumentNullException("sql cannot be null"); + + int remainingRetries = RETRIES; + bool queryWasSuccessful = false; + Exception exception = null; + int rowsAffected = 0; + while (!queryWasSuccessful && remainingRetries > 0) { + int backoffSeconds = (RETRIES - remainingRetries--) * BACKOFF_SECONDS_INTERVAL; + Task.Delay(backoffSeconds * 1000).Wait(); + + try { + _logger.LogInformation($"Attempting to execute {sql} with parameters. Remaining retries: {remainingRetries}"); + + using (IDbConnection conn = _dbConnectionService.GetConnection()) { + rowsAffected = await conn.ExecuteAsync(sql, parameters); + } + + queryWasSuccessful = true; + } catch (Exception ex) { + _logger.LogError($"An exception occurred while attempting to execute a query. Exception: {ex.Message}"); + exception = ex; + } + } + + if (!queryWasSuccessful && exception is not null) { + throw exception; + } + + return rowsAffected; + } +} \ No newline at end of file diff --git a/Fab2ApprovalMKLink/Services/DbConnectionService.cs b/Fab2ApprovalMKLink/Services/DbConnectionService.cs new file mode 100644 index 0000000..05dcab0 --- /dev/null +++ b/Fab2ApprovalMKLink/Services/DbConnectionService.cs @@ -0,0 +1,22 @@ +using System.Data; + +using Fab2ApprovalSystem.Models; + +using Microsoft.Data.SqlClient; + +namespace Fab2ApprovalSystem.Services; + +public interface IDbConnectionService { + IDbConnection GetConnection(); +} + +public class DbConnectionService : IDbConnectionService { + private readonly string _dbConnectionString; + + public DbConnectionService(AppSettings appSettings) { + _dbConnectionString = appSettings.DBConnectionString; + } + + public IDbConnection GetConnection() => + new SqlConnection(_dbConnectionString); +} \ No newline at end of file diff --git a/Fab2ApprovalMKLink/Services/UserService.cs b/Fab2ApprovalMKLink/Services/UserService.cs new file mode 100644 index 0000000..e255f9e --- /dev/null +++ b/Fab2ApprovalMKLink/Services/UserService.cs @@ -0,0 +1,150 @@ +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> GetAllActiveUsers(); + Task GetUserByLoginId(string loginId); + Task GetUserByUserId(int userId); + Task> GetApproverUserIdsBySubRoleCategoryItem(string item); +} + +public class UserService : IUserService { + private readonly ILogger _logger; + private readonly IDalService _dalService; + private readonly IMemoryCache _cache; + + public UserService(ILogger 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> GetAllActiveUsers() { + try { + _logger.LogInformation("Attempting to get all active users"); + + IEnumerable? allActiveUsers = _cache.Get>("allActiveUsers"); + + if (allActiveUsers is null) { + string sql = "select * from Users where IsActive = 1"; + + allActiveUsers = (await _dalService.QueryAsync(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 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($"userByLoginId{loginId}"); + + user ??= _cache.Get>("allActiveUsers")?.FirstOrDefault(u => u.LoginID == loginId); + + if (user is null) { + string sql = $"select * from Users where LoginID = '{loginId}';"; + + user = (await _dalService.QueryAsync(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 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($"userByUserId{userId}"); + + user ??= _cache.Get>("allActiveUsers")?.FirstOrDefault(u => u.UserID == userId); + + if (user is null) { + string sql = $"select * from Users where UserID = '{userId}';"; + + user = (await _dalService.QueryAsync(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> 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? userIds = _cache.Get>($"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(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; + } + } +} \ No newline at end of file diff --git a/Fab2ApprovalMKLink/Views/_ViewImports.cshtml b/Fab2ApprovalMKLink/Views/_ViewImports.cshtml new file mode 100644 index 0000000..d40c141 --- /dev/null +++ b/Fab2ApprovalMKLink/Views/_ViewImports.cshtml @@ -0,0 +1,8 @@ +@using Fab2ApprovalSystem.DMO +@using Fab2ApprovalSystem.JobSchedules +@using Fab2ApprovalSystem.Misc +@using Fab2ApprovalSystem.Models +@using Fab2ApprovalSystem.PdfGenerator +@using Fab2ApprovalSystem.Utilities +@using Fab2ApprovalSystem.ViewModels +@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers diff --git a/Fab2ApprovalMKLink/Views/_ViewStart.cshtml b/Fab2ApprovalMKLink/Views/_ViewStart.cshtml new file mode 100644 index 0000000..2d57c48 --- /dev/null +++ b/Fab2ApprovalMKLink/Views/_ViewStart.cshtml @@ -0,0 +1,3 @@ +@{ + Layout = null; +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/App_Start/FilterConfig.cs b/Fab2ApprovalSystem/App_Start/FilterConfig.cs index ebf4bd4..4643534 100644 --- a/Fab2ApprovalSystem/App_Start/FilterConfig.cs +++ b/Fab2ApprovalSystem/App_Start/FilterConfig.cs @@ -1,5 +1,7 @@ using System.Web; +#if !NET8 using System.Web.Mvc; +#endif namespace Fab2ApprovalSystem; diff --git a/Fab2ApprovalSystem/App_Start/RouteConfig.cs b/Fab2ApprovalSystem/App_Start/RouteConfig.cs index 4fa2886..98157e3 100644 --- a/Fab2ApprovalSystem/App_Start/RouteConfig.cs +++ b/Fab2ApprovalSystem/App_Start/RouteConfig.cs @@ -3,13 +3,16 @@ using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; +#if !NET8 using System.Web.Mvc; +#endif using System.Web.Routing; namespace Fab2ApprovalSystem; public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { +#if !NET8 routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( @@ -20,5 +23,6 @@ public class RouteConfig { // otherwise MVC generates the wrong form action url defaults: new { controller = "Home", action = "MyTasks", id = UrlParameter.Optional } ); +#endif } } \ No newline at end of file diff --git a/Fab2ApprovalSystem/App_Start/WebApiConfig.cs b/Fab2ApprovalSystem/App_Start/WebApiConfig.cs index b618fc8..b76f6f1 100644 --- a/Fab2ApprovalSystem/App_Start/WebApiConfig.cs +++ b/Fab2ApprovalSystem/App_Start/WebApiConfig.cs @@ -6,10 +6,12 @@ public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.MapHttpAttributeRoutes(); +#if !NET8 config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); +#endif } } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/AccountController.cs b/Fab2ApprovalSystem/Controllers/AccountController.cs index ed95e29..a1fae14 100644 --- a/Fab2ApprovalSystem/Controllers/AccountController.cs +++ b/Fab2ApprovalSystem/Controllers/AccountController.cs @@ -1,30 +1,47 @@ +#if !NET8 +using System.Web; +using System.Web.Mvc; +using System.Web.Security; +#endif + +#if NET8 +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +#endif + +#if !NET8 +using Fab2ApprovalSystem.DMO; +using Fab2ApprovalSystem.Misc; +using Fab2ApprovalSystem.Models; +#endif + +#if !NET8 +using Microsoft.AspNet.Identity; +using Microsoft.AspNet.Identity.EntityFramework; +using Microsoft.AspNet.Identity.Owin; +using Microsoft.Owin.Security; +#endif + +#if !NET8 using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Security.Claims; -using System.Text; using System.Threading.Tasks; -using System.Web; -using System.Web.Mvc; -using System.Web.Security; - -using Fab2ApprovalSystem.DMO; -using Fab2ApprovalSystem.Misc; -using Fab2ApprovalSystem.Models; - -using Microsoft.AspNet.Identity; -using Microsoft.AspNet.Identity.EntityFramework; -using Microsoft.AspNet.Identity.Owin; -using Microsoft.Owin.Security; - using Newtonsoft.Json; +#endif namespace Fab2ApprovalSystem.Controllers; [Authorize] +#if NET8 +[Route("[controller]")] +#endif public class AccountController : Controller { +#if !NET8 + public AccountController() : this(new UserManager(new UserStore(new ApplicationDbContext()))) { } @@ -35,25 +52,23 @@ public class AccountController : Controller { public UserManager UserManager { get; private set; } +#endif + +#if !NET8 // GET: /Account/Login [AllowAnonymous] // try to make the browser refresh the login page every time, to prevent issues with changing usernames and the anti-forgery token validation [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] +#endif public ActionResult Login(string returnUrl) { ViewBag.ReturnUrl = returnUrl; return View(); } - private void SetSessionParameters(LoginResult loginResult, LoginModel user) { - Session["JWT"] = loginResult.AuthTokens.JwtToken; - Session["RefreshToken"] = loginResult.AuthTokens.RefreshToken; +#if !NET8 - Session[GlobalVars.SESSION_USERID] = user.UserID; - Session[GlobalVars.SESSION_USERNAME] = user.FullName; - Session[GlobalVars.IS_ADMIN] = user.IsAdmin; - Session[GlobalVars.IS_MANAGER] = user.IsManager; - Session[GlobalVars.OOO] = user.OOO; - Session[GlobalVars.CAN_CREATE_PARTS_REQUEST] = user.IsAdmin || PartsRequestController.CanCreatePartsRequest(user.UserID); + private void SetSessionParameters(LoginResult loginResult, LoginModel user) { + GlobalVars.SetSessionParameters(GetSession(), loginResult, user); FormsAuthentication.SetAuthCookie(user.LoginID, true); } @@ -102,8 +117,8 @@ public class AccountController : Controller { ModelState.AddModelError("", "The user name or password provided is incorrect."); } } catch (Exception ex) { - Functions.WriteEvent(GlobalVars.AppSettings, @User.Identity.Name + " " + ex.InnerException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = 99999, UserID = @User.Identity.Name, DocumentType = "Login", OperationType = "Error", Comments = "Reject - " + ex.Message }); + Functions.WriteEvent(GlobalVars.AppSettings, GetUserIdentityName() + " " + ex.InnerException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = 99999, UserID = GetUserIdentityName(), DocumentType = "Login", OperationType = "Error", Comments = "Reject - " + ex.Message }); ModelState.AddModelError("", ex.Message); } @@ -158,20 +173,24 @@ public class AccountController : Controller { return new HttpResponseMessage(HttpStatusCode.Unauthorized); } } catch (Exception ex) { - Functions.WriteEvent(GlobalVars.AppSettings, @User.Identity.Name + " " + ex.InnerException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = 99999, UserID = @User.Identity.Name, DocumentType = "Login", OperationType = "Error", Comments = "Reject - " + ex.Message }); + Functions.WriteEvent(GlobalVars.AppSettings, GetUserIdentityName() + " " + ex.InnerException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = 99999, UserID = GetUserIdentityName(), DocumentType = "Login", OperationType = "Error", Comments = "Reject - " + ex.Message }); ModelState.AddModelError("", ex.Message); return new HttpResponseMessage(HttpStatusCode.InternalServerError); } } +#endif + // GET: /Account/Register [AllowAnonymous] public ActionResult Register() { return View(); } +#if !NET8 + // POST: /Account/Disassociate [HttpPost] [ValidateAntiForgeryToken] @@ -186,6 +205,8 @@ public class AccountController : Controller { return RedirectToAction("Manage", new { Message = message }); } +#endif + // GET: /Account/Manage #pragma warning disable IDE0060 // Remove unused parameter public ActionResult Manage(ManageMessageId? message) { @@ -193,6 +214,8 @@ public class AccountController : Controller { } #pragma warning restore IDE0060 // Remove unused parameter +#if !NET8 + // POST: /Account/ExternalLogin [HttpPost] [AllowAnonymous] @@ -223,7 +246,6 @@ public class AccountController : Controller { return RedirectToAction("Manage", new { Message = ManageMessageId.Error }); } - // POST: /Account/LogOff [HttpPost] [ValidateAntiForgeryToken] public ActionResult LogOff() { @@ -231,12 +253,15 @@ public class AccountController : Controller { return RedirectToAction("Login", "Account"); } - // GET: /Account/ExternalLoginFailure +#endif + [AllowAnonymous] public ActionResult ExternalLoginFailure() { return View(); } +#if !NET8 + [ChildActionOnly] public ActionResult RemoveAccountList() { IList linkedAccounts = UserManager.GetLogins(User.Identity.GetUserId()); @@ -252,10 +277,14 @@ public class AccountController : Controller { base.Dispose(disposing); } +#endif + #region Helpers // Used for XSRF protection when adding external logins private const string XsrfKey = "XsrfId"; +#if !NET8 + private IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; @@ -282,6 +311,8 @@ public class AccountController : Controller { return false; } +#endif + public enum ManageMessageId { ChangePasswordSuccess, SetPasswordSuccess, @@ -297,7 +328,18 @@ public class AccountController : Controller { } } +#if !NET8 + private class ChallengeResult : HttpUnauthorizedResult { + +#endif + +#if NET8 + + private class ChallengeResult { + +#endif + public ChallengeResult(string provider, string redirectUri) : this(provider, redirectUri, null) { } @@ -311,6 +353,8 @@ public class AccountController : Controller { public string RedirectUri { get; set; } public string UserId { get; set; } +#if !NET8 + public override void ExecuteResult(ControllerContext context) { AuthenticationProperties properties = new AuthenticationProperties() { RedirectUri = RedirectUri }; if (UserId != null) { @@ -318,6 +362,40 @@ public class AccountController : Controller { } context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider); } + +#endif + } + #endregion + +#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; + } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/AdminController.cs b/Fab2ApprovalSystem/Controllers/AdminController.cs index e94e766..2cb754c 100644 --- a/Fab2ApprovalSystem/Controllers/AdminController.cs +++ b/Fab2ApprovalSystem/Controllers/AdminController.cs @@ -1,31 +1,47 @@ using System; using System.Collections.Generic; -using System.Linq; +#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/ - UserAccountDMO userDMO = new UserAccountDMO(); - AdminDMO adminDMO = new AdminDMO(); - TrainingDMO trainingDMO = new TrainingDMO(); - LotDispositionDMO ldDMO = new LotDispositionDMO(); - private readonly AppSettings _AppSettings = GlobalVars.AppSettings; + 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 ((bool)Session[GlobalVars.IS_ADMIN]) { + if (GlobalVars.IsAdmin(GetSession())) { var model = userDMO.GetAllUsers(); ViewBag.AllActiveUsers = userDMO.GetAllActiveUsers(); return View(model); @@ -33,8 +49,10 @@ public class AdminController : Controller { return Content("Not Autthorized"); } +#if !NET8 + public ActionResult AssignRoles() { - if ((bool)Session[GlobalVars.IS_ADMIN]) { + if (GlobalVars.IsAdmin(GetSession())) { ViewBag.ToplevelNode = GetRoles_SubRolesList(); return View(); } else @@ -43,36 +61,33 @@ public class AdminController : Controller { public ActionResult GetAllUserList([DataSourceRequest] DataSourceRequest request) { IEnumerable userlist = userDMO.GetAllActiveUsers(); - return Json(userlist, JsonRequestBehavior.AllowGet); + return GetJsonResult(userlist); } - /// - /// For the Administration of the Users - /// public ActionResult GetGridUserList([DataSourceRequest] DataSourceRequest request) { - return Json(userDMO.GetAllUsers().ToDataSourceResult(request)); + return GetJsonResult(userDMO.GetAllUsers().ToDataSourceResult(request)); } +#endif + public JsonResult GetAllUserListBySubRole(int subRole) { IEnumerable userlist = adminDMO.GetAllUsersBySubRole(subRole); - return Json(userlist, JsonRequestBehavior.AllowGet); + return GetJsonResult(userlist); } public JsonResult AllSubRoles(string showInactiveRoles = "") { List newRoles = adminDMO.GetAllSubRoles(showInactiveRoles); - - return Json(newRoles, JsonRequestBehavior.AllowGet); + 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)); } - /// - /// OBSOLETE FUNCTION BELOW FOR THE KENDO TREEVIEW - /// private IEnumerable GetRoles_SubRolesList() { List roles = adminDMO.GetSubRoles(); @@ -103,6 +118,8 @@ public class AdminController : Controller { return ToplevelNode; } +#endif + public ActionResult AddUserRoles(int subRole, string users) { adminDMO.AddUserRoles(subRole, users); return View(); @@ -128,6 +145,8 @@ public class AdminController : Controller { return View(); } +#if !NET8 + // POST: /Workflow/Create [HttpPost] public ActionResult Create(FormCollection collection) { @@ -154,12 +173,16 @@ public class AdminController : Controller { 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 { @@ -174,6 +197,8 @@ public class AdminController : Controller { 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 @@ -191,7 +216,7 @@ public class AdminController : Controller { } public ActionResult ManageTrainingGroups() { - if ((bool)Session[GlobalVars.IS_ADMIN]) { + if (GlobalVars.IsAdmin(GetSession())) { ViewBag.AllGroups = GetTrainingGroups(); return View(); } else @@ -212,15 +237,17 @@ public class AdminController : Controller { return TrainingGroups; } +#if !NET8 + public ActionResult GetTaskListByUser([DataSourceRequest] DataSourceRequest request, string userId) { IEnumerable data = ldDMO.GetTaskList(Convert.ToInt32(userId)); data = from a in data where a.PendingApprovers != null select a; - return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet); + return GetJsonResult(data.ToDataSourceResult(request)); } public ActionResult GetOpenActionItemsByUser([DataSourceRequest] DataSourceRequest request, string userId) { IEnumerable data = ldDMO.GetMyOpenActionItems(Convert.ToInt32(userId)); - return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet); + return GetJsonResult(data.ToDataSourceResult(request)); } public ActionResult AddNewTrainingGroup(string groupName) { @@ -232,6 +259,8 @@ public class AdminController : Controller { } } +#endif + public ActionResult DeleteTrainingGroup(int groupID) { try { adminDMO.DeleteTrainingGroup(groupID); @@ -246,6 +275,8 @@ public class AdminController : Controller { return View(); } +#if !NET8 + public ActionResult TrainingGroupPartial(int TrainingGroupID) { ViewBag.AllUsers = userDMO.GetAllActiveUsers(); ViewBag.TrainingGroupId = TrainingGroupID; @@ -263,6 +294,8 @@ public class AdminController : Controller { return Json(new { test = "Succesfully saved" }); } +#endif + public ActionResult DeleteFromGroup(int userId, int groupId) { try { adminDMO.DeleteFromGroup(userId, groupId); @@ -274,7 +307,7 @@ public class AdminController : Controller { } public ActionResult JobSchedulerConfiguration() { - if ((bool)Session[GlobalVars.IS_ADMIN]) { + if (GlobalVars.IsAdmin(GetSession())) { return View(); } else return Content("Not Autthorized"); @@ -283,7 +316,7 @@ public class AdminController : Controller { public ActionResult TrainingReportConfig() { ViewBag.AllUsers = userDMO.GetAllActiveUsers(); List currentTrainingReportUsersIds = adminDMO.GetTrainingReportUsers(); - List currentTrainingReportUsers = new List(); + List currentTrainingReportUsers = new(); foreach (TrainingReportUser id in currentTrainingReportUsersIds) { currentTrainingReportUsers.Add(userDMO.GetUserByID(id.UserId)); @@ -292,10 +325,12 @@ public class AdminController : Controller { return PartialView(); } +#if !NET8 + public ActionResult TECNNotificationConfig() { ViewBag.AllUsers = userDMO.GetAllActiveUsers(); List currentTECNNotificationUsersIds = adminDMO.GetTECNNotificationUsers(); - List currentTECNNotificationUsers = new List(); + List currentTECNNotificationUsers = new(); foreach (TECNNotificationsUser id in currentTECNNotificationUsersIds) { currentTECNNotificationUsers.Add(userDMO.GetUserByID(id.UserId)); @@ -304,8 +339,10 @@ public class AdminController : Controller { return PartialView(); } +#endif + public ActionResult AddToTrainingReport(int userId) { - if ((bool)Session[GlobalVars.IS_ADMIN]) { + if (GlobalVars.IsAdmin(GetSession())) { // Check to make sure user is not apart of the group already bool userExists = false; List existingUsers = adminDMO.GetTrainingReportUsers(); @@ -329,8 +366,10 @@ public class AdminController : Controller { } } +#if !NET8 + public ActionResult AddToTECNNotification(int userId) { - if ((bool)Session[GlobalVars.IS_ADMIN]) { + if (GlobalVars.IsAdmin(GetSession())) { // Check to make sure user is not apart of the group already bool userExists = false; List existingUsers = adminDMO.GetTECNNotificationUsers(); @@ -360,8 +399,10 @@ public class AdminController : Controller { } } +#endif + public ActionResult DeleteFromTrainingReport(int userId) { - if ((bool)Session[GlobalVars.IS_ADMIN]) { + if (GlobalVars.IsAdmin(GetSession())) { try { adminDMO.TrainingReportDeleteUser(userId); return Content("Successfully Deleted"); @@ -374,7 +415,7 @@ public class AdminController : Controller { } public ActionResult DeleteFromTECNNotification(int userId) { - if ((bool)Session[GlobalVars.IS_ADMIN]) { + if (GlobalVars.IsAdmin(GetSession())) { try { adminDMO.TECNExpirationDeleteUser(userId); return Content("Successfully Deleted"); @@ -386,4 +427,33 @@ public class AdminController : Controller { } } +#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; + } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/AuditController.cs b/Fab2ApprovalSystem/Controllers/AuditController.cs index d8653c6..39c40d6 100644 --- a/Fab2ApprovalSystem/Controllers/AuditController.cs +++ b/Fab2ApprovalSystem/Controllers/AuditController.cs @@ -1,27 +1,43 @@ using System; using System.Collections.Generic; -using System.Configuration; -using System.Linq; +#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.Configuration; +using System.Linq; using Fab2ApprovalSystem.Utilities; +#endif +#if !NET8 using Kendo.Mvc.Extensions; using Kendo.Mvc.UI; +#endif namespace Fab2ApprovalSystem.Controllers; [Authorize] +#if !NET8 [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] [SessionExpireFilter] +#endif +#if NET8 +[Route("[controller]")] +#endif public class AuditController : Controller { - AuditDMO auditDMO = new AuditDMO(GlobalVars.AppSettings); - CorrectiveActionDMO caDMO = new CorrectiveActionDMO(); + private readonly AuditDMO auditDMO = new(GlobalVars.AppSettings); + private readonly CorrectiveActionDMO caDMO = new(); private readonly AppSettings _AppSettings = GlobalVars.AppSettings; // GET: Audit @@ -30,11 +46,11 @@ public class AuditController : Controller { } public ActionResult Create() { - Audit audit = new Audit(); + Audit audit = new(); try { // TODO: Add insert logic here - audit.OriginatorID = (int)Session[GlobalVars.SESSION_USERID]; + audit.OriginatorID = GlobalVars.GetUserId(GetSession()); auditDMO.InsertAudit(audit); return RedirectToAction("Edit", new { issueID = audit.AuditNo }); } catch (Exception e) { @@ -45,19 +61,19 @@ public class AuditController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + audit.AuditNo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SubmitDocument - Audit\r\n" + audit.AuditNo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = audit.AuditNo, UserID = @User.Identity.Name, DocumentType = "Audit", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n SubmitDocument - Audit\r\n" + audit.AuditNo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = audit.AuditNo, UserID = GetUserIdentityName(), DocumentType = "Audit", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); throw new Exception(e.Message); } } public ActionResult Edit(int issueID) { int isITARCompliant = 1; - Audit audit = new Audit(); + Audit audit = new(); try { - bool isAdmin = (bool)Session[GlobalVars.IS_ADMIN]; - int userId = (int)Session[GlobalVars.SESSION_USERID]; + bool isAdmin = GlobalVars.IsAdmin(GetSession()); + int userId = GlobalVars.GetUserId(GetSession()); audit = auditDMO.GetAuditItem(issueID, userId); AuditEdit auditEdit = auditDMO.GetAuditEdit(issueID, audit, isAdmin, userId); if (auditEdit.RedirectToAction) @@ -81,8 +97,8 @@ public class AuditController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + audit.AuditNo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Edit - Audit\r\n" + audit.AuditNo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = audit.AuditNo, UserID = @User.Identity.Name, DocumentType = "Audit", OperationType = "Error", Comments = "Edit - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Edit - Audit\r\n" + audit.AuditNo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = audit.AuditNo, UserID = GetUserIdentityName(), DocumentType = "Audit", OperationType = "Error", Comments = "Edit - " + exceptionString }); throw new Exception(e.Message); } @@ -93,7 +109,7 @@ public class AuditController : Controller { public ActionResult Edit(Audit model) { try { var data = model; - auditDMO.UpdateAudit(model, (int)Session[GlobalVars.SESSION_USERID]); + auditDMO.UpdateAudit(model, GlobalVars.GetUserId(GetSession())); } catch (Exception ex) { return Content(ex.Message); } @@ -113,8 +129,8 @@ public class AuditController : Controller { } public ActionResult ReadOnlyAudit(int auditNo) { - Audit audit = new Audit(); - audit = auditDMO.GetAuditItemReadOnly(auditNo, (int)Session[GlobalVars.SESSION_USERID]); + Audit audit = new(); + audit = auditDMO.GetAuditItemReadOnly(auditNo, GlobalVars.GetUserId(GetSession())); ViewBag.AuditTypeList = auditDMO.GetAuditTypeList(); ViewBag.AuditorList = auditDMO.GetAuditorList(); @@ -124,11 +140,13 @@ public class AuditController : Controller { return View(audit); } +#if !NET8 + public ActionResult AuditReportAttachSave(IEnumerable AuditReportFiles, int auditNo) { try { // The Name of the Upload component is "files" if (AuditReportFiles != null) { - int userId = (int)Session[GlobalVars.SESSION_USERID]; + int userId = GlobalVars.GetUserId(GetSession()); foreach (var file in AuditReportFiles) { AuditHelper.AuditReportAttachSave(_AppSettings, auditDMO, auditNo, userId, file.FileName, file.InputStream); } @@ -145,6 +163,8 @@ public class AuditController : Controller { return Json(auditDMO.GetAuditReportAttachments(auditNo).ToDataSourceResult(request)); } +#endif + [HttpPost] public void DeleteAuditReportAttachment(int attachID) { auditDMO.DeleteAuditReportAttachment(attachID); @@ -173,18 +193,21 @@ public class AuditController : Controller { } } +#if !NET8 + public ActionResult GetAuditFindingsList([DataSourceRequest] DataSourceRequest request, int auditNo) { return Json(auditDMO.GetAuditFindingsList(auditNo).ToDataSourceResult(request)); } +#endif + public ActionResult InsertAuditFindingsItem(AuditFindings data) { if ((data.FindingType == "Major" || data.FindingType == "Minor") && data.CANo == 0) { throw new ArgumentException("You must select add a CA for a Major or Minor finding."); } else { - int userId = (int)Session[GlobalVars.SESSION_USERID]; + int userId = GlobalVars.GetUserId(GetSession()); Audit audit = auditDMO.InsertAndGetAudit(caDMO, data, userId); - - return Json(audit, JsonRequestBehavior.AllowGet); + return GetJsonResult(audit); } } @@ -192,25 +215,24 @@ public class AuditController : Controller { if ((data.FindingType == "Major" || data.FindingType == "Minor") && data.CANo == 0) { throw new ArgumentException("You must select add a CA for a Major or Minor finding."); } else { - int userId = (int)Session[GlobalVars.SESSION_USERID]; + int userId = GlobalVars.GetUserId(GetSession()); Audit audit = auditDMO.UpdateAndGetAudit(caDMO, data, userId); - - return Json(audit, JsonRequestBehavior.AllowGet); + return GetJsonResult(audit); } } public ActionResult DeleteAuditFindingsItem(int auditFindingsID) { - int userId = (int)Session[GlobalVars.SESSION_USERID]; + int userId = GlobalVars.GetUserId(GetSession()); Audit audit = auditDMO.DeleteAndGetAudit(auditFindingsID, userId); - return Json(audit, JsonRequestBehavior.AllowGet); + return GetJsonResult(audit); } public void ReleaseLockOnDocument(int issueID) { try { - auditDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], issueID); + auditDMO.ReleaseLockOnDocument(GlobalVars.GetUserId(GetSession()), issueID); } catch (Exception e) { try { - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReleaseLockOnDocument CA\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ReleaseLockOnDocument CA\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error); } catch { } auditDMO.ReleaseLockOnDocument(-1, issueID); } @@ -237,6 +259,8 @@ public class AuditController : Controller { return Content(""); } +#if !NET8 + public ActionResult GetCAFindingsList([DataSourceRequest] DataSourceRequest request, int auditNo) { return Json(auditDMO.GetCAFindingsList(auditNo).ToDataSourceResult(request)); } @@ -245,8 +269,10 @@ public class AuditController : Controller { return Json(auditDMO.GetCAFindingsItemAttachments(caFindingsID).ToDataSourceResult(request)); } +#endif + public ActionResult GetCAFindingsItem(int caFindingsID) { - var model = new CAFindings(); + CAFindings model = new(); model = auditDMO.GetCAFindingsItem(caFindingsID); return PartialView("_CAFindingsAttachment", model); @@ -257,11 +283,13 @@ public class AuditController : Controller { auditDMO.DeleteCAFindingsItem(caFindingsID); } +#if !NET8 + public ActionResult SaveCAFindings_Attachemnt(IEnumerable CAFindings_Attachemnt, int caFindingsID, int auditNo) { try { // The Name of the Upload component is "files" if (CAFindings_Attachemnt != null) { - int userId = (int)Session[GlobalVars.SESSION_USERID]; + int userId = GlobalVars.GetUserId(GetSession()); foreach (var file in CAFindings_Attachemnt) { AuditHelper.SaveAndInsert(_AppSettings, auditDMO, caFindingsID, auditNo, userId, file.FileName, file.InputStream); } @@ -273,12 +301,14 @@ public class AuditController : Controller { return Content(""); } +#endif + public void NotifyActionItemOwner(int issueID, DateTime? dueDate, int? responsibleOwnerID) { try { string email = auditDMO.NotifyActionItemOwner(issueID, dueDate, responsibleOwnerID, _AppSettings.EmailTemplatesPath); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Task Assigned for 5S/CA Findings" + ":" + email }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Email", Comments = "Task Assigned for 5S/CA Findings" + ":" + email }); } catch { } } catch (Exception e) { string detailedException = ""; @@ -289,8 +319,8 @@ public class AuditController : Controller { } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " 5s/CAFindings:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n 5s/CAFindings - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "5s/CAFindings Notification - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n 5s/CAFindings - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "5s/CAFindings Notification - " + exceptionString }); } } @@ -298,4 +328,33 @@ public class AuditController : Controller { return Content(auditDMO.IsCAAssignedToAudit(caNo, auditNo).ToString()); } +#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; + } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/ChangeControlController.cs b/Fab2ApprovalSystem/Controllers/ChangeControlController.cs index c6efb7a..968550a 100644 --- a/Fab2ApprovalSystem/Controllers/ChangeControlController.cs +++ b/Fab2ApprovalSystem/Controllers/ChangeControlController.cs @@ -1,36 +1,50 @@ using System; using System.Collections.Generic; using System.Linq; +#if !NET8 using System.Web; using System.Web.Mvc; using System.Web.Services; +#endif + +#if NET8 +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Authorization; +#endif using Fab2ApprovalSystem.DMO; using Fab2ApprovalSystem.Misc; using Fab2ApprovalSystem.Models; using Fab2ApprovalSystem.ViewModels; +#if !NET8 using Kendo.Mvc.Extensions; using Kendo.Mvc.UI; +#endif namespace Fab2ApprovalSystem.Controllers; [Authorize] +#if !NET8 [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] [SessionExpireFilter] +#endif +#if NET8 +[Route("[controller]")] +#endif public class ChangeControlController : Controller { - ChangeControlDMO ccDMO = new ChangeControlDMO(); - private readonly AppSettings _AppSettings = GlobalVars.AppSettings; + private readonly ChangeControlDMO ccDMO = new(); + private readonly AppSettings? _AppSettings = GlobalVars.AppSettings; public ActionResult Index() { return View(); } public ActionResult Create() { - ChangeControlViewModel cc = new ChangeControlViewModel(); + ChangeControlViewModel cc = new(); try { - cc.OwnerID = (int)Session[GlobalVars.SESSION_USERID]; + cc.OwnerID = GlobalVars.GetUserId(GetSession()); ccDMO.InsertChangeControl(cc); return RedirectToAction("Edit", new { issueID = cc.PlanNumber }); } catch (Exception e) { @@ -41,16 +55,16 @@ public class ChangeControlController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + cc.PlanNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Create - Change Control\r\n" + cc.PlanNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = cc.PlanNumber, UserID = @User.Identity.Name, DocumentType = "Change Control", OperationType = "Error", Comments = "Create - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Create - Change Control\r\n" + cc.PlanNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = cc.PlanNumber, UserID = GetUserIdentityName(), DocumentType = "Change Control", OperationType = "Error", Comments = "Create - " + exceptionString }); throw new Exception(e.Message); } } public ActionResult Edit(int issueID) { - string jwt = Session["JWT"].ToString(); + string jwt = GlobalVars.GetJWT(GetSession()); string encodedJwt = System.Net.WebUtility.UrlEncode(jwt); - string refreshToken = Session["RefreshToken"].ToString(); + string refreshToken = GlobalVars.GetRefreshToken(GetSession()); string encodedRefreshToken = System.Net.WebUtility.UrlEncode(refreshToken); string mrbUrl = $"{GlobalVars.AppSettings.WasmClientUrl}/redirect?jwt={encodedJwt}&refreshToken={encodedRefreshToken}&redirectPath=pcrb/{issueID}"; @@ -58,9 +72,9 @@ public class ChangeControlController : Controller { } public ActionResult ReadOnlyCC(int issueID) { - string jwt = Session["JWT"].ToString(); + string jwt = GlobalVars.GetJWT(GetSession()); string encodedJwt = System.Net.WebUtility.UrlEncode(jwt); - string refreshToken = Session["RefreshToken"].ToString(); + string refreshToken = GlobalVars.GetRefreshToken(GetSession()); string encodedRefreshToken = System.Net.WebUtility.UrlEncode(refreshToken); string mrbUrl = $"{GlobalVars.AppSettings.WasmClientUrl}/redirect?jwt={encodedJwt}&refreshToken={encodedRefreshToken}&redirectPath=pcrb/{issueID}"; @@ -71,7 +85,7 @@ public class ChangeControlController : Controller { public ActionResult Edit(ChangeControlViewModel model) { try { var data = model; - ccDMO.UpdateChangeControl(model, (int)Session[GlobalVars.SESSION_USERID]); + ccDMO.UpdateChangeControl(model, GlobalVars.GetUserId(GetSession())); ViewBag.AIResponsibles = ccDMO.GetActionItemResponsible(); } catch (Exception ex) { return Content(ex.Message); @@ -93,10 +107,12 @@ public class ChangeControlController : Controller { } public JsonResult SearchParts(string searchText) { - List partList = MiscDMO.SearchLTParts(searchText.Trim()).Select(x => x.WIPPartData).ToList(); - return Json(partList, JsonRequestBehavior.AllowGet); + List partList = MiscDMO.SearchLTParts(searchText.Trim()).Select(x => x.WIPPartData).ToList(); + return GetJsonResult(partList); } +#if !NET8 + public ActionResult GetCCAttachments([DataSourceRequest] DataSourceRequest request, int planNumber) { return Json(ccDMO.GetCCAttachment(planNumber).ToDataSourceResult(request)); } @@ -130,7 +146,7 @@ public class ChangeControlController : Controller { public ActionResult AttachSaveCC(IEnumerable files, int planNumber, int attachID) { // The Name of the Upload component is "files" if (files != null) { - int userId = (int)Session[GlobalVars.SESSION_USERID]; + int userId = GlobalVars.GetUserId(GetSession()); foreach (var file in files) { ChangeControlHelper.AttachSaveCC(_AppSettings, ccDMO, planNumber, attachID, userId, file.FileName, file.InputStream); } @@ -145,6 +161,7 @@ public class ChangeControlController : Controller { public ActionResult GetMeetingAttachments([DataSourceRequest] DataSourceRequest request, int meetingID) { return Json(ccDMO.GetMeetingAttachments(meetingID).ToDataSourceResult(request)); } + public ActionResult GetPCRB([DataSourceRequest] DataSourceRequest request, int PlanNumber, string PCRB) { return Json(ccDMO.GetPCRB(PlanNumber, PCRB).ToDataSourceResult(request)); } @@ -177,7 +194,7 @@ public class ChangeControlController : Controller { public ActionResult AttachSaveMeeting(IEnumerable files, int planNumber, int meetingID, int attachID) { // The Name of the Upload component is "files" if (files != null) { - int userId = (int)Session[GlobalVars.SESSION_USERID]; + int userId = GlobalVars.GetUserId(GetSession()); foreach (var file in files) { ChangeControlHelper.AttachSaveMeeting(_AppSettings, ccDMO, planNumber, attachID, userId, file.FileName, file.InputStream); } @@ -185,6 +202,8 @@ public class ChangeControlController : Controller { return Content(""); } +#endif + public FileResult DownloadCCFile(string fileGuid, int planNumber) { string fileName = ccDMO.GetCCFileName(fileGuid); @@ -219,20 +238,20 @@ public class ChangeControlController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + planNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Create - Meeting\r\n" + planNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = planNumber, UserID = @User.Identity.Name, DocumentType = "Meeting", OperationType = "Error", Comments = "Create - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Create - Meeting\r\n" + planNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = planNumber, UserID = GetUserIdentityName(), DocumentType = "Meeting", OperationType = "Error", Comments = "Create - " + exceptionString }); throw new Exception("Error: " + e.Message); } } public ActionResult EditMeeting(int meetingID) { int isITARCompliant = 1; - CCMeeting meeting = new CCMeeting(); - meeting = ccDMO.GetMeetingRead(meetingID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + CCMeeting meeting = new(); + meeting = ccDMO.GetMeetingRead(meetingID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); ViewBag.MeetingList = ccDMO.GetMeetingList(meeting.PlanNumber); // TODO locked functionality List userList = MiscDMO.GetApproversListByDocument(meeting.PlanNumber, meeting.CurrentStep, (int)GlobalVars.DocumentType.ChangeControl); - ApproversListViewModel appUser = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); + ApproversListViewModel appUser = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == GlobalVars.GetUserId(GetSession()); }); if (appUser != null) { ViewBag.IsApprover = "true"; } @@ -241,7 +260,7 @@ public class ChangeControlController : Controller { { return View("UnAuthorizedAccess"); } else { - if ((meeting.RecordLockIndicator && meeting.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) + if ((meeting.RecordLockIndicator && meeting.RecordLockedBy != GlobalVars.GetUserId(GetSession())) || (meeting.PCRBClosed)) { return RedirectToAction("ReadOnlyMeeting", new { meetingID = meetingID }); } else if (meeting.Decision != -1) { @@ -251,7 +270,7 @@ public class ChangeControlController : Controller { ViewBag.Attendees = ccDMO.GetUsers(); ViewBag.Sites = ccDMO.GetSites(); ViewBag.PCRValues = ccDMO.GetPCRValues(); - meeting = ccDMO.GetMeeting(meetingID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + meeting = ccDMO.GetMeeting(meetingID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); return View(meeting); } @@ -260,8 +279,8 @@ public class ChangeControlController : Controller { public ActionResult ReadOnlyMeeting(int meetingID) { int isITARCompliant = 1; - CCMeeting meeting = new CCMeeting(); - meeting = ccDMO.GetMeetingRead(meetingID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + CCMeeting meeting = new(); + meeting = ccDMO.GetMeetingRead(meetingID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); ViewBag.MeetingList = ccDMO.GetMeetingList(meeting.PlanNumber); ViewBag.PCRValues = ccDMO.GetPCRValues(); @@ -286,13 +305,13 @@ public class ChangeControlController : Controller { public ActionResult EditMeetingUpdate(int meetingID) { int isITARCompliant = 1; - CCMeeting meeting = new CCMeeting(); - meeting = ccDMO.GetMeetingRead(meetingID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + CCMeeting meeting = new(); + meeting = ccDMO.GetMeetingRead(meetingID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); ViewBag.MeetingList = ccDMO.GetMeetingList(meeting.PlanNumber); ViewBag.PCRValues = ccDMO.GetPCRValues(); // TODO locked functionality List userList = MiscDMO.GetApproversListByDocument(meeting.PlanNumber, meeting.CurrentStep, (int)GlobalVars.DocumentType.ChangeControl); - ApproversListViewModel appUser = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); + ApproversListViewModel appUser = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == GlobalVars.GetUserId(GetSession()); }); if (appUser != null) { ViewBag.IsApprover = "true"; } @@ -301,11 +320,11 @@ public class ChangeControlController : Controller { { return View("UnAuthorizedAccess"); } else { - if ((meeting.RecordLockIndicator && meeting.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) + if ((meeting.RecordLockIndicator && meeting.RecordLockedBy != GlobalVars.GetUserId(GetSession())) || (meeting.PCRBClosed)) { return RedirectToAction("ReadOnlyMeeting", new { meetingID = meetingID }); } else { - meeting = ccDMO.GetMeeting(meetingID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + meeting = ccDMO.GetMeeting(meetingID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); ViewBag.AIResponsibles = ccDMO.GetActionItemResponsible(); @@ -336,10 +355,14 @@ public class ChangeControlController : Controller { return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); } +#if !NET8 + public ActionResult GetDecisionsSummaryList([DataSourceRequest] DataSourceRequest request, int meetingID) { return Json(ccDMO.GetDecisionsSummaryList(meetingID).ToDataSourceResult(request)); } +#endif + public ActionResult UpdateMeetingDecisionNotes(CCDecisionSummary model) { try { ccDMO.UpdateDecisionSummary(model); @@ -349,6 +372,8 @@ public class ChangeControlController : Controller { return Content("Saved Succesfully"); } +#if !NET8 + [AcceptVerbs(HttpVerbs.Post)] public ActionResult DeleteDecisionsSummary([DataSourceRequest] DataSourceRequest request, CCDecisionSummary model) { if (model != null && ModelState.IsValid) { @@ -357,6 +382,8 @@ public class ChangeControlController : Controller { return Json(new[] { model }.ToDataSourceResult(request, ModelState)); } +#endif + public ActionResult InsertDecisionsSummary(CCDecisionSummary model) { try { ccDMO.InsertDecisionSummary(model); @@ -375,19 +402,23 @@ public class ChangeControlController : Controller { return Content("Saved Succesfully", "application/json"); } +#if !NET8 + public ActionResult GetMeetingList([DataSourceRequest] DataSourceRequest request, int planNumber) { var meetingList = ccDMO.GetMeetingList(planNumber); return Json(meetingList.ToDataSourceResult(request)); } - /// public ActionResult GetMeetingAttendees([DataSourceRequest] DataSourceRequest request, int meetingID) { return Json(ccDMO.GetMeetingAttendees(meetingID).ToDataSourceResult(request)); } + public ActionResult GetPCRBAttendees([DataSourceRequest] DataSourceRequest request, int PCRBID) { return Json(ccDMO.GetPCRBAttendees(PCRBID).ToDataSourceResult(request)); } +#endif + public void InsertNewMeetingAttendee(string attendeeName, string jobTitle, string siteName) { try { } catch (Exception e) { @@ -412,8 +443,8 @@ public class ChangeControlController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + docid.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n UpdateMeetingAttendee - Change Control\r\n" + docid.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = docid, UserID = @User.Identity.Name, DocumentType = "Change Control", OperationType = "Error", Comments = "UpdateMeetingAttendee - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n UpdateMeetingAttendee - Change Control\r\n" + docid.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = docid, UserID = GetUserIdentityName(), DocumentType = "Change Control", OperationType = "Error", Comments = "UpdateMeetingAttendee - " + exceptionString }); throw new Exception(e.Message); } } @@ -432,12 +463,14 @@ public class ChangeControlController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + docid.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n UpdateMeetingAttendee - Change Control\r\n" + docid.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = docid, UserID = @User.Identity.Name, DocumentType = "Change Control", OperationType = "Error", Comments = "UpdateMeetingAttendee - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n UpdateMeetingAttendee - Change Control\r\n" + docid.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = docid, UserID = GetUserIdentityName(), DocumentType = "Change Control", OperationType = "Error", Comments = "UpdateMeetingAttendee - " + exceptionString }); throw new Exception(e.Message); } } +#if !NET8 + [AcceptVerbs(HttpVerbs.Post)] public ActionResult DeleteMeetingAttendee([DataSourceRequest] DataSourceRequest request, CCMeetingAttendee model) { if (model != null && ModelState.IsValid) { @@ -475,6 +508,8 @@ public class ChangeControlController : Controller { return Json(ccDMO.GetMeetingActionItems_All(planNumber).ToDataSourceResult(request)); } +#endif + public ActionResult InsertPCRBActionItem(CCPCRBActionItem model) { try { if (model != null) { @@ -501,6 +536,8 @@ public class ChangeControlController : Controller { return Content("1"); } +#if !NET8 + public ActionResult InsertPCRBAttendee([DataSourceRequest] DataSourceRequest request, int pcrId, int attendeeId, string jobTitle, string siteName) { CCPCRBAttendee newAttendee = new CCPCRBAttendee(); newAttendee.AttendeeID = attendeeId; @@ -517,6 +554,8 @@ public class ChangeControlController : Controller { return Content("1"); } +#endif + public ActionResult UpdatePCRBActionItem(CCPCRBActionItem model) { try { if (model != null) { @@ -529,10 +568,12 @@ public class ChangeControlController : Controller { return Content("1"); } +#if !NET8 + [AcceptVerbs(HttpVerbs.Post)] public ActionResult UpdateMeetingActionItemAll([DataSourceRequest] DataSourceRequest request, CCMeetingActionItemAll model) { if (model != null && ModelState.IsValid) { - model.ClosedBy = (int)Session[GlobalVars.SESSION_USERID]; + model.ClosedBy = GlobalVars.GetUserId(GetSession()); ccDMO.UpdateMeetingActionItem_All(model); } if (model.ClosedStatus) @@ -543,6 +584,8 @@ public class ChangeControlController : Controller { return Json(new[] { model }.ToDataSourceResult(request, ModelState)); } +#endif + public ActionResult UpdateMeetingActionItem(CCMeetingActionItem model) { try { if (model != null) { @@ -557,11 +600,11 @@ public class ChangeControlController : Controller { [HttpPost] public ActionResult ReassignMeetingActionItemResponsiblePersons(int meetingActionItemId, string newResponsiblePersonIDs, string comments) { - if (Session[GlobalVars.IS_ADMIN] == null) + if (GlobalVars.IsAdminValueNull(GetSession())) throw new Exception("Permission denied"); try { - ccDMO.ReassignMeetingActionItemResponsiblePersons(meetingActionItemId, newResponsiblePersonIDs, comments, (int)Session[GlobalVars.SESSION_USERID]); + ccDMO.ReassignMeetingActionItemResponsiblePersons(meetingActionItemId, newResponsiblePersonIDs, comments, GlobalVars.GetUserId(GetSession())); } catch (Exception ex) { return Content(ex.Message.ToString()); } @@ -569,6 +612,8 @@ public class ChangeControlController : Controller { return Content("1"); } +#if !NET8 + [AcceptVerbs(HttpVerbs.Post)] public ActionResult DeleteMeetingActionItem([DataSourceRequest] DataSourceRequest request, CCMeetingActionItem model) { if (model != null && ModelState.IsValid) { @@ -584,6 +629,8 @@ public class ChangeControlController : Controller { return Json(new[] { model }.ToDataSourceResult(request, ModelState)); } +#endif + public void CompleteCC(int planNumber) { int docid = planNumber; try { @@ -596,8 +643,8 @@ public class ChangeControlController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + docid.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n CompleteCC - Change Control\r\n" + docid.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = docid, UserID = @User.Identity.Name, DocumentType = "Change Control", OperationType = "Error", Comments = "CompleteCC - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n CompleteCC - Change Control\r\n" + docid.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = docid, UserID = GetUserIdentityName(), DocumentType = "Change Control", OperationType = "Error", Comments = "CompleteCC - " + exceptionString }); throw new Exception(e.Message); } } @@ -614,16 +661,18 @@ public class ChangeControlController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + docid.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n CompleteCC - Change Control\r\n" + docid.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = docid, UserID = @User.Identity.Name, DocumentType = "Change Control", OperationType = "Error", Comments = "CancelCC - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n CompleteCC - Change Control\r\n" + docid.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = docid, UserID = GetUserIdentityName(), DocumentType = "Change Control", OperationType = "Error", Comments = "CancelCC - " + exceptionString }); throw new Exception(e.Message); } } +#if !NET8 + public ActionResult AttachSaveActionItem(IEnumerable AIfiles, int planNumber, int attachID) { // The Name of the Upload component is "files" if (AIfiles != null) { - int userId = (int)Session[GlobalVars.SESSION_USERID]; + int userId = GlobalVars.GetUserId(GetSession()); foreach (var file in AIfiles) { ChangeControlHelper.AttachSaveActionItem(_AppSettings, ccDMO, planNumber, attachID, userId, file.FileName, file.InputStream); } @@ -631,6 +680,8 @@ public class ChangeControlController : Controller { return Content(""); } +#endif + public FileResult DownloadActionItemFile(string fileGuid, int planNumber) { string fileName = ccDMO.GetActionItemFileName(fileGuid); @@ -658,36 +709,36 @@ public class ChangeControlController : Controller { } public void ReleaseLockOnDocument(int planNumber) { - ccDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], planNumber); + ccDMO.ReleaseLockOnDocument(GlobalVars.GetUserId(GetSession()), planNumber); try { - ccDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], planNumber); + ccDMO.ReleaseLockOnDocument(GlobalVars.GetUserId(GetSession()), planNumber); } catch (Exception e) { try { - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReleaseLockOnDocument LD\r\n" + planNumber.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ReleaseLockOnDocument LD\r\n" + planNumber.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error); } catch { } ccDMO.ReleaseLockOnDocument(-1, planNumber); } } public JsonResult GetAllUsersList() { - UserAccountDMO userDMO = new UserAccountDMO(); + UserAccountDMO userDMO = new(); IEnumerable userlist = userDMO.GetAllUsers(); - return Json(userlist, JsonRequestBehavior.AllowGet); + return GetJsonResult(userlist); } [HttpPost] public void ReAssignOwnerByAdmin(string planNumber, string comments, int newOwnerId) { - if (Session[GlobalVars.IS_ADMIN] == null) + if (GlobalVars.IsAdminValueNull(GetSession())) throw new Exception("Permission denied"); int planNumberInt = 0; try { // remove non-numeric characters from Plan # then convert to int - planNumberInt = Int32.Parse(new String(planNumber.Where(c => char.IsNumber(c)).ToArray())); + planNumberInt = int.Parse(new string(planNumber.Where(char.IsNumber).ToArray())); - ccDMO.ReassignOwner(planNumberInt, newOwnerId, comments, (int)Session[GlobalVars.SESSION_USERID]); + ccDMO.ReassignOwner(planNumberInt, newOwnerId, comments, GlobalVars.GetUserId(GetSession())); } catch (Exception e) { string detailedException = ""; try { @@ -698,17 +749,46 @@ public class ChangeControlController : Controller { string exceptionString = e.Message.ToString().Trim(); if (exceptionString.Length > 450) exceptionString = exceptionString.Substring(0, 450); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReAssignOwnerByAdmin\r\n" + planNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = planNumberInt, UserID = @User.Identity.Name, DocumentType = "ChangeControl", OperationType = "Error", Comments = "ReAssignOwnerByAdmin - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ReAssignOwnerByAdmin\r\n" + planNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = planNumberInt, UserID = GetUserIdentityName(), DocumentType = "ChangeControl", OperationType = "Error", Comments = "ReAssignOwnerByAdmin - " + exceptionString }); throw new Exception(e.Message); } } public ActionResult GetPCRBMesaTitle(int issueID) { int isItarCompliant = 1; - ChangeControlViewModel cc = ccDMO.GetChangeControlRead(issueID, out isItarCompliant, (int)Session[GlobalVars.SESSION_USERID]); + ChangeControlViewModel cc = ccDMO.GetChangeControlRead(issueID, out isItarCompliant, GlobalVars.GetUserId(GetSession())); string content = cc.PlanTitle; return Content(content); } +#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; + } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/CorrectiveActionController.cs b/Fab2ApprovalSystem/Controllers/CorrectiveActionController.cs index fbcda14..3128de1 100644 --- a/Fab2ApprovalSystem/Controllers/CorrectiveActionController.cs +++ b/Fab2ApprovalSystem/Controllers/CorrectiveActionController.cs @@ -1,43 +1,63 @@ using System; using System.Collections.Generic; -using System.Configuration; using System.Linq; +#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 Fab2ApprovalSystem.Utilities; +#endif using Fab2ApprovalSystem.ViewModels; +#if !NET8 using Kendo.Mvc.Extensions; using Kendo.Mvc.UI; +#endif namespace Fab2ApprovalSystem.Controllers; [Authorize] +#if !NET8 [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] [SessionExpireFilter] +#endif +#if NET8 +[Route("[controller]")] +#endif public class CorrectiveActionController : Controller { - AuditDMO auditDMO = new AuditDMO(GlobalVars.AppSettings); - CorrectiveActionDMO caDMO = new CorrectiveActionDMO(); - WorkflowDMO wfDMO = new WorkflowDMO(); + private readonly AuditDMO auditDMO = new(GlobalVars.AppSettings); + private readonly CorrectiveActionDMO caDMO = new(); + private readonly WorkflowDMO wfDMO = new(); private readonly AppSettings _AppSettings = GlobalVars.AppSettings; - UserAccountDMO userDMO = new UserAccountDMO(); + private readonly UserAccountDMO userDMO = new(); + +#if !NET8 + FileUtilities fileUtilities = new FileUtilities(); +#endif + public ActionResult Index() { return View(); } public ActionResult Create() { - CorrectiveAction ca = new CorrectiveAction(); + CorrectiveAction ca = new(); try { // TODO: Add insert logic here - ca.RequestorID = (int)Session[GlobalVars.SESSION_USERID]; + ca.RequestorID = GlobalVars.GetUserId(GetSession()); caDMO.InsertCA(ca); return RedirectToAction("Edit", new { issueID = ca.CANo }); } catch (Exception e) { @@ -48,18 +68,18 @@ public class CorrectiveActionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ca.CANo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SubmitDocument - Audit\r\n" + ca.CANo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ca.CANo, UserID = @User.Identity.Name, DocumentType = "CA", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n SubmitDocument - Audit\r\n" + ca.CANo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ca.CANo, UserID = GetUserIdentityName(), DocumentType = "CA", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); throw new Exception(e.Message); } } public ActionResult CreateFromAudit(string title) { - CorrectiveAction ca = new CorrectiveAction(); + CorrectiveAction ca = new(); try { // TODO: Add insert logic here - ca.RequestorID = (int)Session[GlobalVars.SESSION_USERID]; + ca.RequestorID = GlobalVars.GetUserId(GetSession()); ca.CASource = "Audit"; caDMO.InsertCA(ca); string test = ca.CANoDisp; @@ -72,43 +92,43 @@ public class CorrectiveActionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ca.CANo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SubmitDocument - Audit\r\n" + ca.CANo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ca.CANo, UserID = @User.Identity.Name, DocumentType = "CA", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n SubmitDocument - Audit\r\n" + ca.CANo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ca.CANo, UserID = GetUserIdentityName(), DocumentType = "CA", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); throw new Exception(e.Message); } } public ActionResult Edit(int issueID) { - CorrectiveAction ca = new CorrectiveAction(); + CorrectiveAction ca = new(); string s = Functions.ReturnCANoStringFormat(issueID); try { List _8DQAList = caDMO.Get8DQA(); - int QAs = _8DQAList.Find(delegate (int al) { return al == (int)Session[GlobalVars.SESSION_USERID]; }); + int QAs = _8DQAList.Find(delegate (int al) { return al == GlobalVars.GetUserId(GetSession()); }); ViewBag.Is8DQA = "false"; if (QAs != 0) { ViewBag.Is8DQA = "true"; } - ca = caDMO.GetCAItem(issueID, (int)Session[GlobalVars.SESSION_USERID]); + ca = caDMO.GetCAItem(issueID, GlobalVars.GetUserId(GetSession())); ViewBag.CanCompleteCA = "false"; - if (ca.D1AssigneeID == (int)Session[GlobalVars.SESSION_USERID]) + if (ca.D1AssigneeID == GlobalVars.GetUserId(GetSession())) ViewBag.CanCompleteCA = "true"; List userList = MiscDMO.GetPendingApproversListByDocument(issueID, ca.CurrentStep, (int)GlobalVars.DocumentType.CorrectiveAction); - ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); + ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == GlobalVars.GetUserId(GetSession()); }); if (approver == null) ViewBag.IsApprover = "false"; else ViewBag.IsApprover = "true"; - ViewBag.IsAIAssignee = caDMO.IsAIAssignee((int)Session[GlobalVars.SESSION_USERID], issueID); - ViewBag.IsSectionApprover = caDMO.IsUserSectionApprover(ca.CANo, (int)Session[GlobalVars.SESSION_USERID]); + ViewBag.IsAIAssignee = caDMO.IsAIAssignee(GlobalVars.GetUserId(GetSession()), issueID); + ViewBag.IsSectionApprover = caDMO.IsUserSectionApprover(ca.CANo, GlobalVars.GetUserId(GetSession())); ViewBag.AuditFindingCategoriesOptions = auditDMO.GetAuditFindingCategories().ToList(); - if (ca.RelatedAudit != null && ca.RelatedAudit > 0) { - Audit audit = auditDMO.GetAuditItem(ca.RelatedAudit, (int)Session[GlobalVars.SESSION_USERID]); + if (ca.RelatedAudit > 0) { + Audit audit = auditDMO.GetAuditItem(ca.RelatedAudit, GlobalVars.GetUserId(GetSession())); IEnumerable auditFindings = auditDMO.GetAuditFindingsList(audit.AuditNo); AuditFindings relatedFinding = (from a in auditFindings where a.CANo == ca.CANo select a).First(); @@ -129,7 +149,7 @@ public class CorrectiveActionController : Controller { if ((ca.ClosedDate != null) || // TODO Aproverslist================================================================ (ca.ClosedDate != null && ViewBag.IsApprover == "false" && ViewBag.IsAIAssignee == "false") || - (ca.RecordLockIndicator && ca.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) || (ca.Status == 11 && ViewBag.IsApprover == "false")) { + (ca.RecordLockIndicator && ca.RecordLockedBy != GlobalVars.GetUserId(GetSession())) || (ca.Status == 11 && ViewBag.IsApprover == "false")) { return RedirectToAction("ReadOnlyCA", new { caNo = ca.CANo }); } else { ViewBag.ECNList = caDMO.GetECNList(); @@ -154,8 +174,8 @@ public class CorrectiveActionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ca.CANo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Edit - CA\r\n" + ca.CANo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ca.CANo, UserID = @User.Identity.Name, DocumentType = "Audit", OperationType = "Error", Comments = "Edit - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Edit - CA\r\n" + ca.CANo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ca.CANo, UserID = GetUserIdentityName(), DocumentType = "Audit", OperationType = "Error", Comments = "Edit - " + exceptionString }); throw new Exception(e.Message); } @@ -164,7 +184,7 @@ public class CorrectiveActionController : Controller { [HttpPost] public ActionResult Edit(CorrectiveAction model) { - int currentUserId = (int)Session[GlobalVars.SESSION_USERID]; + int currentUserId = GlobalVars.GetUserId(GetSession()); CorrectiveAction caPrevious = caDMO.GetCAItemReadOnly(model.CANo, currentUserId); if ((currentUserId != caPrevious.D1AssigneeID && currentUserId != caPrevious.QAID && currentUserId != caPrevious.RequestorID)) { return Content("User is not authorized to save the CA."); @@ -201,7 +221,7 @@ public class CorrectiveActionController : Controller { return Content("Successfully Saved...Approval initiated!"); } if (model.TriggerApproval) { - caDMO.StartApproval(model.CANo, (int)Session[GlobalVars.SESSION_USERID], model.WorkFlowNumber); + caDMO.StartApproval(model.CANo, GlobalVars.GetUserId(GetSession()), model.WorkFlowNumber); NotifyApprovers(model.CANo, 1); return Content("Successfully Saved...Approval initiated!"); } @@ -213,9 +233,9 @@ public class CorrectiveActionController : Controller { } public ActionResult ReadOnlyCA(int caNo) { - CorrectiveAction ca = new CorrectiveAction(); + CorrectiveAction ca = new(); - ca = caDMO.GetCAItemReadOnly(caNo, (int)Session[GlobalVars.SESSION_USERID]); + ca = caDMO.GetCAItemReadOnly(caNo, GlobalVars.GetUserId(GetSession())); if (ca.Status == 1 || ca.Status == 2 || ca.Status == 11 || ca.ClosedDate != null) { ViewBag.UserList = caDMO.GetAllUserList(); } else { @@ -227,8 +247,8 @@ public class CorrectiveActionController : Controller { ViewBag.D5D6ImprovementIDs = caDMO.GetD5D6Improvement(); ViewBag.AuditFindingCategoriesOptions = auditDMO.GetAuditFindingCategories().ToList(); - if (ca.RelatedAudit != null && ca.RelatedAudit > 0) { - Audit audit = auditDMO.GetAuditItem(ca.RelatedAudit, (int)Session[GlobalVars.SESSION_USERID]); + if (ca.RelatedAudit > 0) { + Audit audit = auditDMO.GetAuditItem(ca.RelatedAudit, GlobalVars.GetUserId(GetSession())); IEnumerable auditFindings = auditDMO.GetAuditFindingsList(audit.AuditNo); AuditFindings relatedFinding = (from a in auditFindings where a.CANo == ca.CANo select a).First(); @@ -254,26 +274,32 @@ public class CorrectiveActionController : Controller { caDMO.ReleaseLockOnDocument(-1, issueID); } catch (Exception e) { try { - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReleaseLockOnDocument CA\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ReleaseLockOnDocument CA\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error); } catch { } caDMO.ReleaseLockOnDocument(-1, issueID); } } +#if !NET8 + public ActionResult GetD2AttachmentList([DataSourceRequest] DataSourceRequest request, int caNo) { return Json(caDMO.GetCAAttachmentsList(caNo, Functions.CASectionMapper(GlobalVars.CASection.D2)).ToDataSourceResult(request)); } public ActionResult Attachment_Read([DataSourceRequest] DataSourceRequest request, int caNO) { - return Json(caDMO.GetCAAttachmentsList(caNO, "Main").ToDataSourceResult(request), JsonRequestBehavior.AllowGet); + return GetJsonResult(caDMO.GetCAAttachmentsList(caNO, "Main").ToDataSourceResult(request)); } +#endif + [HttpPost] public void DeleteCAAttachment(int attachmentID) { caDMO.DeleteCAAttachment(attachmentID); } +#if !NET8 + public ActionResult DownloadCAAttachment(string fileGuid, int caNo) { try { string fileName = caDMO.GetCAAttachmentFileName(fileGuid); @@ -312,7 +338,7 @@ public class CorrectiveActionController : Controller { try { // The Name of the Upload component is "files" if (files != null) { - int userId = (int)Session[GlobalVars.SESSION_USERID]; + int userId = GlobalVars.GetUserId(GetSession()); foreach (var file in files) { CorrectiveActionHelper.AttachSave(_AppSettings, caDMO, caNo, userId, file.FileName, file.InputStream); } @@ -328,6 +354,8 @@ public class CorrectiveActionController : Controller { return Json(caDMO.GetD3ContainmentActions(caNo).ToDataSourceResult(request)); } +#endif + public ActionResult UpdateD3ContainmentAction(D3ContainmentAction data) { caDMO.UpdateD3ContainmentAction(data); if (data.ResponsibilityOwnerID != data.CurrentResponsibilityOwnerID && data.ResponsibilityOwnerID != 0) { @@ -339,7 +367,7 @@ public class CorrectiveActionController : Controller { public ActionResult InsertD3ContainmentAction(D3ContainmentAction data) { caDMO.InsertD3ContainmentAction(data); - if (data.ResponsibilityOwnerID != null && data.ResponsibilityOwnerID != 0) { + if (data.ResponsibilityOwnerID != 0) { NotifyActionItemOwner(data.CANo, data.ECD, data.ResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt"); } return Content(""); @@ -350,6 +378,8 @@ public class CorrectiveActionController : Controller { caDMO.DeleteD3ContainmentActionItem(d3ContainmentActionID); } +#if !NET8 + public ActionResult GetD4AttachmentList([DataSourceRequest] DataSourceRequest request, int caNo) { return Json(caDMO.GetCAAttachmentsList(caNo, Functions.CASectionMapper(GlobalVars.CASection.D4)).ToDataSourceResult(request)); } @@ -358,7 +388,7 @@ public class CorrectiveActionController : Controller { try { // The Name of the Upload component is "files" if (D4Files != null) { - int userId = (int)Session[GlobalVars.SESSION_USERID]; + int userId = GlobalVars.GetUserId(GetSession()); foreach (var file in D4Files) { CorrectiveActionHelper.D4FilesAttachSave(_AppSettings, caDMO, caNo, userId, file.FileName, file.InputStream); } @@ -374,6 +404,8 @@ public class CorrectiveActionController : Controller { return Json(caDMO.GetD5D6CorrectivetActions(caNo).ToDataSourceResult(request)); } +#endif + public ActionResult InsertD5D6CAItem(D5D6CorrectivetAction data) { try { caDMO.InsertD5D6CorrectivetAction(data); @@ -385,7 +417,7 @@ public class CorrectiveActionController : Controller { public ActionResult UpdateD5D6CAItem(D5D6CorrectivetAction data) { D5D6CorrectivetAction previousData = caDMO.GetD5D5CAItem(data.ID); - CorrectiveAction caData = caDMO.GetCAItem(data.CANo, (int)Session[GlobalVars.SESSION_USERID]); + CorrectiveAction caData = caDMO.GetCAItem(data.CANo, GlobalVars.GetUserId(GetSession())); try { caDMO.UpdateD5D6CorrectivetAction(data); } catch (Exception e) { @@ -404,26 +436,32 @@ public class CorrectiveActionController : Controller { } public ActionResult GetD5D6CAItem(int d5d6CAID) { - var model = new D5D6CorrectivetAction(); + D5D6CorrectivetAction model = new(); model = caDMO.GetD5D5CAItem(d5d6CAID); return PartialView("_D5D6CAAttachment", model); } +#if !NET8 + public ActionResult GetD5D6ItemAttachments([DataSourceRequest] DataSourceRequest request, int d5d6CAID) { return Json(caDMO.GetD5D6ItemAttachments(d5d6CAID).ToDataSourceResult(request)); } +#endif + [HttpPost] public void DeleteD5D6CAItem(int d5d6CAID) { caDMO.DeleteD5D6CorrectivetAction(d5d6CAID); } +#if !NET8 + public ActionResult SaveD5D6CA_Attachemnt(IEnumerable D5D6CA_Attachemnt, int d5d6CAID, int caNo) { try { // The Name of the Upload component is "files" if (D5D6CA_Attachemnt != null) { - int userId = (int)Session[GlobalVars.SESSION_USERID]; + int userId = GlobalVars.GetUserId(GetSession()); foreach (var file in D5D6CA_Attachemnt) { CorrectiveActionHelper.SaveD5D6CA_Attachemnt(_AppSettings, caDMO, d5d6CAID, caNo, userId, file.FileName, file.InputStream); } @@ -435,14 +473,15 @@ public class CorrectiveActionController : Controller { return Content(""); } - // D7 ==================================================================================== public ActionResult GetD7PreventiveActionList([DataSourceRequest] DataSourceRequest request, int caNo) { return Json(caDMO.GetD7PreventiveActions(caNo).ToDataSourceResult(request)); } +#endif + public ActionResult InsertD7PAItem(D7PreventiveAction data) { caDMO.InsertD7PreventiveAction(data); - if (data.ResponsibilityOwnerID != null && data.ResponsibilityOwnerID != 0) { + if (data.ResponsibilityOwnerID != 0) { NotifyActionItemOwner(data.CANo, data.ECD, data.ResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt"); } @@ -459,26 +498,32 @@ public class CorrectiveActionController : Controller { } public ActionResult GetD7PAItem(int d7paID) { - var model = new D7PreventiveAction(); + D7PreventiveAction model = new(); model = caDMO.GetD7PAItem(d7paID); return PartialView("_D7PAAttachment", model); } +#if !NET8 + public ActionResult GetD7ItemAttachments([DataSourceRequest] DataSourceRequest request, int d7PAID) { return Json(caDMO.GetD7ItemAttachments(d7PAID).ToDataSourceResult(request)); } +#endif + [HttpPost] public void DeleteD7PAItem(int d7PAID) { caDMO.DeleteD7PreventiveActionItem(d7PAID); } +#if !NET8 + public ActionResult SaveD7PA_Attachemnt(IEnumerable D7PA_Attachemnt, int d7PAID, int caNo) { try { // The Name of the Upload component is "files" if (D7PA_Attachemnt != null) { - int userId = (int)Session[GlobalVars.SESSION_USERID]; + int userId = GlobalVars.GetUserId(GetSession()); foreach (var file in D7PA_Attachemnt) { CorrectiveActionHelper.SaveD7PA_Attachemnt(_AppSettings, caDMO, d7PAID, caNo, userId, file.FileName, file.InputStream); } @@ -490,21 +535,23 @@ public class CorrectiveActionController : Controller { return Content(""); } +#endif + public void ReleaseLockOnDocument(int issueID) { try { - caDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], issueID); + caDMO.ReleaseLockOnDocument(GlobalVars.GetUserId(GetSession()), issueID); } catch (Exception e) { try { - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReleaseLockOnDocument CA\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ReleaseLockOnDocument CA\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error); } catch { } caDMO.ReleaseLockOnDocument(-1, issueID); } } public JsonResult GetAllUsersList() { - UserAccountDMO userDMO = new UserAccountDMO(); + UserAccountDMO userDMO = new(); IEnumerable userlist = userDMO.GetAllUsers(); - return Json(userlist, JsonRequestBehavior.AllowGet); + return GetJsonResult(userlist); } public void ReAssignApproverByAdmin(int issueID, int reAssignApproverFrom, int reAssignApproverTo, byte step, int docType) { @@ -519,20 +566,20 @@ public class CorrectiveActionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReAssignApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "CA", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ReAssignApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "CA", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); throw new Exception(e.Message); } CorrectiveActionHelper.ReAssignApproverByAdmin(_AppSettings, issueID, email); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "ReAssign Approver: " + email }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Email", Comments = "ReAssign Approver: " + email }); } catch { } } public void ReAssignApproval(int issueID, int userIDs, byte step) { var email = ""; try { - email = wfDMO.ReAssignApproval(issueID, (int)Session[GlobalVars.SESSION_USERID], userIDs, step, (int)GlobalVars.DocumentType.CorrectiveAction); + email = wfDMO.ReAssignApproval(issueID, GlobalVars.GetUserId(GetSession()), userIDs, step, (int)GlobalVars.DocumentType.CorrectiveAction); } catch (Exception e) { string detailedException = ""; try { @@ -541,20 +588,20 @@ public class CorrectiveActionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReAssignApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ReAssignApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); throw new Exception(e.Message); } CorrectiveActionHelper.ReAssignApproval(_AppSettings, issueID, email); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "ReAssign Approver: " + email }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Email", Comments = "ReAssign Approver: " + email }); } catch { } } public void Reject(int issueID, byte currentStep, string comments) { try { - if (Session[GlobalVars.SESSION_USERID] != null) { - wfDMO.Reject(issueID, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.CorrectiveAction); + if (GlobalVars.IsUserIdValueNotNull(GetSession())) { + wfDMO.Reject(issueID, currentStep, comments, GlobalVars.GetUserId(GetSession()), (int)GlobalVars.DocumentType.CorrectiveAction); NotifyRejectionToAssignee(issueID, comments); } else { Response.Redirect("~/Account/Login"); @@ -567,18 +614,18 @@ public class CorrectiveActionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Reject\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Reject - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Reject\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "Reject - " + exceptionString }); throw new Exception(e.Message); } } public void NotifyRejectionToAssignee(int issueID, string comments) { - string username = Session[GlobalVars.SESSION_USERNAME].ToString(); + string username = GlobalVars.GetUserName(GetSession()); List emailIst = caDMO.GetRejectionAssigneeEmailList(@issueID).Distinct().ToList(); string userEmail = CorrectiveActionHelper.NotifyRejectionToAssignee(_AppSettings, issueID, comments, username, emailIst); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Rejection: " + userEmail }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Email", Comments = "Rejection: " + userEmail }); } catch { } } @@ -586,9 +633,9 @@ public class CorrectiveActionController : Controller { int isITARCompliant = 1; try { bool lastStep = false; - CorrectiveAction ca = caDMO.GetCAItemReadOnly(issueID, (int)Session[GlobalVars.SESSION_USERID]); + CorrectiveAction ca = caDMO.GetCAItemReadOnly(issueID, GlobalVars.GetUserId(GetSession())); - bool lastApprover = wfDMO.Approve(_AppSettings, issueID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.CorrectiveAction, ca.WorkFlowNumber); + bool lastApprover = wfDMO.Approve(_AppSettings, issueID, currentStep, comments, out lastStep, GlobalVars.GetUserId(GetSession()), (int)GlobalVars.DocumentType.CorrectiveAction, ca.WorkFlowNumber); if (lastApprover && !lastStep) { // Set to complete @@ -610,8 +657,8 @@ public class CorrectiveActionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n " + "Approve\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Approve - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n " + "Approve\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "Approve - " + exceptionString }); throw new Exception(e.Message); } } @@ -621,7 +668,7 @@ public class CorrectiveActionController : Controller { string userEmail = userDMO.GetUserEmailByID(userId); CorrectiveActionHelper.NotifySectionApprover(_AppSettings, issueID, section, userEmail); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Approvers for Step " }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Email", Comments = "Approvers for Step " }); } catch { } } catch (Exception e) { string detailedException = ""; @@ -631,9 +678,9 @@ public class CorrectiveActionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Corrective Action - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); - throw e; + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Corrective Action - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); + throw; } } @@ -642,7 +689,7 @@ public class CorrectiveActionController : Controller { List emailIst = MiscDMO.GetApproverEmailListByDocument(@issueID, currentStep, (int)GlobalVars.DocumentType.CorrectiveAction).Distinct().ToList(); string emailSentList = CorrectiveActionHelper.NotifyApprovers(_AppSettings, issueID, emailIst); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); } catch { } } catch (Exception e) { string detailedException = ""; @@ -652,9 +699,9 @@ public class CorrectiveActionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Corrective Action - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); - throw e; + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Corrective Action - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); + throw; } } @@ -673,18 +720,20 @@ public class CorrectiveActionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + " Userid:" + userIDs + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n AddAdditionalApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n AddAdditionalApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); throw new Exception(e.Message); } emailSentList = CorrectiveActionHelper.AddAdditionalApproval(_AppSettings, issueID, emailSentList, emailArray); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Additonal Approver: " + emailSentList }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Email", Comments = "Additonal Approver: " + emailSentList }); } catch { } } #endregion +#if !NET8 + public ActionResult GetApproversList([DataSourceRequest] DataSourceRequest request, int issueID, byte step) { return Json(MiscDMO.GetApproversListByDocument(issueID, step, (int)GlobalVars.DocumentType.CorrectiveAction).ToDataSourceResult(request)); } @@ -693,12 +742,14 @@ public class CorrectiveActionController : Controller { return Json(caDMO.GetCASectionApprovalLog(caNo).ToDataSourceResult(request)); } +#endif + public void NotifyRequestor(int issueID, DateTime? dueDate, int? responsibleOwnerID, string template) { try { string email = MiscDMO.GetEmail(responsibleOwnerID); CorrectiveActionHelper.NotifyRequestor(_AppSettings, issueID, dueDate, template, email); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Task Assigned for 8D Item" + ":" + email }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Email", Comments = "Task Assigned for 8D Item" + ":" + email }); } catch { } } catch (Exception e) { string detailedException = ""; @@ -709,8 +760,8 @@ public class CorrectiveActionController : Controller { } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " 8D Action Item:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n 8D Action Item - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "8D Action Item Notification - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n 8D Action Item - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "8D Action Item Notification - " + exceptionString }); } } @@ -719,7 +770,7 @@ public class CorrectiveActionController : Controller { string email = MiscDMO.GetEmail(responsibleOwnerID); CorrectiveActionHelper.NotifyAssignee(_AppSettings, issueID, template, D3DueDate, D5D7DueDate, email); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Task Assigned for 8D Item" + ":" + email }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Email", Comments = "Task Assigned for 8D Item" + ":" + email }); } catch { } } catch (Exception e) { string detailedException = ""; @@ -730,8 +781,8 @@ public class CorrectiveActionController : Controller { } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " 8D Action Item:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n 8D Action Item - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "8D Action Item Notification - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n 8D Action Item - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "8D Action Item Notification - " + exceptionString }); } } @@ -739,7 +790,7 @@ public class CorrectiveActionController : Controller { try { string email = CorrectiveActionHelper.NotifyActionItemOwner(_AppSettings, issueID, dueDate, responsibleOwnerID, template); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Task Assigned for 8D Item" + ":" + email }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Email", Comments = "Task Assigned for 8D Item" + ":" + email }); } catch { } } catch (Exception e) { string detailedException = ""; @@ -750,8 +801,8 @@ public class CorrectiveActionController : Controller { } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " 8D Action Item:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n 8D Action Item - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "8D Action Item Notification - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n 8D Action Item - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "8D Action Item Notification - " + exceptionString }); } } @@ -759,7 +810,7 @@ public class CorrectiveActionController : Controller { try { string email = CorrectiveActionHelper.NotifyActionItemCompletion(_AppSettings, issueID, dueDate, recipientId, template); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Task Assigned for 8D Item" + ":" + email }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Email", Comments = "Task Assigned for 8D Item" + ":" + email }); } catch { } } catch (Exception e) { string detailedException = ""; @@ -770,8 +821,8 @@ public class CorrectiveActionController : Controller { } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " 8D Action Item:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n 8D Action Item - NotifyActionItemCompletion\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "8D Action Item Notification - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n 8D Action Item - NotifyActionItemCompletion\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "8D Action Item Notification - " + exceptionString }); } } @@ -779,7 +830,7 @@ public class CorrectiveActionController : Controller { try { string emailSentList = CorrectiveActionHelper.NotifyClosureOf8D(_AppSettings, issueID); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Closure of 8D Item" + ":" + emailSentList }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Email", Comments = "Closure of 8D Item" + ":" + emailSentList }); } catch { } } catch (Exception e) { string detailedException = ""; @@ -790,8 +841,8 @@ public class CorrectiveActionController : Controller { } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Closure of 8D:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Closure of 8D - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Closure of 8D Notification - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Closure of 8D - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "Closure of 8D Notification - " + exceptionString }); } } @@ -799,7 +850,7 @@ public class CorrectiveActionController : Controller { try { string emailSentList = CorrectiveActionHelper.NotifyCompletionOf8D(_AppSettings, issueID, followUpDate); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Closure of 8D Item" + ":" + emailSentList }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Email", Comments = "Closure of 8D Item" + ":" + emailSentList }); } catch { } } catch (Exception e) { string detailedException = ""; @@ -810,14 +861,14 @@ public class CorrectiveActionController : Controller { } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Closure of 8D:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Closure of 8D - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Closure of 8D Notification - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Closure of 8D - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "Closure of 8D Notification - " + exceptionString }); } } public void StartSectionApproval(int issueID, string dSection) { try { - CorrectiveAction ca = caDMO.GetCAItem(issueID, (int)Session[GlobalVars.SESSION_USERID]); + CorrectiveAction ca = caDMO.GetCAItem(issueID, GlobalVars.GetUserId(GetSession())); int requestorId = ca.RequestorID; int qaId = ca.QAID; @@ -834,16 +885,16 @@ public class CorrectiveActionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n " + "Approve\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Approve - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n " + "Approve\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "Approve - " + exceptionString }); throw new Exception(e.Message); } } [HttpPost] public ActionResult ApproveSection(int issueID, string dSection) { try { - int userID = (int)Session[GlobalVars.SESSION_USERID]; - CorrectiveAction caItem = caDMO.GetCAItem(issueID, (int)Session[GlobalVars.SESSION_USERID]); + int userID = GlobalVars.GetUserId(GetSession()); + CorrectiveAction caItem = caDMO.GetCAItem(issueID, GlobalVars.GetUserId(GetSession())); caDMO.ApproveSection(issueID, userID, dSection); bool isLastApprover = caDMO.IsLastSectionApprover(issueID, dSection); if (isLastApprover) { @@ -876,8 +927,8 @@ public class CorrectiveActionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n " + "Approve\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Approve - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n " + "Approve\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "Approve - " + exceptionString }); return Content(e.Message); } } @@ -885,7 +936,7 @@ public class CorrectiveActionController : Controller { public ActionResult RejectSection(int issueID, string dSection, string comments) { try { - int userID = (int)Session[GlobalVars.SESSION_USERID]; + int userID = GlobalVars.GetUserId(GetSession()); CorrectiveAction ca = caDMO.GetCAItem(issueID, userID); caDMO.RejectSection(issueID, userID, dSection, comments); // Notify Rejection to assignee and requestor @@ -905,18 +956,19 @@ public class CorrectiveActionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n " + "Reject\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Reject - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n " + "Reject\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "Reject - " + exceptionString }); return Content(e.Message); } } + public void NotifySectionRejection(int issueID, int recipientUserId, int loggedInUserId, string section, string comment) { try { LoginModel recipient = userDMO.GetUserByID(recipientUserId); LoginModel loggedInUser = userDMO.GetUserByID(loggedInUserId); CorrectiveActionHelper.NotifySectionRejection(_AppSettings, issueID, section, comment, recipient, loggedInUser); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Approvers for Step " }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Email", Comments = "Approvers for Step " }); } catch { } } catch (Exception e) { string detailedException = ""; @@ -926,9 +978,9 @@ public class CorrectiveActionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Corrective Action - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); - throw e; + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Corrective Action - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); + throw; } } @@ -937,7 +989,7 @@ public class CorrectiveActionController : Controller { string userEmail = userDMO.GetUserEmailByID(userId); CorrectiveActionHelper.NotifyForD5D6D7Validation(_AppSettings, issueID, dSection, userEmail); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Approvers for Step " }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Email", Comments = "Approvers for Step " }); } catch { } } catch (Exception e) { string detailedException = ""; @@ -947,9 +999,9 @@ public class CorrectiveActionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Corrective Action - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); - throw e; + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Corrective Action - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); + throw; } } @@ -958,7 +1010,7 @@ public class CorrectiveActionController : Controller { string userEmail = userDMO.GetUserEmailByID(userId); CorrectiveActionHelper.NotifyUsersDSectionApproved(_AppSettings, issueID, dSection, userEmail); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Approvers for Step " }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Email", Comments = "Approvers for Step " }); } catch { } } catch (Exception e) { string detailedException = ""; @@ -968,9 +1020,9 @@ public class CorrectiveActionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Corrective Action - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); - throw e; + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Corrective Action - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); + throw; } } @@ -979,10 +1031,12 @@ public class CorrectiveActionController : Controller { return d3DueDate; } + public DateTime SetD5D7DueDate(int caNo) { DateTime d5d7DueDate = caDMO.SetCAD5D7DueDate(caNo); return d5d7DueDate; } + public bool ProcessCARDueDates() { bool isSuccess = false; List dueCAs = caDMO.GetCAD3D5D7Due().ToList(); @@ -1006,8 +1060,8 @@ public class CorrectiveActionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + dueCA.CANo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Corrective Action - ProcessCARDueDates\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = dueCA.CANo, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "ProcessCARDueDates - Called via API - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Corrective Action - ProcessCARDueDates\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = dueCA.CANo, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "ProcessCARDueDates - Called via API - " + exceptionString }); } @@ -1018,4 +1072,33 @@ public class CorrectiveActionController : Controller { public void ProcessCAForFollowUp() { } +#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; + } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/ECNController.cs b/Fab2ApprovalSystem/Controllers/ECNController.cs index b0541e4..dd5da44 100644 --- a/Fab2ApprovalSystem/Controllers/ECNController.cs +++ b/Fab2ApprovalSystem/Controllers/ECNController.cs @@ -1,37 +1,57 @@ using System; using System.Collections.Generic; -using System.Configuration; +using System.Diagnostics; +using System.IO; using System.Linq; + +#if !NET8 using System.Web; using System.Web.Mvc; -using Dapper; +using Fab2ApprovalSystem.PdfGenerator; +#endif + +#if NET8 +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +#endif + +#if NET8 +using Fab2ApprovalSystem.Extensions; +#endif using Fab2ApprovalSystem.DMO; using Fab2ApprovalSystem.Misc; using Fab2ApprovalSystem.Models; -using Fab2ApprovalSystem.PdfGenerator; using Fab2ApprovalSystem.ViewModels; +#if !NET8 using Kendo.Mvc.Extensions; using Kendo.Mvc.UI; +#endif namespace Fab2ApprovalSystem.Controllers; [Authorize] +#if !NET8 [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] [SessionExpireFilter] public class ECNController : PdfViewController { +#endif +#if NET8 +[Route("[controller]")] +public class ECNController : Controller { +#endif private const string ECN_PREFIX = "ECN_"; private const string TECN_PREFIX = "TECN_"; private const string ETECN_PREFIX = "ETECN_"; - ECN_DMO ecnDMO = new ECN_DMO(); - WorkflowDMO wfDMO = new WorkflowDMO(); - TrainingDMO trainingDMO = new TrainingDMO(); - UserAccountDMO userDMO = new UserAccountDMO(); - private readonly AppSettings _AppSettings = GlobalVars.AppSettings; + private readonly ECN_DMO ecnDMO = new(); + private readonly WorkflowDMO wfDMO = new(); + private readonly TrainingDMO trainingDMO = new(); + private readonly UserAccountDMO userDMO = new(); + private readonly AppSettings? _AppSettings = GlobalVars.AppSettings; // GET: /ECN/ public ActionResult Index() { @@ -46,11 +66,11 @@ public class ECNController : PdfViewController { // GET: /ECN/Create public ActionResult Create() { - ECN ecn = new ECN(); + ECN ecn = new(); try { // TODO: Add insert logic here - ecn.OriginatorID = (int)Session[GlobalVars.SESSION_USERID]; + ecn.OriginatorID = GlobalVars.GetUserId(GetSession()); ecnDMO.InsertECN(ecn); return RedirectToAction("Edit", new { issueID = ecn.ECNNumber }); } catch (Exception e) { @@ -61,8 +81,8 @@ public class ECNController : PdfViewController { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecn.ECNNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SubmitDocument - ECN\r\n" + ecn.ECNNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecn.ECNNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n SubmitDocument - ECN\r\n" + ecn.ECNNumber.ToString() + "\r\n" + detailedException, EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecn.ECNNumber, UserID = GetUserIdentityName(), DocumentType = "ECN", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); throw new Exception(e.Message); } } @@ -70,10 +90,10 @@ public class ECNController : PdfViewController { // GET: /ECN/Edit/5 public ActionResult Edit(int issueID) { int isITARCompliant = 1; - ECN ecn = new ECN(); + ECN ecn = new(); try { - ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); if (isITARCompliant == 0) // not ITAR Compliant { @@ -87,10 +107,10 @@ public class ECNController : PdfViewController { return RedirectToAction("EditApproval", new { issueID = issueID }); } else { - if ((ecn.RecordLockIndicator && ecn.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID])) { + if ((ecn.RecordLockIndicator && ecn.RecordLockedBy != GlobalVars.GetUserId(GetSession()))) { return RedirectToAction("ReadOnly", new { issueID = issueID }); } else { - ecn = ecnDMO.GetECN(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + ecn = ecnDMO.GetECN(issueID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); ViewBag.Departments = ecnDMO.GetDepartments(); ViewBag.AffectedModules = ecnDMO.GetModules(); ViewBag.AffectedAreas = ecnDMO.GetECNAreas(); @@ -107,9 +127,9 @@ public class ECNController : PdfViewController { string exceptionString = e.Message.ToString().Trim().Length > 500 ? e.Message.ToString().Substring(0, 250) : e.Message.ToString(); Functions.WriteEvent( _AppSettings, - String.Format("{0}\r\nEdit ECN\r\n{1}\r\n{2}", @User?.Identity?.Name, ecn?.ECNNumber, e.InnerException), - System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = exceptionString }); + string.Format("{0}\r\nEdit ECN\r\n{1}\r\n{2}", @User?.Identity?.Name, ecn?.ECNNumber, e.InnerException), + EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "ECN", OperationType = "Error", Comments = exceptionString }); return View("Error"); } } @@ -128,10 +148,10 @@ public class ECNController : PdfViewController { public ActionResult ReadOnly(int issueID) { int isITARCompliant = 1; - ECN ecn = new ECN(); + ECN ecn = new(); try { - ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); bool trainingRequired = ecn.TrainingRequired; if (isITARCompliant == 0) // not ITAR Compliant { @@ -142,13 +162,13 @@ public class ECNController : PdfViewController { docType = GlobalVars.DocumentType.EECN; List userList = MiscDMO.GetPendingApproversListByDocument(issueID, ecn.CurrentStep, (int)docType); - ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); + ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == GlobalVars.GetUserId(GetSession()); }); if (approver == null) ViewBag.IsApprover = "false"; else ViewBag.IsApprover = "true"; - if ((int)Session[GlobalVars.SESSION_USERID] == ecn.OriginatorID) + if (GlobalVars.GetUserId(GetSession()) == ecn.OriginatorID) ViewBag.IsOriginator = "true"; else ViewBag.IsOriginator = "false"; @@ -179,18 +199,20 @@ public class ECNController : PdfViewController { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReadOnly ECN\r\n" + ecn.ECNNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ReadOnly ECN\r\n" + ecn.ECNNumber.ToString() + "\r\n" + detailedException, EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "ECN", OperationType = "Error", Comments = exceptionString }); throw new Exception(e.Message); } } +#if !NET8 [OutputCache(Duration = 60, VaryByCustom = "host")] +#endif public ActionResult ECNTrainingView(int issueID) { int isITARCompliant = 1; - ECN ecn = new ECN(); + ECN ecn = new(); try { - ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); if (isITARCompliant == 0) // not ITAR Compliant { return PartialView("UnAuthorizedAccess"); @@ -214,17 +236,17 @@ public class ECNController : PdfViewController { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReadOnly ECN\r\n" + ecn.ECNNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ReadOnly ECN\r\n" + ecn.ECNNumber.ToString() + "\r\n" + detailedException, EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "ECN", OperationType = "Error", Comments = exceptionString }); throw new Exception(e.Message); } } public ActionResult Acknowledge(int issueID) { int isITARCompliant = 1; - ECN ecn = new ECN(); + ECN ecn = new(); try { - ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); if (isITARCompliant == 0) // not ITAR Compliant { return View("UnAuthorizedAccess"); @@ -234,13 +256,13 @@ public class ECNController : PdfViewController { docType = GlobalVars.DocumentType.EECN; List userList = MiscDMO.GetPendingApproversListByDocument(issueID, ecn.CurrentStep, (int)docType); - ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); + ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == GlobalVars.GetUserId(GetSession()); }); if (approver == null) ViewBag.IsApprover = "false"; else ViewBag.IsApprover = "true"; - if ((int)Session[GlobalVars.SESSION_USERID] == ecn.OriginatorID) + if (GlobalVars.GetUserId(GetSession()) == ecn.OriginatorID) ViewBag.IsOriginator = "true"; else ViewBag.IsOriginator = "false"; @@ -263,17 +285,17 @@ public class ECNController : PdfViewController { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReadOnly ECN\r\n" + ecn.ECNNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ReadOnly ECN\r\n" + ecn.ECNNumber.ToString() + "\r\n" + detailedException, EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "ECN", OperationType = "Error", Comments = exceptionString }); throw new Exception(e.Message); } } public ActionResult EditApproval(int issueID) { int isITARCompliant = 1; - ECN ecn = new ECN(); + ECN ecn = new(); try { - ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); if (isITARCompliant == 0) // not ITAR Compliant { return View("UnAuthorizedAccess"); @@ -289,13 +311,13 @@ public class ECNController : PdfViewController { docType = GlobalVars.DocumentType.TECNCancelledExpired; List userList = MiscDMO.GetPendingApproversListByDocument(issueID, ecn.CurrentStep, (int)docType); - ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); + ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == GlobalVars.GetUserId(GetSession()); }); if (approver == null) ViewBag.IsApprover = "false"; else ViewBag.IsApprover = "true"; - if ((int)Session[GlobalVars.SESSION_USERID] == ecn.OriginatorID) + if (GlobalVars.GetUserId(GetSession()) == ecn.OriginatorID) ViewBag.IsOriginator = "true"; else ViewBag.IsOriginator = "false"; @@ -308,8 +330,8 @@ public class ECNController : PdfViewController { ViewBag.TrainingStatus = trainingStatus; } if (ViewBag.IsApprover == "true" || ViewBag.IsOriginator == "true") { - ecn = ecnDMO.GetECN(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - if (ecn.RecordLockIndicator && ecn.RecordLockedBy == (int)Session[GlobalVars.SESSION_USERID]) { + ecn = ecnDMO.GetECN(issueID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); + if (ecn.RecordLockIndicator && ecn.RecordLockedBy == GlobalVars.GetUserId(GetSession())) { ViewBag.Departments = ecnDMO.GetDepartments(); ViewBag.AffectedModules = ecnDMO.GetModules(); @@ -336,17 +358,19 @@ public class ECNController : PdfViewController { } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReadOnly ECN\r\n" + ecn.ECNNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ReadOnly ECN\r\n" + ecn.ECNNumber.ToString() + "\r\n" + detailedException, EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "ECN", OperationType = "Error", Comments = exceptionString }); throw new Exception(e.Message); } } +#if !NET8 + public ActionResult AttachSave(IEnumerable files, int ecnNumber) { string returnString = ""; // The Name of the Upload component is "files" if (files != null) { - int userId = (int)Session[GlobalVars.SESSION_USERID]; + int userId = GlobalVars.GetUserId(GetSession()); foreach (var file in files) { returnString = ECNHelper.AttachSave(_AppSettings, ecnDMO, ecnNumber, returnString, userId, file.FileName, file.InputStream); } @@ -355,21 +379,23 @@ public class ECNController : PdfViewController { } public ActionResult Attachment_Read([DataSourceRequest] DataSourceRequest request, int ecnNumber) { - return Json(ecnDMO.GetECNAttachments(ecnNumber).ToDataSourceResult(request), JsonRequestBehavior.AllowGet); + return GetJsonResult(ecnDMO.GetECNAttachments(ecnNumber).ToDataSourceResult(request)); } public ActionResult ApprovalLogHistory_Read([DataSourceRequest] DataSourceRequest request, int ecnNumber) { - return Json(ecnDMO.GetECNApprovalLogHistory(ecnNumber).ToDataSourceResult(request), JsonRequestBehavior.AllowGet); + return GetJsonResult(ecnDMO.GetECNApprovalLogHistory(ecnNumber).ToDataSourceResult(request)); } +#endif + [HttpPost] public void DeleteAttachment(int attachmentID, string fileName, int ecnNumber) { try { if (ModelState.IsValid) { ecnDMO.DeleteECNAttachment(attachmentID); - var physicalPath = System.IO.Path.Combine(_AppSettings.AttachmentFolder + @"ECN\" + ecnNumber.ToString(), fileName); + var physicalPath = Path.Combine(_AppSettings.AttachmentFolder + @"ECN\" + ecnNumber.ToString(), fileName); - System.IO.FileInfo f = new System.IO.FileInfo(physicalPath); + FileInfo f = new(physicalPath); if (f.Exists) f.Delete(); @@ -383,12 +409,14 @@ public class ECNController : PdfViewController { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "AttachmentID=" + attachmentID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n DeleteAttachment ECN\r\n" + ecnNumber.ToString() + detailedException.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = 999, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Delete Attachment " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n DeleteAttachment ECN\r\n" + ecnNumber.ToString() + detailedException.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = 999, UserID = GetUserIdentityName(), DocumentType = "ECN", OperationType = "Error", Comments = "Delete Attachment " + exceptionString }); throw new Exception(e.Message); } } +#if !NET8 + [AcceptVerbs(HttpVerbs.Post)] public ActionResult Attachment_Destroy([DataSourceRequest] DataSourceRequest request, Attachment attachment) { try { @@ -402,10 +430,12 @@ public class ECNController : PdfViewController { return Json(new[] { attachment }.ToDataSourceResult(request, ModelState)); } +#endif + public ActionResult SubmitDocument(int ecnNumber, int documentType, string ecnTypeString) { int isITARCompliant = 1; try { - int appoverCount = ecnDMO.SubmitDocument(ecnNumber, (int)Session[GlobalVars.SESSION_USERID], documentType, out isITARCompliant); + int appoverCount = ecnDMO.SubmitDocument(ecnNumber, GlobalVars.GetUserId(GetSession()), documentType, out isITARCompliant); if (isITARCompliant == 0) // not ITAR Compliant { // the content gets evaluated on the client side @@ -419,11 +449,11 @@ public class ECNController : PdfViewController { } - if (Request.IsAjaxRequest()) { - // the content gets evaluated on the client side + if (IsAjaxRequest()) { return Content("Redirect"); - } else + } else { return Content("Invalid"); + } } } catch (Exception e) { string detailedException = ""; @@ -433,15 +463,15 @@ public class ECNController : PdfViewController { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SubmitDocument\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n SubmitDocument\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = "ECN", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); throw new Exception(e.Message); } } public ActionResult SubmitTECNExtension(int ecnNumber, int documentType, string ecnTypeString, DateTime extensionDate) { try { - int appoverCount = ecnDMO.SubmitTECNExtensionDocument(ecnNumber, (int)Session[GlobalVars.SESSION_USERID], documentType, extensionDate); + int appoverCount = ecnDMO.SubmitTECNExtensionDocument(ecnNumber, GlobalVars.GetUserId(GetSession()), documentType, extensionDate); if (appoverCount > 0) NotifyApprovers(ecnNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1, documentType, ecnTypeString); @@ -450,10 +480,11 @@ public class ECNController : PdfViewController { Approve(ecnNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1, "", documentType, ecnTypeString); // this is the Submit Level Approval } - if (Request.IsAjaxRequest()) { + if (IsAjaxRequest()) { return Content("Redirect"); - } else + } else { return Content("Invalid"); + } } catch (Exception e) { string detailedException = ""; try { @@ -462,8 +493,8 @@ public class ECNController : PdfViewController { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SubmitDocument\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n SubmitDocument\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = "ECN", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); throw new Exception(e.Message); } } @@ -471,16 +502,17 @@ public class ECNController : PdfViewController { public ActionResult SubmitDocument_EmergencyTECN(int ecnNumber, int documentType) { int isITARCompliant = 0; try { - ecnDMO.SubmitDocument(ecnNumber, (int)Session[GlobalVars.SESSION_USERID], documentType, out isITARCompliant); + ecnDMO.SubmitDocument(ecnNumber, GlobalVars.GetUserId(GetSession()), documentType, out isITARCompliant); if (isITARCompliant == 0) // not ITAR Compliant { return View("ITAR"); } else { - if (Request.IsAjaxRequest()) { + if (IsAjaxRequest()) { return Content("Redirect"); - } else + } else { return Content("Invalid"); + } } } catch (Exception e) { string detailedException = ""; @@ -490,8 +522,8 @@ public class ECNController : PdfViewController { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SubmitDocument ETECN\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "SubmitDocument-ETECN - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n SubmitDocument ETECN\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = "ECN", OperationType = "Error", Comments = "SubmitDocument-ETECN - " + exceptionString }); throw new Exception(e.Message); } } @@ -500,7 +532,7 @@ public class ECNController : PdfViewController { try { bool lastStep = false; ECN ecn = ecnDMO.GetECN(ecnNumber); - bool lastApprover = wfDMO.Approve(_AppSettings, ecnNumber, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], documentType, ecn.WorkFlowNumber); + bool lastApprover = wfDMO.Approve(_AppSettings, ecnNumber, currentStep, comments, out lastStep, GlobalVars.GetUserId(GetSession()), documentType, ecn.WorkFlowNumber); while (lastApprover && !lastStep) { @@ -516,7 +548,7 @@ public class ECNController : PdfViewController { NotifySubmitter(ecn.ECNNumber, ecnTypeString); NotifyAdmin(ecn.ECNNumber, ecnTypeString); if (ecn.TrainingRequired) { - TrainingController NewTraining = new TrainingController(); + TrainingController NewTraining = new(); NewTraining.Create(ecnNumber); } @@ -536,11 +568,11 @@ public class ECNController : PdfViewController { IssueID = (int)ecn.ConvertedFromNumber, DocumentTypeID = documentType, OperationType = "Change to " + ecnTypeString + ecnNumber.ToString() + " Approved", - UserID = (int)Session[GlobalVars.SESSION_USERID], + UserID = GlobalVars.GetUserId(GetSession()), OperationLog = "Approval of the Document conversion" }); - List attachments = new List(); + List attachments = new(); attachments.Add(_AppSettings.AttachmentFolder + "ECN\\" + ecnNumber + "\\ECNForm_" + ecnNumber + ".pdf"); attachments.Add(_AppSettings.AttachmentFolder + "ECN\\" + ecnNumber + "\\ECNForm_" + ecn.ConvertedFromNumber + ".pdf"); @@ -557,20 +589,20 @@ public class ECNController : PdfViewController { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Approve\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Approve - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Approve\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = "ECN", OperationType = "Error", Comments = "Approve - " + exceptionString }); throw new Exception(e.Message); } } private void PostApproval(int ecnNumber, int documentType) { try { - ECNPdf ecn = new ECNPdf(); + ECNPdf ecn = new(); // Generate the PDF version of the ECN form and Approval log if (GenerateECNPdf(ecnNumber, out ecn)) { // Zip up all the attached files along with the Pdf version of the ECN form and the Approval Log - if (ECNHelper.CreateZip(_AppSettings, ecn, @User.Identity.Name)) { + if (ECNHelper.CreateZip(_AppSettings, ecn, GetUserIdentityName())) { } else { // TODO How to recreate and send the files to documentum throw new Exception("Problems while generating the ZIP file. Please contact the system Administrator"); @@ -591,9 +623,9 @@ public class ECNController : PdfViewController { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ECN - PostApproval \r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "PostApprovalForECNsDerivedFromTECN - " + exceptionString }); - throw e; + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ECN - PostApproval \r\n" + ecnNumber.ToString() + "\r\n" + detailedException, EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = "ECN", OperationType = "Error", Comments = "PostApprovalForECNsDerivedFromTECN - " + exceptionString }); + throw; } } @@ -603,7 +635,7 @@ public class ECNController : PdfViewController { ECN ecn = ecnDMO.GetECN(ecnNumber); emailSentList = ECNHelper.NotifySubmitter(_AppSettings, ecnNumber, ecnTypeString, ecn); try { - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + ":" + emailSentList }); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + ":" + emailSentList }); } catch { } } catch (Exception e) { string detailedException = ""; @@ -613,9 +645,9 @@ public class ECNController : PdfViewController { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ECN - Notify Approvers \r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Approve - " + exceptionString }); - throw e; + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ECN - Notify Approvers \r\n" + ecnNumber.ToString() + "\r\n" + detailedException, EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = "ECN", OperationType = "Error", Comments = "Approve - " + exceptionString }); + throw; } } @@ -627,7 +659,7 @@ public class ECNController : PdfViewController { foreach (int id in ecnAdminIDs) { emailSentList = ECNHelper.NotifyAdmin(_AppSettings, ecnNumber, ecnTypeString, ecn, id); try { - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + ":" + emailSentList }); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + ":" + emailSentList }); } catch { } } @@ -639,9 +671,9 @@ public class ECNController : PdfViewController { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ECN - Notify Approvers \r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Approve - " + exceptionString }); - throw e; + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ECN - Notify Approvers \r\n" + ecnNumber.ToString() + "\r\n" + detailedException, EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = "ECN", OperationType = "Error", Comments = "Approve - " + exceptionString }); + throw; } } @@ -652,7 +684,7 @@ public class ECNController : PdfViewController { List emailIst = MiscDMO.GetApproverEmailListByDocument(@ecnNumber, currentStep, documentType).Distinct().ToList(); emailSentList = ECNHelper.NotifyApprovers(_AppSettings, ecnNumber, ecnTypeString, emailSentList, ecn, emailIst); try { - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); } catch { } } catch (Exception e) { @@ -663,19 +695,17 @@ public class ECNController : PdfViewController { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ECN - Notify Approvers \r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Approve - " + exceptionString }); - throw e; + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ECN - Notify Approvers \r\n" + ecnNumber.ToString() + "\r\n" + detailedException, EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = "ECN", OperationType = "Error", Comments = "Approve - " + exceptionString }); + throw; } } - /// - /// Get a list of Approvers and the status - /// +#if !NET8 public ActionResult GetApproversList([DataSourceRequest] DataSourceRequest request, int issueID, byte step, bool isTECN, bool isEmergrncyTECN) { int isITARCompliant = 0; ECN ecn = new ECN(); - ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + ecn = ecnDMO.GetECNForRead(issueID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); GlobalVars.DocumentType docType; // fix related to ticket #35336 @@ -687,24 +717,26 @@ public class ECNController : PdfViewController { return Json(MiscDMO.GetApproversListByDocument(issueID, step, (int)docType).ToDataSourceResult(request)); } +#endif + public void NotifyRejectionToOrginator(int issueID, string ecnTypeString, string comments) { List emailIst = ecnDMO.GetRejectionOrginatorEmailList(@issueID).Distinct().ToList(); ECN ecn = ecnDMO.GetECN(issueID); - string username = Session[GlobalVars.SESSION_USERNAME].ToString(); + string username = GlobalVars.GetUserName(GetSession()); string userEmail = ECNHelper.NotifyRejectionToOrginator(_AppSettings, issueID, ecnTypeString, comments, emailIst, ecn, username); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Rejection: " + userEmail }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = ecnTypeString, OperationType = "Email", Comments = "Rejection: " + userEmail }); } catch { } } public void NotifyTECNExtensionRejectionToOrginator(int issueID, string ecnTypeString) { List emailIst = ecnDMO.GetRejectionOrginatorEmailList(@issueID).Distinct().ToList(); ECN ecn = ecnDMO.GetECN(issueID); - string username = Session[GlobalVars.SESSION_USERNAME].ToString(); + string username = GlobalVars.GetUserName(GetSession()); string userEmail = ECNHelper.NotifyTECNExtensionRejectionToOrginator(_AppSettings, issueID, ecnTypeString, emailIst, ecn, username); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Rejection: " + userEmail }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = ecnTypeString, OperationType = "Email", Comments = "Rejection: " + userEmail }); } catch { } } @@ -714,19 +746,19 @@ public class ECNController : PdfViewController { // Check Rejection is for the TECN Extension int isITARCompliant = 0; - ECN ecn = new ECN(); - ecn = ecnDMO.GetECNForRead(ecnNumber, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + ECN ecn = new(); + ecn = ecnDMO.GetECNForRead(ecnNumber, out isITARCompliant, GlobalVars.GetUserId(GetSession())); - if (Session[GlobalVars.SESSION_USERID] != null) { + if (GlobalVars.IsUserIdValueNotNull(GetSession())) { if (ecn.TECNExtensionState) { - wfDMO.RejectTECNExtension(ecnNumber, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], docType); + wfDMO.RejectTECNExtension(ecnNumber, currentStep, comments, GlobalVars.GetUserId(GetSession()), docType); NotifyTECNExtensionRejectionToOrginator(ecnNumber, ecnTypeString); } else { if (ecn.IsECN && ecn.ConvertedFromNumber != null) { - ecnDMO.ECNResetTECNAtRejection(ecnNumber, (int)Session[GlobalVars.SESSION_USERID], docType); + ecnDMO.ECNResetTECNAtRejection(ecnNumber, GlobalVars.GetUserId(GetSession()), docType); } - wfDMO.Reject(ecnNumber, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], docType); + wfDMO.Reject(ecnNumber, currentStep, comments, GlobalVars.GetUserId(GetSession()), docType); NotifyRejectionToOrginator(ecnNumber, ecnTypeString, comments); } } else { @@ -741,8 +773,8 @@ public class ECNController : PdfViewController { } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Reject\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Reject - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Reject\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = "ECN", OperationType = "Error", Comments = "Reject - " + exceptionString }); throw new Exception(e.Message); } } @@ -753,12 +785,12 @@ public class ECNController : PdfViewController { // Check Rejection is for the TECN Extension int isITARCompliant = 0; - ECN ecn = new ECN(); - ecn = ecnDMO.GetECNForRead(ecnNumber, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + ECN ecn = new(); + ecn = ecnDMO.GetECNForRead(ecnNumber, out isITARCompliant, GlobalVars.GetUserId(GetSession())); - if (Session[GlobalVars.SESSION_USERID] != null) { + if (GlobalVars.IsUserIdValueNotNull(GetSession())) { NotifyApproversForRecall(ecnNumber, currentStep, docType, ecnTypeString, comments); - wfDMO.Recall(ecnNumber, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], docType); + wfDMO.Recall(ecnNumber, currentStep, comments, GlobalVars.GetUserId(GetSession()), docType); } else { Response.Redirect("~/Account/Login"); } @@ -771,8 +803,8 @@ public class ECNController : PdfViewController { } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Reject\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Reject - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Reject\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = "ECN", OperationType = "Error", Comments = "Reject - " + exceptionString }); throw new Exception(e.Message); } } @@ -789,25 +821,25 @@ public class ECNController : PdfViewController { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReAssignApproval\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ReAssignApproval\r\n" + issueID.ToString() + "\r\n" + detailedException, EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "ECN", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); throw new Exception(e.Message); } ECN ecn = ecnDMO.GetECN(issueID); ECNHelper.ReAssignApproverByAdmin(_AppSettings, issueID, ecnTypeString, email, ecn); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "ReAssign Approver: " + email }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = ecnTypeString, OperationType = "Email", Comments = "ReAssign Approver: " + email }); } catch { } } [HttpPost] public void ReAssignOriginatorByAdmin(int ecnNumber, string comments, int newOriginatorId) { - if (Session[GlobalVars.IS_ADMIN] == null) + if (GlobalVars.IsAdminValueNull(GetSession())) throw new Exception("Permission denied"); try { - ecnDMO.ReassignOriginatorECN(ecnNumber, newOriginatorId, comments, (int)Session[GlobalVars.SESSION_USERID]); + ecnDMO.ReassignOriginatorECN(ecnNumber, newOriginatorId, comments, GlobalVars.GetUserId(GetSession())); } catch (Exception e) { string detailedException = ""; try { @@ -818,8 +850,8 @@ public class ECNController : PdfViewController { string exceptionString = e.Message.ToString().Trim(); if (exceptionString.Length > 450) exceptionString = exceptionString.Substring(0, 450); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReAssignOriginatorByAdmin\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "ReAssignOriginatorByAdmin - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ReAssignOriginatorByAdmin\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = "ECN", OperationType = "Error", Comments = "ReAssignOriginatorByAdmin - " + exceptionString }); throw new Exception(e.Message); } } @@ -827,7 +859,7 @@ public class ECNController : PdfViewController { public void ReAssignApproval(int issueID, int userIDs, byte step, int docType, string ecnTypeString) { var email = ""; try { - email = wfDMO.ReAssignApproval(issueID, (int)Session[GlobalVars.SESSION_USERID], userIDs, step, docType); + email = wfDMO.ReAssignApproval(issueID, GlobalVars.GetUserId(GetSession()), userIDs, step, docType); } catch (Exception e) { string detailedException = ""; try { @@ -836,22 +868,22 @@ public class ECNController : PdfViewController { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReAssignApproval\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ReAssignApproval\r\n" + issueID.ToString() + "\r\n" + detailedException, EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = ecnTypeString, OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); throw new Exception(e.Message); } ECN ecn = ecnDMO.GetECN(issueID); ECNHelper.ReAssignApproval(_AppSettings, issueID, ecnTypeString, email, ecn); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "ReAssign Approver: " + email }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = ecnTypeString, OperationType = "Email", Comments = "ReAssign Approver: " + email }); } catch { } } public JsonResult GetAllUsersList() { - UserAccountDMO userDMO = new UserAccountDMO(); + UserAccountDMO userDMO = new(); IEnumerable userlist = userDMO.GetAllActiveUsers(); - return Json(userlist, JsonRequestBehavior.AllowGet); + return GetJsonResult(userlist); } public void AddAdditionalApproval(int issueID, byte step, string userIDs, int docType, string ecnTypeString) { @@ -867,14 +899,14 @@ public class ECNController : PdfViewController { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + " Userid:" + userIDs + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n AddAdditionalApproval\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n AddAdditionalApproval\r\n" + issueID.ToString() + "\r\n" + detailedException, EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "ECN", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); throw new Exception(e.Message); } ECN ecn = ecnDMO.GetECN(issueID); emailSentList = ECNHelper.AddAdditionalApproval(_AppSettings, issueID, ecnTypeString, emailSentList, emailArray, ecn); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Additonal Approver: " + emailSentList }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = ecnTypeString, OperationType = "Email", Comments = "Additonal Approver: " + emailSentList }); } catch { } } @@ -888,17 +920,26 @@ public class ECNController : PdfViewController { outputFileName = ecnNumber.ToString() + ".pdf"; string ecnFolderPath = _AppSettings.AttachmentFolder + "ECN\\" + ecnNumber.ToString(); - System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(ecnFolderPath); + DirectoryInfo di = new(ecnFolderPath); // create the folder for the ECN if it does not exist if (!di.Exists) di.Create(); // To render a PDF instead of an HTML, all we need to do is call ViewPdf instead of View. This // requires the controller to be inherited from MyController instead of MVC's Controller. +#if !NET8 SavePdf(ecnFolderPath + "\\ECNForm_" + outputFileName, "ECNPdf", ecn); SavePdf(ecnFolderPath + "\\ECNApprovalLog_" + outputFileName, "ECNApprovalPdf", ecn); +#endif +#if !NET8 + string html; + html = RenderViewToString("ECNPdf", ecn); + System.IO.File.WriteAllText(ecnFolderPath + "\\ECNForm_" + outputFileName, html); + html = RenderViewToString("ECNApprovalPdf", ecn); + System.IO.File.WriteAllText(ecnFolderPath + "\\ECNApprovalLog_" + outputFileName, html); +#endif } catch (Exception ex) { - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Generate PDF", Comments = ex.Message }); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = "ECN", OperationType = "Generate PDF", Comments = ex.Message }); ecn = null; return false; } @@ -906,8 +947,32 @@ public class ECNController : PdfViewController { return true; } + public ActionResult GetBinaryContentResult(string viewName, string contentType, ECNPdf ecnPdf) { + string pageTitle = string.Empty; + string htmlText = RenderViewToString(viewName, ecnPdf); + StandardPdfRenderer standardPdfRenderer = new(); + byte[] buffer = standardPdfRenderer.Render(htmlText, pageTitle); + return new BinaryContentResult(buffer, contentType); + } + + public string RenderViewToString(string viewName, ECNPdf ecnPdf) { + ViewData.Model = ecnPdf; + using (StringWriter writer = new()) { + try { + ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerContext, viewName, string.Empty); + if (viewResult is null) + return $"A view with the name '{viewName}' could not be found"; + ViewContext viewContext = new(ControllerContext, viewResult.View, ViewData, TempData, writer); + viewResult.View.Render(viewContext, writer); + return writer.GetStringBuilder().ToString(); + } catch (Exception ex) { + return $"Failed - {ex.Message}"; + } + } + } + public bool GenerateECNPdfDifferentLocation(int ecnNumber, int folderName) { - ECNPdf ecn = new ECNPdf(); + ECNPdf ecn = new(); try { string outputFileName = ""; @@ -918,16 +983,22 @@ public class ECNController : PdfViewController { string ecnFolderPath = _AppSettings.AttachmentFolder + "ECN\\" + folderName.ToString(); - System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(ecnFolderPath); + DirectoryInfo di = new(ecnFolderPath); // create the folder for the ECN if it does not exist if (!di.Exists) di.Create(); // To render a PDF instead of an HTML, all we need to do is call ViewPdf instead of View. This // requires the controller to be inherited from MyController instead of MVC's Controller. +#if !NET8 SavePdf(ecnFolderPath + "\\ECNForm_" + outputFileName, "ECNPdf", ecn); +#endif +#if !NET8 + string html = RenderViewToString("ECNPdf", ecn); + System.IO.File.WriteAllText(ecnFolderPath + "\\ECNForm_" + outputFileName, html); +#endif } catch (Exception ex) { - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Generate PDF", Comments = ex.Message }); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = "ECN", OperationType = "Generate PDF", Comments = ex.Message }); ecn = null; return false; } @@ -935,6 +1006,9 @@ public class ECNController : PdfViewController { return true; } +#if NET8 + [HttpGet("print-ecn-pdf")] +#endif public ActionResult PrintECNPdf(int ecnNumber) { ECNPdf ecn; try { @@ -943,9 +1017,17 @@ public class ECNController : PdfViewController { ViewBag.TrainingNotificationTo = ecnDMO.GetTrainingNotificationTo(ecn, trainingDMO); // To render a PDF instead of an HTML, all we need to do is call ViewPdf instead of View. This // requires the controller to be inherited from MyController instead of MVC's Controller. - return this.ViewPdf("", "ECNPdf", ecn); +#if !NET8 + return ViewPdf("", "ECNPdf", ecn); +#endif +#if !NET8 + if (Debugger.IsAttached) + return Content(RenderViewToString("ECNPdf", ecn), "text/html"); + else + return GetBinaryContentResult("ECNPdf", "application/pdf", ecn); +#endif } catch (Exception ex) { - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Print PDF", Comments = ex.Message }); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = "ECN", OperationType = "Print PDF", Comments = ex.Message }); ecn = null; return Content("An unexpected error has occurred!"); } @@ -955,14 +1037,14 @@ public class ECNController : PdfViewController { ECN ecn = ecnDMO.GetECN(ecnNumber); string emailSentList = ECNHelper.NotifyEmergencyTECNApproval(_AppSettings, ecnNumber, expDate, ecn); try { - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "E-TECN", OperationType = "Email", Comments = "Approvers for Step 1:" + emailSentList }); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = "E-TECN", OperationType = "Email", Comments = "Approvers for Step 1:" + emailSentList }); } catch { } } public void NotifyApproversForCancellation(int ecnNumber, ECN ecn, byte currentStep, int documentType, string ecnTypeString) { string emailSentList = ECNHelper.NotifyApproversForCancellation(_AppSettings, ecnNumber, currentStep, documentType, ecnTypeString, ecn); try { - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); } catch { } } @@ -970,7 +1052,7 @@ public class ECNController : PdfViewController { ECN ecn = ecnDMO.GetECN(ecnNumber); string emailSentList = ECNHelper.NotifyApproversForRecall(_AppSettings, ecnNumber, currentStep, documentType, ecnTypeString, recallComments, ecn); try { - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); } catch { } } @@ -978,7 +1060,7 @@ public class ECNController : PdfViewController { ECN ecn = ecnDMO.GetECN(ecnNumber); string emailSentList = ECNHelper.NotifyApproversForExpiration(_AppSettings, ecnNumber, currentStep, documentType, ecnTypeString, ecn); try { - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = ecnTypeString, OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); } catch { } } @@ -987,7 +1069,7 @@ public class ECNController : PdfViewController { List notificationUserList = ecnDMO.GetTECNNotificationUsers().ToList(); string emailSentList = ECNHelper.NotifyTECNCancellation(_AppSettings, userDMO, ecnNumber, ecnFolderPath, comments, ecn, notificationUserList); try { - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "E-TECN", OperationType = "Email", Comments = "Approvers for Cancellation :" + emailSentList }); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = "E-TECN", OperationType = "Email", Comments = "Approvers for Cancellation :" + emailSentList }); } catch { } } @@ -995,7 +1077,7 @@ public class ECNController : PdfViewController { ECN ecn = ecnDMO.GetECN(tecnNumber); string emailSentList = ECNHelper.NotifyTECNAutoCancellation(_AppSettings, ecnNumber, tecnNumber, attachments, ecn); try { - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "E-TECN", OperationType = "Email", Comments = "Approvers for Cancellation :" + emailSentList }); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = "E-TECN", OperationType = "Email", Comments = "Approvers for Cancellation :" + emailSentList }); } catch { } } @@ -1003,15 +1085,15 @@ public class ECNController : PdfViewController { ECN ecn = ecnDMO.GetECN(ecnNumber); string emailSentList = ECNHelper.NotifyTECNExpiration(_AppSettings, ecnNumber, ecnFolderPath, ecn); try { - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "TECN", OperationType = "Email", Comments = "Approvers for Expiration:" + emailSentList }); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = "TECN", OperationType = "Email", Comments = "Approvers for Expiration:" + emailSentList }); } catch { } } public void AddEECNApproval(int ecnNumber, byte step, string engUserIDs, string OpUserIDs) { ECN ecn = ecnDMO.GetECN(ecnNumber); - string emailSentList = ECNHelper.AddEECNApproval(_AppSettings, @User.Identity.Name, wfDMO, ecnNumber, out step, engUserIDs, OpUserIDs, ecn); + string emailSentList = ECNHelper.AddEECNApproval(_AppSettings, GetUserIdentityName(), wfDMO, ecnNumber, out step, engUserIDs, OpUserIDs, ecn); try { - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "E-TECN", OperationType = "Email", Comments = "Additonal Approver: " + emailSentList }); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = "E-TECN", OperationType = "Email", Comments = "Additonal Approver: " + emailSentList }); } catch { } } @@ -1026,15 +1108,15 @@ public class ECNController : PdfViewController { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " - " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SaveAfterSubmitByApprover\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "E-TECN ", OperationType = "Error", Comments = "SaveAfterSubmitByApprover - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n SaveAfterSubmitByApprover\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = "E-TECN ", OperationType = "Error", Comments = "SaveAfterSubmitByApprover - " + exceptionString }); throw new Exception(e.Message); } } public void DeleteDocument(int ecnNumber, string ecnTypeString) { try { - ecnDMO.DeleteDocument(ecnNumber, (int)Session[GlobalVars.SESSION_USERID], ecnTypeString); + ecnDMO.DeleteDocument(ecnNumber, GlobalVars.GetUserId(GetSession()), ecnTypeString); } catch (Exception e) { string detailedException = ""; try { @@ -1043,8 +1125,8 @@ public class ECNController : PdfViewController { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " - " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n DeleteDocument\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "", OperationType = "Error", Comments = "DeleteDocument - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n DeleteDocument\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = "", OperationType = "Error", Comments = "DeleteDocument - " + exceptionString }); throw new Exception(e.Message); } } @@ -1052,9 +1134,9 @@ public class ECNController : PdfViewController { public void DeleteDocumentBySubmitter(int ecnNumber, string ecnTypeString) { ECN ecn = ecnDMO.GetECN(ecnNumber); int submitterId = ecn.OriginatorID; - if (submitterId == (int)Session[GlobalVars.SESSION_USERID]) { + if (submitterId == GlobalVars.GetUserId(GetSession())) { try { - ecnDMO.DeleteDocument(ecnNumber, (int)Session[GlobalVars.SESSION_USERID], ecnTypeString); + ecnDMO.DeleteDocument(ecnNumber, GlobalVars.GetUserId(GetSession()), ecnTypeString); } catch (Exception e) { string detailedException = ""; try { @@ -1063,8 +1145,8 @@ public class ECNController : PdfViewController { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + " - " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n DeleteDocument\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "", OperationType = "Error", Comments = "DeleteDocument - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n DeleteDocument\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = "", OperationType = "Error", Comments = "DeleteDocument - " + exceptionString }); throw new Exception(e.Message); } } else { @@ -1072,16 +1154,16 @@ public class ECNController : PdfViewController { } public ActionResult ReSubmitDocument(int ecnNumber, int documentType, string ecnTypeString, string oldECNTypeString, string descriptionOfChange, string reasonForChange, string categoryId = "") { - ECN ecn = new ECN(); + ECN ecn = new(); int isITARCompliant = 1; int newECNNumber = 0; int catId = 0; - Int32.TryParse(categoryId, out catId); + int.TryParse(categoryId, out catId); try { int appoverCount = ecnDMO.ReSubmitDocument( ecnNumber, - (int)Session[GlobalVars.SESSION_USERID], + GlobalVars.GetUserId(GetSession()), documentType, out isITARCompliant, descriptionOfChange, @@ -1103,7 +1185,7 @@ public class ECNController : PdfViewController { IssueID = ecnNumber, DocumentTypeID = documentType, OperationType = "Changed From " + oldECNTypeString + " To " + ecnTypeString, - UserID = (int)Session[GlobalVars.SESSION_USERID], + UserID = GlobalVars.GetUserId(GetSession()), OperationLog = "Changed the Document Type" }); } catch (Exception e) { @@ -1114,15 +1196,15 @@ public class ECNController : PdfViewController { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReSubmitDocument (ApprovalLogDMO)\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Error", Comments = "ReSubmitDocument (ApprovalLogDMO)" + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ReSubmitDocument (ApprovalLogDMO)\r\n" + detailedException, EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = ecnTypeString, OperationType = "Error", Comments = "ReSubmitDocument (ApprovalLogDMO)" + exceptionString }); } try { ECNTypeChangeLogDMO.Add(new ECNTypeChangeLog { ECNNumber = ecnNumber, - UserID = (int)Session[GlobalVars.SESSION_USERID], + UserID = GlobalVars.GetUserId(GetSession()), ECNTypeFrom = oldECNTypeString, ECNTypeTo = ecnTypeString }); @@ -1134,15 +1216,14 @@ public class ECNController : PdfViewController { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReSubmitDocument (ECNTypeChangeLogDMO)\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Error", Comments = "ReSubmitDocument (ECNTypeChangeLogDMO)" + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ReSubmitDocument (ECNTypeChangeLogDMO)\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = ecnTypeString, OperationType = "Error", Comments = "ReSubmitDocument (ECNTypeChangeLogDMO)" + exceptionString }); } - - if (Request.IsAjaxRequest()) { + if (IsAjaxRequest()) { return Content("Redirect~" + newECNNumber); - - } else + } else { return Content("Invalid"); + } } } catch (Exception e) { string detailedException = ""; @@ -1152,8 +1233,8 @@ public class ECNController : PdfViewController { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ecnNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SubmitDocument\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "ECN", OperationType = "Error", Comments = "Re-SubmitDocument - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n SubmitDocument\r\n" + ecnNumber.ToString() + "\r\n" + detailedException, EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = "ECN", OperationType = "Error", Comments = "Re-SubmitDocument - " + exceptionString }); throw new Exception(e.Message); } } @@ -1166,8 +1247,8 @@ public class ECNController : PdfViewController { ECN ecn = ecnDMO.GetECN(ecnNumber); bool lastApproverAndLastStep = false; if (ecn.SubmitedDate is not null && currentStep >= 1) - wfDMO.Approve(_AppSettings, ecnNumber, currentStep, comments, out bool lastStep, (int)Session[GlobalVars.SESSION_USERID], documentType, ecn.WorkFlowNumber); - int appoverCount = ecnDMO.SubmitForCancellation(ecnNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1, (int)Session[GlobalVars.SESSION_USERID], documentType, ecnTypeString, (int)GlobalVars.TECNExpirationCancellation.Cancellation); + wfDMO.Approve(_AppSettings, ecnNumber, currentStep, comments, out bool lastStep, GlobalVars.GetUserId(GetSession()), documentType, ecn.WorkFlowNumber); + int appoverCount = ecnDMO.SubmitForCancellation(ecnNumber, (byte)GlobalVars.WorkFLowStepNumber.Step1, GlobalVars.GetUserId(GetSession()), documentType, ecnTypeString, (int)GlobalVars.TECNExpirationCancellation.Cancellation); if (appoverCount > 0) { NotifyApproversForCancellation(ecnNumber, ecn, currentStep, documentType, ecnTypeString); } else { // TODO Automatically close the @@ -1178,7 +1259,13 @@ public class ECNController : PdfViewController { try { lastApproverAndLastStep = true; - ECNPdf ecnPDF = new ECNPdf(); + ecn.CancellationDate = DateTime.Now; + ecn.CancellationApprovalDate = DateTime.Now; + ecn.CancellationApproved = true; + ecn.Cancelled = true; + ecnDMO.UpdateECN(ecn); + + ECNPdf ecnPDF = new(); GenerateECNPdf(ecnNumber, out ecnPDF); string sourceDirectory = _AppSettings.AttachmentFolder + "ECN\\" + ecnNumber.ToString() + "\\"; @@ -1189,12 +1276,12 @@ public class ECNController : PdfViewController { outputFullFilePath = _AppSettings.AttachmentFolder + "\\TECNCancelledZipped\\" + outputFileName; - Zipper zip = new Zipper(); + Zipper zip = new(); zip.CreateZip(outputFullFilePath, sourceDirectory); NotifyTECNCancellation(ecnNumber, outputFullFilePath, comments); } catch (Exception ex) { - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "TECN", OperationType = "Error", Comments = ex.Message }); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = "TECN", OperationType = "Error", Comments = ex.Message }); } @@ -1202,10 +1289,11 @@ public class ECNController : PdfViewController { int trainingId = trainingDMO.GetTrainingId(ecnNumber); trainingDMO.DeleteTraining(trainingId); - if (Request.IsAjaxRequest()) { + if (IsAjaxRequest()) { return Content("Redirect"); - } else + } else { return Content("Invalid"); + } } public ActionResult CancelDocumentBySubmitter(int ecnNumber, byte currentStep, int documentType, string ecnTypeString) { @@ -1216,10 +1304,10 @@ public class ECNController : PdfViewController { bool lastApproverAndLastStep = false; bool lastStep = false; ECN ecn = ecnDMO.GetECN(ecnNumber); - bool lastApprover = ecnDMO.ECNApproveCancelled_ExpiredDocument(ecnNumber, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], documentType); + bool lastApprover = ecnDMO.ECNApproveCancelled_ExpiredDocument(ecnNumber, currentStep, comments, out lastStep, GlobalVars.GetUserId(GetSession()), documentType); while (lastApprover && !lastStep) { currentStep++; - lastApprover = ecnDMO.ECNApproveCancelled_ExpiredDocument(ecnNumber, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], documentType); + lastApprover = ecnDMO.ECNApproveCancelled_ExpiredDocument(ecnNumber, currentStep, comments, out lastStep, GlobalVars.GetUserId(GetSession()), documentType); NotifyApproversForCancellation(ecnNumber, ecn, currentStep, documentType, ecnTypeString); } @@ -1233,7 +1321,7 @@ public class ECNController : PdfViewController { ecn.Cancelled = true; ecnDMO.UpdateECN(ecn); - ECNPdf ecnPDF = new ECNPdf(); + ECNPdf ecnPDF = new(); GenerateECNPdf(ecnNumber, out ecnPDF); string sourceDirectory = _AppSettings.AttachmentFolder + "ECN\\" + ecnNumber.ToString() + "\\"; @@ -1244,12 +1332,12 @@ public class ECNController : PdfViewController { outputFullFilePath = _AppSettings.AttachmentFolder + "\\TECNCancelledZipped\\" + outputFileName; - Zipper zip = new Zipper(); + Zipper zip = new(); zip.CreateZip(outputFullFilePath, sourceDirectory); NotifyTECNCancellation(ecnNumber, outputFullFilePath, comments); } catch (Exception ex) { - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "TECN", OperationType = "Error", Comments = ex.Message }); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = "TECN", OperationType = "Error", Comments = ex.Message }); } } @@ -1259,15 +1347,15 @@ public class ECNController : PdfViewController { public void ApproveExpiration(int ecnNumber, byte currentStep, string comments, int documentType, string ecnTypeString) { bool lastStep = false; - bool lastApprover = ecnDMO.ECNApproveCancelled_ExpiredDocument(ecnNumber, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], documentType); + bool lastApprover = ecnDMO.ECNApproveCancelled_ExpiredDocument(ecnNumber, currentStep, comments, out lastStep, GlobalVars.GetUserId(GetSession()), documentType); while (lastApprover && !lastStep) { currentStep++; - lastApprover = lastApprover = ecnDMO.ECNApproveCancelled_ExpiredDocument(ecnNumber, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], documentType); + lastApprover = lastApprover = ecnDMO.ECNApproveCancelled_ExpiredDocument(ecnNumber, currentStep, comments, out lastStep, GlobalVars.GetUserId(GetSession()), documentType); NotifyApproversForExpiration(ecnNumber, currentStep, documentType, ecnTypeString); } if (lastApprover && lastStep) { try { - ECNPdf ecn = new ECNPdf(); + ECNPdf ecn = new(); GenerateECNPdf(ecnNumber, out ecn); string sourceDirectory = _AppSettings.AttachmentFolder + "ECN\\" + ecnNumber.ToString() + "\\"; @@ -1278,12 +1366,12 @@ public class ECNController : PdfViewController { outputFullFilePath = _AppSettings.AttachmentFolder + "\\TECNExpiredZipped\\" + outputFileName; - Zipper zip = new Zipper(); + Zipper zip = new(); zip.CreateZip(outputFullFilePath, sourceDirectory); NotifyTECNExpiration(ecnNumber, outputFullFilePath); } catch (Exception ex) { - EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = @User.Identity.Name, DocumentType = "TECN", OperationType = "Error", Comments = ex.Message }); + EventLogDMO.Add(new WinEventLog() { IssueID = ecnNumber, UserID = GetUserIdentityName(), DocumentType = "TECN", OperationType = "Error", Comments = ex.Message }); } } @@ -1298,10 +1386,10 @@ public class ECNController : PdfViewController { public void ReleaseLockOnDocument(int issueID) { try { - ecnDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], issueID); + ecnDMO.ReleaseLockOnDocument(GlobalVars.GetUserId(GetSession()), issueID); } catch (Exception e) { try { - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReleaseLockOnDocument ECN\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ReleaseLockOnDocument ECN\r\n" + issueID.ToString() + "\r\n" + e.Message, EventLogEntryType.Error); } catch { } ecnDMO.ReleaseLockOnDocument(-1, issueID); } @@ -1312,7 +1400,7 @@ public class ECNController : PdfViewController { ecnDMO.ReleaseLockOnDocument(-1, issueID); } catch (Exception e) { try { - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReleaseLockOnDocument ECN\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ReleaseLockOnDocument ECN\r\n" + issueID.ToString() + "\r\n" + e.Message, EventLogEntryType.Error); } catch { } ecnDMO.ReleaseLockOnDocument(-1, issueID); } @@ -1322,7 +1410,7 @@ public class ECNController : PdfViewController { string fileName = ecnDMO.GetFileName(attachmentID); string ecnFolderPath = _AppSettings.AttachmentFolder + "ECN\\" + ecnNumber.ToString(); - var sDocument = System.IO.Path.Combine(ecnFolderPath, fileName); + var sDocument = Path.Combine(ecnFolderPath, fileName); var FDir_AppData = _AppSettings.AttachmentFolder; if (!sDocument.StartsWith(FDir_AppData)) { @@ -1336,4 +1424,33 @@ public class ECNController : PdfViewController { return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); } +#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; + } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/HomeController.cs b/Fab2ApprovalSystem/Controllers/HomeController.cs index 75d2d1e..3a4fb4e 100644 --- a/Fab2ApprovalSystem/Controllers/HomeController.cs +++ b/Fab2ApprovalSystem/Controllers/HomeController.cs @@ -1,35 +1,53 @@ using System; using System.Collections.Generic; -using System.Configuration; -using System.Linq; +#if !NET8 using System.Web; using System.Web.Mvc; +#endif + +#if NET8 +using Microsoft.AspNetCore.Mvc; +#endif using Fab2ApprovalSystem.DMO; using Fab2ApprovalSystem.Misc; using Fab2ApprovalSystem.Models; using Fab2ApprovalSystem.Utilities; -using Fab2ApprovalSystem.ViewModels; +#if !NET8 +using System.Configuration; +using System.Linq; +using Fab2ApprovalSystem.ViewModels; +#endif + +#if !NET8 using Kendo.Mvc.Extensions; using Kendo.Mvc.UI; +#endif namespace Fab2ApprovalSystem.Controllers; +#if !NET8 [Authorize] +#if !NET8 [SessionExpireFilter] +#endif [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] +#endif +#if NET8 +[Route("[controller]")] +#endif public class HomeController : Controller { - MRB_DMO mrbDMO = new MRB_DMO(GlobalVars.AppSettings); - PartsRequestDMO prDMO = new PartsRequestDMO(); - LotDispositionDMO ldDMO = new LotDispositionDMO(); - WorkflowDMO wfDMO = new WorkflowDMO(); - ECN_DMO ecnDMO = new ECN_DMO(); - UserUtilities userDMO = new UserUtilities(); - UserAccountDMO originalUserDMO = new UserAccountDMO(); - TrainingDMO trainingDMO = new TrainingDMO(); - MiscDMO miscDMO = new MiscDMO(); + private readonly MRB_DMO mrbDMO = new(GlobalVars.AppSettings); + private readonly PartsRequestDMO prDMO = new(); + private readonly LotDispositionDMO ldDMO = new(); + private readonly WorkflowDMO wfDMO = new(); + private readonly ECN_DMO ecnDMO = new(); + private readonly UserUtilities userDMO = new(); + private readonly UserAccountDMO originalUserDMO = new(); + private readonly TrainingDMO trainingDMO = new(); + private readonly MiscDMO miscDMO = new(); private readonly AppSettings _AppSettings = GlobalVars.AppSettings; public ActionResult Index(string tabName) { @@ -57,6 +75,7 @@ public class HomeController : Controller { public ActionResult ECNList() { return View(); } + public ActionResult TrainingList() { return View(); } @@ -82,25 +101,25 @@ public class HomeController : Controller { return View(); } +#if !NET8 + public ActionResult GetTaskList([DataSourceRequest] DataSourceRequest request, string tabName) { try { ViewBag.ActiveTabName = tabName; - List data = ldDMO.GetTaskList((int)Session[GlobalVars.SESSION_USERID]).Distinct().ToList(); - return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet); + List data = ldDMO.GetTaskList(GlobalVars.GetUserId(GetSession())).Distinct().ToList(); + return GetJsonResult(data.ToDataSourceResult(request)); } catch (Exception ex) { - // TODO record the error - throw ex; + throw; } } public ActionResult GetMyOpenActionItems([DataSourceRequest] DataSourceRequest request, string tabName) { try { ViewBag.ActiveTabName = tabName; - List data = ldDMO.GetMyOpenActionItems((int)Session[GlobalVars.SESSION_USERID]).Distinct().ToList(); - return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet); + List data = ldDMO.GetMyOpenActionItems(GlobalVars.GetUserId(GetSession())).Distinct().ToList(); + return GetJsonResult(data.ToDataSourceResult(request)); } catch (Exception ex) { - // TODO record the error - throw ex; + throw; } } @@ -116,76 +135,82 @@ public class HomeController : Controller { } public ActionResult GetChangeControlList([DataSourceRequest] DataSourceRequest request) { - IEnumerable data = ldDMO.GetChangeControls(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); + IEnumerable data = ldDMO.GetChangeControls(GlobalVars.GetUserId(GetSession())); return Json(data.ToDataSourceResult(request)); } public ActionResult GetAuditList([DataSourceRequest] DataSourceRequest request) { - IEnumerable data = ldDMO.GetAuditList(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); + IEnumerable data = ldDMO.GetAuditList(GlobalVars.GetUserId(GetSession())); return Json(data.ToDataSourceResult(request)); } public ActionResult GetCorrectiveActionList([DataSourceRequest] DataSourceRequest request) { - IEnumerable data = ldDMO.GetCorrectiveActionList(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); + IEnumerable data = ldDMO.GetCorrectiveActionList(GlobalVars.GetUserId(GetSession())); return Json(data.ToDataSourceResult(request)); } public ActionResult GetMRBList([DataSourceRequest] DataSourceRequest request) { - IEnumerable data = ldDMO.GetMRBList(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); + IEnumerable data = ldDMO.GetMRBList(GlobalVars.GetUserId(GetSession())); return Json(data.ToDataSourceResult(request)); } public ActionResult GetLotDispositionList([DataSourceRequest] DataSourceRequest request) { - IEnumerable data = ldDMO.GetLotDispositionList(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); + IEnumerable data = ldDMO.GetLotDispositionList(GlobalVars.GetUserId(GetSession())); return Json(data.ToDataSourceResult(request)); } public ActionResult GetECNList([DataSourceRequest] DataSourceRequest request) { - IEnumerable data = ldDMO.GetECNList(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); + IEnumerable data = ldDMO.GetECNList(GlobalVars.GetUserId(GetSession())); return Json(data.ToDataSourceResult(request)); } + public ActionResult GetTrainingList([DataSourceRequest] DataSourceRequest request) { IEnumerable data = trainingDMO.GetAllTrainings(); return Json(data.ToDataSourceResult(request)); } +#endif + public ActionResult MyECNsTECNs(string dataType) { ViewBag.ActiveTabName = dataType; return View(); } +#if !NET8 + public ActionResult GetECN_TECNsPendingApproval([DataSourceRequest] DataSourceRequest request) { - IEnumerable data = ecnDMO.GetECN_TECNPendingApprovals(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); + IEnumerable data = ecnDMO.GetECN_TECNPendingApprovals(GlobalVars.GetUserId(GetSession())); ViewBag.ViewOption = "Pending Approvals"; - Session[GlobalVars.ECN_VIEW_OPTION] = ViewBag.ViewOption; + GlobalVars.SetECNViewOption(GetSession(), ViewBag.ViewOption); return Json(data.ToDataSourceResult(request)); } public ActionResult GetMyExpiredTECNs([DataSourceRequest] DataSourceRequest request) { - IEnumerable data = ecnDMO.GetMyExpiredTECNs(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), 7); + IEnumerable data = ecnDMO.GetMyExpiredTECNs(GlobalVars.GetUserId(GetSession()), 7); ViewBag.ViewOption = "Expired TECNs"; - Session[GlobalVars.ECN_VIEW_OPTION] = ViewBag.ViewOption; + GlobalVars.SetECNViewOption(GetSession(), ViewBag.ViewOption); return Json(data.ToDataSourceResult(request)); } + public ActionResult GetAllTECNs([DataSourceRequest] DataSourceRequest request) { IEnumerable data = ecnDMO.GetAllTECNs(); ViewBag.ViewOption = "All TECNs"; - Session[GlobalVars.ECN_VIEW_OPTION] = ViewBag.ViewOption; + GlobalVars.SetECNViewOption(GetSession(), ViewBag.ViewOption); return Json(data.ToDataSourceResult(request)); } public ActionResult GetMyConvertedTECNsToECNs([DataSourceRequest] DataSourceRequest request) { - IEnumerable data = ecnDMO.GetMyConvertedTECNsToECNs(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), 7); + IEnumerable data = ecnDMO.GetMyConvertedTECNsToECNs(GlobalVars.GetUserId(GetSession()), 7); ViewBag.ViewOption = "Converted TECNs"; - Session[GlobalVars.ECN_VIEW_OPTION] = ViewBag.ViewOption; + GlobalVars.SetECNViewOption(GetSession(), ViewBag.ViewOption); return Json(data.ToDataSourceResult(request)); } public ActionResult GetMyExpiringTECNs([DataSourceRequest] DataSourceRequest request) { - IEnumerable data = ecnDMO.GetMyExpiringTECNs(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), 7); + IEnumerable data = ecnDMO.GetMyExpiringTECNs(GlobalVars.GetUserId(GetSession()), 7); ViewBag.ViewOption = "Expiring TECNs"; - Session[GlobalVars.ECN_VIEW_OPTION] = ViewBag.ViewOption; + GlobalVars.SetECNViewOption(GetSession(), ViewBag.ViewOption); return Json(data.ToDataSourceResult(request)); } @@ -194,17 +219,17 @@ public class HomeController : Controller { return Json(LotTravDMO.GetLotListBasedOnSWRNumber(workRequestID).ToDataSourceResult(request)); } - /// +#endif public ActionResult SetOOOStatus(int delegatedTo, DateTime startDate, DateTime endDate, string tab) { - if (Session[GlobalVars.SESSION_USERID] != null) { - int returnValue = MiscDMO.EnableOOOStatus(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), delegatedTo, startDate, endDate); + if (GlobalVars.IsUserIdValueNotNull(GetSession())) { + int returnValue = MiscDMO.EnableOOOStatus(GlobalVars.GetUserId(GetSession()), delegatedTo, startDate, endDate); if (returnValue == 3) // the delegator is already a delegator to someone else { return Content("3"); } if (startDate <= DateTime.Today) - Session[GlobalVars.OOO] = true; + GlobalVars.SetOOO(GetSession(), true); NotifyDelegation(delegatedTo, startDate, endDate); } @@ -213,12 +238,14 @@ public class HomeController : Controller { } public void ExpireOOOStatus(string tab) { - if (Session[GlobalVars.SESSION_USERID] != null) { - MiscDMO.ExpireOOOStatus(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); - Session[GlobalVars.OOO] = false; + if (GlobalVars.IsUserIdValueNotNull(GetSession())) { + MiscDMO.ExpireOOOStatus(GlobalVars.GetUserId(GetSession())); + GlobalVars.SetOOO(GetSession(), false); } } +#if !NET8 + [AcceptVerbs(HttpVerbs.Post)] public ActionResult DeleteItem([DataSourceRequest] DataSourceRequest request, IssuesViewModel issue) { GlobalVars.DocumentType dType; @@ -228,20 +255,22 @@ public class HomeController : Controller { else if (dType == GlobalVars.DocumentType.LotDisposition) ldDMO.DeleteLotDisposition(issue.IssueID); else if (dType == GlobalVars.DocumentType.ECN) - ecnDMO.DeleteDocument(issue.IssueID, int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), "ECN"); + ecnDMO.DeleteDocument(issue.IssueID, GlobalVars.GetUserId(GetSession()), "ECN"); else if (dType == GlobalVars.DocumentType.CorrectiveAction) - ldDMO.DeleteCADocument(issue.IssueID, int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), "Corrective Action"); + ldDMO.DeleteCADocument(issue.IssueID, GlobalVars.GetUserId(GetSession()), "Corrective Action"); return Json(new[] { issue }.ToDataSourceResult(request, ModelState)); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult DeleteCAItem([DataSourceRequest] DataSourceRequest request, CorrectiveAction ca) { - ldDMO.DeleteCADocument(ca.CANo, int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), "Corrective Action"); + ldDMO.DeleteCADocument(ca.CANo, GlobalVars.GetUserId(GetSession()), "Corrective Action"); return Json(new[] { ca }.ToDataSourceResult(request, ModelState)); } +#endif + public ActionResult About() { ViewBag.Message = "Your application description page."; @@ -283,61 +312,63 @@ public class HomeController : Controller { public void DelegateDocumentApproval(int issueID, int delegateTo, string ecnTypeString, string title) { var email = ""; - int delegateFrom = (int)Session[GlobalVars.SESSION_USERID]; + int delegateFrom = GlobalVars.GetUserId(GetSession()); try { email = wfDMO.DelegateDocumentApproval(issueID, delegateFrom, delegateTo); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Delegation", Comments = "Delegated from - " + delegateFrom + " to " + delegateTo }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = ecnTypeString, OperationType = "Delegation", Comments = "Delegated from - " + delegateFrom + " to " + delegateTo }); } catch (Exception e) { string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n DelegateApproval\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = " + ecnTypeString + ", OperationType = "Error", Comments = "DelegateApproval - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n DelegateApproval\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = " + ecnTypeString + ", OperationType = "Error", Comments = "DelegateApproval - " + exceptionString }); throw new Exception(e.Message); } HomeHelper.DelegateDocumentApproval(_AppSettings, issueID, ecnTypeString, title, email); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = ecnTypeString, OperationType = "Email", Comments = "Delegated to Approver: " + email }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = ecnTypeString, OperationType = "Email", Comments = "Delegated to Approver: " + email }); } catch { } } public JsonResult GetAllUsersList() { - UserAccountDMO userDMO = new UserAccountDMO(); + UserAccountDMO userDMO = new(); IEnumerable userlist = userDMO.GetAllUsers(); - return Json(userlist, JsonRequestBehavior.AllowGet); + return GetJsonResult(userlist); } public ActionResult SaveAllDocumentsFilter(string data) { - Session["AllDocumentsFilterData"] = data; + GlobalVars.SetAllDocumentsFilterData(GetSession(), data); return new EmptyResult(); } public ActionResult LoadAllDocumentsFilter() { - return Json(Session["AllDocumentsFilterData"], JsonRequestBehavior.AllowGet); + return GetJsonResult(GlobalVars.GetAllDocumentsFilterData(GetSession())); } public ActionResult SaveSWRFilter(string data) { - Session["SWRFilterData"] = data; + GlobalVars.SetSWRFilterData(GetSession(), data); return new EmptyResult(); } public ActionResult LoadSWRFilter() { - return Json(Session["SWRFilterData"], JsonRequestBehavior.AllowGet); + return GetJsonResult(GlobalVars.GetSWRFilterData(GetSession())); } public ActionResult SavePCRBFilter(string data) { - Session["PCRBFilterData"] = data; + GlobalVars.SetPCRBFilterData(GetSession(), data); return new EmptyResult(); } public ActionResult LoadPCRBFilter() { - return Json(Session["PCRBFilterData"], JsonRequestBehavior.AllowGet); + return GetJsonResult(GlobalVars.GetPCRBFilterData(GetSession())); } public ActionResult PartsRequestList() { - ViewBag.CanDeletePR = Session[GlobalVars.CAN_CREATE_PARTS_REQUEST]; + ViewBag.CanDeletePR = GlobalVars.GetCanCreatePartsRequest(GetSession()); return View(); } +#if !NET8 + public ActionResult GetPartsRequestList([DataSourceRequest] DataSourceRequest request) { IEnumerable data = prDMO.GetPartsRequestList(); return Json(data.ToDataSourceResult(request)); @@ -346,31 +377,32 @@ public class HomeController : Controller { public ActionResult GetMyPartsRequestsList([DataSourceRequest] DataSourceRequest request, string tabName) { try { ViewBag.ActiveTabName = tabName; - var data = prDMO.GetMyPartsRequests((int)Session[GlobalVars.SESSION_USERID]); - return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet); + var data = prDMO.GetMyPartsRequests(GlobalVars.GetUserId(GetSession())); + return GetJsonResult(data.ToDataSourceResult(request)); } catch (Exception ex) { - // TODO record the error - throw ex; + throw; } } [AcceptVerbs(HttpVerbs.Post)] public ActionResult DeletePR([DataSourceRequest] DataSourceRequest request, MyPartsRequestList pr) { try { - if (Convert.ToBoolean(Session[GlobalVars.CAN_CREATE_PARTS_REQUEST]) == false) + if (!GlobalVars.GetCanCreatePartsRequest(GetSession())) throw new Exception("Permission denied"); - prDMO.DeleteDocument(pr.PRNumber, (int)Session[GlobalVars.SESSION_USERID]); + prDMO.DeleteDocument(pr.PRNumber, GlobalVars.GetUserId(GetSession())); return Json(new[] { pr }.ToDataSourceResult(request, ModelState)); } catch (Exception ex) { return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, ex.Message); } } +#endif + public void NotifyDelegation(int delegatedUser, DateTime startDate, DateTime endDate) { - LoginModel delegateFrom = originalUserDMO.GetUserByID((int)Session[GlobalVars.SESSION_USERID]); + LoginModel delegateFrom = originalUserDMO.GetUserByID(GlobalVars.GetUserId(GetSession())); LoginModel delegateTo = originalUserDMO.GetUserByID(delegatedUser); - List emailList = new List(); + List emailList = new(); emailList.Add(delegateFrom.Email); emailList.Add(delegateTo.Email); HomeHelper.NotifyDelegation(_AppSettings, startDate, endDate, delegateFrom, delegateTo, emailList); @@ -381,22 +413,24 @@ public class HomeController : Controller { public bool ProcessOoO() { try { - UserAccountDMO userDMO = new UserAccountDMO(); + UserAccountDMO userDMO = new(); userDMO.ProcessOoO(); return true; } catch { return false; } } + public bool ExpireOoO() { try { - UserAccountDMO userDMO = new UserAccountDMO(); + UserAccountDMO userDMO = new(); userDMO.ExpireOoO(); return true; } catch { return false; } } + public bool ApprovalsReminderNotifications() { try { // Get list of approvals @@ -417,12 +451,13 @@ public class HomeController : Controller { return false; } } + public void NotifyApprover(string toEmail, string title, int issueId, string docType) { try { HomeHelper.NotifyApprover(_AppSettings, toEmail, title, issueId, docType); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueId, UserID = @User.Identity.Name, DocumentType = docType, OperationType = "Email", Comments = "Approval reminders" }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueId, UserID = GetUserIdentityName(), DocumentType = docType, OperationType = "Email", Comments = "Approval reminders" }); } catch { } } catch (Exception e) { @@ -432,9 +467,38 @@ public class HomeController : Controller { } catch { detailedException = e.Message; } - EventLogDMO.Add(new WinEventLog() { IssueID = issueId, UserID = @User.Identity.Name, DocumentType = docType, OperationType = "Email", Comments = "Approval reminders" }); - throw e; + EventLogDMO.Add(new WinEventLog() { IssueID = issueId, UserID = GetUserIdentityName(), DocumentType = docType, OperationType = "Email", Comments = "Approval reminders" }); + throw; } } +#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; + } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/LotDispositionController.cs b/Fab2ApprovalSystem/Controllers/LotDispositionController.cs index ffc5ee6..ce1de1e 100644 --- a/Fab2ApprovalSystem/Controllers/LotDispositionController.cs +++ b/Fab2ApprovalSystem/Controllers/LotDispositionController.cs @@ -1,39 +1,57 @@ using System; -using System.Collections; using System.Collections.Generic; -using System.Configuration; using System.Linq; using System.Reflection; -using System.Runtime.Serialization; +#if !NET8 using System.Web; using System.Web.Mvc; +#endif + +#if NET8 +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Rendering; +using Microsoft.AspNetCore.Authorization; +#endif using Fab2ApprovalSystem.DMO; using Fab2ApprovalSystem.Misc; using Fab2ApprovalSystem.Models; using Fab2ApprovalSystem.ViewModels; +#if !NET8 using Kendo.Mvc.Extensions; using Kendo.Mvc.UI; +#endif + +#if !NET8 +using System.Collections; +using System.Configuration; +using System.Runtime.Serialization; +#endif namespace Fab2ApprovalSystem.Controllers; [Authorize] +#if !NET8 [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] [SessionExpireFilter] +#endif +#if NET8 +[Route("[controller]")] +#endif public class LotDispositionController : Controller { - LotDispositionDMO ldDMO = new LotDispositionDMO(); - WorkflowDMO wfDMO = new WorkflowDMO(); - private readonly AppSettings _AppSettings = GlobalVars.AppSettings; + private readonly LotDispositionDMO ldDMO = new(); + private readonly WorkflowDMO wfDMO = new(); + private readonly AppSettings? _AppSettings = GlobalVars.AppSettings; // GET: /LotDisposition/Create public ActionResult Create() { - LotDisposition lotDispo = new LotDisposition(); + LotDisposition lotDispo = new(); try { // insert a records to get the issueID - lotDispo.OriginatorID = (int)Session[GlobalVars.SESSION_USERID]; + lotDispo.OriginatorID = GlobalVars.GetUserId(GetSession()); ldDMO.InsertLotDisposition(lotDispo); return RedirectToAction("Edit", new { issueID = lotDispo.IssueID.ToString() }); } catch (Exception e) { @@ -44,16 +62,16 @@ public class LotDispositionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\nCreat Lot Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = lotDispo.IssueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\nCreat Lot Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = lotDispo.IssueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); return View("Error"); } } public JsonResult AddLot(Lot lot) { Lot l = lot; - MRB_DMO mrbDMO = new MRB_DMO(_AppSettings); - IssueWithExistingLotsViewModel issueWEL = new IssueWithExistingLotsViewModel(); + MRB_DMO mrbDMO = new(_AppSettings); + IssueWithExistingLotsViewModel issueWEL = new(); try { lot.LotStatusOption.LotStatusOptionID = l.LotStatusOptionID; @@ -67,22 +85,22 @@ public class LotDispositionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + lot.IssueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Add Lot Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = l.IssueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Add Lot Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = l.IssueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); throw new Exception(e.Message); } - return Json(l, JsonRequestBehavior.AllowGet); + return GetJsonResult(l); } public JsonResult AddLots(string lotNumbers, int issueID) { - MRB_DMO mrbDMO = new MRB_DMO(_AppSettings); + MRB_DMO mrbDMO = new(_AppSettings); bool existingLotUpdated; - IssueWithExistingLotsViewModel issueWEL = new IssueWithExistingLotsViewModel(); + IssueWithExistingLotsViewModel issueWEL = new(); try { if (lotNumbers.Length > 0) { string[] tempLots = lotNumbers.Split(new char[] { '~' }); foreach (string lotNumber in tempLots) { - Lot l = new Lot(); + Lot l = new(); l.LotNumber = lotNumber; l.IssueID = issueID; l.LotStatusOption.LotStatusOptionID = (int)GlobalVars.LotStatusOption.NotAvailable; @@ -104,20 +122,19 @@ public class LotDispositionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n AddLots Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n AddLots Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); throw new Exception(e.Message); } - - return Json(issueWEL, JsonRequestBehavior.AllowGet); + return GetJsonResult(issueWEL); } // GET: /LotDisposition/Edit/5 public ActionResult Edit(int issueID) { int isITARCompliant = 1; try { - LotDisposition lotDispo = new LotDisposition(); - lotDispo = ldDMO.GetLotDispositionItemForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + LotDisposition lotDispo = new(); + lotDispo = ldDMO.GetLotDispositionItemForRead(issueID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); if (isITARCompliant == 0) // not ITAR Compliant { @@ -128,20 +145,20 @@ public class LotDispositionController : Controller { } if (lotDispo.CurrentStep == 1) { List userList = MiscDMO.GetPendingApproversListByDocument(issueID, lotDispo.CurrentStep, (int)GlobalVars.DocumentType.LotDisposition); - ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); + ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == GlobalVars.GetUserId(GetSession()); }); if (approver == null) ViewBag.IsApprover = "false"; else ViewBag.IsApprover = "true"; - if (approver == null && (!(bool)Session[GlobalVars.IS_ADMIN]) && (int)Session[GlobalVars.SESSION_USERID] != lotDispo.OriginatorID) { + if (approver == null && (!GlobalVars.IsAdmin(GetSession())) && GlobalVars.GetUserId(GetSession()) != lotDispo.OriginatorID) { return RedirectToAction("ReadOnly", new { issueID = issueID }); } else { - if ((ViewBag.IsApprover == "true" || (bool)Session[GlobalVars.IS_ADMIN]) - || (int)Session[GlobalVars.SESSION_USERID] == lotDispo.OriginatorID) { - lotDispo = ldDMO.GetLotDispositionItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + if ((ViewBag.IsApprover == "true" || GlobalVars.IsAdmin(GetSession())) + || GlobalVars.GetUserId(GetSession()) == lotDispo.OriginatorID) { + lotDispo = ldDMO.GetLotDispositionItem(issueID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); - if (lotDispo.RecordLockIndicator && lotDispo.RecordLockedBy == (int)Session[GlobalVars.SESSION_USERID]) { + if (lotDispo.RecordLockIndicator && lotDispo.RecordLockedBy == GlobalVars.GetUserId(GetSession())) { PopulateLotStatusOptions(); ViewBag.OriginatorList = ldDMO.GetUserList(); ViewBag.deps = ldDMO.GetDepartments(); @@ -159,7 +176,7 @@ public class LotDispositionController : Controller { } else if (lotDispo.CurrentStep > 1) { List userList = MiscDMO.GetPendingApproversListByDocument(issueID, lotDispo.CurrentStep, (int)GlobalVars.DocumentType.LotDisposition); - ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); + ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == GlobalVars.GetUserId(GetSession()); }); if (approver == null) { ViewBag.IsApprover = "false"; @@ -168,12 +185,12 @@ public class LotDispositionController : Controller { } - if (approver == null && (!(bool)Session[GlobalVars.IS_ADMIN]) && (int)Session[GlobalVars.SESSION_USERID] != lotDispo.OriginatorID) { + if (approver == null && (!GlobalVars.IsAdmin(GetSession())) && GlobalVars.GetUserId(GetSession()) != lotDispo.OriginatorID) { return RedirectToAction("ReadOnly", new { issueID = issueID }); } else { - if ((ViewBag.IsApprover == "true" || (bool)Session[GlobalVars.IS_ADMIN]) - || (int)Session[GlobalVars.SESSION_USERID] == lotDispo.OriginatorID) { + if ((ViewBag.IsApprover == "true" || GlobalVars.IsAdmin(GetSession())) + || GlobalVars.GetUserId(GetSession()) == lotDispo.OriginatorID) { return RedirectToAction("EditStep", new { issueID = issueID }); } else { @@ -185,10 +202,10 @@ public class LotDispositionController : Controller { } else { // TODO // Check the recordlock indicator - if ((lotDispo.RecordLockIndicator && lotDispo.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) || (ViewBag.IsApprover == "false")) { + if ((lotDispo.RecordLockIndicator && lotDispo.RecordLockedBy != GlobalVars.GetUserId(GetSession())) || (ViewBag.IsApprover == "false")) { return RedirectToAction("ReadOnly", new { issueID = issueID }); } else { - lotDispo = ldDMO.GetLotDispositionItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + lotDispo = ldDMO.GetLotDispositionItem(issueID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); PopulateLotStatusOptions(); ViewBag.OriginatorList = ldDMO.GetUserList(); ViewBag.deps = ldDMO.GetDepartments(); @@ -207,8 +224,8 @@ public class LotDispositionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\nEdit Lot Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\nEdit Lot Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); return View("Error"); } } @@ -227,8 +244,8 @@ public class LotDispositionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + lotDispo.IssueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n UpdatEdit Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = lotDispo.IssueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n UpdatEdit Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = lotDispo.IssueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); throw new Exception(e.Message); } } @@ -236,8 +253,8 @@ public class LotDispositionController : Controller { public ActionResult ReadOnly(int issueID) { int isITARCompliant = 1; try { - LotDisposition lotDispo = new LotDisposition(); - lotDispo = ldDMO.GetLotDispositionItemForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + LotDisposition lotDispo = new(); + lotDispo = ldDMO.GetLotDispositionItemForRead(issueID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); PopulateLotStatusOptions(); ViewBag.OriginatorList = ldDMO.GetUserList(); @@ -254,8 +271,8 @@ public class LotDispositionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReadOnly Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ReadOnly Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); throw new Exception(e.Message); } } @@ -264,10 +281,10 @@ public class LotDispositionController : Controller { int isITARCompliant = 1; try { - LotDisposition lotDispo = new LotDisposition(); - lotDispo = ldDMO.GetLotDispositionItemForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + LotDisposition lotDispo = new(); + lotDispo = ldDMO.GetLotDispositionItemForRead(issueID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); List userList = MiscDMO.GetPendingApproversListByDocument(issueID, lotDispo.CurrentStep, (int)GlobalVars.DocumentType.LotDisposition); - ApproversListViewModel appUser = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); + ApproversListViewModel appUser = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == GlobalVars.GetUserId(GetSession()); }); if (appUser == null) ViewBag.IsApprover = "false"; else @@ -275,10 +292,10 @@ public class LotDispositionController : Controller { // Check the recordlock indicator - if ((ViewBag.IsApprover == "true" || (bool)Session[GlobalVars.IS_ADMIN])) { - lotDispo = ldDMO.GetLotDispositionItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + if ((ViewBag.IsApprover == "true" || GlobalVars.IsAdmin(GetSession()))) { + lotDispo = ldDMO.GetLotDispositionItem(issueID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); - if (lotDispo.RecordLockIndicator && lotDispo.RecordLockedBy == (int)Session[GlobalVars.SESSION_USERID]) { + if (lotDispo.RecordLockIndicator && lotDispo.RecordLockedBy == GlobalVars.GetUserId(GetSession())) { PopulateLotStatusOptions(); ViewBag.OriginatorList = ldDMO.GetUserList(); ViewBag.deps = ldDMO.GetDepartments(); @@ -301,8 +318,8 @@ public class LotDispositionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n EditStep Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n EditStep Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); throw new Exception(e.Message); } } @@ -315,30 +332,32 @@ public class LotDispositionController : Controller { public JsonResult GetResponsibilityIssue(int responsibilityID) { List respIssue = ldDMO.GetResponsibilityIssueList(responsibilityID); - var data = respIssue.Select(s => new SelectListItem { Value = s.ResponsibilityIssueID.ToString(), Text = s.Issue }); - return Json(data, JsonRequestBehavior.AllowGet); + var data = respIssue.Select(s => new SelectListItem() { Value = s.ResponsibilityIssueID.ToString(), Text = s.Issue }); + return GetJsonResult(data); } +#if !NET8 + public JsonResult GetDepartments([DataSourceRequest] DataSourceRequest request) { var departments = ldDMO.GetDepartments(); - return Json(departments, JsonRequestBehavior.AllowGet); + return GetJsonResult(departments); } +#endif + public void PopulateLotStatusOptions() { var lotStatusOptions = ldDMO.GetLotStatusOptions(); ViewData["LotStatusOptions"] = lotStatusOptions; } +#if !NET8 + public ActionResult EditingCustom_Read([DataSourceRequest] DataSourceRequest request, int issueID) { return Json(ldDMO.GetLotDispositionLots(issueID).ToDataSourceResult(request)); } - /// - /// Updates the lot tables - /// [AcceptVerbs(HttpVerbs.Post)] public ActionResult EditingCustom_Update([DataSourceRequest] DataSourceRequest request, Lot lot) { - if (lot != null && ModelState.IsValid) { ldDMO.UpdateLotDispoLot(lot); } @@ -347,10 +366,6 @@ public class LotDispositionController : Controller { return Json(new[] { lot }.ToDataSourceResult(request, ModelState)); } - /// - /// Deletes record from the lot table - /// - [AcceptVerbs(HttpVerbs.Post)] public ActionResult EditingCustom_Destroy([DataSourceRequest] DataSourceRequest request, Lot lot) { try { @@ -366,8 +381,6 @@ public class LotDispositionController : Controller { return Json(new[] { lot }.ToDataSourceResult(request, ModelState)); } - // REGION ATTACHMENT - public ActionResult Attachment_Read([DataSourceRequest] DataSourceRequest request, int issueID) { return Json(ldDMO.GetLotDispoAttachments(issueID).ToDataSourceResult(request)); } @@ -385,6 +398,8 @@ public class LotDispositionController : Controller { return Json(new[] { attachment }.ToDataSourceResult(request, ModelState)); } +#endif + [HttpPost] public void DeleteAttachment(int attachmentID, string fileName) { try { @@ -392,7 +407,7 @@ public class LotDispositionController : Controller { ldDMO.DeleteLotDispoAttachment(attachmentID); var physicalPath = System.IO.Path.Combine(_AppSettings.AttachmentFolder + "LotDisposition", fileName); - System.IO.FileInfo f = new System.IO.FileInfo(physicalPath); + System.IO.FileInfo f = new(physicalPath); if (f.Exists) f.Delete(); @@ -406,21 +421,23 @@ public class LotDispositionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "AttachmentID=" + attachmentID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n AttachmentID Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = 999, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "AttachmentID Disposition " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n AttachmentID Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = 999, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "AttachmentID Disposition " + exceptionString }); throw new Exception(e.Message); } } public JsonResult GetLotDispoAttachments(int issueID) { var model = ldDMO.GetLotDispoAttachments(issueID); - return Json(model, JsonRequestBehavior.AllowGet); + return GetJsonResult(model); } +#if !NET8 + public ActionResult AttachSave(IEnumerable files, int issueID) { // The Name of the Upload component is "files" if (files != null) { - int userId = (int)Session[GlobalVars.SESSION_USERID]; + int userId = GlobalVars.GetUserId(GetSession()); foreach (var file in files) { LotDispositionHelper.AttachSave(_AppSettings, ldDMO, issueID, userId, file.FileName, file.InputStream); } @@ -429,10 +446,11 @@ public class LotDispositionController : Controller { return Content(""); } - public JsonResult SearchLots(string searchText, string searchBy) { - List lotlist = MiscDMO.SearchLots(searchText, searchBy).Select(x => x.LotNumber).ToList(); +#endif - return Json(lotlist, JsonRequestBehavior.AllowGet); + public JsonResult SearchLots(string searchText, string searchBy) { + List lotlist = MiscDMO.SearchLots(searchText, searchBy).Select(x => x.LotNumber).ToList(); + return GetJsonResult(lotlist); } public void DeleteAllLots(int issueID) { @@ -440,10 +458,12 @@ public class LotDispositionController : Controller { ldDMO.DeleteAllLotDispoLot(issueID); } +#if !NET8 [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] +#endif public ActionResult LotStatusDetail(int issueID, string lotNumber, bool readonlyView, string lotLocation = "") { ViewBag.LotLocation = lotLocation; - var model = new ScrapLot(); + ScrapLot model = new(); var data = ldDMO.GetLotStausDetail(issueID, lotNumber); if (data != null) model = data; @@ -470,7 +490,8 @@ public class LotDispositionController : Controller { try { foreach (PropertyInfo pi in sl.GetType().GetProperties()) { if (pi.Name.ToLower().StartsWith("lot") && pi.Name.ToLower().EndsWith("state")) { - byte currentValue = (byte)pi.GetValue(sl, null); + object? check = pi.GetValue(sl, null); + byte currentValue = check is null ? (byte)0 : (byte)check; if (currentValue == (int)GlobalVars.LotStatusOption.Release || currentValue == (int)GlobalVars.LotStatusOption.CloseToQDB) { releaseCount++; // required to update the lot status option @@ -498,8 +519,8 @@ public class LotDispositionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + sl.IssueID.ToString() + " LotNo:" + sl.LotNo.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Scrap Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = sl.IssueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "UpdateLotScrapReleaseStatus - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Scrap Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = sl.IssueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "UpdateLotScrapReleaseStatus - " + exceptionString }); throw new Exception(e.Message); } } @@ -508,7 +529,7 @@ public class LotDispositionController : Controller { /// Update the all the lots to "RELEASE" Status for a given Lot disposition document /// public void ReleaseAll(int issueID) { - ScrapLot sl = new ScrapLot(); + ScrapLot sl = new(); try { sl.IssueID = issueID; foreach (PropertyInfo pi in sl.GetType().GetProperties()) { @@ -526,8 +547,8 @@ public class LotDispositionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + sl.IssueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Release All Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = sl.IssueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "ReleaseAll - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Release All Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = sl.IssueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "ReleaseAll - " + exceptionString }); throw new Exception(e.Message); } } @@ -536,7 +557,7 @@ public class LotDispositionController : Controller { /// Update the all the lots to "SCRAP" Status for a given Lot disposition document /// public void ScrapAll(int issueID) { - ScrapLot sl = new ScrapLot(); + ScrapLot sl = new(); try { sl.IssueID = issueID; foreach (PropertyInfo pi in sl.GetType().GetProperties()) { @@ -554,20 +575,20 @@ public class LotDispositionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + sl.IssueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Scrap All Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = sl.IssueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "ScrapAll - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Scrap All Disposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = sl.IssueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "ScrapAll - " + exceptionString }); throw new Exception(e.Message); } } public JsonResult GetLotDispositionLotSummary(int issueID) { - return Json(ldDMO.GetLotDispositionLotSummary(issueID), JsonRequestBehavior.AllowGet); + return GetJsonResult(ldDMO.GetLotDispositionLotSummary(issueID)); } /// public ActionResult SubmitDocument(int issueID, bool peRequired, bool mrbRequired) { try { - int appoverCount = ldDMO.SubmitDocument(issueID, peRequired, mrbRequired, (int)Session[GlobalVars.SESSION_USERID]); + int appoverCount = ldDMO.SubmitDocument(issueID, peRequired, mrbRequired, GlobalVars.GetUserId(GetSession())); if (appoverCount > 0) NotifyApprovers(issueID, (byte)GlobalVars.WorkFLowStepNumber.Step1); else { @@ -576,10 +597,11 @@ public class LotDispositionController : Controller { } - if (Request.IsAjaxRequest()) { + if (IsAjaxRequest()) { return Content("Redirect"); - } else + } else { return Content("Invalid"); + } } catch (Exception e) { string detailedException = ""; try { @@ -588,11 +610,11 @@ public class LotDispositionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SubmitDocument\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n SubmitDocument\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError; - return Json(new { result = "Error", issueID = issueID, detail = e.Message }, JsonRequestBehavior.AllowGet); + return GetJsonResult(new { result = "Error", issueID = issueID, detail = e.Message }); } } @@ -600,13 +622,13 @@ public class LotDispositionController : Controller { int isITARCompliant = 1; try { bool lastStep = false; - LotDisposition ltDispo = ldDMO.GetLotDispositionItemForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + LotDisposition ltDispo = ldDMO.GetLotDispositionItemForRead(issueID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); - bool lastApprover = wfDMO.Approve(_AppSettings, issueID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.LotDisposition, ltDispo.WorkFlowNumber); + bool lastApprover = wfDMO.Approve(_AppSettings, issueID, currentStep, comments, out lastStep, GlobalVars.GetUserId(GetSession()), (int)GlobalVars.DocumentType.LotDisposition, ltDispo.WorkFlowNumber); while (lastApprover && !lastStep) { currentStep++; - lastApprover = wfDMO.Approve(_AppSettings, issueID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.LotDisposition, ltDispo.WorkFlowNumber); + lastApprover = wfDMO.Approve(_AppSettings, issueID, currentStep, comments, out lastStep, GlobalVars.GetUserId(GetSession()), (int)GlobalVars.DocumentType.LotDisposition, ltDispo.WorkFlowNumber); NotifyApprovers(issueID, currentStep); } } catch (Exception e) { @@ -617,16 +639,16 @@ public class LotDispositionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n " + "Approve\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "Approve - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n " + "Approve\r\n" + issueID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "Approve - " + exceptionString }); throw new Exception(e.Message); } } public void Reject(int issueID, byte currentStep, string comments) { try { - if (Session[GlobalVars.SESSION_USERID] != null) { - wfDMO.Reject(issueID, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.LotDisposition); + if (GlobalVars.IsUserIdValueNotNull(GetSession())) { + wfDMO.Reject(issueID, currentStep, comments, GlobalVars.GetUserId(GetSession()), (int)GlobalVars.DocumentType.LotDisposition); NotifyRejectionToOrginator(issueID); } else { @@ -640,29 +662,30 @@ public class LotDispositionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Reject\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "Reject - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Reject\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "Reject - " + exceptionString }); throw new Exception(e.Message); } } - /// - /// Get a list of Approvers and the status - /// +#if !NET8 + public ActionResult GetApproversList([DataSourceRequest] DataSourceRequest request, int issueID, byte step) { return Json(MiscDMO.GetApproversListByDocument(issueID, step, (int)GlobalVars.DocumentType.LotDisposition).ToDataSourceResult(request)); } +#endif + public JsonResult GetAllUsersList() { - UserAccountDMO userDMO = new UserAccountDMO(); + UserAccountDMO userDMO = new(); IEnumerable userlist = userDMO.GetAllUsers(); - return Json(userlist, JsonRequestBehavior.AllowGet); + return GetJsonResult(userlist); } public void ReAssignApproval(int issueID, int userIDs, byte step) { var email = ""; try { - email = wfDMO.ReAssignApproval(issueID, (int)Session[GlobalVars.SESSION_USERID], userIDs, step, (int)GlobalVars.DocumentType.LotDisposition); + email = wfDMO.ReAssignApproval(issueID, GlobalVars.GetUserId(GetSession()), userIDs, step, (int)GlobalVars.DocumentType.LotDisposition); } catch (Exception e) { string detailedException = ""; try { @@ -671,13 +694,13 @@ public class LotDispositionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReAssignApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ReAssignApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); throw new Exception(e.Message); } LotDispositionHelper.ReAssignApproval(_AppSettings, issueID, email); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Email", Comments = "ReAssign Approver: " + email }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Email", Comments = "ReAssign Approver: " + email }); } catch { } } @@ -693,22 +716,22 @@ public class LotDispositionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReAssignApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ReAssignApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); throw new Exception(e.Message); } LotDispositionHelper.ReAssignApproverByAdmin(_AppSettings, issueID, email); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Email", Comments = "ReAssign Approver: " + email }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Email", Comments = "ReAssign Approver: " + email }); } catch { } } #region Additional Approvers public JsonResult GetUserListForAdditionalAppprrovers() { - UserAccountDMO userDMO = new UserAccountDMO(); + UserAccountDMO userDMO = new(); IEnumerable userlist = userDMO.GetAllUsers(); - return Json(userlist, JsonRequestBehavior.AllowGet); + return GetJsonResult(userlist); } public void AddAdditionalApproval(int issueID, byte step, string userIDs) { @@ -724,13 +747,13 @@ public class LotDispositionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + step + " " + " Userid:" + userIDs + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n AddAdditionalApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n AddAdditionalApproval\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); throw new Exception(e.Message); } emailSentList = LotDispositionHelper.AddAdditionalApproval(_AppSettings, issueID, emailSentList, emailArray); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Email", Comments = "Additonal Approver: " + emailSentList }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Email", Comments = "Additonal Approver: " + emailSentList }); } catch { } } @@ -741,7 +764,7 @@ public class LotDispositionController : Controller { List emailIst = MiscDMO.GetApproverEmailListByDocument(@issueID, currentStep, (int)GlobalVars.DocumentType.LotDisposition).Distinct().ToList(); string emailSentList = LotDispositionHelper.NotifyApprovers(_AppSettings, issueID, emailIst); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); } catch { } } catch (Exception e) { string detailedException = ""; @@ -751,19 +774,19 @@ public class LotDispositionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Lot Dispo - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); - throw e; + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Lot Dispo - NotifyApprovers\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); + throw; } } public void NotifyRejectionToOrginator(int issueID) { - string username = Session[GlobalVars.SESSION_USERNAME].ToString(); + string username = GlobalVars.GetUserName(GetSession()); List emailIst = ldDMO.GetRejectionOrginatorEmailList(@issueID).Distinct().ToList(); string userEmail = LotDispositionHelper.NotifyRejectionToOrginator(_AppSettings, issueID, username, emailIst); try { - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Email", Comments = "Rejection: " + userEmail }); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Email", Comments = "Rejection: " + userEmail }); } catch { } } @@ -778,19 +801,23 @@ public class LotDispositionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n UpdateReasonForDisposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "UpdateReasonForDisposition - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n UpdateReasonForDisposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "UpdateReasonForDisposition - " + exceptionString }); throw new Exception(e.Message); } } +#if !NET8 + public ActionResult GetComments([DataSourceRequest] DataSourceRequest request, int issueID) { return Json(ldDMO.GetComments(issueID).ToDataSourceResult(request)); } +#endif + public void InsertComments(int issueID, string Comments) { try { - ldDMO.InsertComments(issueID, Comments, (int)Session[GlobalVars.SESSION_USERID]); + ldDMO.InsertComments(issueID, Comments, GlobalVars.GetUserId(GetSession())); } catch (Exception e) { string detailedException = ""; try { @@ -799,17 +826,19 @@ public class LotDispositionController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n UpdateCopmments\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "UpdateCopmments - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n UpdateCopmments\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "UpdateCopmments - " + exceptionString }); throw new Exception(e.Message); } } +#if !NET8 + public ActionResult ExcelLotOpen(IEnumerable Lotfile, int issueID) { MRB_DMO mrbDMO = new MRB_DMO(_AppSettings); var physicalPath = ""; try { - string userIdentityName = @User.Identity.Name; + string userIdentityName = GetUserIdentityName(); foreach (var file in Lotfile) { physicalPath = LotDispositionHelper.ExcelLotOpen(ldDMO, issueID, userIdentityName, _AppSettings.LotTempPipeLine, file.FileName, file.InputStream); } @@ -824,12 +853,14 @@ public class LotDispositionController : Controller { } } +#endif + public void ReleaseLockOnDocument(int issueID) { try { - ldDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], issueID); + ldDMO.ReleaseLockOnDocument(GlobalVars.GetUserId(GetSession()), issueID); } catch (Exception e) { try { - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReleaseLockOnDocument LD\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ReleaseLockOnDocument LD\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error); } catch { } ldDMO.ReleaseLockOnDocument(-1, issueID); } @@ -857,4 +888,34 @@ public class LotDispositionController : Controller { return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); } + +#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; + } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/LotTravelerController.cs b/Fab2ApprovalSystem/Controllers/LotTravelerController.cs index b1503d7..f061728 100644 --- a/Fab2ApprovalSystem/Controllers/LotTravelerController.cs +++ b/Fab2ApprovalSystem/Controllers/LotTravelerController.cs @@ -1,65 +1,86 @@ using System; using System.Collections.Generic; -using System.Configuration; +using System.Diagnostics; using System.Linq; -using System.Threading; + +#if !NET8 using System.Web; using System.Web.Mvc; +using System.Configuration; +using System.Threading; +using Fab2ApprovalSystem.PdfGenerator; +#endif + +#if NET8 +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +#endif + +#if NET8 +using Fab2ApprovalSystem.Extensions; +#endif using Fab2ApprovalSystem.DMO; using Fab2ApprovalSystem.Misc; using Fab2ApprovalSystem.Models; -using Fab2ApprovalSystem.PdfGenerator; using Fab2ApprovalSystem.ViewModels; +#if !NET8 using Kendo.Mvc.Extensions; using Kendo.Mvc.UI; +#endif namespace Fab2ApprovalSystem.Controllers; [Authorize] +#if !NET8 [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] [SessionExpireFilter] public class LotTravelerController : PdfViewController { +#endif +#if NET8 +[Route("[controller]")] +public class LotTravelerController : Controller { +#endif - LotTravelerDMO LotTravDMO = new LotTravelerDMO(); - string docTypeString = "LotTraveler"; - WorkflowDMO wfDMO = new WorkflowDMO(); - private readonly AppSettings _AppSettings = GlobalVars.AppSettings; + private readonly LotTravelerDMO LotTravDMO = new(); + private readonly string docTypeString = "LotTraveler"; + private readonly WorkflowDMO wfDMO = new(); + private readonly AppSettings? _AppSettings = GlobalVars.AppSettings; public ActionResult CreateWorkRequest() { - LTWorkRequest workRequest = new LTWorkRequest(); + LTWorkRequest workRequest = new(); try { - workRequest.OriginatorID = (int)Session[GlobalVars.SESSION_USERID]; + workRequest.OriginatorID = GlobalVars.GetUserId(GetSession()); LotTravDMO.InsertWorkRequest(workRequest); return RedirectToAction("Edit", new { issueID = workRequest.ID }); } catch (Exception e) { string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + workRequest.SWRNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n CreateWorkRequest - LotTraveler\r\n" + e.InnerException == null ? e.Message : e.InnerException.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = workRequest.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "CreateWorkRequest - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n CreateWorkRequest - LotTraveler\r\n" + e.InnerException == null ? e.Message : e.InnerException.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = workRequest.SWRNumber, UserID = GetUserIdentityName(), DocumentType = "Lot Traveler", OperationType = "Error", Comments = "CreateWorkRequest - " + exceptionString }); throw new Exception(e.Message); } } public ActionResult Edit(int issueID) { int isITARCompliant = 1; - Session["CreateNewRevision"] = "false"; + GlobalVars.SetCreateNewRevision(GetSession(), false); ViewBag.NewRevision = "false"; - LTWorkRequest workRequest = new LTWorkRequest(); + LTWorkRequest workRequest = new(); try { - workRequest = LotTravDMO.GetLTWorkRequestItemForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + workRequest = LotTravDMO.GetLTWorkRequestItemForRead(issueID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); if (isITARCompliant == 0) // not ITAR Compliant { return View("UnAuthorizedAccess"); } - if ((int)Session[GlobalVars.SESSION_USERID] == workRequest.OriginatorID) + if (GlobalVars.GetUserId(GetSession()) == workRequest.OriginatorID) ViewBag.IsOriginator = "true"; else ViewBag.IsOriginator = "false"; List userList = MiscDMO.GetPendingApproversListByDocument(issueID, workRequest.CurrentStep, (int)GlobalVars.DocumentType.LotTraveler); - ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); + ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == GlobalVars.GetUserId(GetSession()); }); if (approver == null) ViewBag.IsApprover = "false"; else @@ -72,23 +93,23 @@ public class LotTravelerController : PdfViewController { // open the view based on the Workflow step if (workRequest.CurrentStep == 0) { - if ((workRequest.RecordLockIndicator && workRequest.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID])) { + if ((workRequest.RecordLockIndicator && workRequest.RecordLockedBy != GlobalVars.GetUserId(GetSession()))) { return RedirectToAction("WorkRequestReadOnly", new { issueID = issueID }); } } else if (workRequest.CurrentStep >= 1 && workRequest.CurrentStep < 3 && workRequest.CloseDate == null) // Before { - if ((ViewBag.IsApprover == "true") || ((bool)Session[GlobalVars.IS_ADMIN])) + if ((ViewBag.IsApprover == "true") || (GlobalVars.IsAdmin(GetSession()))) return RedirectToAction("WorkRequestApproval", new { issueID = issueID }); else return RedirectToAction("WorkRequestReadOnly", new { issueID = issueID }); } else if (workRequest.CurrentStep == 3) { - if ((workRequest.RecordLockIndicator && workRequest.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) || (ViewBag.IsApprover == "false")) { + if ((workRequest.RecordLockIndicator && workRequest.RecordLockedBy != GlobalVars.GetUserId(GetSession())) || (ViewBag.IsApprover == "false")) { return RedirectToAction("WorkRequestReadOnly", new { issueID = issueID }); } else { - Session["CreateNewRevision"] = "true"; + GlobalVars.SetCreateNewRevision(GetSession(), true); ViewBag.NewRevision = "true"; - workRequest = LotTravDMO.GetLTWorkRequestItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + workRequest = LotTravDMO.GetLTWorkRequestItem(issueID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); return RedirectToAction("WorkRequestRevision", new { workRequestID = issueID }); } @@ -96,7 +117,7 @@ public class LotTravelerController : PdfViewController { // Call the Edit Form } - workRequest = LotTravDMO.GetLTWorkRequestItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + workRequest = LotTravDMO.GetLTWorkRequestItem(issueID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); // else do this part ViewBag.Departments = MiscDMO.GetDepartments(); ViewBag.AffectedModules = MiscDMO.GetModules(); @@ -104,8 +125,8 @@ public class LotTravelerController : PdfViewController { return View(workRequest); } catch (Exception e) { string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + workRequest.SWRNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Edit WorkRequest - LotTraveler\r\n" + e.InnerException == null ? e.Message : e.InnerException.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = workRequest.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "Edit WorkRequest - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Edit WorkRequest - LotTraveler\r\n" + e.InnerException == null ? e.Message : e.InnerException.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = workRequest.SWRNumber, UserID = GetUserIdentityName(), DocumentType = "Lot Traveler", OperationType = "Error", Comments = "Edit WorkRequest - " + exceptionString }); throw new Exception(e.Message); } } @@ -113,33 +134,33 @@ public class LotTravelerController : PdfViewController { public ActionResult SaveRevision(LTWorkRequest model) { try { var data = model; - if (Session["CreateNewRevision"].ToString() == "true") { + if (GlobalVars.GetCreateNewRevision(GetSession())) { ViewBag.NewRevision = "false"; - Session["CreateNewRevision"] = "false"; - model.OriginatorID = (int)Session[GlobalVars.SESSION_USERID]; - int newRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); + GlobalVars.SetCreateNewRevision(GetSession(), false); + model.OriginatorID = GlobalVars.GetUserId(GetSession()); + int newRequestID = LotTravDMO.CreateWorkRequestRevision(model, GlobalVars.GetUserId(GetSession())); // TODO // Send email to the Originator and Group of People NotifyfWorkRequestRevisionChange(newRequestID); return Content(newRequestID.ToString()); } else { - LotTravDMO.UpdateWorkRequest(model, (int)Session[GlobalVars.SESSION_USERID]); + LotTravDMO.UpdateWorkRequest(model, GlobalVars.GetUserId(GetSession())); return Content(""); } } catch (Exception e) { string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + model.SWRNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SaveRevision - LotTraveler\r\n" + e.InnerException == null ? e.Message : e.InnerException.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = model.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "SaveRevision - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n SaveRevision - LotTraveler\r\n" + e.InnerException == null ? e.Message : e.InnerException.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = model.SWRNumber, UserID = GetUserIdentityName(), DocumentType = "Lot Traveler", OperationType = "Error", Comments = "SaveRevision - " + exceptionString }); throw new Exception(e.Message); } } public ActionResult WorkRequestReadOnly(int issueID) { int isITARCompliant = 1; - LTWorkRequest workRequest = new LTWorkRequest(); + LTWorkRequest workRequest = new(); try { - workRequest = LotTravDMO.GetLTWorkRequestItemForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + workRequest = LotTravDMO.GetLTWorkRequestItemForRead(issueID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); ViewBag.Departments = MiscDMO.GetDepartments(); ViewBag.AffectedModules = MiscDMO.GetModules(); @@ -148,31 +169,31 @@ public class LotTravelerController : PdfViewController { return View(workRequest); } catch (Exception e) { string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n WorkRequestReadOnly - LotTraveler\r\n" + e.InnerException == null ? e.Message : e.InnerException.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "WorkRequestReadOnly - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n WorkRequestReadOnly - LotTraveler\r\n" + e.InnerException == null ? e.Message : e.InnerException.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Traveler", OperationType = "Error", Comments = "WorkRequestReadOnly - " + exceptionString }); throw new Exception(e.Message); } } public ActionResult WorkRequestApproval(int issueID) { int isITARCompliant = 1; - LTWorkRequest workRequest = new LTWorkRequest(); + LTWorkRequest workRequest = new(); try { - workRequest = LotTravDMO.GetLTWorkRequestItemForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + workRequest = LotTravDMO.GetLTWorkRequestItemForRead(issueID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); List userList = MiscDMO.GetPendingApproversListByDocument(issueID, workRequest.CurrentStep, (int)GlobalVars.DocumentType.LotTraveler); - ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); + ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == GlobalVars.GetUserId(GetSession()); }); if (approver == null) ViewBag.IsApprover = "false"; else ViewBag.IsApprover = "true"; - if (workRequest.RecordLockIndicator && workRequest.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) { + if (workRequest.RecordLockIndicator && workRequest.RecordLockedBy != GlobalVars.GetUserId(GetSession())) { return RedirectToAction("WorkRequestReadOnly", new { issueID = issueID }); } - workRequest = LotTravDMO.GetLTWorkRequestItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + workRequest = LotTravDMO.GetLTWorkRequestItem(issueID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); ViewBag.Departments = MiscDMO.GetDepartments(); ViewBag.AffectedModules = MiscDMO.GetModules(); ViewBag.WorkReqRevisionList = LotTravDMO.GetWorkReqRevisions(workRequest.SWRNumber); @@ -180,31 +201,39 @@ public class LotTravelerController : PdfViewController { return View(workRequest); } catch (Exception e) { string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n WorkRequestApproval - LotTraveler\r\n" + e.InnerException == null ? e.Message : e.InnerException.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "WorkRequestApproval - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n WorkRequestApproval - LotTraveler\r\n" + e.InnerException == null ? e.Message : e.InnerException.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Traveler", OperationType = "Error", Comments = "WorkRequestApproval - " + exceptionString }); throw new Exception(e.Message); } } public ActionResult GetWorkRequestRevision(int workRequestID) { int isITARCompliant = 1; - LTWorkRequest workRequest = new LTWorkRequest(); - workRequest = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + LTWorkRequest workRequest = new(); + workRequest = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); return Content(""); } public ActionResult DisplayWorkRequestPDF(int workRequestID) { - WorkRequestPdf workRequest = new WorkRequestPdf(); + WorkRequestPdf workRequest = new(); try { workRequest = LotTravDMO.GetLTWorkRequestItemPDF(workRequestID); // To render a PDF instead of an HTML, all we need to do is call ViewPdf instead of View. This // requires the controller to be inherited from MyController instead of MVC's Controller. - return this.ViewPdf("", "WorkRequestPDF", workRequest); +#if !NET8 + return ViewPdf("", "WorkRequestPDF", workRequest); +#endif +#if NET8 + if (Debugger.IsAttached) + return Content(this.RenderViewToString("WorkRequestPDF", workRequest), "text/html"); + else + return this.GetBinaryContentResult("WorkRequestPDF", "application/pdf", workRequest); +#endif } catch (Exception ex) { - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n DisplayWorkRequestPDF - LotTraveler\r\n" + ex.InnerException.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = workRequest.SWRNumber, UserID = @User.Identity.Name, DocumentType = "LotTravler", OperationType = "Generate PDF", Comments = ex.Message }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n DisplayWorkRequestPDF - LotTraveler\r\n" + ex.InnerException.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = workRequest.SWRNumber, UserID = GetUserIdentityName(), DocumentType = "LotTravler", OperationType = "Generate PDF", Comments = ex.Message }); workRequest = null; return Content(""); } @@ -212,17 +241,17 @@ public class LotTravelerController : PdfViewController { public ActionResult WorkRequestRevision(int workRequestID) { int isITARCompliant = 1; - LTWorkRequest workRequest = new LTWorkRequest(); - workRequest = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + LTWorkRequest workRequest = new(); + workRequest = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); List userList = MiscDMO.GetPendingApproversListByDocument(workRequestID, workRequest.CurrentStep, (int)GlobalVars.DocumentType.LotTraveler); - ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); + ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == GlobalVars.GetUserId(GetSession()); }); if (approver == null) ViewBag.IsApprover = "false"; else ViewBag.IsApprover = "true"; if ( - (workRequest.RecordLockIndicator && workRequest.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID] + (workRequest.RecordLockIndicator && workRequest.RecordLockedBy != GlobalVars.GetUserId(GetSession()) || (ViewBag.IsApprover == "false")) || (!workRequest.IsCurrentRevision) || (workRequest.CloseDate != null) @@ -230,7 +259,7 @@ public class LotTravelerController : PdfViewController { return RedirectToAction("WorkRequestReadOnly", new { issueID = workRequestID }); } - workRequest = LotTravDMO.GetLTWorkRequestItem(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + workRequest = LotTravDMO.GetLTWorkRequestItem(workRequestID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); ViewBag.Departments = MiscDMO.GetDepartments(); ViewBag.AffectedModules = MiscDMO.GetModules(); @@ -242,9 +271,9 @@ public class LotTravelerController : PdfViewController { [HttpPost] public ActionResult Edit(LTWorkRequest model) { try { - Session["CreateNewRevision"] = "false"; + GlobalVars.SetCreateNewRevision(GetSession(), false); var data = model; - LotTravDMO.UpdateWorkRequest(model, (int)Session[GlobalVars.SESSION_USERID]); + LotTravDMO.UpdateWorkRequest(model, GlobalVars.GetUserId(GetSession())); } catch (Exception ex) { return Content(ex.Message); } @@ -256,34 +285,40 @@ public class LotTravelerController : PdfViewController { /// public JsonResult GetBaseFlowLocations(string baseFlow) { List loclist = LotTravDMO.GetBaseFlowLocations(baseFlow); - return Json(loclist, JsonRequestBehavior.AllowGet); + return GetJsonResult(loclist); } public JsonResult GetMaterialRecord(int materialID) { LTMaterial ltMaterial = LotTravDMO.GetMaterialRecord(materialID); - return Json(ltMaterial, JsonRequestBehavior.AllowGet); + return GetJsonResult(ltMaterial); } public JsonResult GetBaseFlowOperations(string baseFlow, string location) { List operationslist = LotTravDMO.GetBaseFlowOperations(baseFlow, location); - return Json(operationslist, JsonRequestBehavior.AllowGet); + return GetJsonResult(operationslist); } +#if !NET8 + public ActionResult GetMaterialDetails([DataSourceRequest] DataSourceRequest request, int workRequestID) { return Json(LotTravDMO.GetMaterialDetails(workRequestID).ToDataSourceResult(request)); } +#endif + public JsonResult GetPartNumbers() { List operationslist = LotTravDMO.GetPartNumbers(); - return Json(operationslist, JsonRequestBehavior.AllowGet); + return GetJsonResult(operationslist); } +#if !NET8 + [AcceptVerbs(HttpVerbs.Post)] public ActionResult InsertMaterialDetail([DataSourceRequest] DataSourceRequest request, LTMaterialViewModel model) { try { - string s = Session["CreateNewRevision"].ToString(); + bool s = GlobalVars.GetCreateNewRevision(GetSession()); if (model != null && ModelState.IsValid) { - LotTravDMO.InsertMaterialDetail(model, (int)Session[GlobalVars.SESSION_USERID]); + LotTravDMO.InsertMaterialDetail(model, GlobalVars.GetUserId(GetSession())); } return Json(new[] { model }.ToDataSourceResult(request, ModelState)); @@ -298,7 +333,7 @@ public class LotTravelerController : PdfViewController { public ActionResult UpdateMaterialDetail([DataSourceRequest] DataSourceRequest request, LTMaterialViewModel model) { try { if (model != null && ModelState.IsValid) { - LotTravDMO.UpdateMaterialDetail(model, (int)Session[GlobalVars.SESSION_USERID]); + LotTravDMO.UpdateMaterialDetail(model, GlobalVars.GetUserId(GetSession())); } return Json(new[] { model }.ToDataSourceResult(request, ModelState)); @@ -309,23 +344,25 @@ public class LotTravelerController : PdfViewController { } } +#endif + public ActionResult AddMaterialDetailRevision(LTWorkRequest model) { var modelMaterialDetail = model.LTMaterial; int previousMaterialID = model.LTMaterial.ID; int newWorkRequestID = model.ID; - if (Session["CreateNewRevision"].ToString() == "true") { - Session["CreateNewRevision"] = "false"; + if (GlobalVars.GetCreateNewRevision(GetSession())) { + GlobalVars.SetCreateNewRevision(GetSession(), false); - newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); + newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, GlobalVars.GetUserId(GetSession())); modelMaterialDetail.LTWorkRequestID = newWorkRequestID; // Any update will be a new entry - LotTravDMO.InsertMaterialDetail(modelMaterialDetail, (int)Session[GlobalVars.SESSION_USERID]); + LotTravDMO.InsertMaterialDetail(modelMaterialDetail, GlobalVars.GetUserId(GetSession())); // TODO NotifyfWorkRequestRevisionChange(newWorkRequestID); } else { if (modelMaterialDetail != null && ModelState.IsValid) { - LotTravDMO.InsertMaterialDetail(modelMaterialDetail, (int)Session[GlobalVars.SESSION_USERID]); + LotTravDMO.InsertMaterialDetail(modelMaterialDetail, GlobalVars.GetUserId(GetSession())); } } @@ -340,10 +377,10 @@ public class LotTravelerController : PdfViewController { int previousMaterialID = model.LTMaterial.ID; int newWorkRequestID = model.ID; - if (Session["CreateNewRevision"].ToString() == "true") { - Session["CreateNewRevision"] = "false"; + if (GlobalVars.GetCreateNewRevision(GetSession())) { + GlobalVars.SetCreateNewRevision(GetSession(), false); - newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); + newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, GlobalVars.GetUserId(GetSession())); modelMaterialDetail.LTWorkRequestID = newWorkRequestID; // Any update will be a new entry @@ -353,13 +390,15 @@ public class LotTravelerController : PdfViewController { NotifyfWorkRequestRevisionChange(newWorkRequestID); } else { if (modelMaterialDetail != null && ModelState.IsValid) { - LotTravDMO.UpdateMaterialDetail(modelMaterialDetail, (int)Session[GlobalVars.SESSION_USERID]); + LotTravDMO.UpdateMaterialDetail(modelMaterialDetail, GlobalVars.GetUserId(GetSession())); } } return Content(newWorkRequestID.ToString()); } +#if !NET8 + public ActionResult DeleteMaterialDetail([DataSourceRequest] DataSourceRequest request, LTMaterialViewModel model) { try { if (model != null && ModelState.IsValid) { @@ -372,14 +411,16 @@ public class LotTravelerController : PdfViewController { return Json(new[] { model }.ToDataSourceResult(request, ModelState)); } +#endif + public ActionResult DeleteMaterialDetailRevision(LTWorkRequest model) { var modelMaterialDetail = model.LTMaterial; int newWorkRequestID = model.ID; - if (Session["CreateNewRevision"].ToString() == "true") { - Session["CreateNewRevision"] = "false"; + if (GlobalVars.GetCreateNewRevision(GetSession())) { + GlobalVars.SetCreateNewRevision(GetSession(), false); - newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); + newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, GlobalVars.GetUserId(GetSession())); modelMaterialDetail.LTWorkRequestID = newWorkRequestID; // Any update will be a new entry @@ -396,27 +437,31 @@ public class LotTravelerController : PdfViewController { return Content(newWorkRequestID.ToString()); } +#if !NET8 + public ActionResult GetHoldSteps([DataSourceRequest] DataSourceRequest request, int workRequestID) { return Json(LotTravDMO.GetHoldSteps(workRequestID).ToDataSourceResult(request)); } public ActionResult InsertHoldStep([DataSourceRequest] DataSourceRequest request, LTHoldStep model) { if (model != null && ModelState.IsValid) { - model.UpdatedBy = (int)Session[GlobalVars.SESSION_USERID]; + model.UpdatedBy = GlobalVars.GetUserId(GetSession()); LotTravDMO.InsertHoldStep(model); } return Json(new[] { model }.ToDataSourceResult(request, ModelState)); } +#endif + public ActionResult UpdateHoldStepRevision(LTWorkRequest model) { var holdStepModel = model.LTHoldStep; int newWorkRequestID = model.ID; - if (Session["CreateNewRevision"].ToString() == "true") { - Session["CreateNewRevision"] = "false"; + if (GlobalVars.GetCreateNewRevision(GetSession())) { + GlobalVars.SetCreateNewRevision(GetSession(), false); - newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); + newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, GlobalVars.GetUserId(GetSession())); holdStepModel.LTWorkRequestID = newWorkRequestID; // Any update will be a new entry @@ -426,7 +471,7 @@ public class LotTravelerController : PdfViewController { NotifyfWorkRequestRevisionChange(newWorkRequestID); } else { if (holdStepModel != null && ModelState.IsValid) { - holdStepModel.UpdatedBy = (int)Session[GlobalVars.SESSION_USERID]; + holdStepModel.UpdatedBy = GlobalVars.GetUserId(GetSession()); LotTravDMO.UpdateHoldStep(holdStepModel); } } @@ -438,10 +483,10 @@ public class LotTravelerController : PdfViewController { var holdStepModel = model.LTHoldStep; int newWorkRequestID = model.ID; - if (Session["CreateNewRevision"].ToString() == "true") { - Session["CreateNewRevision"] = "false"; + if (GlobalVars.GetCreateNewRevision(GetSession())) { + GlobalVars.SetCreateNewRevision(GetSession(), false); - newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); + newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, GlobalVars.GetUserId(GetSession())); holdStepModel.LTWorkRequestID = newWorkRequestID; // Any update will be a new entry @@ -451,7 +496,7 @@ public class LotTravelerController : PdfViewController { NotifyfWorkRequestRevisionChange(newWorkRequestID); } else { if (holdStepModel != null && ModelState.IsValid) { - holdStepModel.UpdatedBy = (int)Session[GlobalVars.SESSION_USERID]; + holdStepModel.UpdatedBy = GlobalVars.GetUserId(GetSession()); LotTravDMO.InsertHoldStep(holdStepModel); } } @@ -463,10 +508,10 @@ public class LotTravelerController : PdfViewController { var holdStepModel = model.LTHoldStep; int newWorkRequestID = model.ID; - if (Session["CreateNewRevision"].ToString() == "true") { - Session["CreateNewRevision"] = "false"; + if (GlobalVars.GetCreateNewRevision(GetSession())) { + GlobalVars.SetCreateNewRevision(GetSession(), false); - newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); + newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, GlobalVars.GetUserId(GetSession())); holdStepModel.LTWorkRequestID = newWorkRequestID; // Any update will be a new entry @@ -477,7 +522,7 @@ public class LotTravelerController : PdfViewController { } else { if (holdStepModel != null && ModelState.IsValid) { - LotTravDMO.DeleteHoldStep(holdStepModel.ID, (int)Session[GlobalVars.SESSION_USERID]); + LotTravDMO.DeleteHoldStep(holdStepModel.ID, GlobalVars.GetUserId(GetSession())); } } @@ -490,11 +535,13 @@ public class LotTravelerController : PdfViewController { } } +#if !NET8 + [AcceptVerbs(HttpVerbs.Post)] public ActionResult DeleteHoldStep([DataSourceRequest] DataSourceRequest request, LTHoldStep model) { try { if (model != null && ModelState.IsValid) { - LotTravDMO.DeleteHoldStep(model.ID, (int)Session[GlobalVars.SESSION_USERID]); + LotTravDMO.DeleteHoldStep(model.ID, GlobalVars.GetUserId(GetSession())); } } catch (Exception ex) { @@ -506,26 +553,30 @@ public class LotTravelerController : PdfViewController { return Json(new[] { model }.ToDataSourceResult(request, ModelState)); } +#endif + public ActionResult GetHoldStep(int holdStepID) { - var model = new LTHoldStep(); + LTHoldStep model = new(); model = LotTravDMO.GetHoldStep(holdStepID); return PartialView("_HoldStepAttachments", model); } public ActionResult GetHoldStepRevision(int holdStepID) { - var model = new LTHoldStep(); + LTHoldStep model = new(); model = LotTravDMO.GetHoldStep(holdStepID); return PartialView("_HoldStepAttachmentsRevision", model); } public ActionResult GetLotTravHoldStepRevision(int ltHoldStepID) { - var model = new LTLotTravelerHoldSteps(); + LTLotTravelerHoldSteps model = new(); model = LotTravDMO.GetLotTravHoldStep(ltHoldStepID); return PartialView("_LotTravHoldStepAttachRev", model); } +#if !NET8 + public ActionResult GetHoldStepAttachments([DataSourceRequest] DataSourceRequest request, int holdStepID) { return Json(LotTravDMO.GetHoldStepAttachemnts(holdStepID).ToDataSourceResult(request)); } @@ -543,11 +594,10 @@ public class LotTravelerController : PdfViewController { } } catch (Exception e) { string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Delete =" + model.ID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n AttachmentID Work Request\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { UserID = @User.Identity.Name, OperationType = "Error", Comments = exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n AttachmentID Work Request\r\n" + e.Message.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { UserID = GetUserIdentityName(), OperationType = "Error", Comments = exceptionString }); throw new Exception(e.Message); } - return Json(new[] { model }.ToDataSourceResult(request, ModelState)); } @@ -564,15 +614,17 @@ public class LotTravelerController : PdfViewController { return Json(new[] { model }.ToDataSourceResult(request, ModelState)); } +#endif + public ActionResult UpdateWorkRequestAttachmentRevision(LTWorkRequest model) { var wrAttachmentDetail = model.WorkRequestAttachment; int previousWorkRequestAttachmentID = model.WorkRequestAttachment.ID; int newWorkRequestID = model.ID; - if (Session["CreateNewRevision"].ToString() == "true") { - Session["CreateNewRevision"] = "false"; + if (GlobalVars.GetCreateNewRevision(GetSession())) { + GlobalVars.SetCreateNewRevision(GetSession(), false); - newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); + newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, GlobalVars.GetUserId(GetSession())); wrAttachmentDetail.WorkRequestID = newWorkRequestID; // Any update will be a new entry @@ -589,6 +641,8 @@ public class LotTravelerController : PdfViewController { return Content(newWorkRequestID.ToString()); } +#if !NET8 + [AcceptVerbs(HttpVerbs.Post)] public ActionResult DeleteWorkRequestAttachment([DataSourceRequest] DataSourceRequest request, LTWorkRequestAttachment model) { try { @@ -598,23 +652,25 @@ public class LotTravelerController : PdfViewController { } } catch (Exception e) { string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Delete =" + model.ID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n AttachmentID WorkRequiest\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { UserID = @User.Identity.Name, OperationType = "Error", Comments = exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n AttachmentID WorkRequiest\r\n" + e.Message.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { UserID = GetUserIdentityName(), OperationType = "Error", Comments = exceptionString }); throw new Exception(e.Message); } return Json(new[] { model }.ToDataSourceResult(request, ModelState)); } +#endif + public ActionResult DeleteWorkRequestAttachmentRevision(LTWorkRequest model) { var wrAttachmentDetail = model.WorkRequestAttachment; int previousWorkRequestAttachmentID = model.WorkRequestAttachment.ID; int newWorkRequestID = model.ID; - if (Session["CreateNewRevision"].ToString() == "true") { - Session["CreateNewRevision"] = "false"; + if (GlobalVars.GetCreateNewRevision(GetSession())) { + GlobalVars.SetCreateNewRevision(GetSession(), false); - newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); + newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, GlobalVars.GetUserId(GetSession())); wrAttachmentDetail.WorkRequestID = newWorkRequestID; // Any update will be a new entry @@ -631,10 +687,12 @@ public class LotTravelerController : PdfViewController { return Content(newWorkRequestID.ToString()); } +#if !NET8 + public ActionResult AttachSaveWorkRequest(IEnumerable files, int workRequestID, int currentRevision, int swrNo, string comments, string docType) { // The Name of the Upload component is "files" if (files != null) { - int userId = (int)Session[GlobalVars.SESSION_USERID]; + int userId = GlobalVars.GetUserId(GetSession()); foreach (var file in files) { LotTravelerHelper.AttachSaveWorkRequest(_AppSettings, LotTravDMO, workRequestID, swrNo, comments, docType, userId, file.FileName, file.InputStream); } @@ -646,13 +704,13 @@ public class LotTravelerController : PdfViewController { bool newRevision = false; int newWorkRequestID = -1; int isITARCompliant = 1; - LTWorkRequest model = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + LTWorkRequest model = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); model.RevisionComments = revComments; - if (Session["CreateNewRevision"].ToString() == "true") { + if (GlobalVars.GetCreateNewRevision(GetSession())) { newRevision = true; - Session["CreateNewRevision"] = "false"; - newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); + GlobalVars.SetCreateNewRevision(GetSession(), false); + newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, GlobalVars.GetUserId(GetSession())); // Send email to the Originator and Group of People NotifyfWorkRequestRevisionChange(newWorkRequestID); @@ -660,7 +718,7 @@ public class LotTravelerController : PdfViewController { // The Name of the Upload component is "files" if (files != null) { - int userId = (int)Session[GlobalVars.SESSION_USERID]; + int userId = GlobalVars.GetUserId(GetSession()); foreach (var file in files) { LotTravelerHelper.AttachSaveWorkRequestRevision(_AppSettings, LotTravDMO, workRequestID, swrNo, docType, attachComments, newRevision, userId, file.FileName, file.InputStream); } @@ -672,15 +730,15 @@ public class LotTravelerController : PdfViewController { // The Name of the Upload component is "files" try { if (HoldStepAttachment != null) { - int userId = (int)Session[GlobalVars.SESSION_USERID]; + int userId = GlobalVars.GetUserId(GetSession()); foreach (var file in HoldStepAttachment) { LotTravelerHelper.HoldStepAttachSave(_AppSettings, LotTravDMO, holdStepID, swrNo, docType, comments, userId, file.FileName, file.InputStream); } } } catch (Exception e) { string exceptionString = e.Message.ToString().Trim().Length > 500 ? "HoldStep=" + holdStepID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = holdStepID, UserID = @User.Identity.Name, DocumentType = docTypeString, OperationType = "Error", Comments = "HoldStep Attachment - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Approve\r\n" + e.Message.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = holdStepID, UserID = GetUserIdentityName(), DocumentType = docTypeString, OperationType = "Error", Comments = "HoldStep Attachment - " + exceptionString }); throw new Exception(e.Message); } return Content(""); @@ -691,33 +749,35 @@ public class LotTravelerController : PdfViewController { bool newRevision = false; int newWorkRequestID = -1; int isITARCompliant = 1; - LTWorkRequest model = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + LTWorkRequest model = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); model.RevisionComments = revComments; - if (Session["CreateNewRevision"].ToString() == "true") { + if (GlobalVars.GetCreateNewRevision(GetSession())) { newRevision = true; - Session["CreateNewRevision"] = "false"; - newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, (int)Session[GlobalVars.SESSION_USERID]); + GlobalVars.SetCreateNewRevision(GetSession(), false); + newWorkRequestID = LotTravDMO.CreateWorkRequestRevision(model, GlobalVars.GetUserId(GetSession())); NotifyfWorkRequestRevisionChange(newWorkRequestID); } try { if (HoldStepAttachment != null) { - int userId = (int)Session[GlobalVars.SESSION_USERID]; + int userId = GlobalVars.GetUserId(GetSession()); foreach (var file in HoldStepAttachment) { LotTravelerHelper.HoldStepAttachSaveRev(_AppSettings, LotTravDMO, holdStepID, swrNo, docType, comments, newRevision, userId, file.FileName, file.InputStream); } } } catch (Exception e) { string exceptionString = e.Message.ToString().Trim().Length > 500 ? "HoldStep=" + holdStepID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = holdStepID, UserID = @User.Identity.Name, DocumentType = docTypeString, OperationType = "Error", Comments = "HoldStep Attachment - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Approve\r\n" + e.Message.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = holdStepID, UserID = GetUserIdentityName(), DocumentType = docTypeString, OperationType = "Error", Comments = "HoldStep Attachment - " + exceptionString }); throw new Exception(e.Message); } return Content(""); } +#endif + public int GetRevisedWrkReqIDFromHoldStepID(int prevHoldStepID) { return LotTravDMO.GetRevisedWrkReqIDFromHoldStepID(prevHoldStepID); } @@ -728,14 +788,14 @@ public class LotTravelerController : PdfViewController { public JsonResult GetWorkRequestAttachDetail(int wrAttachmentID) { LTWorkRequestAttachment data = LotTravDMO.GetWorkRequestAttachDetail(wrAttachmentID); - return Json(data, JsonRequestBehavior.AllowGet); + return GetJsonResult(data); } public ActionResult SubmitDocument(int workRequestID, int documentType) { int isITARCompliant = 1; - LTWorkRequest ltWR = new LTWorkRequest(); + LTWorkRequest ltWR = new(); try { - int appoverCount = LotTravDMO.SubmitDocument(workRequestID, (int)Session[GlobalVars.SESSION_USERID], documentType, out isITARCompliant); + int appoverCount = LotTravDMO.SubmitDocument(workRequestID, GlobalVars.GetUserId(GetSession()), documentType, out isITARCompliant); if (isITARCompliant == 0) // not ITAR Compliant { return View("UnAuthorizedAccess"); @@ -748,46 +808,45 @@ public class LotTravelerController : PdfViewController { } - ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); - List userList = MiscDMO.GetPendingApproversListByDocument(workRequestID, ltWR.CurrentStep, (int)documentType); - ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; }); + List userList = MiscDMO.GetPendingApproversListByDocument(workRequestID, ltWR.CurrentStep, documentType); + ApproversListViewModel approver = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == GlobalVars.GetUserId(GetSession()); }); if (approver == null) ViewBag.IsApprover = "false"; else ViewBag.IsApprover = "true"; - if ((int)Session[GlobalVars.SESSION_USERID] == ltWR.OriginatorID) + if (GlobalVars.GetUserId(GetSession()) == ltWR.OriginatorID) ViewBag.IsOriginator = "true"; else ViewBag.IsOriginator = "false"; - if (Request.IsAjaxRequest()) { - // the content gets evaluated on the client side + if (IsAjaxRequest()) { return Content("Redirect"); - } else + } else { return Content("Invalid"); - + } } } catch (Exception e) { string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + workRequestID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SubmitDocument\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = docTypeString, OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n SubmitDocument\r\n" + e.Message.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = GetUserIdentityName(), DocumentType = docTypeString, OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); throw new Exception(e.Message); } } public void Approve(int workRequestID, byte currentStep, string comments, int documentType) { - LTWorkRequest ltWR = new LTWorkRequest(); + LTWorkRequest ltWR = new(); int isITAR = 1; - ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITAR, (int)Session[GlobalVars.SESSION_USERID]); + ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITAR, GlobalVars.GetUserId(GetSession())); try { bool lastStep = false; - bool lastApprover = wfDMO.Approve(_AppSettings, workRequestID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], documentType, ltWR.WorkFlowNumber); + bool lastApprover = wfDMO.Approve(_AppSettings, workRequestID, currentStep, comments, out lastStep, GlobalVars.GetUserId(GetSession()), documentType, ltWR.WorkFlowNumber); while (lastApprover && !lastStep) { currentStep++; - lastApprover = wfDMO.Approve(_AppSettings, workRequestID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], documentType, ltWR.WorkFlowNumber); + lastApprover = wfDMO.Approve(_AppSettings, workRequestID, currentStep, comments, out lastStep, GlobalVars.GetUserId(GetSession()), documentType, ltWR.WorkFlowNumber); NotifyApprovers(workRequestID, currentStep, documentType); } @@ -798,113 +857,117 @@ public class LotTravelerController : PdfViewController { } catch (Exception e) { string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + workRequestID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "Approve - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Approve\r\n" + e.Message.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = GetUserIdentityName(), DocumentType = "Lot Traveler", OperationType = "Error", Comments = "Approve - " + exceptionString }); throw new Exception(e.Message); } } public void Reject(int workRequestID, byte currentStep, string comments, int docType) { - LTWorkRequest ltWR = new LTWorkRequest(); + LTWorkRequest ltWR = new(); int isITARCompliant = 1; - ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); try { - if (Session[GlobalVars.SESSION_USERID] != null) { - wfDMO.Reject(workRequestID, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], docType); + if (GlobalVars.IsUserIdValueNotNull(GetSession())) { + wfDMO.Reject(workRequestID, currentStep, comments, GlobalVars.GetUserId(GetSession()), docType); NotifyRejectionToOrginator(workRequestID); } else { Response.Redirect("~/Account/Login"); } } catch (Exception e) { string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + workRequestID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Reject\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "Reject - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Reject\r\n" + e.Message.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = GetUserIdentityName(), DocumentType = "Lot Traveler", OperationType = "Error", Comments = "Reject - " + exceptionString }); throw new Exception(e.Message); } } public void NotifyRejectionToOrginator(int workRequestID) { int isITARCompliant = 0; - string username = Session[GlobalVars.SESSION_USERNAME].ToString(); + string username = GlobalVars.GetUserName(GetSession()); List emailIst = LotTravDMO.GetRejectionOrginatorEmailList(workRequestID).Distinct().ToList(); - LTWorkRequest ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); - string userEmail = LotTravelerHelper.NotifyRejectionToOrginator(_AppSettings, @User.Identity.Name, workRequestID, username, emailIst, ltWR); + LTWorkRequest ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); + string userEmail = LotTravelerHelper.NotifyRejectionToOrginator(_AppSettings, GetUserIdentityName(), workRequestID, username, emailIst, ltWR); try { - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Email", Comments = "Rejection: " + userEmail }); + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = GetUserIdentityName(), DocumentType = "Work Request", OperationType = "Email", Comments = "Rejection: " + userEmail }); } catch { } } public void NotifyApprovers(int workRequestID, byte currentStep, int documentType) { string emailSentList = ""; int isITARCompliant = 0; - LTWorkRequest ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + LTWorkRequest ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); List emailIst = MiscDMO.GetApproverEmailListByDocument(workRequestID, currentStep, documentType).Distinct().ToList(); - emailSentList = LotTravelerHelper.NotifyApprovers(_AppSettings, @User.Identity.Name, workRequestID, emailSentList, ltWR, emailIst); + emailSentList = LotTravelerHelper.NotifyApprovers(_AppSettings, GetUserIdentityName(), workRequestID, emailSentList, ltWR, emailIst); try { - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = GetUserIdentityName(), DocumentType = "Work Request", OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); } catch { } } public void NotifyApprovalOfWorkRequest(int workRequestID) { string emailSentList = ""; int isITARCompliant = 0; - LTWorkRequest ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + LTWorkRequest ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); - List emailIst = MiscDMO.GetWorkRequestApprovedNotifyList((int)GlobalVars.NotificationType.WorkRequest, workRequestID, (int)Session[GlobalVars.SESSION_USERID]).Distinct().ToList(); - emailSentList = LotTravelerHelper.NotifyApprovalOfWorkRequest(_AppSettings, @User.Identity.Name, workRequestID, emailSentList, ltWR, emailIst); + List emailIst = MiscDMO.GetWorkRequestApprovedNotifyList((int)GlobalVars.NotificationType.WorkRequest, workRequestID, GlobalVars.GetUserId(GetSession())).Distinct().ToList(); + emailSentList = LotTravelerHelper.NotifyApprovalOfWorkRequest(_AppSettings, GetUserIdentityName(), workRequestID, emailSentList, ltWR, emailIst); try { - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Email", Comments = "Approvers for WorkRequest: " + emailSentList }); + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = GetUserIdentityName(), DocumentType = "Work Request", OperationType = "Email", Comments = "Approvers for WorkRequest: " + emailSentList }); } catch { } } public void NotifyfWorkRequestRevisionChange(int workRequestID) { string emailSentList = ""; int isITARCompliant = 0; - int currentUserID = (int)Session[GlobalVars.SESSION_USERID]; + int currentUserID = GlobalVars.GetUserId(GetSession()); LTWorkRequest ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, currentUserID); List emailIst = MiscDMO.GetWorkRequestRevisionNotifyList((int)GlobalVars.NotificationType.WorkRequest, workRequestID, currentUserID).Distinct().ToList(); - emailSentList = LotTravelerHelper.NotifyfWorkRequestRevisionChange(_AppSettings, @User.Identity.Name, workRequestID, emailSentList, ltWR, emailIst); + emailSentList = LotTravelerHelper.NotifyfWorkRequestRevisionChange(_AppSettings, GetUserIdentityName(), workRequestID, emailSentList, ltWR, emailIst); try { - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Email", Comments = "Work Request Revision Change for :" + emailSentList }); + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = GetUserIdentityName(), DocumentType = "Work Request", OperationType = "Email", Comments = "Work Request Revision Change for :" + emailSentList }); } catch { } } public void NotifyLotTravelerRevisionChange(int ltLotID, int revisionNumber) { string emailSentList = ""; LTLotTravelerHeaderViewModel data = LotTravDMO.GetLotTravelerHeaderForReadOnly(ltLotID, revisionNumber); - int currentUserID = (int)Session[GlobalVars.SESSION_USERID]; + int currentUserID = GlobalVars.GetUserId(GetSession()); List emailIst = MiscDMO.GetLotTravelerCreationAndRevisionNotifyList(ltLotID, data.LTWorkRequestID, currentUserID).Distinct().ToList(); - emailSentList = LotTravelerHelper.NotifyLotTravelerRevisionChange(_AppSettings, @User.Identity.Name, emailSentList, data, emailIst); + emailSentList = LotTravelerHelper.NotifyLotTravelerRevisionChange(_AppSettings, GetUserIdentityName(), emailSentList, data, emailIst); try { - EventLogDMO.Add(new WinEventLog() { IssueID = data.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Email", Comments = "Lot Traveler Revision Change Notification:" + emailSentList }); + EventLogDMO.Add(new WinEventLog() { IssueID = data.SWRNumber, UserID = GetUserIdentityName(), DocumentType = "Lot Traveler", OperationType = "Email", Comments = "Lot Traveler Revision Change Notification:" + emailSentList }); } catch { } } public void NotifyLotTravelerCreation(int ltLotID, int revisionNumber) { string emailSentList = ""; LTLotTravelerHeaderViewModel data = LotTravDMO.GetLotTravelerHeaderForReadOnly(ltLotID, revisionNumber); - int currentUserID = (int)Session[GlobalVars.SESSION_USERID]; + int currentUserID = GlobalVars.GetUserId(GetSession()); List emailIst = MiscDMO.GetLotTravelerCreationAndRevisionNotifyList(ltLotID, data.LTWorkRequestID, currentUserID).Distinct().ToList(); - emailSentList = LotTravelerHelper.NotifyLotTravelerCreation(_AppSettings, @User.Identity.Name, emailSentList, data, emailIst); + emailSentList = LotTravelerHelper.NotifyLotTravelerCreation(_AppSettings, GetUserIdentityName(), emailSentList, data, emailIst); try { - EventLogDMO.Add(new WinEventLog() { IssueID = data.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Email", Comments = "Lot Traveler Revision Change Notification:" + emailSentList }); + EventLogDMO.Add(new WinEventLog() { IssueID = data.SWRNumber, UserID = GetUserIdentityName(), DocumentType = "Lot Traveler", OperationType = "Email", Comments = "Lot Traveler Revision Change Notification:" + emailSentList }); } catch { } } +#if !NET8 + public ActionResult GetApproversList([DataSourceRequest] DataSourceRequest request, int workRequestID, byte step) { return Json(MiscDMO.GetApproversListByDocument(workRequestID, step, (int)GlobalVars.DocumentType.LotTraveler).ToDataSourceResult(request)); } +#endif + public void ReleaseLockOnDocument(int workRequestID) { - LotTravDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], workRequestID); + LotTravDMO.ReleaseLockOnDocument(GlobalVars.GetUserId(GetSession()), workRequestID); } public void ReleaseLockOnLotTravelerUpdateDoc(int lotID) { try { - LotTravDMO.ReleaseLockOnLotTravelerUpdateDoc((int)Session[GlobalVars.SESSION_USERID], lotID); + LotTravDMO.ReleaseLockOnLotTravelerUpdateDoc(GlobalVars.GetUserId(GetSession()), lotID); } catch { // TODO // unlock the current revision of the Lot traveler @@ -913,44 +976,44 @@ public class LotTravelerController : PdfViewController { } public JsonResult GetAllUsersList() { - UserAccountDMO userDMO = new UserAccountDMO(); + UserAccountDMO userDMO = new(); IEnumerable userlist = userDMO.GetAllUsers(); - return Json(userlist, JsonRequestBehavior.AllowGet); + return GetJsonResult(userlist); } public void ReAssignApproverByAdmin(int workRequestID, int reAssignApproverFrom, int reAssignApproverTo, byte step, int docType) { var email = ""; int isITARCompliant = 0; - LTWorkRequest ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + LTWorkRequest ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); try { email = wfDMO.ReAssignApproval(workRequestID, reAssignApproverFrom, reAssignApproverTo, step, docType); } catch (Exception e) { string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + workRequestID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReAssignApproval\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ReAssignApproval\r\n" + e.Message.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = GetUserIdentityName(), DocumentType = "Work Request", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); throw new Exception(e.Message); } - LotTravelerHelper.ReAssignApproverByAdmin(_AppSettings, @User.Identity.Name, workRequestID, email, ltWR); + LotTravelerHelper.ReAssignApproverByAdmin(_AppSettings, GetUserIdentityName(), workRequestID, email, ltWR); try { - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Email", Comments = "ReAssign Approver: " + email }); + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = GetUserIdentityName(), DocumentType = "Work Request", OperationType = "Email", Comments = "ReAssign Approver: " + email }); } catch { } } public void ReAssignApproval(int workRequestID, int userIDs, byte step, int docType) { var email = ""; int isITARCompliant = 0; - LTWorkRequest ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + LTWorkRequest ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); try { - email = wfDMO.ReAssignApproval(workRequestID, (int)Session[GlobalVars.SESSION_USERID], userIDs, step, docType); + email = wfDMO.ReAssignApproval(workRequestID, GlobalVars.GetUserId(GetSession()), userIDs, step, docType); } catch (Exception e) { string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + workRequestID.ToString() + " Step:" + step + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReAssignApproval\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ReAssignApproval\r\n" + e.Message.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = GetUserIdentityName(), DocumentType = "Work Request", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString }); throw new Exception(e.Message); } - LotTravelerHelper.ReAssignApproval(_AppSettings, @User.Identity.Name, workRequestID, email, ltWR); + LotTravelerHelper.ReAssignApproval(_AppSettings, GetUserIdentityName(), workRequestID, email, ltWR); try { - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Email", Comments = "ReAssign Approver: " + email }); + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = GetUserIdentityName(), DocumentType = "Work Request", OperationType = "Email", Comments = "ReAssign Approver: " + email }); } catch { } } @@ -958,31 +1021,31 @@ public class LotTravelerController : PdfViewController { string emailSentList = ""; var emailArray = ""; int isITARCompliant = 0; - LTWorkRequest ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + LTWorkRequest ltWR = LotTravDMO.GetLTWorkRequestItemForRead(workRequestID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); try { emailArray = wfDMO.AddAdditionalApproval(workRequestID, userIDs, step, docType); } catch (Exception e) { string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + workRequestID.ToString() + " Step:" + step + " " + " Userid:" + userIDs + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n AddAdditionalApproval\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n AddAdditionalApproval\r\n" + e.Message.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = GetUserIdentityName(), DocumentType = "Work Request", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString }); throw new Exception(e.Message); } - emailSentList = LotTravelerHelper.AddAdditionalApproval(_AppSettings, @User.Identity.Name, workRequestID, emailSentList, emailArray, ltWR); + emailSentList = LotTravelerHelper.AddAdditionalApproval(_AppSettings, GetUserIdentityName(), workRequestID, emailSentList, emailArray, ltWR); try { - EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Email", Comments = "Additonal Approver: " + emailSentList }); + EventLogDMO.Add(new WinEventLog() { IssueID = ltWR.SWRNumber, UserID = GetUserIdentityName(), DocumentType = "Work Request", OperationType = "Email", Comments = "Additonal Approver: " + emailSentList }); } catch { } } public JsonResult AddLots(string lotNumbers, int workRequestID) { - IssueWithExistingLotsViewModel issueWEL = new IssueWithExistingLotsViewModel(); + IssueWithExistingLotsViewModel issueWEL = new(); try { if (lotNumbers.Length > 0) { string[] tempLots = lotNumbers.Split(new char[] { '~' }); foreach (string lotNumber in tempLots) { - LTLot l = new LTLot(); + LTLot l = new(); l.LotNumber = lotNumber; l.WorkRequestID = workRequestID; - l.LotUploadedBy = (int)Session[GlobalVars.SESSION_USERID]; + l.LotUploadedBy = GlobalVars.GetUserId(GetSession()); LotTravDMO.InsertLot(l); if (l.WRWithExistingLot != 0) { issueWEL.LotList += l.LotNumber + "~"; @@ -993,58 +1056,66 @@ public class LotTravelerController : PdfViewController { } catch (Exception e) { string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + workRequestID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n AddLots Work Request\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { UserID = @User.Identity.Name, DocumentType = "Work Request", OperationType = "Error", Comments = exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n AddLots Work Request\r\n" + e.Message.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { UserID = GetUserIdentityName(), DocumentType = "Work Request", OperationType = "Error", Comments = exceptionString }); throw new Exception(e.Message); } - return Json(issueWEL, JsonRequestBehavior.AllowGet); + return GetJsonResult(issueWEL); } +#if !NET8 + public JsonResult SearchLots(string searchText, string searchBy) { List lotlist = MiscDMO.SearchLTLots(searchText, searchBy).Select(x => x.LotNumber).ToList(); - return Json(lotlist, JsonRequestBehavior.AllowGet); + return GetJsonResult(lotlist); } public JsonResult SearchParts(string searchText) { List partList = MiscDMO.SearchLTParts(searchText.Trim()).Select(x => x.WIPPartData).ToList(); - return Json(partList, JsonRequestBehavior.AllowGet); + return GetJsonResult(partList); } public ActionResult GetLotList([DataSourceRequest] DataSourceRequest request, int workRequestID) { return Json(LotTravDMO.GetLotList(workRequestID).ToDataSourceResult(request)); } +#endif + public void CreateTaveler(int ltLotID, int workRequestID) { try { - LotTravDMO.CreateTraveler(ltLotID, workRequestID, (int)Session[GlobalVars.SESSION_USERID]); + LotTravDMO.CreateTraveler(ltLotID, workRequestID, GlobalVars.GetUserId(GetSession())); // Thread.Sleep(10000); NotifyLotTravelerCreation(ltLotID, -1); } catch (Exception ex) { - EventLogDMO.Add(new WinEventLog() { IssueID = workRequestID, UserID = @User.Identity.Name, DocumentType = "LotTraveler", OperationType = "CreateTaveler", Comments = ex.Message }); + EventLogDMO.Add(new WinEventLog() { IssueID = workRequestID, UserID = GetUserIdentityName(), DocumentType = "LotTraveler", OperationType = "CreateTaveler", Comments = ex.Message }); throw new Exception(ex.Message); } } +#if !NET8 + public JsonResult GetLotTravelerHeader(int ltLotID) { LTLotTravelerHeaderViewModel data = new LTLotTravelerHeaderViewModel(); - data = LotTravDMO.GetLotTravelerHeaderForUpdate(ltLotID, (int)Session[GlobalVars.SESSION_USERID]); - return Json(data, JsonRequestBehavior.AllowGet); + data = LotTravDMO.GetLotTravelerHeaderForUpdate(ltLotID, GlobalVars.GetUserId(GetSession())); + return GetJsonResult(data); } public ActionResult GetLotTravRevisions(int ltLotID) { - return Json(LotTravDMO.GetLotTravRevisions(ltLotID), JsonRequestBehavior.AllowGet); + return GetJsonResult(LotTravDMO.GetLotTravRevisions(ltLotID)); } +#endif + public ActionResult DisplayLotTraveler(int ltLotID) { - LTLotTravelerHeaderViewModel data = new LTLotTravelerHeaderViewModel(); - data = LotTravDMO.GetLotTravelerHeaderForUpdate(ltLotID, (int)Session[GlobalVars.SESSION_USERID]); + LTLotTravelerHeaderViewModel data = new(); + data = LotTravDMO.GetLotTravelerHeaderForUpdate(ltLotID, GlobalVars.GetUserId(GetSession())); ViewBag.LotTravRevisionList = LotTravDMO.GetLotTravRevisions(ltLotID); ViewBag.LotList = LotTravDMO.GetLotsWithTraveler(data.LTWorkRequestID); - if (data.RecordLockIndicator && data.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) { + if (data.RecordLockIndicator && data.RecordLockedBy != GlobalVars.GetUserId(GetSession())) { // redirect to a readonly Lot Travler return Content("Readonly" + "~" + data.LotTravCurrentRevision.ToString()); } else @@ -1053,8 +1124,8 @@ public class LotTravelerController : PdfViewController { public ActionResult LotTravelerUpdate(int ltLotID) { - LTLotTravelerHeaderViewModel data = new LTLotTravelerHeaderViewModel(); - data = LotTravDMO.GetLotTravelerHeaderForUpdate(ltLotID, (int)Session[GlobalVars.SESSION_USERID]); + LTLotTravelerHeaderViewModel data = new(); + data = LotTravDMO.GetLotTravelerHeaderForUpdate(ltLotID, GlobalVars.GetUserId(GetSession())); if (data.TravelerClosedDate != null) { return RedirectToAction("LotTravelerReadOnly", new { ltLotID = ltLotID, revisionNumber = -1 }); @@ -1063,12 +1134,12 @@ public class LotTravelerController : PdfViewController { ViewBag.LotTravRevisionList = LotTravDMO.GetLotTravRevisions(ltLotID); ViewBag.LotList = LotTravDMO.GetLotsWithTraveler(data.LTWorkRequestID); - Session["CreateLotTravNewRevision"] = "true"; + GlobalVars.SetCreateLotTravNewRevision(GetSession(), true); return View(data); } public ActionResult LotTravelerReadonly(int ltLotID, int revisionNumber) { - LTLotTravelerHeaderViewModel data = new LTLotTravelerHeaderViewModel(); + LTLotTravelerHeaderViewModel data = new(); data = LotTravDMO.GetLotTravelerHeaderForReadOnly(ltLotID, revisionNumber); if (data.IsCurrentRevision && (!data.RecordLockIndicator)) { @@ -1081,12 +1152,12 @@ public class LotTravelerController : PdfViewController { } public ActionResult DisplayLotTravelerForExecute(int ltLotID) { - LTLotTravelerHeaderViewModel data = new LTLotTravelerHeaderViewModel(); - data = LotTravDMO.GetLotTravelerHeaderForUpdate(ltLotID, (int)Session[GlobalVars.SESSION_USERID]); + LTLotTravelerHeaderViewModel data = new(); + data = LotTravDMO.GetLotTravelerHeaderForUpdate(ltLotID, GlobalVars.GetUserId(GetSession())); ViewBag.LotTravRevisionList = LotTravDMO.GetLotTravRevisions(ltLotID); ViewBag.LotList = LotTravDMO.GetLotsWithTraveler(data.LTWorkRequestID); - if (data.RecordLockIndicator && data.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) { + if (data.RecordLockIndicator && data.RecordLockedBy != GlobalVars.GetUserId(GetSession())) { // redirect to a readonly Lot Travler return Content("Readonly" + "~" + data.LotTravCurrentRevision.ToString()); } else @@ -1094,14 +1165,16 @@ public class LotTravelerController : PdfViewController { } public ActionResult LotTravelerExecute(int ltLotID) { - LTLotTravelerHeaderViewModel data = new LTLotTravelerHeaderViewModel(); - data = LotTravDMO.GetLotTravelerHeaderForUpdate(ltLotID, (int)Session[GlobalVars.SESSION_USERID]); + LTLotTravelerHeaderViewModel data = new(); + data = LotTravDMO.GetLotTravelerHeaderForUpdate(ltLotID, GlobalVars.GetUserId(GetSession())); ViewBag.LotTravRevisionList = LotTravDMO.GetLotTravRevisions(ltLotID); ViewBag.LotList = LotTravDMO.GetLotsWithTraveler(data.LTWorkRequestID); return View(data); } +#if !NET8 + public ActionResult GetLotTravHoldSteps([DataSourceRequest] DataSourceRequest request, int LotID) { return Json(LotTravDMO.GetLotTravHoldSteps(LotID).ToDataSourceResult(request)); } @@ -1114,26 +1187,32 @@ public class LotTravelerController : PdfViewController { return Json(LotTravDMO.GetLotTravHoldStepsCompleted(LotID).ToDataSourceResult(request)); } +#endif + public void UpdateLotTravlerExecution(int currentHoldStepID, string taskComments, bool taskcompleted) { - LotTravDMO.UpdateLotTravlerExecution(currentHoldStepID, taskComments, taskcompleted, (int)Session[GlobalVars.SESSION_USERID]); + LotTravDMO.UpdateLotTravlerExecution(currentHoldStepID, taskComments, taskcompleted, GlobalVars.GetUserId(GetSession())); } +#if !NET8 + public ActionResult GetLotTravHoldStepsByRevision([DataSourceRequest] DataSourceRequest request, int LotID, int revisionNumber) { return Json(LotTravDMO.GetLotTravelerHolStepsByRevision(LotID, revisionNumber).ToDataSourceResult(request)); } +#endif + public ActionResult UpdateLotTravHoldStepRevision(LTLotTravelerHoldSteps ltHoldStepObj) { int prevLotTravRevID = ltHoldStepObj.LotTravelerRevisionID; int newLotTravRevID = 1; try { - if (Session["CreateLotTravNewRevision"].ToString() == "true") { + if (GlobalVars.GetCreateLotTravNewRevision(GetSession())) { // Create a new Revision - Session["CreateLotTravNewRevision"] = "false"; - newLotTravRevID = LotTravDMO.CreateLotTravelerRevision(ltHoldStepObj, (int)Session[GlobalVars.SESSION_USERID]); + GlobalVars.SetCreateLotTravNewRevision(GetSession(), false); + newLotTravRevID = LotTravDMO.CreateLotTravelerRevision(ltHoldStepObj, GlobalVars.GetUserId(GetSession())); try { - LotTravDMO.UpdateRevisedLotTravelerHoldStep(ltHoldStepObj, (int)Session[GlobalVars.SESSION_USERID]); + LotTravDMO.UpdateRevisedLotTravelerHoldStep(ltHoldStepObj, GlobalVars.GetUserId(GetSession())); } catch { LotTravDMO.RestoreLotTravToPrevRevision(prevLotTravRevID, newLotTravRevID); @@ -1144,7 +1223,7 @@ public class LotTravelerController : PdfViewController { // - 1 indicates to return the current revision NotifyLotTravelerRevisionChange(ltHoldStepObj.LTLotID, -1); } else { - int result = LotTravDMO.UpdateLotTravelerHoldStep(ltHoldStepObj, (int)Session[GlobalVars.SESSION_USERID]); + int result = LotTravDMO.UpdateLotTravelerHoldStep(ltHoldStepObj, GlobalVars.GetUserId(GetSession())); if (result == -1) { throw new Exception("Cannot add the Hold Step as the step has already been passed in the Mfg Process."); } @@ -1160,21 +1239,21 @@ public class LotTravelerController : PdfViewController { int prevLotTravRevID = ltHoldStepObj.LotTravelerRevisionID; int newLotTravRevID = -1; try { - if (Session["CreateLotTravNewRevision"].ToString() == "true") { + if (GlobalVars.GetCreateLotTravNewRevision(GetSession())) { // Create a new Revision - Session["CreateLotTravNewRevision"] = "false"; + GlobalVars.SetCreateLotTravNewRevision(GetSession(), false); int result = LotTravDMO.CanAddLocationOperation(ltHoldStepObj); if (result == -1) { - Session["CreateLotTravNewRevision"] = "true"; + GlobalVars.SetCreateLotTravNewRevision(GetSession(), true); throw new Exception("Cannot add the Hold Step as the step has already been passed in the Mfg Process."); } - newLotTravRevID = LotTravDMO.CreateLotTravelerRevision(ltHoldStepObj, (int)Session[GlobalVars.SESSION_USERID]); + newLotTravRevID = LotTravDMO.CreateLotTravelerRevision(ltHoldStepObj, GlobalVars.GetUserId(GetSession())); ltHoldStepObj.LotTravelerRevisionID = newLotTravRevID; try { - LotTravDMO.InsertLotTravelerHoldStep(ltHoldStepObj, (int)Session[GlobalVars.SESSION_USERID]); + LotTravDMO.InsertLotTravelerHoldStep(ltHoldStepObj, GlobalVars.GetUserId(GetSession())); } catch { // roll back the revision creation LotTravDMO.RestoreLotTravToPrevRevision(prevLotTravRevID, newLotTravRevID); @@ -1186,7 +1265,7 @@ public class LotTravelerController : PdfViewController { NotifyLotTravelerRevisionChange(ltHoldStepObj.LTLotID, -1); } else { - int result = LotTravDMO.InsertLotTravelerHoldStep(ltHoldStepObj, (int)Session[GlobalVars.SESSION_USERID]); + int result = LotTravDMO.InsertLotTravelerHoldStep(ltHoldStepObj, GlobalVars.GetUserId(GetSession())); if (result == -1) { throw new Exception("Cannot add the Hold Step as the step has already been passed in the Mfg Process."); } @@ -1202,10 +1281,10 @@ public class LotTravelerController : PdfViewController { int prevLotTravRevID = ltHoldStepObj.LotTravelerRevisionID; int newLotTravRevID = -1; try { - if (Session["CreateLotTravNewRevision"].ToString() == "true") { + if (GlobalVars.GetCreateLotTravNewRevision(GetSession())) { // Create a new Revision - Session["CreateLotTravNewRevision"] = "false"; - newLotTravRevID = LotTravDMO.CreateLotTravelerRevision(ltHoldStepObj, (int)Session[GlobalVars.SESSION_USERID]); + GlobalVars.SetCreateLotTravNewRevision(GetSession(), false); + newLotTravRevID = LotTravDMO.CreateLotTravelerRevision(ltHoldStepObj, GlobalVars.GetUserId(GetSession())); try { LotTravDMO.DeleteLotTravHoldStepRevision(ltHoldStepObj.ID); @@ -1232,32 +1311,41 @@ public class LotTravelerController : PdfViewController { LotTravDMO.DeleteLot(ltLotID); } - /// public ActionResult DisplayLotTravlerPdf(int ltLotID, int revisionNumber) { - LotTravelerPdf traveler = new LotTravelerPdf(); + LotTravelerPdf traveler = new(); try { traveler = LotTravDMO.GetLotTravlerPdf(ltLotID, revisionNumber); // To render a PDF instead of an HTML, all we need to do is call ViewPdf instead of View. This // requires the controller to be inherited from MyController instead of MVC's Controller. - return this.ViewPdf("", "LotTravelerPDF", traveler); +#if !NET8 + return ViewPdf("", "LotTravelerPDF", traveler); +#endif +#if NET8 + if (Debugger.IsAttached) + return Content(this.RenderViewToString("LotTravelerPDF", traveler), "text/html"); + else + return this.GetBinaryContentResult("LotTravelerPDF", "application/pdf", traveler); +#endif } catch (Exception ex) { - EventLogDMO.Add(new WinEventLog() { IssueID = traveler.SWRNumber, UserID = @User.Identity.Name, DocumentType = "LotTraveler", OperationType = "Generate PDF", Comments = ex.Message }); + EventLogDMO.Add(new WinEventLog() { IssueID = traveler.SWRNumber, UserID = GetUserIdentityName(), DocumentType = "LotTraveler", OperationType = "Generate PDF", Comments = ex.Message }); traveler = null; return Content(""); } } +#if !NET8 + public ActionResult ApprovalLogHistory_Read([DataSourceRequest] DataSourceRequest request, int swrNumber) { - return Json(LotTravDMO.GetWorkReqApprovalLogHistory(swrNumber).ToDataSourceResult(request), JsonRequestBehavior.AllowGet); + return GetJsonResult(LotTravDMO.GetWorkReqApprovalLogHistory(swrNumber).ToDataSourceResult(request)); } public ActionResult GetWorkRequestRevisionHistory([DataSourceRequest] DataSourceRequest request, int swrNumber) { - return Json(LotTravDMO.GetWorkReqRevisionHistory(swrNumber).ToDataSourceResult(request), JsonRequestBehavior.AllowGet); + return GetJsonResult(LotTravDMO.GetWorkReqRevisionHistory(swrNumber).ToDataSourceResult(request)); } public ActionResult GetLotTravelerRevisionHistory([DataSourceRequest] DataSourceRequest request, int lotID) { - return Json(LotTravDMO.GetLotTravelerRevisionHistory(lotID).ToDataSourceResult(request), JsonRequestBehavior.AllowGet); + return GetJsonResult(LotTravDMO.GetLotTravelerRevisionHistory(lotID).ToDataSourceResult(request)); } public ActionResult LotTravHoldStepAttachSaveRev(IEnumerable LotTravHoldStepAttachment, int ltHoldStepID, int swrNo, string docType, string revComments) { @@ -1272,17 +1360,17 @@ public class LotTravelerController : PdfViewController { model.RevisionComments = revComments; - if (Session["CreateLotTravNewRevision"].ToString() == "true") { + if (GlobalVars.GetCreateLotTravNewRevision(GetSession())) { // Create a new Revision newRevision = true; - Session["CreateLotTravNewRevision"] = "false"; - newLotTravRevID = LotTravDMO.CreateLotTravelerRevision(model, (int)Session[GlobalVars.SESSION_USERID]); + GlobalVars.SetCreateLotTravNewRevision(GetSession(), false); + newLotTravRevID = LotTravDMO.CreateLotTravelerRevision(model, GlobalVars.GetUserId(GetSession())); model.LotTravelerRevisionID = newLotTravRevID; } try { if (LotTravHoldStepAttachment != null) { - int userId = (int)Session[GlobalVars.SESSION_USERID]; + int userId = GlobalVars.GetUserId(GetSession()); foreach (var file in LotTravHoldStepAttachment) { LotTravelerHelper.LotTravHoldStepAttachSaveRev(_AppSettings, LotTravDMO, ltHoldStepID, swrNo, docType, prevLotTravRevID, newLotTravRevID, newRevision, userId, file.FileName, file.InputStream); } @@ -1295,15 +1383,17 @@ public class LotTravelerController : PdfViewController { } } catch (Exception e) { string exceptionString = e.Message.ToString().Trim().Length > 500 ? "LotTravHoldStep=" + ltHoldStepID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Attachment \r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = ltHoldStepID, UserID = @User.Identity.Name, DocumentType = docTypeString, OperationType = "Error", Comments = "Lot Traveler HoldStep Attachment - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Attachment \r\n" + e.Message.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = ltHoldStepID, UserID = GetUserIdentityName(), DocumentType = docTypeString, OperationType = "Error", Comments = "Lot Traveler HoldStep Attachment - " + exceptionString }); throw new Exception(e.Message); } return Content(""); } +#endif + public bool IsWorkRequestDocLockedByUser(int workRequestID) { - int result = LotTravDMO.IsWorkRequestDocLockedByUser(workRequestID, (int)Session[GlobalVars.SESSION_USERID]); + int result = LotTravDMO.IsWorkRequestDocLockedByUser(workRequestID, GlobalVars.GetUserId(GetSession())); if (result == 0) return false; else @@ -1311,7 +1401,7 @@ public class LotTravelerController : PdfViewController { } public ActionResult CloseTraveler(int ltLotID, string reason) { - int result = LotTravDMO.CloseTraveler(ltLotID, (int)Session[GlobalVars.SESSION_USERID], reason); + int result = LotTravDMO.CloseTraveler(ltLotID, GlobalVars.GetUserId(GetSession()), reason); if (result == 1) return Content("C"); @@ -1343,11 +1433,11 @@ public class LotTravelerController : PdfViewController { [HttpPost] public void ReAssignOriginatorByAdmin(int workRequestID, string comments, int newOriginatorId) { - if (Session[GlobalVars.IS_ADMIN] == null) + if (GlobalVars.IsAdminValueNull(GetSession())) throw new Exception("Permission denied"); try { - LotTravDMO.ReassignOriginator(workRequestID, newOriginatorId, comments, (int)Session[GlobalVars.SESSION_USERID]); + LotTravDMO.ReassignOriginator(workRequestID, newOriginatorId, comments, GlobalVars.GetUserId(GetSession())); } catch (Exception e) { string detailedException = ""; try { @@ -1358,9 +1448,39 @@ public class LotTravelerController : PdfViewController { string exceptionString = e.Message.ToString().Trim(); if (exceptionString.Length > 450) exceptionString = exceptionString.Substring(0, 450); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReAssignOriginatorByAdmin\r\n" + workRequestID.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = workRequestID, UserID = @User.Identity.Name, DocumentType = "Lot Traveler", OperationType = "Error", Comments = "ReAssignOriginatorByAdmin - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n ReAssignOriginatorByAdmin\r\n" + workRequestID.ToString() + "\r\n" + detailedException, EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = workRequestID, UserID = GetUserIdentityName(), DocumentType = "Lot Traveler", OperationType = "Error", Comments = "ReAssignOriginatorByAdmin - " + exceptionString }); throw new Exception(e.Message); } } + +#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; + } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/MRBController.cs b/Fab2ApprovalSystem/Controllers/MRBController.cs index d954e41..b319e14 100644 --- a/Fab2ApprovalSystem/Controllers/MRBController.cs +++ b/Fab2ApprovalSystem/Controllers/MRBController.cs @@ -1,33 +1,50 @@ using System; using System.Collections.Generic; -using System.Configuration; using System.Diagnostics; -using System.Dynamic; using System.Linq; using System.Text; -using System.Threading; +#if !NET8 using System.Web; using System.Web.Mvc; using System.Web.Script.Serialization; +#endif + +#if NET8 +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Authorization; +#endif using Fab2ApprovalSystem.DMO; using Fab2ApprovalSystem.Misc; using Fab2ApprovalSystem.Models; using Fab2ApprovalSystem.ViewModels; +#if !NET8 +using System.Dynamic; +using System.Threading; +using System.Configuration; +#endif + +#if !NET8 using Kendo.Mvc.Extensions; using Kendo.Mvc.UI; +#endif namespace Fab2ApprovalSystem.Controllers; [Authorize] +#if !NET8 [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] [SessionExpireFilter] +#endif +#if NET8 +[Route("[controller]")] +#endif public class MRBController : Controller { - MRB_DMO mrbDMO = new MRB_DMO(GlobalVars.AppSettings); - WorkflowDMO wfDMO = new WorkflowDMO(); - CredentialsStorage credentialsStorage = new CredentialsStorage(); + private readonly MRB_DMO mrbDMO = new(GlobalVars.AppSettings); + private readonly WorkflowDMO wfDMO = new(); + private readonly CredentialsStorage credentialsStorage = new(); private readonly AppSettings _AppSettings = GlobalVars.AppSettings; // GET: /MRB/ @@ -42,25 +59,27 @@ public class MRBController : Controller { // GET: /MRB/Create public ActionResult Create() { - MRB mrb = new MRB(); - MRB_DMO mrbDMO = new MRB_DMO(_AppSettings); - mrb.OriginatorID = (int)Session[GlobalVars.SESSION_USERID]; + MRB mrb = new(); + MRB_DMO mrbDMO = new(_AppSettings); + mrb.OriginatorID = GlobalVars.GetUserId(GetSession()); mrbDMO.InsertMRB(mrb); // Automatically Submit the Document as soon as an MRB is created try { PopulateCloseToQDB(); - mrbDMO.SubmitDocument(mrb.MRBNumber, (int)Session[GlobalVars.SESSION_USERID]); + mrbDMO.SubmitDocument(mrb.MRBNumber, GlobalVars.GetUserId(GetSession())); } catch (Exception e) { string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + mrb.MRBNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SubmitDocument - MRB\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = mrb.MRBNumber, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n SubmitDocument - MRB\r\n" + e.Message.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = mrb.MRBNumber, UserID = GetUserIdentityName(), DocumentType = "MRB", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); throw new Exception(e.Message); } return RedirectToAction("Edit", new { IssueID = mrb.MRBNumber }); } +#if !NET8 + // POST: /MRB/Create [HttpPost] public ActionResult Create(FormCollection collection) { @@ -73,11 +92,13 @@ public class MRBController : Controller { } } +#endif + // GET: /MRB/Edit/5 public ActionResult Edit(int issueID) { - string jwt = Session["JWT"].ToString(); + string jwt = GlobalVars.GetJWT(GetSession()); string encodedJwt = System.Net.WebUtility.UrlEncode(jwt); - string refreshToken = Session["RefreshToken"].ToString(); + string refreshToken = GlobalVars.GetRefreshToken(GetSession()); string encodedRefreshToken = System.Net.WebUtility.UrlEncode(refreshToken); string mrbUrl = $"{GlobalVars.AppSettings.WasmClientUrl}/redirect?jwt={encodedJwt}&refreshToken={encodedRefreshToken}&redirectPath=mrb/{issueID}"; @@ -91,16 +112,16 @@ public class MRBController : Controller { mrbDMO.UpdateMRB(mrb); } catch (Exception e) { string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + mrb.MRBNumber.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n UpdateEdit MRB\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = mrb.MRBNumber, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n UpdateEdit MRB\r\n" + e.Message.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = mrb.MRBNumber, UserID = GetUserIdentityName(), DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); throw new Exception(e.Message); } } public ActionResult ReadOnly(int issueID) { - string jwt = Session["JWT"].ToString(); + string jwt = GlobalVars.GetJWT(GetSession()); string encodedJwt = System.Net.WebUtility.UrlEncode(jwt); - string refreshToken = Session["RefreshToken"].ToString(); + string refreshToken = GlobalVars.GetRefreshToken(GetSession()); string encodedRefreshToken = System.Net.WebUtility.UrlEncode(refreshToken); string mrbUrl = $"{GlobalVars.AppSettings.WasmClientUrl}/redirect?jwt={encodedJwt}&refreshToken={encodedRefreshToken}&redirectPath=mrb/{issueID}"; @@ -112,6 +133,8 @@ public class MRBController : Controller { return View(); } +#if !NET8 + // POST: /MRB/Delete/5 [HttpPost] public ActionResult Delete(int id, FormCollection collection) { @@ -124,23 +147,31 @@ public class MRBController : Controller { } } +#endif + public JsonResult SearchLots(string searchText, string searchBy) { - List lotlist = MiscDMO.SearchLots(searchText, searchBy).Select(x => x.LotNumber).ToList(); - return Json(lotlist, JsonRequestBehavior.AllowGet); + List lotlist = MiscDMO.SearchLots(searchText, searchBy).Select(x => x.LotNumber).ToList(); + return GetJsonResult(lotlist); } +#if !NET8 + public ActionResult GetMRBLots([DataSourceRequest] DataSourceRequest request, int mrbNumber) { return Json(mrbDMO.GetMRBLots(mrbNumber).ToDataSourceResult(request)); } +#endif + [HttpGet] public ActionResult GetTools() { - return Json(mrbDMO.GetTools(), JsonRequestBehavior.AllowGet); + return GetJsonResult(mrbDMO.GetTools()); } /// /// Updates the lot tables /// +#if !NET8 + [AcceptVerbs(HttpVerbs.Post)] public ActionResult UpdateMRBLot([DataSourceRequest] DataSourceRequest request, Lot lot) { if (lot != null && ModelState.IsValid) { @@ -168,6 +199,8 @@ public class MRBController : Controller { return Json(new[] { lot }.ToDataSourceResult(request, ModelState)); } +#endif + public void DeleteAllMRBLots(int issueID) { // trap the error on then client side mrbDMO.DeleteAllMRBLot(issueID); @@ -183,24 +216,24 @@ public class MRBController : Controller { mrbDMO.InsertLot(lot, false, out existingRowUpdated); } catch (Exception e) { string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + lot.IssueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Add Lot Disposition\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = l.IssueID, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Add Lot Disposition\r\n" + e.Message.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = l.IssueID, UserID = GetUserIdentityName(), DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); throw new Exception(e.Message); } - return Json(l, JsonRequestBehavior.AllowGet); + return GetJsonResult(l); } public ActionResult AddLots(string lotNumbers, int mrbNumber) { // This is for adding lot(s) via search try { - var warnings = new StringBuilder(); + StringBuilder warnings = new(); if (lotNumbers.Length > 0) { string[] tempLots = lotNumbers.Split(new char[] { '~' }); foreach (string lotNumber in tempLots) { bool existingRowUpdated; - Lot l = new Lot(); + Lot l = new(); l.LotNumber = lotNumber; l.MRBNumber = mrbNumber; mrbDMO.InsertLot(l, true, out existingRowUpdated); @@ -210,8 +243,8 @@ public class MRBController : Controller { return Content(warnings.ToString()); } catch (Exception e) { string exceptionString = e.Message.ToString().Trim().Length > 500 ? "MRBNumber=" + mrbNumber.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n AddLots MRB\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { UserID = @User.Identity.Name, OperationType = "Error", DocumentType = "MRB", Comments = exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n AddLots MRB\r\n" + e.Message.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { UserID = GetUserIdentityName(), OperationType = "Error", DocumentType = "MRB", Comments = exceptionString }); Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError; return Content(e.Message); @@ -220,10 +253,14 @@ public class MRBController : Controller { #region ATTACHMENT +#if !NET8 + public ActionResult Attachment_Read([DataSourceRequest] DataSourceRequest request, int mrbNumber) { return Json(mrbDMO.GetMRBAttachments(mrbNumber).ToDataSourceResult(request)); } +#endif + [HttpPost] public void DeleteAttachment(int attachmentID) { try { @@ -233,16 +270,16 @@ public class MRBController : Controller { if (attachment == null) return; - String fileName = attachment.Path; - if (String.IsNullOrEmpty(fileName)) + string fileName = attachment.Path; + if (string.IsNullOrEmpty(fileName)) fileName = attachment.FileName; mrbDMO.DeleteMRBAttachment(attachmentID); - if (!String.IsNullOrWhiteSpace(fileName)) { + if (!string.IsNullOrWhiteSpace(fileName)) { var physicalPath = System.IO.Path.Combine(_AppSettings.AttachmentFolder + "MRB", fileName); - System.IO.FileInfo f = new System.IO.FileInfo(physicalPath); + System.IO.FileInfo f = new(physicalPath); if (f.Exists) f.Delete(); @@ -250,18 +287,20 @@ public class MRBController : Controller { } } catch (Exception e) { string exceptionString = e.Message.ToString().Trim().Length > 500 ? "AttachmentID=" + attachmentID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n AttachmentID MRB\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = 999, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = "AttachmentID Disposition " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n AttachmentID MRB\r\n" + e.Message.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = 999, UserID = GetUserIdentityName(), DocumentType = "MRB", OperationType = "Error", Comments = "AttachmentID Disposition " + exceptionString }); throw new Exception(e.Message); } } +#if !NET8 + public ActionResult AttachSave(IEnumerable files, int mrbNumber) { var errorList = new List(); // The Name of the Upload component is "files" if (files != null) { - int userId = (int)Session[GlobalVars.SESSION_USERID]; + int userId = GlobalVars.GetUserId(GetSession()); foreach (var file in files) { MRBHelper.AttachSave(_AppSettings, mrbDMO, mrbNumber, userId, file.FileName, file.InputStream); } @@ -269,13 +308,17 @@ public class MRBController : Controller { return Json(new { errors = errorList }); } +#endif + #endregion +#if !NET8 + public ActionResult ExcelLotOpen(IEnumerable Lotfile, int mrbNumber) { var warnings = new StringBuilder(); var physicalPath = ""; try { - string userIdentityName = @User.Identity.Name; + string userIdentityName = GetUserIdentityName(); var dispos = mrbDMO.GetDispositions(mrbNumber); foreach (var file in Lotfile) { physicalPath = MRBHelper.ExcelLotOpen(mrbDMO, mrbNumber, warnings, dispos, userIdentityName, _AppSettings.LotTempPipeLine, file.FileName, file.InputStream); @@ -290,8 +333,8 @@ public class MRBController : Controller { detailedException = e.Message; } string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + mrbNumber.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n MRB Excel\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = mrbNumber, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n MRB Excel\r\n" + detailedException, EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = mrbNumber, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); System.IO.FileInfo f = new System.IO.FileInfo(physicalPath); if (f.Exists) @@ -307,7 +350,7 @@ public class MRBController : Controller { try { string message; string c = Server.MapPath("/FTPBatch/"); - string userIdentityName = @User.Identity.Name; + string userIdentityName = GetUserIdentityName(); string b = Server.MapPath("/FTPBatch/" + _AppSettings.FTPSPNBatchFileName); string a = Server.MapPath("/FTPBatch/" + _AppSettings.FTPSPNBatchFileName_Test); foreach (var file in AddQDBFlag) { @@ -332,7 +375,7 @@ public class MRBController : Controller { try { string message; string c = Server.MapPath("/FTPBatch/"); - string userIdentityName = @User.Identity.Name; + string userIdentityName = GetUserIdentityName(); string b = Server.MapPath("/FTPBatch/" + _AppSettings.FTPSPNBatchFileName); string a = Server.MapPath("/FTPBatch/" + _AppSettings.FTPSPNBatchFileName_Test); foreach (var file in RemoveQDBFlag) { @@ -352,11 +395,19 @@ public class MRBController : Controller { } } +#if !NET8 + public ActionResult GetContainmentActions([DataSourceRequest] DataSourceRequest request, int mrbNumber) { return Json(mrbDMO.GetContainmentActions(mrbNumber).ToDataSourceResult(request)); } +#endif + +#endif + +#if !NET8 [AcceptVerbs(HttpVerbs.Post)] +#endif public ActionResult UpdateContainmentAction(ContainmentActionObj model) { if (model != null && ModelState.IsValid) { mrbDMO.UpdateContainmentAction(model); @@ -365,7 +416,9 @@ public class MRBController : Controller { return Content(""); } +#if !NET8 [AcceptVerbs(HttpVerbs.Post)] +#endif public ActionResult InsertContainmentAction(ContainmentActionObj model) { if (model != null && ModelState.IsValid) { mrbDMO.InsertContainmentAction(model); @@ -374,6 +427,8 @@ public class MRBController : Controller { return Content(""); } +#if !NET8 + [AcceptVerbs(HttpVerbs.Post)] public ActionResult DeleteContainmentAction([DataSourceRequest] DataSourceRequest request, ContainmentActionObj model) { if (model != null && ModelState.IsValid) { @@ -383,19 +438,25 @@ public class MRBController : Controller { return Json(new[] { model }.ToDataSourceResult(request, ModelState)); } +#endif + #region +#if !NET8 public ActionResult GetDispostions([DataSourceRequest] DataSourceRequest request, int mrbNumber) { return Json(mrbDMO.GetDispositions(mrbNumber).ToDataSourceResult(request)); } +#endif + +#if !NET8 + [AcceptVerbs(HttpVerbs.Post)] public ActionResult UpdateDisposition(Disposition model) { if (model != null && ModelState.IsValid) { mrbDMO.UpdateDisposition(model); } - - return Json(model, JsonRequestBehavior.AllowGet); + return GetJsonResult(model); } [AcceptVerbs(HttpVerbs.Post)] @@ -411,13 +472,15 @@ public class MRBController : Controller { mrbDMO.DeleteDisposition(model); } - return Json(model, JsonRequestBehavior.AllowGet); + return GetJsonResult(model); } +#endif + #endregion public void PopulateCloseToQDB() { - List options = new List(); + List options = new(); options.Add(new CloseToQDBOptionViewModel { CloseToQDBOptionID = 0, CloseToQDBOption = "No" }); options.Add(new CloseToQDBOptionViewModel { CloseToQDBOptionID = 1, CloseToQDBOption = "Yes" }); ViewData["CloseToQDBOptions"] = options; @@ -428,28 +491,28 @@ public class MRBController : Controller { List emailIst = MiscDMO.GetApproverEmailListByDocument(mrbNumber, currentStep, (int)GlobalVars.DocumentType.MRB).Distinct().ToList(); string emailSentList = MRBHelper.NotifyApprovers(_AppSettings, mrbNumber, emailIst); try { - EventLogDMO.Add(new WinEventLog() { IssueID = mrbNumber, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); + EventLogDMO.Add(new WinEventLog() { IssueID = mrbNumber, UserID = GetUserIdentityName(), DocumentType = "MRB", OperationType = "Email", Comments = "Approvers for Step " + currentStep.ToString() + ":" + emailSentList }); } catch { } } public void Approve(int issueID, byte currentStep, string comments) { int isITARCompliant = 1; - MRB mrb = new MRB(); - mrb = mrbDMO.GetMRBItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); + MRB mrb = new(); + mrb = mrbDMO.GetMRBItem(issueID, out isITARCompliant, GlobalVars.GetUserId(GetSession())); try { bool lastStep = false; - bool lastApprover = wfDMO.Approve(_AppSettings, issueID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.MRB, mrb.WorkFlowNumber); + bool lastApprover = wfDMO.Approve(_AppSettings, issueID, currentStep, comments, out lastStep, GlobalVars.GetUserId(GetSession()), (int)GlobalVars.DocumentType.MRB, mrb.WorkFlowNumber); while (lastApprover && !lastStep) { currentStep++; - lastApprover = wfDMO.Approve(_AppSettings, issueID, currentStep, comments, out lastStep, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.MRB, mrb.WorkFlowNumber); + lastApprover = wfDMO.Approve(_AppSettings, issueID, currentStep, comments, out lastStep, GlobalVars.GetUserId(GetSession()), (int)GlobalVars.DocumentType.MRB, mrb.WorkFlowNumber); NotifyApprovers(issueID, currentStep); } } catch (Exception e) { string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + currentStep + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "Approve - " + exceptionString }); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Approve\r\n" + e.Message.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "Approve - " + exceptionString }); throw new Exception(e.Message); } } @@ -467,9 +530,11 @@ public class MRBController : Controller { int waferCount = 0; int dieCount = 0; mrbDMO.GetLotWaferDieCount(mrbNumber, out lotCount, out waferCount, out dieCount); - return Json(lotCount.ToString() + "~" + waferCount.ToString() + "~" + dieCount, JsonRequestBehavior.AllowGet); + return GetJsonResult(lotCount.ToString() + "~" + waferCount.ToString() + "~" + dieCount); } +#if !NET8 + public ActionResult SendMRBHoldFlagToSPN(int mrbNumber) { MRB mrbInfo; try { @@ -480,7 +545,7 @@ public class MRBController : Controller { } if (!mrbInfo.ToolCSV.ToUpper().Equals("NA")) { - Lot l = new Lot(); + Lot l = new(); var mrbLotInfo = mrbDMO.GetLotsToFindNewChildLots(mrbNumber); foreach (Lot lot in mrbLotInfo) { @@ -493,10 +558,10 @@ public class MRBController : Controller { // SEND DATA to SPN - StringBuilder output = new StringBuilder(); + StringBuilder output = new(); try { string c = Server.MapPath("/FTPBatch/"); - string userIdentityName = @User.Identity.Name; + string userIdentityName = GetUserIdentityName(); string b = Server.MapPath("/FTPBatch/" + _AppSettings.FTPSPNBatchFileName); string a = Server.MapPath("/FTPBatch/" + _AppSettings.FTPSPNBatchFileName_Test); IEnumerable data = mrbDMO.GetMRBHoldLots(mrbNumber); @@ -526,33 +591,33 @@ public class MRBController : Controller { } } catch (Exception e) { string exceptionString = e.Message.ToString().Trim().Length > 500 ? "MRB =" + mrbNumber.ToString() + " FTPToSPN(): SendMRBHoldFlagToSPN(mrbNumber) - FTP Upload Error " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); - return Json(new { Error = true, Message = e.Message }, JsonRequestBehavior.AllowGet); + EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = GetUserIdentityName(), DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); + return GetJsonResult(new { Error = true, Message = e.Message }); } } } catch (Exception e) { string exceptionString = e.Message.ToString().Trim().Length > 500 ? "MRB =" + mrbNumber.ToString() + " SendMRBHoldFlagToSPN(mrbNumber) " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); - return Json(new { Error = true, Message = e.Message }, JsonRequestBehavior.AllowGet); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Approve\r\n" + e.Message.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = GetUserIdentityName(), DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); + return GetJsonResult(new { Error = true, Message = e.Message }); ; } - return Json(new { Error = false, Message = "Success" }, JsonRequestBehavior.AllowGet); + return GetJsonResult(new { Error = false, Message = "Success" }); } catch (Exception e) { string exceptionString = e.Message.ToString().Trim().Length > 500 ? "GUID =" + mrbNumber.ToString() + " SendMRBHoldFlagToSPN(mrbNumber) " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); - EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); - return Json(new { Error = true, Message = e.Message }, JsonRequestBehavior.AllowGet); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Approve\r\n" + e.Message.ToString(), EventLogEntryType.Error); + EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = GetUserIdentityName(), DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); + return GetJsonResult(new { Error = true, Message = e.Message }); } } public bool BatchFTP_Old(string sourceFile, string destFile) { - System.IO.FileInfo sourcefile = new System.IO.FileInfo(sourceFile); + System.IO.FileInfo sourcefile = new(sourceFile); try { - ProcessStartInfo psiFab1 = new ProcessStartInfo(); + ProcessStartInfo psiFab1 = new(); if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") { psiFab1.FileName = Server.MapPath("/FTPBatch/" + _AppSettings.FTPSPNBatchFileName_Test); } else { @@ -561,24 +626,26 @@ public class MRBController : Controller { psiFab1.Arguments = sourcefile.FullName + " " + destFile; - Process procFab1 = new Process(); + Process procFab1 = new(); procFab1.StartInfo = psiFab1; procFab1.Start(); return true; } catch (Exception e) { - Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Approve\r\n" + e.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); + Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Approve\r\n" + e.Message.ToString(), EventLogEntryType.Error); return false; } } +#endif + public FileResult DownloadFile(string attachmentID) { var attachment = mrbDMO.GetMRBAttachment(Convert.ToInt32(attachmentID)); if (attachment == null) throw new Exception("Invalid attachment ID"); - String fileName = attachment.Path; - if (String.IsNullOrEmpty(fileName)) + string fileName = attachment.Path; + if (string.IsNullOrEmpty(fileName)) fileName = attachment.FileName; var sDocument = System.IO.Path.Combine(_AppSettings.AttachmentFolder + "MRB", fileName); @@ -597,7 +664,7 @@ public class MRBController : Controller { } public FileResult ExportMRBHoldFlagReport(int mrbNumber) { - var sb = new StringBuilder(); + StringBuilder sb = new(); sb.AppendLine("LotNo,PartNo ,CurrentLocation,CurrentOperation,StartQty,CurrentQty,LotStatus,OperStatus,Successful,Comment,PriorMRB_DispoType,PriorMRBHoldLocation,PriorMRBHoldOperation,CurrentMRB_DispoType,CurrentMRBHoldLocation,CurrentMRBHoldOperation,TransactionDatetime"); foreach (var report in mrbDMO.GetMRBHoldFlagReport(mrbNumber)) { sb.AppendLine(MRB_DMO.FormCSV( @@ -626,7 +693,7 @@ public class MRBController : Controller { } public FileResult PreviewMRBHoldFlagTobeSentToSPN(int mrbNumber) { - var sb = new StringBuilder(); + StringBuilder sb = new(); sb.AppendLine("LotNumber,MRBNumber,DispoType,MRB Flag,Modified,Sent To SPN,Last Sent to SPN"); foreach (var lot in mrbDMO.GetMRHoldFlagSentHistory(mrbNumber)) { sb.AppendLine(MRB_DMO.FormCSV( @@ -644,7 +711,7 @@ public class MRBController : Controller { } public FileResult ExportLots(int mrbNumber) { - var sb = new StringBuilder(); + StringBuilder sb = new(); sb.AppendLine("LotNumber,DieLotNumber,WipPartNo,DispoType,WaferCount,DiePartNo,DieCount,SourceLot,TotalCost,ProductFamily,Gen,HexSize,Channel,Voltage,Location,Status,QualityCode"); foreach (var lot in mrbDMO.GetMRBLots(mrbNumber)) { sb.AppendLine(MRB_DMO.FormCSV( @@ -671,4 +738,33 @@ public class MRBController : Controller { return File(b, "application/octet-stream", "mrb_lots_" + mrbNumber.ToString() + ".csv"); } +#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; + } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/ManagerController.cs b/Fab2ApprovalSystem/Controllers/ManagerController.cs index f0e9fe7..36762ae 100644 --- a/Fab2ApprovalSystem/Controllers/ManagerController.cs +++ b/Fab2ApprovalSystem/Controllers/ManagerController.cs @@ -1,31 +1,75 @@ -using System; -using System.Collections.Generic; -using System.Linq; +#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; + +#if !NET8 +using System; +using System.Collections.Generic; +using System.Linq; using Fab2ApprovalSystem.Models; +#endif namespace Fab2ApprovalSystem.Controllers; [Authorize] +#if !NET8 [SessionExpireFilter] +#endif +#if NET8 +[Route("[controller]")] +#endif public class ManagerController : Controller { - UserAccountDMO userDMO = new UserAccountDMO(); - AdminDMO adminDMO = new AdminDMO(); - TrainingDMO trainingDMO = new TrainingDMO(); - LotDispositionDMO ldDMO = new LotDispositionDMO(); - private readonly AppSettings _AppSettings = GlobalVars.AppSettings; + private readonly UserAccountDMO userDMO = new(); + private readonly AdminDMO adminDMO = new(); + private readonly TrainingDMO trainingDMO = new(); + private readonly LotDispositionDMO ldDMO = new(); public ActionResult Index() { - if ((bool)Session[GlobalVars.IS_MANAGER]) { + if (GlobalVars.IsManager(GetSession())) { var model = userDMO.GetAllUsers(); ViewBag.AllActiveUsers = userDMO.GetAllActiveUsers(); return View(model); } 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; + } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/PCRBController.cs b/Fab2ApprovalSystem/Controllers/PCRBController.cs index 03ee413..54a1246 100644 --- a/Fab2ApprovalSystem/Controllers/PCRBController.cs +++ b/Fab2ApprovalSystem/Controllers/PCRBController.cs @@ -1,20 +1,62 @@ -using System; +#if !NET8 +using System; using System.Web.Mvc; +#endif + +#if NET8 +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Authorization; +#endif using Fab2ApprovalSystem.Misc; namespace Fab2ApprovalSystem.Controllers; [Authorize] +#if !NET8 [SessionExpireFilter] +#endif +#if NET8 +[Route("[controller]")] +#endif public class PCRBController : Controller { public ActionResult Edit(int issueID) { - string jwt = Session["JWT"].ToString(); + string jwt = GlobalVars.GetJWT(GetSession()); string encodedJwt = System.Net.WebUtility.UrlEncode(jwt); - string refreshToken = Session["RefreshToken"].ToString(); + string refreshToken = GlobalVars.GetRefreshToken(GetSession()); string encodedRefreshToken = System.Net.WebUtility.UrlEncode(refreshToken); string mrbUrl = $"{GlobalVars.AppSettings.WasmClientUrl}/redirect?jwt={encodedJwt}&refreshToken={encodedRefreshToken}&redirectPath=/pcrb/{issueID}"; return Redirect(mrbUrl); } + +#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; + } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/PartsRequestController.cs b/Fab2ApprovalSystem/Controllers/PartsRequestController.cs index aaeb3a7..a6b12e3 100644 --- a/Fab2ApprovalSystem/Controllers/PartsRequestController.cs +++ b/Fab2ApprovalSystem/Controllers/PartsRequestController.cs @@ -1,29 +1,42 @@ using System; using System.Collections.Generic; using System.Linq; +#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 Kendo.Mvc.Extensions; using Kendo.Mvc.UI; +#endif namespace Fab2ApprovalSystem.Controllers; [Authorize] +#if !NET8 [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] [SessionExpireFilter] +#endif +#if NET8 +[Route("[controller]")] +#endif public class PartsRequestController : Controller { - - const int WorkflowNumber = 1; - PartsRequestDMO prDMO = new PartsRequestDMO(); - UserAccountDMO userDMO = new UserAccountDMO(); - WorkflowDMO wfDMO = new WorkflowDMO(); - private readonly AppSettings _AppSettings = GlobalVars.AppSettings; + private const int WorkflowNumber = 1; + private readonly PartsRequestDMO prDMO = new(); + private readonly UserAccountDMO userDMO = new(); + private readonly WorkflowDMO wfDMO = new(); + private readonly AppSettings? _AppSettings = GlobalVars.AppSettings; public PartsRequestController() { ViewBag.ShowReAssignApprovers = false; @@ -42,13 +55,13 @@ public class PartsRequestController : Controller { } protected void HandleException(int issueID, Exception ex, string additionalKeys = "") { - var st = new System.Diagnostics.StackTrace(); - var sf = st.GetFrame(1); + System.Diagnostics.StackTrace st = new(); + System.Diagnostics.StackFrame? sf = st.GetFrame(1); - String controller = sf.GetMethod().DeclaringType.Name.Replace("Controller", ""); - String method = sf.GetMethod().Name; + string controller = sf.GetMethod().DeclaringType.Name.Replace("Controller", ""); + string method = sf.GetMethod().Name; - string detailedException = String.Format( + string detailedException = string.Format( "Exception for issue # {0}\r\n" + "Controller: {1}, Method: {2}, User: {3}, Keys: {4}\r\n" + "=====\r\n", @@ -69,20 +82,19 @@ public class PartsRequestController : Controller { EventLogDMO.Add(new WinEventLog() { IssueID = issueID, - UserID = @User.Identity.Name, + UserID = GetUserIdentityName(), DocumentType = controller, OperationType = "Error", Comments = detailedException }); } - // GET: PartsRequest public ActionResult Index() { return View(); } public ActionResult Edit(int issueID) { - var pr = new PartsRequest(); + PartsRequest pr = new(); try { pr = prDMO.Get(issueID); @@ -95,8 +107,8 @@ public class PartsRequestController : Controller { } else if (pr.CurrentStep >= 1) { return RedirectToAction("EditApproval", new { issueID = issueID }); } else { - if (pr.OriginatorID != (int)Session[GlobalVars.SESSION_USERID]) { - if (Convert.ToBoolean(Session[GlobalVars.IS_ADMIN]) == false) { + if (pr.OriginatorID != GlobalVars.GetUserId(GetSession())) { + if (!GlobalVars.IsAdmin(GetSession())) { return RedirectToAction("ReadOnly", new { issueID = issueID }); } } @@ -110,6 +122,8 @@ public class PartsRequestController : Controller { } } +#if !NET8 + [HttpPost] public ActionResult Edit(PartsRequest pr) { try { @@ -133,10 +147,12 @@ public class PartsRequestController : Controller { } } +#endif + public ActionResult EditApproval(int issueID) { - var pr = new PartsRequest(); + PartsRequest pr = new(); try { - int myUserID = (int)Session[GlobalVars.SESSION_USERID]; + int myUserID = GlobalVars.GetUserId(GetSession()); pr = prDMO.Get(issueID); @@ -156,15 +172,15 @@ public class PartsRequestController : Controller { if (ViewBag.IsApprover == false) { if (pr.OriginatorID != myUserID) { - if (Convert.ToBoolean(Session[GlobalVars.IS_ADMIN]) == false) { + if (!GlobalVars.IsAdmin(GetSession())) { return RedirectToAction("ReadOnly", new { issueID = issueID }); } } } - ViewBag.IsAdmin = Convert.ToBoolean(Session[GlobalVars.IS_ADMIN]); + ViewBag.IsAdmin = GlobalVars.IsAdmin(GetSession()); ViewBag.IsOriginator = (pr.OriginatorID == myUserID); - ViewBag.AllowReject = (wfStep != null ? (wfStep.AllowReject.HasValue && wfStep.AllowReject.Value) : false); + ViewBag.AllowReject = (wfStep != null && (wfStep.AllowReject.HasValue && wfStep.AllowReject.Value)); ViewBag.ShowReAssignApprovers = ViewBag.IsAdmin || ViewBag.IsOriginator; ViewBag.ShowAddApprovers = ViewBag.IsAdmin || ViewBag.IsApprover || ViewBag.IsOriginator; ViewBag.UserList = userDMO.GetAllUsers(); @@ -176,9 +192,9 @@ public class PartsRequestController : Controller { } public ActionResult ReadOnly(int issueID) { - var pr = new PartsRequest(); + PartsRequest pr = new(); try { - int myUserID = (int)Session[GlobalVars.SESSION_USERID]; + int myUserID = GlobalVars.GetUserId(GetSession()); pr = prDMO.Get(issueID); @@ -191,7 +207,7 @@ public class PartsRequestController : Controller { return View("Error"); } - ViewBag.IsAdmin = Convert.ToBoolean(Session[GlobalVars.IS_ADMIN]); + ViewBag.IsAdmin = GlobalVars.IsAdmin(GetSession()); ViewBag.IsOriginator = (pr.OriginatorID == myUserID); ViewBag.UserList = userDMO.GetAllUsers(); return View(pr); @@ -202,11 +218,11 @@ public class PartsRequestController : Controller { } public ActionResult Create() { - var pr = new PartsRequest(); + PartsRequest pr = new(); try { - pr.OriginatorID = (int)Session[GlobalVars.SESSION_USERID]; + pr.OriginatorID = GlobalVars.GetUserId(GetSession()); - if (!CanCreatePartsRequest(pr.OriginatorID) && Convert.ToBoolean(Session[GlobalVars.CAN_CREATE_PARTS_REQUEST]) == false) + if (!CanCreatePartsRequest(pr.OriginatorID) && !GlobalVars.GetCanCreatePartsRequest(GetSession())) throw new Exception("User does not have permission to create Parts Request"); prDMO.Insert(pr); @@ -218,8 +234,8 @@ public class PartsRequestController : Controller { } public static bool CanCreatePartsRequest(int userID) { - var adminDMO = new AdminDMO(); - var role = adminDMO.GetSubRoles().Where(r => string.Equals(r.RoleName, "Parts Request", StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); + AdminDMO adminDMO = new(); + Role? role = adminDMO.GetSubRoles().FirstOrDefault(r => string.Equals(r.RoleName, "Parts Request", StringComparison.OrdinalIgnoreCase)); if (role != null) { var subrole = role.SubRoles.FirstOrDefault(sr => string.Equals(sr.SubRoleCategoryItem, "Originator", StringComparison.OrdinalIgnoreCase)); if (subrole != null) { @@ -232,9 +248,11 @@ public class PartsRequestController : Controller { return false; } +#if !NET8 + public ActionResult Attachment_Read([DataSourceRequest] DataSourceRequest request, int prNumber) { try { - return Json(prDMO.GetAttachments(prNumber).ToDataSourceResult(request), JsonRequestBehavior.AllowGet); + return GetJsonResult(prDMO.GetAttachments(prNumber).ToDataSourceResult(request)); } catch (Exception ex) { return HandleAPIException(prNumber, ex); } @@ -244,7 +262,7 @@ public class PartsRequestController : Controller { public ActionResult AttachSave(IEnumerable files, int prNumber) { // The Name of the Upload component is "files" if (files != null) { - int userId = (int)Session[GlobalVars.SESSION_USERID]; + int userId = GlobalVars.GetUserId(GetSession()); foreach (var file in files) { PartsRequestHelper.AttachSave(_AppSettings, prDMO, prNumber, userId, file.FileName, file.InputStream); } @@ -253,6 +271,8 @@ public class PartsRequestController : Controller { return Content(""); } +#endif + public FileResult DownloadFile(string attachmentID, string prNumber) { string fileName = prDMO.GetFileName(attachmentID); @@ -289,17 +309,19 @@ public class PartsRequestController : Controller { } } +#if !NET8 + [HttpPost] public ActionResult Submit(int prNumber) { try { - int myUserID = (int)Session[GlobalVars.SESSION_USERID]; + int myUserID = GlobalVars.GetUserId(GetSession()); var pr = prDMO.Get(prNumber); if (pr == null) return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "Document does not exist"); - if (String.IsNullOrWhiteSpace(pr.Title)) + if (string.IsNullOrWhiteSpace(pr.Title)) return HandleValidationError("Title is required"); if (pr.RequestorID <= 0) return HandleValidationError("Requestor is required"); @@ -313,9 +335,9 @@ public class PartsRequestController : Controller { if (approvers.Count(a => a.Step.HasValue && a.Step.Value == 1 && a.UserID == myUserID) > 0) { // Auto-Approve if the user is an approver for workflow step 1 var c = Approve(prNumber, 1, "Auto-Approve"); - if (c != null && c is ContentResult) { - var result = ((ContentResult)c).Content; - if (!String.Equals(result, "OK")) + if (c != null && c is ContentResult contentResult) { + var result = contentResult.Content; + if (!string.Equals(result, "OK")) throw new Exception(result); } if (c != null && c is JsonResult) @@ -325,7 +347,7 @@ public class PartsRequestController : Controller { NotifyApprovers(prNumber, 1); } - if (Request.IsAjaxRequest()) { + if (IsAjaxRequest()) { return Content("Redirect"); } else { return Content("Invalid"); @@ -348,16 +370,18 @@ public class PartsRequestController : Controller { try { UserAccountDMO userDMO = new UserAccountDMO(); IEnumerable userlist = userDMO.GetAllUsers(); - return Json(userlist, JsonRequestBehavior.AllowGet); + return GetJsonResult(userlist); } catch (Exception e) { return HandleAPIException(0, e); } } +#endif + [HttpPost] public ActionResult ReAssignApproval(int issueID, int fromUserID, int userIDs, byte step) { try { - String email = wfDMO.ReAssignApproval( + string email = wfDMO.ReAssignApproval( issueID, fromUserID, userIDs, step, (int)GlobalVars.DocumentType.PartsRequest); NotifyReAssignment(issueID, email); @@ -368,12 +392,14 @@ public class PartsRequestController : Controller { } } +#if !NET8 + [HttpPost] public ActionResult Approve(int prNumber, byte currentStep, string comments) { try { bool lastStep = false; bool lastApproverInCurrentStep = false; - int myUserID = (int)Session[GlobalVars.SESSION_USERID]; + int myUserID = GlobalVars.GetUserId(GetSession()); var pr = prDMO.Get(prNumber); @@ -387,7 +413,7 @@ public class PartsRequestController : Controller { currentStep, comments, out lastStep, - (int)Session[GlobalVars.SESSION_USERID], + GlobalVars.GetUserId(GetSession()), (int)GlobalVars.DocumentType.PartsRequest, WorkflowNumber); @@ -417,22 +443,24 @@ public class PartsRequestController : Controller { } } +#endif + protected void NotifyReAssignment(int prNumber, string email) { var pr = prDMO.Get(prNumber); if (pr == null) return; - string username = Session[GlobalVars.SESSION_USERNAME].ToString(); + string username = GlobalVars.GetUserName(GetSession()); PartsRequestHelper.SendEmailNotification(_AppSettings, username, - subject: String.Format("Parts Request Re-Assignment notice for # {0} - {1}", pr.PRNumber, pr.Title), + subject: string.Format("Parts Request Re-Assignment notice for # {0} - {1}", pr.PRNumber, pr.Title), prNumber: prNumber, toEmail: email, emailTemplate: "PRReAssigned.txt"); EventLogDMO.Add(new WinEventLog() { IssueID = prNumber, - UserID = @User.Identity.Name, + UserID = GetUserIdentityName(), DocumentType = "PR", OperationType = "Email", Comments = "ReAssigned Approver: " + email @@ -446,17 +474,17 @@ public class PartsRequestController : Controller { return; var u = userDMO.GetUserByID(pr.RequestorID); - if ((u != null) && (!String.IsNullOrWhiteSpace(u.Email))) { - string username = Session[GlobalVars.SESSION_USERNAME].ToString(); + if ((u != null) && (!string.IsNullOrWhiteSpace(u.Email))) { + string username = GlobalVars.GetUserName(GetSession()); PartsRequestHelper.SendEmailNotification(_AppSettings, username, - subject: String.Format("Parts Request Completion notice for # {0} - {1}", pr.PRNumber, pr.Title), + subject: string.Format("Parts Request Completion notice for # {0} - {1}", pr.PRNumber, pr.Title), prNumber: prNumber, toEmail: u.Email, emailTemplate: "PRCompleted.txt"); EventLogDMO.Add(new WinEventLog() { IssueID = prNumber, - UserID = @User.Identity.Name, + UserID = GetUserIdentityName(), DocumentType = "PR", OperationType = "Email", Comments = "Completed: " + u.Email @@ -471,17 +499,17 @@ public class PartsRequestController : Controller { return; var u = userDMO.GetUserByID(pr.OriginatorID); - if ((u != null) && (!String.IsNullOrWhiteSpace(u.Email))) { - string username = Session[GlobalVars.SESSION_USERNAME].ToString(); + if ((u != null) && (!string.IsNullOrWhiteSpace(u.Email))) { + string username = GlobalVars.GetUserName(GetSession()); PartsRequestHelper.SendEmailNotification(_AppSettings, username, - subject: String.Format("Parts Request Rejection notice for # {0} - {1}", pr.PRNumber, pr.Title), + subject: string.Format("Parts Request Rejection notice for # {0} - {1}", pr.PRNumber, pr.Title), prNumber: prNumber, toEmail: u.Email, emailTemplate: "PRReject.txt"); EventLogDMO.Add(new WinEventLog() { IssueID = prNumber, - UserID = @User.Identity.Name, + UserID = GetUserIdentityName(), DocumentType = "PR", OperationType = "Email", Comments = "Rejected: " + u.Email @@ -503,9 +531,9 @@ public class PartsRequestController : Controller { foreach (string email in emailList) { try { - string username = Session[GlobalVars.SESSION_USERNAME].ToString(); + string username = GlobalVars.GetUserName(GetSession()); PartsRequestHelper.SendEmailNotification(_AppSettings, username, - subject: String.Format("Parts Request Assignment notice for # {0} - {1}", pr.PRNumber, pr.Title), + subject: string.Format("Parts Request Assignment notice for # {0} - {1}", pr.PRNumber, pr.Title), prNumber: prNumber, toEmail: email, emailTemplate: "PRAssigned.txt"); @@ -519,7 +547,7 @@ public class PartsRequestController : Controller { try { EventLogDMO.Add(new WinEventLog() { IssueID = prNumber, - UserID = @User.Identity.Name, + UserID = GetUserIdentityName(), DocumentType = "PR", OperationType = "Email", Comments = "Approvers for Step " + step.ToString() + ":" + emailSentList @@ -533,8 +561,8 @@ public class PartsRequestController : Controller { [HttpPost] public ActionResult Reject(int prNumber, byte currentStep, string comments) { try { - if (Session[GlobalVars.SESSION_USERID] != null) { - wfDMO.Reject(prNumber, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.PartsRequest); + if (GlobalVars.IsUserIdValueNotNull(GetSession())) { + wfDMO.Reject(prNumber, currentStep, comments, GlobalVars.GetUserId(GetSession()), (int)GlobalVars.DocumentType.PartsRequest); NotifyRejection(prNumber); } else { Response.Redirect("~/Account/Login"); @@ -546,26 +574,30 @@ public class PartsRequestController : Controller { } } +#if !NET8 + public ActionResult ApprovalLogHistory_Read([DataSourceRequest] DataSourceRequest request, int prNumber) { - return Json(prDMO.GetApprovalLogHistory(prNumber).ToDataSourceResult(request), JsonRequestBehavior.AllowGet); + return GetJsonResult(prDMO.GetApprovalLogHistory(prNumber).ToDataSourceResult(request)); } +#endif + protected void NotifyAssignment(int prNumber, string email) { var pr = prDMO.Get(prNumber); if (pr == null) return; - string username = Session[GlobalVars.SESSION_USERNAME].ToString(); + string username = GlobalVars.GetUserName(GetSession()); PartsRequestHelper.SendEmailNotification(_AppSettings, username, - subject: String.Format("Parts Request Assignment notice for # {0} - {1}", pr.PRNumber, pr.Title), + subject: string.Format("Parts Request Assignment notice for # {0} - {1}", pr.PRNumber, pr.Title), prNumber: prNumber, toEmail: email, emailTemplate: "PRAssigned.txt"); EventLogDMO.Add(new WinEventLog() { IssueID = prNumber, - UserID = @User.Identity.Name, + UserID = GetUserIdentityName(), DocumentType = "PR", OperationType = "Email", Comments = "Assigned Approver: " + email @@ -594,7 +626,7 @@ public class PartsRequestController : Controller { try { EventLogDMO.Add(new WinEventLog() { IssueID = issueID, - UserID = @User.Identity.Name, + UserID = GetUserIdentityName(), DocumentType = "PR", OperationType = "Email", Comments = "Additional Approver: " + emailSentList @@ -602,4 +634,33 @@ public class PartsRequestController : Controller { } catch { } } +#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; + } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/ReportsController.cs b/Fab2ApprovalSystem/Controllers/ReportsController.cs index 2c7caea..80107d9 100644 --- a/Fab2ApprovalSystem/Controllers/ReportsController.cs +++ b/Fab2ApprovalSystem/Controllers/ReportsController.cs @@ -1,43 +1,60 @@ using System; -using System.Collections.Generic; using System.Linq; +#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.Collections.Generic; using Fab2ApprovalSystem.ViewModels; +#endif namespace Fab2ApprovalSystem.Controllers; [Authorize] +#if !NET8 [SessionExpireFilter] +#endif +#if NET8 +[Route("[controller]")] +#endif public class ReportsController : Controller { - public const String specialNullString = "~NULL~"; - private readonly AppSettings _AppSettings = GlobalVars.AppSettings; + public const string specialNullString = "~NULL~"; + private readonly AppSettings? _AppSettings = GlobalVars.AppSettings; // GET: Export public ActionResult Index() { - UserAccountDMO userDMO = new UserAccountDMO(); - ViewBag.HasITARAccess = userDMO.GetITARAccess((int)Session[GlobalVars.SESSION_USERID]); + UserAccountDMO userDMO = new(); + ViewBag.HasITARAccess = userDMO.GetITARAccess(GlobalVars.GetUserId(GetSession())); return View(); } - public ActionResult Report(String id, String docType = "") { - if (String.IsNullOrEmpty(id)) +#if !NET8 + + public ActionResult Report(string id, string docType = "") { + if (string.IsNullOrEmpty(id)) return RedirectToAction("Index"); - UserAccountDMO userDMO = new UserAccountDMO(); - if (!userDMO.GetITARAccess((int)Session[GlobalVars.SESSION_USERID])) + UserAccountDMO userDMO = new(); + if (!userDMO.GetITARAccess(GlobalVars.GetUserId(GetSession()))) return View("UnAuthorizedAccess"); - var m = new ReportViewModel(); + ReportViewModel m = new(); var reports = GetReportList(docType); foreach (var report in reports) { - if (String.Equals(report.ReportID, id, StringComparison.OrdinalIgnoreCase)) { + if (string.Equals(report.ReportID, id, StringComparison.OrdinalIgnoreCase)) { m.ReportID = report.ReportID; m.ReportName = report.Name; m.Description = report.Description; @@ -46,8 +63,8 @@ public class ReportsController : Controller { var c = SetupSSRSHelperClient(); m.Parameters = c.GetReportParameters(report.FullPath).Select(parm => { - var r = new ReportParameterViewModel(); - r.Visible = (parm.PromptUser.HasValue == false || parm.PromptUser == true) && !String.IsNullOrEmpty(parm.Prompt); + ReportParameterViewModel r = new(); + r.Visible = (parm.PromptUser.HasValue == false || parm.PromptUser == true) && !string.IsNullOrEmpty(parm.Prompt); r.Prompt = parm.Prompt; r.Name = parm.Name; r.HtmlID = "parm_" + parm.Name; @@ -87,7 +104,7 @@ public class ReportsController : Controller { public SSRSHelper.SSRSClient SetupSSRSHelperClient() { var useCfgForBindings = false; - if (String.Equals(_AppSettings.SSRSBindingsByConfiguration, "true", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(_AppSettings.SSRSBindingsByConfiguration, "true", StringComparison.OrdinalIgnoreCase)) useCfgForBindings = true; var c = new SSRSHelper.SSRSClient( @@ -112,27 +129,26 @@ public class ReportsController : Controller { return c.ListReports(folderName); } - public ActionResult GetReports(String docType) { + public ActionResult GetReports(string docType) { var reports = GetReportList(docType); - return Json(new { + return GetJsonResult(new { Data = - reports.Select(r => new ReportViewModel() { + reports.Select(r => new ReportViewModel() { ReportName = r.Name ?? "", Description = r.Description ?? "", ReportID = r.ReportID ?? "", DocType = docType }) - }, - JsonRequestBehavior.AllowGet); + }); } [HttpPost] - public ActionResult ExportReport(String DocType, String ReportID) { + public ActionResult ExportReport(string DocType, string ReportID) { var c = SetupSSRSHelperClient(); var reports = GetReportList(DocType); - var report = reports.Where(r => String.Equals(r.ReportID, ReportID, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); + var report = reports.Where(r => string.Equals(r.ReportID, ReportID, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); if (report == null) return Content("Invalid report ID"); @@ -140,16 +156,16 @@ public class ReportsController : Controller { var parms = new SSRSHelper.ReportParameterCollection(); parms.Add("DocType", DocType); - parms.Add("UserID", Convert.ToString(Session[GlobalVars.SESSION_USERID])); + parms.Add("UserID", GlobalVars.GetUserIdValue(GetSession())); parms.Add("BaseURL", GlobalVars.hostURL); foreach (var rp in reportParms) { if (rp.MultiValue.HasValue && rp.MultiValue.Value) { - foreach (String v in Request.Params.GetValues("parm_" + rp.Name)) { + foreach (string v in Request.Params.GetValues("parm_" + rp.Name)) { parms.Add(rp.Name, v); } } else { - String value = null; + string value = null; if (Request.Params.AllKeys.Contains("parm_" + rp.Name)) value = Request.Params.GetValues("parm_" + rp.Name).FirstOrDefault(); @@ -173,7 +189,7 @@ public class ReportsController : Controller { } } - var b = c.ExportReport(report.FullPath, @User.Identity.Name, parms, "EXCELOPENXML"); + var b = c.ExportReport(report.FullPath, GetUserIdentityName(), parms, "EXCELOPENXML"); try { var b2 = c.FreezeExcelHeaders(b); return File(b2, "application/octet-stream", MakeFilename(report.Name) + ".xlsx"); @@ -182,8 +198,10 @@ public class ReportsController : Controller { return File(b, "application/octet-stream", MakeFilename(report.Name) + ".xlsx"); } - protected String MakeFilename(String reportName) { - String r = ""; +#endif + + protected string MakeFilename(string reportName) { + string r = ""; char[] invalidChars = System.IO.Path.GetInvalidFileNameChars(); foreach (char c in reportName) { if (invalidChars.Contains(c)) @@ -194,4 +212,33 @@ public class ReportsController : Controller { return r; } +#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; + } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/TrainingController.cs b/Fab2ApprovalSystem/Controllers/TrainingController.cs index 755abae..4f5fa62 100644 --- a/Fab2ApprovalSystem/Controllers/TrainingController.cs +++ b/Fab2ApprovalSystem/Controllers/TrainingController.cs @@ -1,8 +1,14 @@ using System; using System.Collections.Generic; -using System.Configuration; using System.Linq; +#if !NET8 using System.Web.Mvc; +#endif + +#if NET8 +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Authorization; +#endif using Fab2ApprovalSystem.DMO; using Fab2ApprovalSystem.Misc; @@ -10,19 +16,26 @@ using Fab2ApprovalSystem.Models; using Fab2ApprovalSystem.Utilities; using Fab2ApprovalSystem.ViewModels; +#if !NET8 using Kendo.Mvc.Extensions; +#endif namespace Fab2ApprovalSystem.Controllers; [Authorize] +#if !NET8 [SessionExpireFilter] +#endif +#if NET8 +[Route("[controller]")] +#endif public class TrainingController : Controller { - UserAccountDMO userDMO = new UserAccountDMO(); - AdminDMO adminDMO = new AdminDMO(); - TrainingDMO trainingDMO = new TrainingDMO(); - ECN_DMO ecnDMO = new ECN_DMO(); - private readonly AppSettings _AppSettings = GlobalVars.AppSettings; + private readonly UserAccountDMO userDMO = new(); + private readonly AdminDMO adminDMO = new(); + private readonly TrainingDMO trainingDMO = new(); + private readonly ECN_DMO ecnDMO = new(); + private readonly AppSettings? _AppSettings = GlobalVars.AppSettings; // GET: Training public ActionResult Index() { @@ -30,19 +43,19 @@ public class TrainingController : Controller { } public int Create(int ecnId) { - ECN_DMO ecnDMO = new ECN_DMO(); + ECN_DMO ecnDMO = new(); // Delete old training if exists int oldTrainingId = trainingDMO.GetTrainingId(ecnId); - if (oldTrainingId != null && oldTrainingId != 0) { + if (oldTrainingId != 0) { trainingDMO.DeleteTraining(oldTrainingId); } int trainingId = trainingDMO.Create(ecnId); - List TrainingGroups = new List(); + List TrainingGroups = new(); TrainingGroups = trainingDMO.GetECNAssignedTrainingGroups(ecnId); string ECNTitle = ecnDMO.GetECN(ecnId).Title; - List Trainees = new List(); + List Trainees = new(); foreach (int group in TrainingGroups) { Trainees.AddRange(trainingDMO.GetTrainees(group)); } @@ -55,8 +68,9 @@ public class TrainingController : Controller { return trainingId; } + public ActionResult AddUserToTrainingAdHoc(int trainingId, int traineeId, int ecnId) { - if ((bool)Session[GlobalVars.IS_ADMIN]) { + if (GlobalVars.IsAdmin(GetSession())) { // Get ECN ECN ecn = ecnDMO.GetECN(ecnId); @@ -105,7 +119,7 @@ public class TrainingController : Controller { } public ActionResult AddGroupToTrainingAdHoc(int trainingId, int groupId, int ecnId) { - if ((bool)Session[GlobalVars.IS_ADMIN]) { + if (GlobalVars.IsAdmin(GetSession())) { ECN ecn = ecnDMO.GetECN(ecnId); Training training = trainingDMO.GetTraining(trainingId); TrainingGroup group = trainingDMO.GetTrainingGroupByID(groupId); @@ -163,14 +177,14 @@ public class TrainingController : Controller { public ActionResult DeleteTrainingByECN(int ECNNumber) { int trainingId = trainingDMO.GetTrainingId(ECNNumber); - if (trainingId != null && trainingId != 0) { + if (trainingId != 0) { trainingDMO.DeleteTraining(trainingId); } return RedirectToAction("ViewTrainings"); } public ActionResult DeleteTrainingByID(int trainingId) { - if (trainingId != null && trainingId != 0) { + if (trainingId != 0) { trainingDMO.DeleteTraining(trainingId); } return RedirectToAction("ViewTrainings"); @@ -254,7 +268,7 @@ public class TrainingController : Controller { // Group Filter if (filterType == 1 && filterValue != "") { ViewBag.GroupFilter = filterValue; - List filteredTraining = new List(); + List filteredTraining = new(); foreach (Training item in trainingList) { List assignedTrainingGroups = trainingDMO.GetECNAssignedTrainingGroups(item.ECN); foreach (int id in assignedTrainingGroups) { @@ -268,7 +282,7 @@ public class TrainingController : Controller { } // Status Filter if (filterType == 2 && filterValue != "") { - List filteredTraining = new List(); + List filteredTraining = new(); switch (filterValue) { case "1": // Completed @@ -307,7 +321,7 @@ public class TrainingController : Controller { float assignmentCount = (from a in trainingAssignments where a.Deleted != true select a).Count(); float totalCompleted = 0; foreach (TrainingAssignment assignment in trainingAssignments) { - if (assignment.status == true && assignment.Deleted != true) { + if (assignment.status && assignment.Deleted != true) { totalCompleted++; } } @@ -316,7 +330,7 @@ public class TrainingController : Controller { if (groupFilter != "" && groupFilter != null) { ViewBag.GroupFilter = groupFilter; - List groupFilteredTraining = new List(); + List groupFilteredTraining = new(); List groupMemberIds = trainingDMO.GetTrainees(Convert.ToInt32(groupFilter)); foreach (TrainingAssignment assignment in trainingAssignments) { if (trainingDMO.isUserTrainingMember(Convert.ToInt32(groupFilter), assignment.UserID)) { @@ -326,15 +340,15 @@ public class TrainingController : Controller { trainingAssignments = groupFilteredTraining; } if (statusFilter != "" && statusFilter != null) { - List filteredTraining = new List(); + List filteredTraining = new(); switch (statusFilter) { case "1": // Completed - filteredTraining = (from a in trainingAssignments where a.status == true && a.Deleted != true select a).ToList(); + filteredTraining = (from a in trainingAssignments where a.status && a.Deleted != true select a).ToList(); break; case "2": // In Progress - filteredTraining = (from a in trainingAssignments where a.status != true && a.Deleted != true select a).ToList(); + filteredTraining = (from a in trainingAssignments where !a.status && a.Deleted != true select a).ToList(); break; case "3": // Cancelled @@ -369,9 +383,9 @@ public class TrainingController : Controller { /// Method to return all the training assignments for a specified user /// public ActionResult ViewMyTrainingAssignments() { - int userID = (int)Session[GlobalVars.SESSION_USERID]; + int userID = GlobalVars.GetUserId(GetSession()); List assignments = trainingDMO.GetTrainingAssignmentsByUserID(userID); - List ViewData = new List(); + List ViewData = new(); foreach (TrainingAssignment assignment in assignments) { Training training = trainingDMO.GetTraining(assignment.TrainingID); if (training != null && !assignment.status) { @@ -407,7 +421,7 @@ public class TrainingController : Controller { // Group Filter if (filterType == 1 && filterValue != "") { ViewBag.GroupFilter = filterValue; - List filteredTraining = new List(); + List filteredTraining = new(); foreach (Training item in AllTrainings) { List assignedTrainingGroups = trainingDMO.GetECNAssignedTrainingGroups(item.ECN); foreach (int id in assignedTrainingGroups) { @@ -454,8 +468,8 @@ public class TrainingController : Controller { } public ActionResult ManuallyExecuteECNTraining(int ecnId, int[] trainingGroupsIn) { - if ((bool)Session[GlobalVars.IS_ADMIN]) { - List newTrainingGroupIds = new List(trainingGroupsIn); + if (GlobalVars.IsAdmin(GetSession())) { + List newTrainingGroupIds = new(trainingGroupsIn); ECN ecn = ecnDMO.GetECN(ecnId); if (ecn != null) { if (ecn.CloseDate != null) { @@ -493,7 +507,7 @@ public class TrainingController : Controller { if (ecn != null) { if (ecn.CloseDate != null) { List trainingGroupIds = trainingDMO.GetECNAssignedTrainingGroups(ecnId); - List assignedGroups = new List(); + List assignedGroups = new(); foreach (int trainingGroupId in trainingGroupIds) { TrainingGroup trainingGroup = trainingDMO.GetTrainingGroupByID(trainingGroupId); assignedGroups.Add(trainingGroup); @@ -517,7 +531,7 @@ public class TrainingController : Controller { emailBody += ""; // Get all users set up to receive the training report email. List trainingReportUsers = adminDMO.GetTrainingReportUsers(); - List emailList = new List(); + List emailList = new(); foreach (TrainingReportUser user in trainingReportUsers) { string userEmail = userDMO.GetUserByID(user.UserId).Email; emailList.Add(userEmail); @@ -564,4 +578,34 @@ public class TrainingController : Controller { } return isSuccess; } + +#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; + } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/WebAPIController.cs b/Fab2ApprovalSystem/Controllers/WebAPIController.cs index 4d558e4..e4a699b 100644 --- a/Fab2ApprovalSystem/Controllers/WebAPIController.cs +++ b/Fab2ApprovalSystem/Controllers/WebAPIController.cs @@ -1,34 +1,56 @@ -using System; using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Http; +#if !NET8 using System.Web.Http; +#endif + +#if NET8 +using Microsoft.AspNetCore.Mvc; +#endif using Fab2ApprovalSystem.Misc; using Fab2ApprovalSystem.Models; +#if !NET8 +using System; +using System.Linq; +using System.Net; +using System.Net.Http; +#endif + namespace Fab2ApprovalSystem.Controllers; +#if !NET8 public class WebAPIController : ApiController { - public TrainingController trainingFunctions = new TrainingController(); - public CorrectiveActionController carFunctions = new CorrectiveActionController(); - public AccountController accountFunctions = new AccountController(); - public HomeController homeFunctions = new HomeController(); - private readonly AppSettings _AppSettings = GlobalVars.AppSettings; +#endif + +#if NET8 +[ApiController] +[Route("[controller]")] +public class WebAPIController : Controller { +#endif + + public TrainingController trainingFunctions = new(); + public CorrectiveActionController carFunctions = new(); + public AccountController accountFunctions = new(); + public HomeController homeFunctions = new(); + private readonly AppSettings? _AppSettings = GlobalVars.AppSettings; public string Get() { return "Welcome To Web API"; } + public List Get(int Id) { return new List { "Data1", "Data2" }; } + public void Post() { } +#if !NET8 + public HttpResponseMessage Post(HttpRequestMessage request, string action) { switch (action) { case "TrainingReport": @@ -65,4 +87,7 @@ public class WebAPIController : ApiController { return request.CreateResponse(HttpStatusCode.InternalServerError, "Action Not Found"); } } + +#endif + } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Controllers/WorkflowController.cs b/Fab2ApprovalSystem/Controllers/WorkflowController.cs index 667dcc2..1a9162f 100644 --- a/Fab2ApprovalSystem/Controllers/WorkflowController.cs +++ b/Fab2ApprovalSystem/Controllers/WorkflowController.cs @@ -1,17 +1,30 @@ -using System; -using System.Collections.Generic; -using System.Linq; +#if !NET8 using System.Web; using System.Web.Mvc; +#endif +#if NET8 +using Microsoft.AspNetCore.Mvc; +#endif + +#if !NET8 +using System; +using System.Collections.Generic; +using System.Linq; using Fab2ApprovalSystem.DMO; using Fab2ApprovalSystem.Models; +#endif +#if !NET8 using Kendo.Mvc.Extensions; using Kendo.Mvc.UI; +#endif namespace Fab2ApprovalSystem.Controllers; +#if NET8 +[Route("[controller]")] +#endif public class WorkflowController : Controller { // GET: /Workflow/Details/5 @@ -24,6 +37,8 @@ public class WorkflowController : Controller { return View(); } +#if !NET8 + // POST: /Workflow/Create [HttpPost] public ActionResult Create(FormCollection collection) { @@ -36,11 +51,15 @@ public class WorkflowController : Controller { } } +#endif + // GET: /Workflow/Edit/5 public ActionResult Edit(int id) { return View(); } +#if !NET8 + // POST: /Workflow/Edit/5 [HttpPost] public ActionResult Edit(int id, FormCollection collection) { @@ -53,11 +72,15 @@ public class WorkflowController : Controller { } } +#endif + // GET: /Workflow/Delete/5 public ActionResult Delete(int id) { return View(); } +#if !NET8 + // POST: /Workflow/Delete/5 [HttpPost] public ActionResult Delete(int id, FormCollection collection) { @@ -70,4 +93,35 @@ public class WorkflowController : Controller { } } +#endif + +#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; + } \ No newline at end of file diff --git a/Fab2ApprovalSystem/DMO/AdminDMO.cs b/Fab2ApprovalSystem/DMO/AdminDMO.cs index 94cfdea..e07e067 100644 --- a/Fab2ApprovalSystem/DMO/AdminDMO.cs +++ b/Fab2ApprovalSystem/DMO/AdminDMO.cs @@ -130,13 +130,19 @@ public class AdminDMO { } #if !NET8 + public List GetTrainingReportUsers() { List CurrentReportUsers = (from a in FabApprovalDB.TrainingReportUsers select a).ToList(); return CurrentReportUsers; } -#else + +#endif + +#if NET8 + public List GetTrainingReportUsers() => throw new NotImplementedException(); + #endif #if !NET8 @@ -179,14 +185,20 @@ public class AdminDMO { return; } -#if !NET8 public List GetTrainingGroups() { +#if !NET8 var TrainingGroups = from a in FabApprovalDB.TrainingGroups select a; List GroupsToReturn = TrainingGroups.ToList(); return GroupsToReturn; +#endif +#if NET8 + throw new NotImplementedException(); +#endif } +#if !NET8 + public void AddNewTrainingGroup(string groupName) { TrainingGroup existing = null; // Check to see that the group name doesn't exist. diff --git a/Fab2ApprovalSystem/DMO/TrainingDMO.cs b/Fab2ApprovalSystem/DMO/TrainingDMO.cs index 2452282..70e5073 100644 --- a/Fab2ApprovalSystem/DMO/TrainingDMO.cs +++ b/Fab2ApprovalSystem/DMO/TrainingDMO.cs @@ -46,7 +46,9 @@ public class TrainingDMO { IEnumerable allTrainings = (from a in db.Trainings select a).ToList(); return allTrainings; -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -57,7 +59,9 @@ public class TrainingDMO { Training trainingRecord = new Training(); trainingRecord = (from a in db.Trainings where a.TrainingID == trainingId select a).FirstOrDefault(); return trainingRecord; -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -67,7 +71,9 @@ public class TrainingDMO { FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); TrainingAssignment assignmentRecord = (from a in db.TrainingAssignments where a.ID == assignmentId select a).FirstOrDefault(); return assignmentRecord; -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -79,7 +85,9 @@ public class TrainingDMO { int trainingId = (from a in db.Trainings where a.ECN == ECNId select a.TrainingID).FirstOrDefault(); return trainingId; -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -90,7 +98,9 @@ public class TrainingDMO { var users = (from a in db.TrainingGroupMembers where a.TrainingGroupID == groupId select a.UserID).ToList(); return users; -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -105,7 +115,9 @@ public class TrainingDMO { } else { return true; } -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -114,8 +126,11 @@ public class TrainingDMO { #if !NET8 FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); return (from a in db.TrainingGroups select a).ToList(); -#else - throw new NotImplementedException(); +#endif + +#if NET8 + System.Text.StringBuilder query = new("SELECT TrainingGroupID, TrainingGroupName FROM TrainingGroups ORDER BY TrainingGroupID"); + return db.Query(query.ToString()).ToList(); #endif } @@ -124,7 +139,9 @@ public class TrainingDMO { FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); TrainingGroup groups = (from a in db.TrainingGroups where a.TrainingGroupID == groupId select a).FirstOrDefault(); return groups; -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -134,7 +151,9 @@ public class TrainingDMO { List trainingGroups = (from a in FabApprovalDB.ECNTrainingBies where a.ECNNumber == ECNNumber select a.AcknowledgementTrainingByID).ToList(); return trainingGroups; -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -149,7 +168,9 @@ public class TrainingDMO { this.db.Execute("ECNInsertTrainingBy", parameters, commandType: CommandType.StoredProcedure); -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -162,7 +183,9 @@ public class TrainingDMO { this.db.Execute("ECNSetTrainingFlag", parameters, commandType: CommandType.StoredProcedure); -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -177,7 +200,9 @@ public class TrainingDMO { TrainingData = from a in db.TrainingAssignments where a.TrainingID == TrainingID select a; return TrainingData.ToList(); -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -192,7 +217,9 @@ public class TrainingDMO { TrainingData = from a in db.TrainingAssignments where a.TrainingID == TrainingID select a; return TrainingData.ToList(); -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -203,7 +230,9 @@ public class TrainingDMO { var TrainingData = from a in db.TrainingAssignments where a.TrainingID == TrainingID && a.UserID == userID select a; return TrainingData.ToList(); -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -214,7 +243,9 @@ public class TrainingDMO { var docs = (from a in db.TrainingDocAcks where a.TrainingAssignmentID == trainingAssignmentId && a.Deleted != true select a).ToList(); return docs; -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -240,7 +271,9 @@ public class TrainingDMO { Console.WriteLine(e); } } -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -251,7 +284,9 @@ public class TrainingDMO { int trainingID = (from a in db.TrainingAssignments where a.ID == trainingAssignmentID select a.TrainingID).SingleOrDefault(); return trainingID; -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -272,7 +307,9 @@ public class TrainingDMO { Console.WriteLine(e); } } -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -293,7 +330,9 @@ public class TrainingDMO { Console.WriteLine(e); } } -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -311,7 +350,9 @@ public class TrainingDMO { } } return isFinished; -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -331,7 +372,9 @@ public class TrainingDMO { } return isFinished; -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -348,7 +391,9 @@ public class TrainingDMO { } return userHasAssignment; -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -359,7 +404,9 @@ public class TrainingDMO { var trainings = from a in db.Trainings select a; return trainings.ToList(); -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -370,7 +417,9 @@ public class TrainingDMO { var trainingAssignments = from a in db.TrainingAssignments where a.UserID == userID && a.Deleted != true select a; return trainingAssignments.ToList(); -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -390,7 +439,9 @@ public class TrainingDMO { string exception = e.ToString(); Console.WriteLine(e); } -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -410,7 +461,9 @@ public class TrainingDMO { string exception = e.ToString(); Console.WriteLine(e); } -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -431,7 +484,9 @@ public class TrainingDMO { DeleteTrainingAssignment(trainingAssignment.ID); DeleteTrainingDocAck(trainingAssignment.ID); } -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -451,7 +506,9 @@ public class TrainingDMO { } DeleteTrainingAssignment(item.ID); } -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -478,7 +535,9 @@ public class TrainingDMO { } else { return false; } -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -488,7 +547,9 @@ public class TrainingDMO { FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); List openTrainings = (from a in db.Trainings where a.Status != true && a.Deleted != true select a).ToList(); return openTrainings; -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } @@ -498,7 +559,9 @@ public class TrainingDMO { FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); List openAssignments = (from a in FabApprovalDB.TrainingAssignments where a.TrainingID == trainingID && a.status != true && a.Deleted != true select a).ToList(); return openAssignments; -#else +#endif + +#if NET8 throw new NotImplementedException(); #endif } diff --git a/Fab2ApprovalSystem/Fab2ApprovalSystem.csproj b/Fab2ApprovalSystem/Fab2ApprovalSystem.csproj index 6a98c01..3cbe363 100644 --- a/Fab2ApprovalSystem/Fab2ApprovalSystem.csproj +++ b/Fab2ApprovalSystem/Fab2ApprovalSystem.csproj @@ -321,6 +321,7 @@ + diff --git a/Fab2ApprovalSystem/Global.asax.cs b/Fab2ApprovalSystem/Global.asax.cs index 8dcb2c7..840f8fb 100644 --- a/Fab2ApprovalSystem/Global.asax.cs +++ b/Fab2ApprovalSystem/Global.asax.cs @@ -5,7 +5,9 @@ using System.Linq; using System.Web; using System.Web.Hosting; using System.Web.Http; +#if !NET8 using System.Web.Mvc; +#endif using System.Web.Optimization; using System.Web.Routing; using System.Web.Security; @@ -63,7 +65,7 @@ public class MvcApplication : System.Web.HttpApplication { protected void Application_EndRequest() { var context = new HttpContextWrapper(Context); - // Do a direct 401 unauthorized +#if !NET8 if (Context.Response.StatusCode == 301 && context.Request.IsAjaxRequest()) { Context.Response.Clear(); Context.Response.StatusCode = 401; @@ -72,18 +74,27 @@ public class MvcApplication : System.Web.HttpApplication { context.Response.Clear(); context.Response.StatusCode = 401; } +#endif +#if NET8 + if (Context.Response.StatusCode == 301 && context.Request.Headers.TryGetValue("X-Requested-With", out Microsoft.Extensions.Primitives.StringValues strings) && strings[0] == "XMLHttpRequest") { + Context.Response.Clear(); + Context.Response.StatusCode = 401; + } else if (FormsAuthentication.IsEnabled && context.Response.StatusCode == 302 + && context.Request.Headers.TryGetValue("X-Requested-With", out Microsoft.Extensions.Primitives.StringValues strings) && strings[0] == "XMLHttpRequest") { + context.Response.Clear(); + context.Response.StatusCode = 401; + } +#endif } protected void Session_Start(object sender, EventArgs e) { - Session[GlobalVars.ECN_VIEW_OPTION] = "Pending Approvals"; + GlobalVars.SetECNViewOption(Session, "Pending Approvals"); } protected void Session_End(object sender, EventArgs e) { // FormsAuthentication.SignOut(); try { - Session[GlobalVars.SESSION_USERNAME] = ""; - Session[GlobalVars.SESSION_USERID] = ""; - Session[GlobalVars.IS_ADMIN] = null; + GlobalVars.EndSession(Session); } catch (Exception ex) { Functions.WriteEvent(null, @User.Identity.Name + "\r\n Session Closed - \r\n" + ex.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); } diff --git a/Fab2ApprovalSystem/Misc/ExcelData.cs b/Fab2ApprovalSystem/Misc/ExcelData.cs index 7159114..2390ace 100644 --- a/Fab2ApprovalSystem/Misc/ExcelData.cs +++ b/Fab2ApprovalSystem/Misc/ExcelData.cs @@ -2,7 +2,9 @@ using ExcelDataReader; -#else +#endif + +#if !NET8 using Excel; @@ -94,7 +96,9 @@ public class ExcelData { public IEnumerable getData(bool firstRowIsColumnNames = true) => throw new NotImplementedException(); -#else +#endif + +#if !NET8 public IEnumerable getData(bool firstRowIsColumnNames = true) { IExcelDataReader reader = getExcelReader(); diff --git a/Fab2ApprovalSystem/Misc/GlobalVars.cs b/Fab2ApprovalSystem/Misc/GlobalVars.cs index 12a5af7..f3f401f 100644 --- a/Fab2ApprovalSystem/Misc/GlobalVars.cs +++ b/Fab2ApprovalSystem/Misc/GlobalVars.cs @@ -6,10 +6,15 @@ namespace Fab2ApprovalSystem.Misc; public class GlobalVars { public int USER_ID; -#else + +#endif + +#if NET8 + public static class GlobalVars { public static int USER_ID = 0; + #endif public const string SESSION_USERNAME = "UserName"; public const string ApplicationName = "LotDisposition"; @@ -98,4 +103,268 @@ public static class GlobalVars { Main, D1, D2, D3, D4, D5, D6, D7, D8, CF } +#if !NET8 + + public static void EndSession(System.Web.SessionState.HttpSessionState session) { + session[SESSION_USERNAME] = ""; + session[SESSION_USERID] = ""; + session[IS_ADMIN] = null; + } + + public static bool IsAdminValueNull(System.Web.SessionState.HttpSessionState session) => + session[IS_ADMIN] == null; + + public static bool IsUserIdValueNotNull(System.Web.SessionState.HttpSessionState session) => + session[SESSION_USERID] != null; + + public static bool IsAdminValueNotNull(System.Web.SessionState.HttpSessionState session) => + session[IS_ADMIN] != null; + + public static bool IsUserNameNull(System.Web.SessionState.HttpSessionState session) => + session[SESSION_USERNAME] == null; + + public static bool IsAdmin(System.Web.SessionState.HttpSessionState session) => + bool.Parse(session[IS_ADMIN].ToString()); + + public static bool IsManager(System.Web.SessionState.HttpSessionState session) => + bool.Parse(session[IS_MANAGER].ToString()); + + public static bool IsOOO(System.Web.SessionState.HttpSessionState session) => + bool.Parse(session[OOO].ToString()); + + public static bool GetCreateNewRevision(System.Web.SessionState.HttpSessionState session) => + bool.Parse(session["CreateNewRevision"].ToString()); + + public static bool GetCreateLotTravNewRevision(System.Web.SessionState.HttpSessionState session) => + bool.Parse(session["CreateLotTravNewRevision"].ToString()); + + public static int GetUserId(System.Web.SessionState.HttpSessionState session) => + int.Parse(GetUserIdValue(session)); + + public static string GetUserIdValue(System.Web.SessionState.HttpSessionState session) => + session[SESSION_USERID].ToString(); + + public static string GetJWT(System.Web.SessionState.HttpSessionState session) => + session["JWT"].ToString(); + + public static string GetRefreshToken(System.Web.SessionState.HttpSessionState session) => + session["RefreshToken"].ToString(); + + public static string GetAllDocumentsFilterData(System.Web.SessionState.HttpSessionState session) => + session["AllDocumentsFilterData"].ToString(); + + public static string GetSWRFilterData(System.Web.SessionState.HttpSessionState session) => + session["SWRFilterData"].ToString(); + + public static string GetPCRBFilterData(System.Web.SessionState.HttpSessionState session) => + session["PCRBFilterData"].ToString(); + + public static string GetUserName(System.Web.SessionState.HttpSessionState session) => + session[SESSION_USERNAME].ToString(); + + public static bool GetCanCreatePartsRequest(System.Web.SessionState.HttpSessionState session) => + bool.Parse(session[CAN_CREATE_PARTS_REQUEST].ToString()); + + public static void SetECNViewOption(System.Web.SessionState.HttpSessionState session, string value) => + session[ECN_VIEW_OPTION] = value; + + public static void SetCreateNewRevision(System.Web.SessionState.HttpSessionState session, bool value) => + session["CreateNewRevision"] = value; + + public static void SetSWRFilterData(System.Web.SessionState.HttpSessionState session, string value) => + session["SWRFilterData"] = value; + + public static void SetPCRBFilterData(System.Web.SessionState.HttpSessionState session, string value) => + session["PCRBFilterData"] = value; + + public static void SetAllDocumentsFilterData(System.Web.SessionState.HttpSessionState session, string value) => + session["AllDocumentsFilterData"] = value; + + public static void SetCreateLotTravNewRevision(System.Web.SessionState.HttpSessionState session, bool value) => + session["CreateLotTravNewRevision"] = value; + + public static void SetOOO(System.Web.SessionState.HttpSessionState session, bool value) => + session[OOO] = value; + + public static bool IsAdminValueNull(System.Web.HttpSessionStateBase session) => + session[IS_ADMIN] == null; + + public static bool IsUserIdValueNotNull(System.Web.HttpSessionStateBase session) => + session[SESSION_USERID] != null; + + public static bool IsAdminValueNotNull(System.Web.HttpSessionStateBase session) => + session[IS_ADMIN] != null; + + public static bool IsUserNameNull(System.Web.HttpSessionStateBase session) => + session[SESSION_USERNAME] == null; + + public static bool IsAdmin(System.Web.HttpSessionStateBase session) => + bool.Parse(session[IS_ADMIN].ToString()); + + public static bool IsManager(System.Web.HttpSessionStateBase session) => + bool.Parse(session[IS_MANAGER].ToString()); + + public static bool IsOOO(System.Web.HttpSessionStateBase session) => + bool.Parse(session[OOO].ToString()); + + public static bool GetCreateNewRevision(System.Web.HttpSessionStateBase session) => + bool.Parse(session["CreateNewRevision"].ToString()); + + public static bool GetCreateLotTravNewRevision(System.Web.HttpSessionStateBase session) => + bool.Parse(session["CreateLotTravNewRevision"].ToString()); + + public static int GetUserId(System.Web.HttpSessionStateBase session) => + int.Parse(GetUserIdValue(session)); + + public static string GetUserIdValue(System.Web.HttpSessionStateBase session) => + session[SESSION_USERID].ToString(); + + public static string GetJWT(System.Web.HttpSessionStateBase session) => + session["JWT"].ToString(); + + public static string GetRefreshToken(System.Web.HttpSessionStateBase session) => + session["RefreshToken"].ToString(); + + public static string GetAllDocumentsFilterData(System.Web.HttpSessionStateBase session) => + session["AllDocumentsFilterData"].ToString(); + + public static string GetSWRFilterData(System.Web.HttpSessionStateBase session) => + session["SWRFilterData"].ToString(); + + public static string GetPCRBFilterData(System.Web.HttpSessionStateBase session) => + session["PCRBFilterData"].ToString(); + + public static string GetUserName(System.Web.HttpSessionStateBase session) => + session[SESSION_USERNAME].ToString(); + + public static bool GetCanCreatePartsRequest(System.Web.HttpSessionStateBase session) => + bool.Parse(session[CAN_CREATE_PARTS_REQUEST].ToString()); + + public static void SetECNViewOption(System.Web.HttpSessionStateBase session, string value) => + session[ECN_VIEW_OPTION] = value; + + public static void SetCreateNewRevision(System.Web.HttpSessionStateBase session, bool value) => + session["CreateNewRevision"] = value; + + public static void SetSWRFilterData(System.Web.HttpSessionStateBase session, string value) => + session["SWRFilterData"] = value; + + public static void SetPCRBFilterData(System.Web.HttpSessionStateBase session, string value) => + session["PCRBFilterData"] = value; + + public static void SetAllDocumentsFilterData(System.Web.HttpSessionStateBase session, string value) => + session["AllDocumentsFilterData"] = value; + + public static void SetCreateLotTravNewRevision(System.Web.HttpSessionStateBase session, bool value) => + session["CreateLotTravNewRevision"] = value; + + public static void SetOOO(System.Web.HttpSessionStateBase session, bool value) => + session[OOO] = value; + + public static void SetSessionParameters(System.Web.HttpSessionStateBase session, LoginResult loginResult, LoginModel user) { + session["JWT"] = loginResult.AuthTokens.JwtToken; + session["RefreshToken"] = loginResult.AuthTokens.RefreshToken; + + session[SESSION_USERID] = user.UserID; + session[SESSION_USERNAME] = user.FullName; + session[IS_ADMIN] = user.IsAdmin; + session[IS_MANAGER] = user.IsManager; + session[OOO] = user.OOO; + bool check = user.IsAdmin || Fab2ApprovalSystem.Controllers.PartsRequestController.CanCreatePartsRequest(user.UserID); + session[CAN_CREATE_PARTS_REQUEST] = check; + } +#endif + +#if NET8 + + public static bool IsAdminValueNull(Microsoft.AspNetCore.Http.ISession session) => + Microsoft.AspNetCore.Http.SessionExtensions.Get(session, IS_ADMIN) == null; + + public static bool IsUserIdValueNotNull(Microsoft.AspNetCore.Http.ISession session) => + Microsoft.AspNetCore.Http.SessionExtensions.Get(session, SESSION_USERID) != null; + + public static bool IsAdminValueNotNull(Microsoft.AspNetCore.Http.ISession session) => + Microsoft.AspNetCore.Http.SessionExtensions.Get(session, IS_ADMIN) != null; + + public static bool IsUserNameNull(Microsoft.AspNetCore.Http.ISession session) => + Microsoft.AspNetCore.Http.SessionExtensions.Get(session, SESSION_USERNAME) == null; + + public static bool IsAdmin(Microsoft.AspNetCore.Http.ISession session) => + bool.Parse(Microsoft.AspNetCore.Http.SessionExtensions.GetString(session, IS_ADMIN)); + + public static bool IsManager(Microsoft.AspNetCore.Http.ISession session) => + bool.Parse(Microsoft.AspNetCore.Http.SessionExtensions.GetString(session, IS_MANAGER)); + + public static bool IsOOO(Microsoft.AspNetCore.Http.ISession session) => + bool.Parse(Microsoft.AspNetCore.Http.SessionExtensions.GetString(session, OOO)); + + public static bool GetCreateNewRevision(Microsoft.AspNetCore.Http.ISession session) => + bool.Parse(Microsoft.AspNetCore.Http.SessionExtensions.GetString(session, "CreateNewRevision")); + + public static bool GetCreateLotTravNewRevision(Microsoft.AspNetCore.Http.ISession session) => + bool.Parse(Microsoft.AspNetCore.Http.SessionExtensions.GetString(session, "CreateLotTravNewRevision")); + + public static int GetUserId(Microsoft.AspNetCore.Http.ISession session) => + int.Parse(GetUserIdValue(session)); + + public static string GetUserIdValue(Microsoft.AspNetCore.Http.ISession session) => + Microsoft.AspNetCore.Http.SessionExtensions.GetString(session, SESSION_USERID); + + public static string GetJWT(Microsoft.AspNetCore.Http.ISession session) => + Microsoft.AspNetCore.Http.SessionExtensions.GetString(session, "JWT"); + + public static string GetRefreshToken(Microsoft.AspNetCore.Http.ISession session) => + Microsoft.AspNetCore.Http.SessionExtensions.GetString(session, "RefreshToken"); + + public static string GetAllDocumentsFilterData(Microsoft.AspNetCore.Http.ISession session) => + Microsoft.AspNetCore.Http.SessionExtensions.GetString(session, "AllDocumentsFilterData"); + + public static string GetSWRFilterData(Microsoft.AspNetCore.Http.ISession session) => + Microsoft.AspNetCore.Http.SessionExtensions.GetString(session, "SWRFilterData"); + + public static string GetPCRBFilterData(Microsoft.AspNetCore.Http.ISession session) => + Microsoft.AspNetCore.Http.SessionExtensions.GetString(session, "PCRBFilterData"); + + public static string GetUserName(Microsoft.AspNetCore.Http.ISession session) => + Microsoft.AspNetCore.Http.SessionExtensions.GetString(session, SESSION_USERNAME); + + public static bool GetCanCreatePartsRequest(Microsoft.AspNetCore.Http.ISession session) => + bool.Parse(Microsoft.AspNetCore.Http.SessionExtensions.GetString(session, CAN_CREATE_PARTS_REQUEST)); + + public static void SetECNViewOption(Microsoft.AspNetCore.Http.ISession session, string value) => + Microsoft.AspNetCore.Http.SessionExtensions.SetString(session, ECN_VIEW_OPTION, value); + + public static void SetSWRFilterData(Microsoft.AspNetCore.Http.ISession session, string value) => + Microsoft.AspNetCore.Http.SessionExtensions.SetString(session, "SWRFilterData", value); + + public static void SetPCRBFilterData(Microsoft.AspNetCore.Http.ISession session, string value) => + Microsoft.AspNetCore.Http.SessionExtensions.SetString(session, "PCRBFilterData", value); + + public static void SetAllDocumentsFilterData(Microsoft.AspNetCore.Http.ISession session, string value) => + Microsoft.AspNetCore.Http.SessionExtensions.SetString(session, "AllDocumentsFilterData", value); + + public static void SetCreateNewRevision(Microsoft.AspNetCore.Http.ISession session, bool value) => + Microsoft.AspNetCore.Http.SessionExtensions.SetString(session, "CreateNewRevision", value.ToString()); + + public static void SetCreateLotTravNewRevision(Microsoft.AspNetCore.Http.ISession session, bool value) => + Microsoft.AspNetCore.Http.SessionExtensions.SetString(session, "CreateLotTravNewRevision", value.ToString()); + + public static void SetOOO(Microsoft.AspNetCore.Http.ISession session, bool value) => + Microsoft.AspNetCore.Http.SessionExtensions.SetString(session, OOO, value.ToString()); + + public static void SetSessionParameters(Microsoft.AspNetCore.Http.ISession session, LoginResult loginResult, LoginModel user) { + Microsoft.AspNetCore.Http.SessionExtensions.SetString(session, "JWT", loginResult.AuthTokens.JwtToken); + Microsoft.AspNetCore.Http.SessionExtensions.SetString(session, "RefreshToken", loginResult.AuthTokens.RefreshToken); + + Microsoft.AspNetCore.Http.SessionExtensions.SetInt32(session, SESSION_USERID, user.UserID); + Microsoft.AspNetCore.Http.SessionExtensions.SetString(session, SESSION_USERNAME, user.FullName); + Microsoft.AspNetCore.Http.SessionExtensions.SetString(session, IS_ADMIN, user.IsAdmin.ToString()); + Microsoft.AspNetCore.Http.SessionExtensions.SetString(session, IS_MANAGER, user.IsManager.ToString()); + Microsoft.AspNetCore.Http.SessionExtensions.SetString(session, OOO, user.OOO.ToString()); + // bool check = user.IsAdmin || Fab2ApprovalSystem.Controllers.PartsRequestController.CanCreatePartsRequest(user.UserID); + // Microsoft.AspNetCore.Http.SessionExtensions.SetString(session, CAN_CREATE_PARTS_REQUEST, check.ToString()); + } + +#endif + } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Misc/SessionExpireFilterAttribute.cs b/Fab2ApprovalSystem/Misc/SessionExpireFilterAttribute.cs index 6e97b58..849fcbf 100644 --- a/Fab2ApprovalSystem/Misc/SessionExpireFilterAttribute.cs +++ b/Fab2ApprovalSystem/Misc/SessionExpireFilterAttribute.cs @@ -4,7 +4,9 @@ using System; using System.Collections.Generic; using System.Linq; using System.Web; +#if !NET8 using System.Web.Mvc; +#endif namespace Fab2ApprovalSystem.Misc { @@ -16,7 +18,7 @@ namespace Fab2ApprovalSystem.Misc { // check if session is supported - if (session[GlobalVars.SESSION_USERNAME] == null) { + if (GlobalVars.IsUserNameNull(session)) { // check if a new session id was generated // this will force MVC to use the standard login redirect, enabling ReturnURL functionality diff --git a/Fab2ApprovalSystem/Models/AppSettings.cs b/Fab2ApprovalSystem/Models/AppSettings.cs index b193aca..ec8f89c 100644 --- a/Fab2ApprovalSystem/Models/AppSettings.cs +++ b/Fab2ApprovalSystem/Models/AppSettings.cs @@ -26,6 +26,9 @@ public class AppSettings { string ifxContainer, string ifxDomain, bool isInfineonDomain, + string? jwtAudience, + string? jwtIssuer, + string? jwtKey, string lotTempPipeLine, string mesaTemplateFiles, string nDriveURL, @@ -68,6 +71,9 @@ public class AppSettings { IFXContainer = ifxContainer; IFXDomain = ifxDomain; IsInfineonDomain = isInfineonDomain; + JwtAudience = jwtAudience; + JwtIssuer = jwtIssuer; + JwtKey = jwtKey; LotTempPipeLine = lotTempPipeLine; MesaTemplateFiles = mesaTemplateFiles; NDriveURL = nDriveURL; @@ -112,6 +118,9 @@ public class AppSettings { public string IFXContainer { get; } public string IFXDomain { get; } public bool IsInfineonDomain { get; } + public string? JwtAudience { get; } + public string? JwtIssuer { get; } + public string? JwtKey { get; } public string LotTempPipeLine { get; } public string MesaTemplateFiles { get; } public string NAContainer { get; } @@ -223,6 +232,9 @@ public class AppSettings { string? workingDirectoryName = ConfigurationManager.AppSettings["WorkingDirectoryName"]?.ToString(); string wasmClientUrl = Environment.GetEnvironmentVariable("FabApprovalWasmClientUrl") ?? "https://localhost:7255"; + string? jwtAudience = ConfigurationManager.AppSettings["JwtAudience"]?.ToString(); + string? jwtIssuer = ConfigurationManager.AppSettings["JwtIssuer"]?.ToString(); + string? jwtKey = ConfigurationManager.AppSettings["JwtKey"]?.ToString(); result = new(adminNotificationRecepient: adminNotificationRecepient, apiBaseUrl: apiBaseUrl, attachmentFolder: attachmentFolder, @@ -242,6 +254,9 @@ public class AppSettings { ifxContainer: ifxContainer, ifxDomain: ifxDomain, isInfineonDomain: Misc.GlobalVars.IS_INFINEON_DOMAIN, + jwtAudience: jwtAudience, + jwtIssuer: jwtIssuer, + jwtKey: jwtKey, lotTempPipeLine: lotTempPipeLine, mesaTemplateFiles: Misc.GlobalVars.MesaTemplateFiles, naContainer: naContainer, diff --git a/Fab2ApprovalSystem/Models/HttpException.cs b/Fab2ApprovalSystem/Models/HttpException.cs new file mode 100644 index 0000000..738212f --- /dev/null +++ b/Fab2ApprovalSystem/Models/HttpException.cs @@ -0,0 +1,37 @@ +#if NET8 + +using System; + +namespace Fab2ApprovalSystem.Models; + +public class HttpException : Exception { + private readonly int httpStatusCode; + + public HttpException(int httpStatusCode) { + this.httpStatusCode = httpStatusCode; + } + + public HttpException(System.Net.HttpStatusCode httpStatusCode) { + this.httpStatusCode = (int)httpStatusCode; + } + + public HttpException(int httpStatusCode, string message) : base(message) { + this.httpStatusCode = httpStatusCode; + } + + public HttpException(System.Net.HttpStatusCode httpStatusCode, string message) : base(message) { + this.httpStatusCode = (int)httpStatusCode; + } + + public HttpException(int httpStatusCode, string message, Exception inner) : base(message, inner) { + this.httpStatusCode = httpStatusCode; + } + + public HttpException(System.Net.HttpStatusCode httpStatusCode, string message, Exception inner) : base(message, inner) { + this.httpStatusCode = (int)httpStatusCode; + } + + public int StatusCode { get { return httpStatusCode; } } +} + +#endif \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/LoginResult.cs b/Fab2ApprovalSystem/Models/LoginResult.cs index 97b103b..5d23a21 100644 --- a/Fab2ApprovalSystem/Models/LoginResult.cs +++ b/Fab2ApprovalSystem/Models/LoginResult.cs @@ -3,6 +3,7 @@ public class LoginResult { public bool IsAuthenticated { get; set; } + public User User { get; set; } public AuthTokens AuthTokens { get; set; } } \ No newline at end of file diff --git a/Fab2ApprovalSystem/Models/User.cs b/Fab2ApprovalSystem/Models/User.cs new file mode 100644 index 0000000..1859741 --- /dev/null +++ b/Fab2ApprovalSystem/Models/User.cs @@ -0,0 +1,30 @@ +using System; + +namespace Fab2ApprovalSystem.Models; + +public class User { + public int UserID { get; set; } + public string LoginID { get; set; } + public string FirstName { get; set; } + public string LastName { get; set; } + public string Email { get; set; } + public bool IsAdmin { get; set; } = false; + public bool IsManager { get; set; } = false; + public bool IsActive { get; set; } = false; + public bool OOO { get; set; } = false; + public DateTime OOOStartDate { get; set; } + public DateTime OOOExpirationDate { get; set; } + public int DelegatedTo { get; set; } + + public string GetFullName() => + $"{FirstName} {LastName}"; + + public override bool Equals(object? obj) { + User? u = obj as User; + + return u is not null && u.UserID == UserID; + } + + public override int GetHashCode() => + UserID.GetHashCode(); +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/PdfGenerator/BinaryContentResult.cs b/Fab2ApprovalSystem/PdfGenerator/BinaryContentResult.cs index ba08fc7..461925d 100644 --- a/Fab2ApprovalSystem/PdfGenerator/BinaryContentResult.cs +++ b/Fab2ApprovalSystem/PdfGenerator/BinaryContentResult.cs @@ -1,43 +1,47 @@ #if !NET8 +using System.Web; +using System.Web.Mvc; +using System.Web.Security; +#endif -// -------------------------------------------------------------------------------------------------------------------- -// -// http://www.SemanticArchitecture.net pkalkie@gmail.com -// -// -// An ActionResult used to send binary data to the browser. -// -// -------------------------------------------------------------------------------------------------------------------- +#if NET8 +using Microsoft.AspNetCore.Mvc; +#endif -namespace Fab2ApprovalSystem.PdfGenerator { - using System.IO; - using System.Web; - using System.Web.Mvc; +#if !NET8 +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Security.Claims; +using System.Threading.Tasks; +using System.IO; +#endif - /// - /// An ActionResult used to send binary data to the browser. - /// - public class BinaryContentResult : ActionResult { - private readonly string contentType; - private readonly byte[] contentBytes; +namespace Fab2ApprovalSystem.PdfGenerator; - public BinaryContentResult(byte[] contentBytes, string contentType) { - this.contentBytes = contentBytes; - this.contentType = contentType; - } +public class BinaryContentResult : ActionResult { + private readonly string contentType; + private readonly byte[] contentBytes; - public override void ExecuteResult(ControllerContext context) { - var response = context.HttpContext.Response; - response.Clear(); - response.Cache.SetCacheability(HttpCacheability.Public); - response.ContentType = this.contentType; + public BinaryContentResult(byte[] contentBytes, string contentType) { + this.contentBytes = contentBytes; + this.contentType = contentType; + } - using (var stream = new MemoryStream(this.contentBytes)) { - stream.WriteTo(response.OutputStream); - stream.Flush(); - } +#if !NET8 + public override void ExecuteResult(ControllerContext context) { + var response = context.HttpContext.Response; + response.Clear(); + response.Cache.SetCacheability(HttpCacheability.Public); + response.ContentType = contentType; + + using (var stream = new MemoryStream(contentBytes)) { + stream.WriteTo(response.OutputStream); + stream.Flush(); } } -} -#endif \ No newline at end of file +#endif + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/PdfGenerator/FakeView.cs b/Fab2ApprovalSystem/PdfGenerator/FakeView.cs index 1aff427..05c79bf 100644 --- a/Fab2ApprovalSystem/PdfGenerator/FakeView.cs +++ b/Fab2ApprovalSystem/PdfGenerator/FakeView.cs @@ -1,28 +1,36 @@ +using System; +using System.IO; +using System.Threading.Tasks; + #if !NET8 +using System.Web; +using System.Web.Mvc; +using System.Web.Security; +#endif -// -------------------------------------------------------------------------------------------------------------------- -// -// http://www.SemanticArchitecture.net pkalkie@gmail.com -// -// -// Defines the FakeView type. -// -// -------------------------------------------------------------------------------------------------------------------- +#if NET8 +using Microsoft.AspNetCore.Mvc.Rendering; +using Microsoft.AspNetCore.Mvc.ViewEngines; +#endif -namespace Fab2ApprovalSystem.PdfGenerator { - using System; - using System.IO; - using System.Web.Mvc; +#if !NET8 +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Security.Claims; +#endif - public class FakeView : IView { - #region IView Members +namespace Fab2ApprovalSystem.PdfGenerator; - public void Render(ViewContext viewContext, TextWriter writer) { - throw new NotImplementedException(); - } +public class FakeView : IView { - #endregion + public void Render(ViewContext viewContext, TextWriter writer) { + throw new NotImplementedException(); } -} -#endif \ No newline at end of file +#if NET8 + string IView.Path => throw new NotImplementedException(); + Task IView.RenderAsync(ViewContext context) => throw new NotImplementedException(); +#endif + +} diff --git a/Fab2ApprovalSystem/PdfGenerator/HtmlViewRenderer.cs b/Fab2ApprovalSystem/PdfGenerator/HtmlViewRenderer.cs index d3ba69d..9eb85b5 100644 --- a/Fab2ApprovalSystem/PdfGenerator/HtmlViewRenderer.cs +++ b/Fab2ApprovalSystem/PdfGenerator/HtmlViewRenderer.cs @@ -1,49 +1,59 @@ + +#if !NET8 +using System.Web; +using System.Web.Mvc; +using System.Web.Mvc.Html; +using System.Web.Security; +#endif + +#if NET8 +using Microsoft.AspNetCore.Mvc; +#endif + +#if !NET8 +using System; +using System.IO; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Security.Claims; +using System.Threading.Tasks; +#endif + +using System.Text; + +namespace Fab2ApprovalSystem.PdfGenerator; + +public class HtmlViewRenderer { + + public string RenderViewToString(Controller controller, string viewName, object viewData) { + StringBuilder renderedView = new(); +#if !NET8 + using (StringWriter responseWriter = new(renderedView)) { + HttpResponse fakeResponse = new(responseWriter); + HttpContext fakeContext = new(HttpContext.Current.Request, fakeResponse); + ControllerContext fakeControllerContext = new(new HttpContextWrapper(fakeContext), controller.ControllerContext.RouteData, controller.ControllerContext.Controller); + + var oldContext = HttpContext.Current; + HttpContext.Current = fakeContext; + + using (var viewPage = new ViewPage()) { + HtmlHelper html = new HtmlHelper(CreateViewContext(responseWriter, fakeControllerContext), viewPage); + html.RenderPartial(viewName, viewData); + HttpContext.Current = oldContext; + } + } +#endif + + return renderedView.ToString(); + } + #if !NET8 -// -------------------------------------------------------------------------------------------------------------------- -// -// http://www.SemanticArchitecture.net pkalkie@gmail.com -// -// -// This class is responsible for rendering a HTML view to a string. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace Fab2ApprovalSystem.PdfGenerator { - using System.IO; - using System.Text; - using System.Web; - using System.Web.Mvc; - using System.Web.Mvc.Html; - - /// - /// This class is responsible for rendering a HTML view into a string. - /// - public class HtmlViewRenderer { - public string RenderViewToString(Controller controller, string viewName, object viewData) { - var renderedView = new StringBuilder(); - using (var responseWriter = new StringWriter(renderedView)) { - var fakeResponse = new HttpResponse(responseWriter); - var fakeContext = new HttpContext(HttpContext.Current.Request, fakeResponse); - var fakeControllerContext = new ControllerContext(new HttpContextWrapper(fakeContext), controller.ControllerContext.RouteData, controller.ControllerContext.Controller); - - var oldContext = HttpContext.Current; - HttpContext.Current = fakeContext; - - using (var viewPage = new ViewPage()) { - var html = new HtmlHelper(CreateViewContext(responseWriter, fakeControllerContext), viewPage); - html.RenderPartial(viewName, viewData); - HttpContext.Current = oldContext; - } - } - - return renderedView.ToString(); - } - - private static ViewContext CreateViewContext(TextWriter responseWriter, ControllerContext fakeControllerContext) { - return new ViewContext(fakeControllerContext, new FakeView(), new ViewDataDictionary(), new TempDataDictionary(), responseWriter); - } + private static ViewContext CreateViewContext(TextWriter responseWriter, ControllerContext fakeControllerContext) { + return new ViewContext(fakeControllerContext, new FakeView(), new ViewDataDictionary(), new TempDataDictionary(), responseWriter); } -} -#endif \ No newline at end of file +#endif + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/PdfGenerator/PdfViewController.cs b/Fab2ApprovalSystem/PdfGenerator/PdfViewController.cs index f55bdef..4e3c2c5 100644 --- a/Fab2ApprovalSystem/PdfGenerator/PdfViewController.cs +++ b/Fab2ApprovalSystem/PdfGenerator/PdfViewController.cs @@ -1,54 +1,56 @@ #if !NET8 +using System.Web; +using System.Web.Mvc; +using System.Web.Security; +#endif -// -------------------------------------------------------------------------------------------------------------------- -// -// http://www.SemanticArchitecture.net pkalkie@gmail.com -// -// -// Extends the controller with functionality for rendering PDF views -// -// -------------------------------------------------------------------------------------------------------------------- +#if !NET8 +using System; +using System.IO; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Security.Claims; +using System.Threading.Tasks; +#endif -namespace Fab2ApprovalSystem.PdfGenerator { - using System.Web.Mvc; - using System.IO; +namespace Fab2ApprovalSystem.PdfGenerator; - /// - /// Extends the controller with functionality for rendering PDF views - /// - public class PdfViewController : Controller { - private readonly HtmlViewRenderer htmlViewRenderer; - private readonly StandardPdfRenderer standardPdfRenderer; +#if !NET8 - public PdfViewController() { - this.htmlViewRenderer = new HtmlViewRenderer(); - this.standardPdfRenderer = new StandardPdfRenderer(); - } +public class PdfViewController : Controller { - protected ActionResult ViewPdf(string pageTitle, string viewName, object model) { - // Render the view html to a string. - string htmlText = this.htmlViewRenderer.RenderViewToString(this, viewName, model); + private readonly HtmlViewRenderer htmlViewRenderer; + private readonly StandardPdfRenderer standardPdfRenderer; - // Let the html be rendered into a PDF document through iTextSharp. - byte[] buffer = standardPdfRenderer.Render(htmlText, pageTitle); + public PdfViewController() { + htmlViewRenderer = new HtmlViewRenderer(); + standardPdfRenderer = new StandardPdfRenderer(); + } - // Return the PDF as a binary stream to the client. - return new BinaryContentResult(buffer, "application/pdf"); - } + protected ActionResult ViewPdf(string pageTitle, string viewName, object model) { + // Render the view html to a string. + string htmlText = htmlViewRenderer.RenderViewToString(this, viewName, model); - protected void SavePdf(string fileName, string viewName, object model) { - // Render the view html to a string. - string htmlText = this.htmlViewRenderer.RenderViewToString(this, viewName, model); + // Let the html be rendered into a PDF document through iTextSharp. + byte[] buffer = standardPdfRenderer.Render(htmlText, pageTitle); - // Let the html be rendered into a PDF document through iTextSharp. - byte[] buffer = standardPdfRenderer.Render(htmlText, ""); + // Return the PDF as a binary stream to the client. + return new BinaryContentResult(buffer, "application/pdf"); + } - using (FileStream fs = new FileStream(fileName, FileMode.Create)) { - fs.Write(buffer, 0, buffer.Length); - } + protected void SavePdf(string fileName, string viewName, object model) { + // Render the view html to a string. + string htmlText = htmlViewRenderer.RenderViewToString(this, viewName, model); + // Let the html be rendered into a PDF document through iTextSharp. + byte[] buffer = standardPdfRenderer.Render(htmlText, ""); + + using (FileStream fs = new(fileName, FileMode.Create)) { + fs.Write(buffer, 0, buffer.Length); } } + } #endif \ No newline at end of file diff --git a/Fab2ApprovalSystem/PdfGenerator/PrintHeaderFooter.cs b/Fab2ApprovalSystem/PdfGenerator/PrintHeaderFooter.cs index 00322fc..23af4ef 100644 --- a/Fab2ApprovalSystem/PdfGenerator/PrintHeaderFooter.cs +++ b/Fab2ApprovalSystem/PdfGenerator/PrintHeaderFooter.cs @@ -1,79 +1,102 @@ +#if !NET8 +using System.Web; +using System.Web.Mvc; +using System.Web.Security; +#endif #if !NET8 -namespace Fab2ApprovalSystem.PdfGenerator { - using iTextSharp.text; - using iTextSharp.text.pdf; +using iTextSharp.text; +using iTextSharp.text.pdf; +#endif - using System; +#if !NET8 +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Security.Claims; +using System.Threading.Tasks; +#endif - /// - /// This class represents the standard header and footer for a PDF print. - /// application. - /// - public class PrintHeaderFooter : PdfPageEventHelper { - private PdfContentByte pdfContent; - private PdfTemplate pageNumberTemplate; - private BaseFont baseFont; - private DateTime printTime; +namespace Fab2ApprovalSystem.PdfGenerator; - public string Title { get; set; } +#if !NET8 - public override void OnOpenDocument(PdfWriter writer, Document document) { - printTime = DateTime.Now; - baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); - pdfContent = writer.DirectContent; - pageNumberTemplate = pdfContent.CreateTemplate(50, 50); - } +public class PrintHeaderFooter : PdfPageEventHelper { - public override void OnStartPage(PdfWriter writer, Document document) { - base.OnStartPage(writer, document); + private PdfContentByte pdfContent; + private PdfTemplate pageNumberTemplate; + private BaseFont baseFont; + private DateTime printTime; +#endif - Rectangle pageSize = document.PageSize; +#if NET8 - if (Title != string.Empty) { - pdfContent.BeginText(); - pdfContent.SetFontAndSize(baseFont, 11); - pdfContent.SetRGBColorFill(0, 0, 0); - pdfContent.SetTextMatrix(pageSize.GetLeft(40), pageSize.GetTop(40)); - pdfContent.ShowText(Title); - pdfContent.EndText(); - } - } +public class PrintHeaderFooter { - public override void OnEndPage(PdfWriter writer, Document document) { - base.OnEndPage(writer, document); +#endif - int pageN = writer.PageNumber; - string text = pageN + " - "; - float len = baseFont.GetWidthPoint(text, 8); + public string Title { get; set; } - Rectangle pageSize = document.PageSize; - pdfContent = writer.DirectContent; - pdfContent.SetRGBColorFill(100, 100, 100); +#if !NET8 + public override void OnOpenDocument(PdfWriter writer, Document document) { + printTime = DateTime.Now; + baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); + pdfContent = writer.DirectContent; + pageNumberTemplate = pdfContent.CreateTemplate(50, 50); + } + + public override void OnStartPage(PdfWriter writer, Document document) { + base.OnStartPage(writer, document); + + Rectangle pageSize = document.PageSize; + + if (Title != string.Empty) { pdfContent.BeginText(); - pdfContent.SetFontAndSize(baseFont, 8); - pdfContent.SetTextMatrix(pageSize.Width / 2, pageSize.GetBottom(30)); - pdfContent.ShowText(text); + pdfContent.SetFontAndSize(baseFont, 11); + pdfContent.SetRGBColorFill(0, 0, 0); + pdfContent.SetTextMatrix(pageSize.GetLeft(40), pageSize.GetTop(40)); + pdfContent.ShowText(Title); pdfContent.EndText(); - - pdfContent.AddTemplate(pageNumberTemplate, (pageSize.Width / 2) + len, pageSize.GetBottom(30)); - - pdfContent.BeginText(); - pdfContent.SetFontAndSize(baseFont, 8); - pdfContent.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, printTime.ToString(), pageSize.GetRight(40), pageSize.GetBottom(30), 0); - pdfContent.EndText(); - } - - public override void OnCloseDocument(PdfWriter writer, Document document) { - base.OnCloseDocument(writer, document); - - pageNumberTemplate.BeginText(); - pageNumberTemplate.SetFontAndSize(baseFont, 8); - pageNumberTemplate.SetTextMatrix(0, 0); - pageNumberTemplate.ShowText(string.Empty + (writer.PageNumber - 1)); - pageNumberTemplate.EndText(); } } -} -#endif \ No newline at end of file + + public override void OnEndPage(PdfWriter writer, Document document) { + base.OnEndPage(writer, document); + + int pageN = writer.PageNumber; + string text = pageN + " - "; + float len = baseFont.GetWidthPoint(text, 8); + + Rectangle pageSize = document.PageSize; + pdfContent = writer.DirectContent; + pdfContent.SetRGBColorFill(100, 100, 100); + + pdfContent.BeginText(); + pdfContent.SetFontAndSize(baseFont, 8); + pdfContent.SetTextMatrix(pageSize.Width / 2, pageSize.GetBottom(30)); + pdfContent.ShowText(text); + pdfContent.EndText(); + + pdfContent.AddTemplate(pageNumberTemplate, (pageSize.Width / 2) + len, pageSize.GetBottom(30)); + + pdfContent.BeginText(); + pdfContent.SetFontAndSize(baseFont, 8); + pdfContent.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, printTime.ToString(), pageSize.GetRight(40), pageSize.GetBottom(30), 0); + pdfContent.EndText(); + } + + public override void OnCloseDocument(PdfWriter writer, Document document) { + base.OnCloseDocument(writer, document); + + pageNumberTemplate.BeginText(); + pageNumberTemplate.SetFontAndSize(baseFont, 8); + pageNumberTemplate.SetTextMatrix(0, 0); + pageNumberTemplate.ShowText(string.Empty + (writer.PageNumber - 1)); + pageNumberTemplate.EndText(); + } + +#endif + +} \ No newline at end of file diff --git a/Fab2ApprovalSystem/PdfGenerator/StandardPdfRenderer.cs b/Fab2ApprovalSystem/PdfGenerator/StandardPdfRenderer.cs index 27b0946..b4aa92c 100644 --- a/Fab2ApprovalSystem/PdfGenerator/StandardPdfRenderer.cs +++ b/Fab2ApprovalSystem/PdfGenerator/StandardPdfRenderer.cs @@ -8,9 +8,6 @@ using System.IO; namespace Fab2ApprovalSystem.PdfGenerator; -/// -/// This class is responsible for rendering a html text string to a PDF document using the html renderer of iTextSharp. -/// public class StandardPdfRenderer { private const int HorizontalMargin = 40; private const int VerticalMargin = 40; diff --git a/Fab2ApprovalSystem/Utilities/FileUtilities.cs b/Fab2ApprovalSystem/Utilities/FileUtilities.cs index 8c3a03f..aa16899 100644 --- a/Fab2ApprovalSystem/Utilities/FileUtilities.cs +++ b/Fab2ApprovalSystem/Utilities/FileUtilities.cs @@ -20,6 +20,7 @@ using System.Configuration; namespace Fab2ApprovalSystem.Utilities; #if !NET8 + public class FileUtilities : Controller // => System.Web.Mvc.FileContentResult { @@ -28,14 +29,22 @@ public class FileUtilities : Controller // => System.Web.Mvc.FileContentR var result = File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, pathToFile); return (T)Convert.ChangeType(result, typeof(T)); } -#else + +#endif + +#if NET8 + public class FileUtilities { + #endif public byte[] GetFile(string s) { + #if !NET8 FileStream fs = System.IO.File.OpenRead(s); -#else +#endif + +#if NET8 FileStream fs = File.OpenRead(s); #endif byte[] data = new byte[fs.Length]; diff --git a/Fab2ApprovalSystem/Views/Admin/_AdminLayout.cshtml b/Fab2ApprovalSystem/Views/Admin/_AdminLayout.cshtml index c4ec21c..aa585c2 100644 --- a/Fab2ApprovalSystem/Views/Admin/_AdminLayout.cshtml +++ b/Fab2ApprovalSystem/Views/Admin/_AdminLayout.cshtml @@ -34,7 +34,7 @@
@Html.TextBoxFor(model => model.OwnerName, new { id = "txtOwner", @class = "k-textbox", Readonly = "Readonly", style = "background-color:lightblue" }) - @if (Session[GlobalVars.IS_ADMIN] != null) + @if (GlobalVars.IsAdminValueNotNull(Session)) { } @@ -200,7 +200,7 @@
- @if (ViewBag.IsOriginator == "true" || ((bool)Session[GlobalVars.IS_ADMIN])) + @if (ViewBag.IsOriginator == "true" || (GlobalVars.IsAdmin(Session))) { @(Html.Kendo().DropDownList() .Name("IsITAR") diff --git a/Fab2ApprovalSystem/Views/ChangeControl/EditMeetingUpdate.cshtml b/Fab2ApprovalSystem/Views/ChangeControl/EditMeetingUpdate.cshtml index cb3dbc2..95a14de 100644 --- a/Fab2ApprovalSystem/Views/ChangeControl/EditMeetingUpdate.cshtml +++ b/Fab2ApprovalSystem/Views/ChangeControl/EditMeetingUpdate.cshtml @@ -329,7 +329,7 @@ columns.Bound(a => a.Gating).Width("50px"); columns.Bound(a => a.DueDate).Width("50px").Format("{0:MM/dd/yy}").Width("150px"); - if (Session[GlobalVars.IS_ADMIN] != null) + if (GlobalVars.IsAdminValueNotNull(Session)) columns.Command(c => c.Custom("Edit").Click("EditMeetingActionItem")).Width("70px"); //columns.Command(c => c.Destroy()).Width("40px"); diff --git a/Fab2ApprovalSystem/Views/ChangeControl/ReadOnlyCC.cshtml b/Fab2ApprovalSystem/Views/ChangeControl/ReadOnlyCC.cshtml index f0aac23..ebc9fcc 100644 --- a/Fab2ApprovalSystem/Views/ChangeControl/ReadOnlyCC.cshtml +++ b/Fab2ApprovalSystem/Views/ChangeControl/ReadOnlyCC.cshtml @@ -128,7 +128,7 @@
@Html.TextBoxFor(model => model.OwnerName, new { id = "txtOwner", @class = "k-textbox", Readonly = "Readonly", style = "background-color:lightblue" }) - @if (Session[GlobalVars.IS_ADMIN] != null) + @if (GlobalVars.IsAdminValueNotNull(Session)) { } diff --git a/Fab2ApprovalSystem/Views/CorrectiveAction/Edit.cshtml b/Fab2ApprovalSystem/Views/CorrectiveAction/Edit.cshtml index 8732c9f..e136c41 100644 --- a/Fab2ApprovalSystem/Views/CorrectiveAction/Edit.cshtml +++ b/Fab2ApprovalSystem/Views/CorrectiveAction/Edit.cshtml @@ -1465,7 +1465,7 @@ Additional Approvers } - else if ((((bool)Session[GlobalVars.IS_ADMIN] && (Request.IsAuthenticated))) && Model.ClosedDate == null) + else if (((GlobalVars.IsAdmin(Session) && (Request.IsAuthenticated))) && Model.ClosedDate == null) {
- @if ((bool)Session[GlobalVars.IS_ADMIN] && (Request.IsAuthenticated)) + @if (GlobalVars.IsAdmin(Session) && (Request.IsAuthenticated)) { @(Html.Kendo().Grid() .Name("ApproversList") @@ -2180,7 +2180,7 @@ var currentD5D6AttachmentLinks; var currentD7AttachmentLinks; var currentRejectingSection = ''; - var currentUserId = @((int)Session[GlobalVars.SESSION_USERID]) + var currentUserId = @(GlobalVars.GetUserId(Session)) var currentRequestor = @(Model.RequestorID); diff --git a/Fab2ApprovalSystem/Views/CorrectiveAction/ReadOnlyCA.cshtml b/Fab2ApprovalSystem/Views/CorrectiveAction/ReadOnlyCA.cshtml index 338aaa8..ad530da 100644 --- a/Fab2ApprovalSystem/Views/CorrectiveAction/ReadOnlyCA.cshtml +++ b/Fab2ApprovalSystem/Views/CorrectiveAction/ReadOnlyCA.cshtml @@ -44,7 +44,7 @@
- @if (Session[GlobalVars.IS_ADMIN] != null) + @if (GlobalVars.IsAdminValueNotNull(Session)) { } diff --git a/Fab2ApprovalSystem/Views/ECN/Acknowledge.cshtml b/Fab2ApprovalSystem/Views/ECN/Acknowledge.cshtml index 19e35dc..e7d1625 100644 --- a/Fab2ApprovalSystem/Views/ECN/Acknowledge.cshtml +++ b/Fab2ApprovalSystem/Views/ECN/Acknowledge.cshtml @@ -52,7 +52,7 @@ } - @if (Session[GlobalVars.IS_ADMIN] != null) + @if (GlobalVars.IsAdminValueNotNull(Session)) { } @@ -137,7 +137,7 @@
@Html.TextBoxFor(model => model.OriginatorName, new { id = "txtOriginatorName", @class = "k-textbox", disabled = "disabled", style = "background-color:lightblue" }) - @if (Session[GlobalVars.IS_ADMIN] != null) + @if (GlobalVars.IsAdminValueNotNull(Session)) { } @@ -892,9 +892,9 @@
- @if (Session[GlobalVars.IS_ADMIN] != null) + @if (GlobalVars.IsAdminValueNotNull(Session)) { - if ((bool)Session[GlobalVars.IS_ADMIN] && (Request.IsAuthenticated)) + if (GlobalVars.IsAdmin(Session) && (Request.IsAuthenticated)) { @(Html.Kendo().Grid() .Name("ApproversList") diff --git a/Fab2ApprovalSystem/Views/ECN/ECNTrainingView.cshtml b/Fab2ApprovalSystem/Views/ECN/ECNTrainingView.cshtml index 9beefe8..df01c11 100644 --- a/Fab2ApprovalSystem/Views/ECN/ECNTrainingView.cshtml +++ b/Fab2ApprovalSystem/Views/ECN/ECNTrainingView.cshtml @@ -31,7 +31,7 @@
@Html.TextBoxFor(model => model.OriginatorName, new { id = "txtOriginatorName", @class = "k-textbox", disabled = "disabled", style = "background-color:lightblue" }) - @if (Session[GlobalVars.IS_ADMIN] != null) + @if (GlobalVars.IsAdminValueNotNull(Session)) { } diff --git a/Fab2ApprovalSystem/Views/ECN/Edit.cshtml b/Fab2ApprovalSystem/Views/ECN/Edit.cshtml index 75db90d..8f96b15 100644 --- a/Fab2ApprovalSystem/Views/ECN/Edit.cshtml +++ b/Fab2ApprovalSystem/Views/ECN/Edit.cshtml @@ -90,7 +90,7 @@
@Html.TextBoxFor(model => model.OriginatorName, new { id = "txtOriginatorName", @class = "k-textbox", disabled = "disabled", style = "background-color:lightblue" }) - @if (Session[GlobalVars.IS_ADMIN] != null) + @if (GlobalVars.IsAdminValueNotNull(Session)) { } @@ -785,9 +785,9 @@
- @if (Session[GlobalVars.IS_ADMIN] != null) + @if (GlobalVars.IsAdminValueNotNull(Session)) { - if ((bool)Session[GlobalVars.IS_ADMIN] && (Request.IsAuthenticated)) + if (GlobalVars.IsAdmin(Session) && (Request.IsAuthenticated)) { @(Html.Kendo().Grid() .Name("ApproversList") diff --git a/Fab2ApprovalSystem/Views/ECN/EditApproval.cshtml b/Fab2ApprovalSystem/Views/ECN/EditApproval.cshtml index 59f70aa..d767722 100644 --- a/Fab2ApprovalSystem/Views/ECN/EditApproval.cshtml +++ b/Fab2ApprovalSystem/Views/ECN/EditApproval.cshtml @@ -173,7 +173,7 @@
@Html.TextBoxFor(model => model.OriginatorName, new { id = "txtOriginatorName", @class = "k-textbox", disabled = "disabled", style = "background-color:lightblue" }) - @if (Session[GlobalVars.IS_ADMIN] != null) + @if (GlobalVars.IsAdminValueNotNull(Session)) { } @@ -367,7 +367,7 @@ @if ( (ViewBag.IsOriginator == "true" && Model.IsTECN && Model.CloseDate != null && !Model.ExpirationProcessed && !Model.ExpirationInProgress && !Model.CancellationApproved && !Model.CancellationInProgress && Model.ConversionApprovalInProgress == false && (Model.ExpirationDate >= DateTime.Today || Model.ExtensionDate >= DateTime.Today)) || - (Model.IsTECN && (bool)Session[GlobalVars.IS_ADMIN] && (Request.IsAuthenticated) && Model.CloseDate != null && !Model.ExpirationProcessed && !Model.ExpirationInProgress && !Model.CancellationApproved && !Model.CancellationInProgress && Model.ConversionApprovalInProgress == false && (Model.ExpirationDate >= DateTime.Today || Model.ExtensionDate >= DateTime.Today)) + (Model.IsTECN && GlobalVars.IsAdmin(Session) && (Request.IsAuthenticated) && Model.CloseDate != null && !Model.ExpirationProcessed && !Model.ExpirationInProgress && !Model.CancellationApproved && !Model.CancellationInProgress && Model.ConversionApprovalInProgress == false && (Model.ExpirationDate >= DateTime.Today || Model.ExtensionDate >= DateTime.Today)) ) { @(Html.Kendo().DatePickerFor(model => model.ExtensionDate) @@ -980,7 +980,7 @@ Additional Approvers } - else if ((ViewBag.IsOriginator == "true" || ((bool)Session[GlobalVars.IS_ADMIN] && (Request.IsAuthenticated))) && Model.CloseDate == null) + else if ((ViewBag.IsOriginator == "true" || (GlobalVars.IsAdmin(Session) && (Request.IsAuthenticated))) && Model.CloseDate == null) { } @@ -170,7 +170,7 @@
- @if ((bool)Session[GlobalVars.IS_ADMIN]) + @if (GlobalVars.IsAdmin(Session)) { @(Html.Kendo().Grid() .Name("alltasklist") @@ -427,7 +427,7 @@ var issueID=""; var docType = ""; var submitdate = ""; - var userName = "@Session[@GlobalVars.SESSION_USERNAME].ToString()"; + var userName = '@GlobalVars.GetUserName(Session)'; $(document).ready(function () { }) @@ -450,7 +450,7 @@ window.location.href = url.replace('__id__', issueID); })*@ - var userid = @Session[@GlobalVars.SESSION_USERID].ToString() + var userid = @GlobalVars.GetUserId(Session); $("#IncludeAllDocuments").on("click", function () { diff --git a/Fab2ApprovalSystem/Views/Home/LotDispositionList.cshtml b/Fab2ApprovalSystem/Views/Home/LotDispositionList.cshtml index 77477e1..571079c 100644 --- a/Fab2ApprovalSystem/Views/Home/LotDispositionList.cshtml +++ b/Fab2ApprovalSystem/Views/Home/LotDispositionList.cshtml @@ -34,7 +34,7 @@
- @if ((bool)Session[GlobalVars.IS_ADMIN]) + @if (GlobalVars.IsAdmin(Session)) { @(Html.Kendo().Grid() .Name("LotDispoTasklist") diff --git a/Fab2ApprovalSystem/Views/Home/MRBList.cshtml b/Fab2ApprovalSystem/Views/Home/MRBList.cshtml index 5e2d9d6..c5fb853 100644 --- a/Fab2ApprovalSystem/Views/Home/MRBList.cshtml +++ b/Fab2ApprovalSystem/Views/Home/MRBList.cshtml @@ -32,7 +32,7 @@ - @if (Session[GlobalVars.IS_ADMIN] != null) + @if (GlobalVars.IsAdminValueNotNull(Session)) { } @foreach (var item in Model) { - if (item.UserID.ToString() == Session[GlobalVars.SESSION_USERID].ToString() || Session[GlobalVars.IS_ADMIN] != null) + if (item.UserID.ToString() == GlobalVars.GetUserIdValue(Session) || GlobalVars.IsAdminValueNotNull(Session)) { - @if ((bool)Session[GlobalVars.IS_ADMIN] == true) + @if (GlobalVars.IsAdmin(Session)) {
- @if ((bool)Session[GlobalVars.IS_ADMIN]) + @if (GlobalVars.IsAdmin(Session)) { @(Html.Kendo().Upload() .Name("AddQDBFlag") @@ -45,7 +45,7 @@ } - @if ((bool)Session[GlobalVars.IS_ADMIN]) + @if (GlobalVars.IsAdmin(Session)) { @(Html.Kendo().Upload() .Name("RemoveQDBFlag") @@ -72,7 +72,7 @@
- @if ((bool)Session[GlobalVars.IS_ADMIN]) + @if (GlobalVars.IsAdmin(Session)) { @(Html.Kendo().Grid() .Name("mrbTasklist") diff --git a/Fab2ApprovalSystem/Views/Home/MyTasks.cshtml b/Fab2ApprovalSystem/Views/Home/MyTasks.cshtml index d297661..fc72d01 100644 --- a/Fab2ApprovalSystem/Views/Home/MyTasks.cshtml +++ b/Fab2ApprovalSystem/Views/Home/MyTasks.cshtml @@ -175,7 +175,7 @@
- @if (Convert.ToBoolean(Session[GlobalVars.CAN_CREATE_PARTS_REQUEST]) && !Convert.ToBoolean(Session[GlobalVars.IS_ADMIN])) + @if (GlobalVars.GetCanCreatePartsRequest(Session) && !GlobalVars.IsAdmin(Session)) {

diff --git a/Fab2ApprovalSystem/Views/Home/_HomeLayout.cshtml b/Fab2ApprovalSystem/Views/Home/_HomeLayout.cshtml index 0d54966..539fd92 100644 --- a/Fab2ApprovalSystem/Views/Home/_HomeLayout.cshtml +++ b/Fab2ApprovalSystem/Views/Home/_HomeLayout.cshtml @@ -55,11 +55,11 @@
diff --git a/Fab2ApprovalSystem/Views/LotDisposition/Edit.cshtml b/Fab2ApprovalSystem/Views/LotDisposition/Edit.cshtml index 57a5f1b..7e03c02 100644 --- a/Fab2ApprovalSystem/Views/LotDisposition/Edit.cshtml +++ b/Fab2ApprovalSystem/Views/LotDisposition/Edit.cshtml @@ -478,9 +478,9 @@
- @if (Session[GlobalVars.IS_ADMIN] != null) + @if (GlobalVars.IsAdminValueNotNull(Session)) { - if ((bool)Session[GlobalVars.IS_ADMIN] && (Request.IsAuthenticated)) + if (GlobalVars.IsAdmin(Session) && (Request.IsAuthenticated)) { @(Html.Kendo().Grid() .Name("ApproversList") diff --git a/Fab2ApprovalSystem/Views/LotDisposition/EditStep.cshtml b/Fab2ApprovalSystem/Views/LotDisposition/EditStep.cshtml index 4404d28..0b4dcf1 100644 --- a/Fab2ApprovalSystem/Views/LotDisposition/EditStep.cshtml +++ b/Fab2ApprovalSystem/Views/LotDisposition/EditStep.cshtml @@ -421,7 +421,7 @@
- @if ((bool)Session[GlobalVars.IS_ADMIN] && (Request.IsAuthenticated)) + @if (GlobalVars.IsAdmin(Session) && (Request.IsAuthenticated)) { @(Html.Kendo().Grid() .Name("ApproversList") diff --git a/Fab2ApprovalSystem/Views/LotTraveler/Edit.cshtml b/Fab2ApprovalSystem/Views/LotTraveler/Edit.cshtml index c46e671..df1b32c 100644 --- a/Fab2ApprovalSystem/Views/LotTraveler/Edit.cshtml +++ b/Fab2ApprovalSystem/Views/LotTraveler/Edit.cshtml @@ -133,7 +133,7 @@
@Html.TextBoxFor(model => model.OriginatorName, new { id = "txtOriginatorName", @class = "k-textbox", Readonly = "Readonly", style = "background-color:lightblue" }) - @if (Session[GlobalVars.IS_ADMIN] != null) + @if (GlobalVars.IsAdminValueNotNull(Session)) { } @@ -901,9 +901,9 @@
- @if (Session[GlobalVars.IS_ADMIN] != null) + @if (GlobalVars.IsAdminValueNotNull(Session)) { - if ((bool)Session[GlobalVars.IS_ADMIN] && (Request.IsAuthenticated)) + if (GlobalVars.IsAdmin(Session) && (Request.IsAuthenticated)) { @(Html.Kendo().Grid() .Name("ApproversList") diff --git a/Fab2ApprovalSystem/Views/LotTraveler/LotTravelerExecute.cshtml b/Fab2ApprovalSystem/Views/LotTraveler/LotTravelerExecute.cshtml index 9eb2a57..34b9302 100644 --- a/Fab2ApprovalSystem/Views/LotTraveler/LotTravelerExecute.cshtml +++ b/Fab2ApprovalSystem/Views/LotTraveler/LotTravelerExecute.cshtml @@ -125,7 +125,7 @@
@Html.TextBoxFor(model => model.Originator, new { @class = "k-textbox", Readonly = "Readonly", style = "background-color:lightblue" }) - @if (Session[GlobalVars.IS_ADMIN] != null) + @if (GlobalVars.IsAdminValueNotNull(Session)) { } diff --git a/Fab2ApprovalSystem/Views/LotTraveler/LotTravelerReadOnly.cshtml b/Fab2ApprovalSystem/Views/LotTraveler/LotTravelerReadOnly.cshtml index 7bcd326..fa04ab9 100644 --- a/Fab2ApprovalSystem/Views/LotTraveler/LotTravelerReadOnly.cshtml +++ b/Fab2ApprovalSystem/Views/LotTraveler/LotTravelerReadOnly.cshtml @@ -166,7 +166,7 @@
@Html.TextBoxFor(model => model.Originator, new { @class = "k-textbox", Readonly = "Readonly", style = "background-color:lightblue" }) - @if (Session[GlobalVars.IS_ADMIN] != null) + @if (GlobalVars.IsAdminValueNotNull(Session)) { } diff --git a/Fab2ApprovalSystem/Views/LotTraveler/LotTravelerUpdate.cshtml b/Fab2ApprovalSystem/Views/LotTraveler/LotTravelerUpdate.cshtml index ebc4b51..c3ab654 100644 --- a/Fab2ApprovalSystem/Views/LotTraveler/LotTravelerUpdate.cshtml +++ b/Fab2ApprovalSystem/Views/LotTraveler/LotTravelerUpdate.cshtml @@ -146,7 +146,7 @@
@Html.TextBoxFor(model => model.Originator, new { @class = "k-textbox", Readonly = "Readonly", style = "background-color:lightblue" }) - @if (Session[GlobalVars.IS_ADMIN] != null) + @if (GlobalVars.IsAdminValueNotNull(Session)) { } diff --git a/Fab2ApprovalSystem/Views/LotTraveler/WorkRequestApproval.cshtml b/Fab2ApprovalSystem/Views/LotTraveler/WorkRequestApproval.cshtml index 9ff1c97..51391e8 100644 --- a/Fab2ApprovalSystem/Views/LotTraveler/WorkRequestApproval.cshtml +++ b/Fab2ApprovalSystem/Views/LotTraveler/WorkRequestApproval.cshtml @@ -152,7 +152,7 @@
@Html.TextBoxFor(model => model.OriginatorName, new { id = "txtOriginatorName", @class = "k-textbox", Readonly = "Readonly", style = "background-color:lightblue" }) - @if (Session[GlobalVars.IS_ADMIN] != null) + @if (GlobalVars.IsAdminValueNotNull(Session)) { } @@ -818,7 +818,7 @@
- @if (((bool)Session[GlobalVars.IS_ADMIN] && (Request.IsAuthenticated))) + @if ((GlobalVars.IsAdmin(Session) && (Request.IsAuthenticated))) {
@Html.DisplayNameFor(model => model.status) @@ -130,7 +130,7 @@ else Incomplete - @if (Session[GlobalVars.IS_ADMIN] != null && item.status != true) + @if (GlobalVars.IsAdminValueNotNull(Session) && item.status != true) { @@ -138,7 +138,7 @@ else } - @if (Session[GlobalVars.IS_ADMIN] != null && item.status != true) + @if (GlobalVars.IsAdminValueNotNull(Session) && item.status != true) { diff --git a/Fab2ApprovalSystem/Views/Training/ViewTrainingPartial.cshtml b/Fab2ApprovalSystem/Views/Training/ViewTrainingPartial.cshtml index 7db0811..1b423c8 100644 --- a/Fab2ApprovalSystem/Views/Training/ViewTrainingPartial.cshtml +++ b/Fab2ApprovalSystem/Views/Training/ViewTrainingPartial.cshtml @@ -18,7 +18,7 @@
diff --git a/Fab2ApprovalSystem/Views/Training/ViewTrainings.cshtml b/Fab2ApprovalSystem/Views/Training/ViewTrainings.cshtml index a54bbd6..a6c96dc 100644 --- a/Fab2ApprovalSystem/Views/Training/ViewTrainings.cshtml +++ b/Fab2ApprovalSystem/Views/Training/ViewTrainings.cshtml @@ -137,7 +137,7 @@ @Html.ActionLink("View", "ViewTrainingAssignments", new { trainingID = item.TrainingID }, new { @class = "btn btn-primary" }) @Html.ActionLink("Delete", "DeleteTrainingByID", new { trainingId = item.TrainingID }, new { @class = "btn btn-primary" }) diff --git a/Fab2ApprovalSystem/pipelines-manual.yml b/Fab2ApprovalSystem/pipelines-manual.yml index a2e17a8..f6d5a58 100644 --- a/Fab2ApprovalSystem/pipelines-manual.yml +++ b/Fab2ApprovalSystem/pipelines-manual.yml @@ -41,6 +41,7 @@ stages: - script: | mklink /J ".vscode\.UserSecrets" "%AppData%\Microsoft\UserSecrets\f2da5035-aba9-4676-9f8d-d6689f84663d" + mklink /J "Controllers" "..\Fab2ApprovalSystem\Controllers" mklink /J "DMO" "..\Fab2ApprovalSystem\DMO" mklink /J "Jobs" "..\Fab2ApprovalSystem\Jobs" mklink /J "JobSchedules" "..\Fab2ApprovalSystem\JobSchedules" @@ -148,6 +149,7 @@ stages: - script: | mklink /J ".vscode\.UserSecrets" "%AppData%\Microsoft\UserSecrets\f2da5035-aba9-4676-9f8d-d6689f84663d" + mklink /J "Controllers" "..\Fab2ApprovalSystem\Controllers" mklink /J "DMO" "..\Fab2ApprovalSystem\DMO" mklink /J "Jobs" "..\Fab2ApprovalSystem\Jobs" mklink /J "JobSchedules" "..\Fab2ApprovalSystem\JobSchedules" diff --git a/Fab2ApprovalSystem/pipelines.yml b/Fab2ApprovalSystem/pipelines.yml index 179b1a6..b8c9fd1 100644 --- a/Fab2ApprovalSystem/pipelines.yml +++ b/Fab2ApprovalSystem/pipelines.yml @@ -48,6 +48,7 @@ stages: - script: | mklink /J ".vscode\.UserSecrets" "%AppData%\Microsoft\UserSecrets\f2da5035-aba9-4676-9f8d-d6689f84663d" + mklink /J "Controllers" "..\Fab2ApprovalSystem\Controllers" mklink /J "DMO" "..\Fab2ApprovalSystem\DMO" mklink /J "Jobs" "..\Fab2ApprovalSystem\Jobs" mklink /J "JobSchedules" "..\Fab2ApprovalSystem\JobSchedules" @@ -155,6 +156,7 @@ stages: - script: | mklink /J ".vscode\.UserSecrets" "%AppData%\Microsoft\UserSecrets\f2da5035-aba9-4676-9f8d-d6689f84663d" + mklink /J "Controllers" "..\Fab2ApprovalSystem\Controllers" mklink /J "DMO" "..\Fab2ApprovalSystem\DMO" mklink /J "Jobs" "..\Fab2ApprovalSystem\Jobs" mklink /J "JobSchedules" "..\Fab2ApprovalSystem\JobSchedules" diff --git a/Fab2ApprovalTests/DMO/EngChangeNoticeDMOTests.cs b/Fab2ApprovalTests/DMO/EngChangeNoticeDMOTests.cs index 65c4a85..e3cfe44 100644 --- a/Fab2ApprovalTests/DMO/EngChangeNoticeDMOTests.cs +++ b/Fab2ApprovalTests/DMO/EngChangeNoticeDMOTests.cs @@ -52,7 +52,7 @@ public class EngChangeNoticeDMOTests { try { throw new Exception(); } catch (Exception) { } } - private static void EngChangeNoticeDMO(ILogger? logger, AppSettings appSettings) { + private static void EngChangeNoticeDMO(ILogger? logger, AppSettings appSettings, int ecnNumber) { #pragma warning disable IDE0059 SetGlobalVars(logger, appSettings); ECN_DMO ecnDMO = new(); @@ -84,6 +84,9 @@ public class EngChangeNoticeDMOTests { // int SubmitTECNExtensionDocument(int issueID, appSettings.UserId, int documentType, DateTime extensionDate); // void TECNExtensionLog(int ecnNumber, DateTime extensionDate); // void UpdateECNType(int ecnNumber, string ecnType); + ECNPdf ecn = ecnDMO.GetECNPdf(ecnNumber); + string categoryId = ecnDMO.GetCategoryID(ecn); + string trainingNotificationTo = ecnDMO.GetTrainingNotificationTo(ecn, new TrainingDMO()); if (ecnDMO is null) { } #pragma warning restore IDE0059 } @@ -92,13 +95,14 @@ public class EngChangeNoticeDMOTests { [Ignore] #endif [TestMethod] - public void EngChangeNoticeDMOIsAttachedOnly() { + [DataRow(82689)] + public void EngChangeNoticeDMOIsAttachedOnly(int ecnNumber) { _Logger?.LogInformation("Starting Web Application"); IServiceProvider? serviceProvider = _WebApplicationFactory?.Services.CreateScope().ServiceProvider; AppSettings? appSettings = serviceProvider?.GetRequiredService(); Assert.IsTrue(appSettings is not null); if (System.Diagnostics.Debugger.IsAttached) - EngChangeNoticeDMO(_Logger, appSettings); + EngChangeNoticeDMO(_Logger, appSettings, ecnNumber); _Logger?.LogInformation("{TestName} completed", _TestContext?.TestName); NonThrowTryCatch(); }