33 Commits

Author SHA1 Message Date
bdf1a8060f Merge commit '54799f54ec75a1c88f380f1c5aa45f654a87f88e' into 05-28-a 2025-05-28 13:49:08 -07:00
54799f54ec Add #if !NET8 back in to pass the .net core tests 2025-05-28 13:42:05 -07:00
7eba0fa25a NET8 2025-05-28 13:34:48 -07:00
65a433e9ab Merged PR 17498: Removed PdfViewController, HtmlViewRenderer and FakeView to be replaced with...
Removed PdfViewController, HtmlViewRenderer and FakeView to be replaced with ViewEngineResult Render method

To test use url
http://mestsa05ec.infineon.com:8080/ecn/printecnpdf?ecnNumber=82654
2025-05-28 22:21:03 +02:00
8bae94de96 Merged PR 16782: Added logic to display Category and Training Notification fields on PDF
Added logic to display Category and Training Notification fields on PDF

Related work items: #135474, #225483
2025-05-19 22:20:00 +02:00
032c971472 Actually cancel ECNs upon cancel 2025-05-08 10:24:40 -07:00
704df4fa8c Restrict pipeline to only run for old site 2025-04-17 15:52:38 +00:00
e452047dfb PCRB Type field 2025-04-17 07:46:58 -07:00
bf3e46a784 fix redirect links 2025-04-02 12:10:43 -07:00
909f358356 fix email subject bug 2025-04-02 09:14:19 -07:00
b3fb328b98 Audit object was being passed as byref but getting re-instantiated within the method 2025-04-01 13:38:06 -07:00
f110fba4cd Merged PR 13298: Added just one approval back in after removing the method call from bug 239935
Added just one approval back in after removing the method call from bug 239935

Added IExcelDataReader support into MK Project

Changed instructions below the ECN Title field to align with Windchill

Related work items: #225480, #244087
2025-03-19 21:19:06 +01:00
c4d29dad4e PCRB follow up client side services 2025-03-12 17:34:41 -07:00
2dbde5d70c PCRB follow up endpoints 2025-03-11 20:12:26 -07:00
2119b31764 Merged PR 12625: Fix: Incorrectly creating new training records when canceling a TECN
Fix: Incorrectly creating new training records when canceling a TECN

IDE0100

Updated pipelines to build package .zip for msdeploy.exe

Related work items: #239935
2025-03-11 20:16:18 +01:00
55d3a96228 Merged PR 12196: Alphabetize Category List -ECN Module
Moved pipeline to align with other projects in same repo

Changed MSBuild task to be specific and added new MSBuild Release task

Sort GetCategories on CategoryName

Added comments back from feature 135470

Added ItemGroup to allow testing internal methods

Testing for internal methods

Related work items: #135470, #238416
2025-03-05 19:27:20 +01:00
aa38d17daf Fixed redirect bug 2025-02-20 12:50:47 -07:00
d4fcbe0dc6 Set up CI with Azure Pipelines
[skip ci]
2025-02-13 17:02:37 +00:00
6a7bc39ff8 Update pipeline.yml for Azure Pipelines 2025-02-13 16:39:17 +00:00
b3a2ee7285 Setting up API and Client pipelines 2025-02-13 17:22:12 +01:00
a2326315a6 Only show approvals within last two years 2025-02-12 09:02:10 -07:00
8684e97db7 Ensure approvals for user are pending 2025-02-11 11:04:58 -07:00
1946623c9e Fixed PCRB attendees bug 2025-02-06 10:58:54 -07:00
40e7a3f8e0 Fixed MRB Actions Convert bug 2025-01-31 11:17:20 -07:00
f0df620dc9 Default PCR3 document comment to Not required 2025-01-23 15:10:21 -07:00
6a2bc0b4ab Created ECN# autocomplete for PCR3 docs 2025-01-23 07:49:52 -07:00
c4036471f7 Ready to publish
Added new Email Template and new Modal form for expired TECNs.
Updated Email Template and new Modal form for TECNs.
Added more margin on all modal dialogs
2025-01-22 21:06:48 +01:00
e19cb5fcda Fixed processing bug 2025-01-22 10:54:21 -07:00
e68a1a4c3b Fixed app settings 2025-01-17 10:24:26 -07:00
7ddda56987 Moved GetEnvironmentVariable calls to Application_Start 2025-01-15 15:16:36 -07:00
77f45fabb1 Added PCRB controller for my task links 2025-01-15 14:54:22 -07:00
1b22ffa439 Ready to test new column 2025-01-15 17:21:42 +01:00
123bbdb9fe Merged PR 34240: Updates to PCR3 document section
Updates to PCR3 document section
2025-01-15 16:52:17 +01:00
157 changed files with 9803 additions and 5247 deletions

27
.gitignore vendored
View File

@ -351,9 +351,36 @@ ASALocalRun/
/Fab2ApprovalMKLink/Utilities /Fab2ApprovalMKLink/Utilities
/Fab2ApprovalMKLink/ViewModels /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 /Fab2ApprovalMKLink/.vscode/.UserSecrets
/Fab2ApprovalSystem/.vscode/.UserSecrets /Fab2ApprovalSystem/.vscode/.UserSecrets
/Fab2ApprovalTests/.vscode/.UserSecrets /Fab2ApprovalTests/.vscode/.UserSecrets
/MesaFabApproval.API/.vscode/.UserSecrets /MesaFabApproval.API/.vscode/.UserSecrets
/MesaFabApproval.Client/.vscode/.UserSecrets /MesaFabApproval.Client/.vscode/.UserSecrets
/MesaFabApproval.Shared/.vscode/.UserSecrets /MesaFabApproval.Shared/.vscode/.UserSecrets
fab-001
fab-002
fab-004
fab-004
fab-005
fab-006
fab-007
fab-008
fab-009

42
.vscode/launch.json vendored
View File

@ -15,6 +15,48 @@
"console": "integratedTerminal", "console": "integratedTerminal",
"stopAtEntry": false "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", "name": ".NET Core Launch (console) - MesaFabApproval.API",
"type": "coreclr", "type": "coreclr",

View File

@ -420,5 +420,6 @@
"windowsphone", "windowsphone",
"Winsock", "Winsock",
"worlflow" "worlflow"
] ],
"dotnet.preferCSharpExtension": true
} }

33
.vscode/tasks.json vendored
View File

@ -2,7 +2,7 @@
"version": "2.0.0", "version": "2.0.0",
"tasks": [ "tasks": [
{ {
"label": "MSBuild", "label": "MSBuild-Debug",
"command": "C:/Program Files (x86)/Microsoft Visual Studio/2022/BuildTools/MSBuild/Current/Bin/MSBuild.exe", "command": "C:/Program Files (x86)/Microsoft Visual Studio/2022/BuildTools/MSBuild/Current/Bin/MSBuild.exe",
"type": "process", "type": "process",
"args": [ "args": [
@ -16,6 +16,21 @@
], ],
"problemMatcher": "$msCompile" "problemMatcher": "$msCompile"
}, },
{
"label": "MSBuild-Release",
"command": "C:/Program Files (x86)/Microsoft Visual Studio/2022/BuildTools/MSBuild/Current/Bin/MSBuild.exe",
"type": "process",
"args": [
"/target:Build",
"/restore:True",
"/p:RestoreSources=https://artifactory.intra.infineon.com/artifactory/api/nuget/ngt-fi-package-main-vir/%3Bhttps://packagemanagement.eu.infineon.com:4430/api/v2/%3Bhttps://api.nuget.org/v3/index.json",
"/detailedsummary",
"/consoleloggerparameters:PerformanceSummary;ErrorsOnly;",
"/property:Configuration=Release;TargetFrameworkVersion=v4.8",
"Fab2ApprovalSystem/Fab2ApprovalSystem.csproj"
],
"problemMatcher": "$msCompile"
},
{ {
"label": "Fab2ApprovalMKLink-User Secrets Init", "label": "Fab2ApprovalMKLink-User Secrets Init",
"command": "dotnet", "command": "dotnet",
@ -48,6 +63,7 @@
"type": "process", "type": "process",
"args": [ "args": [
"format", "format",
"${workspaceFolder}/Fab2ApprovalMKLink/Fab2ApprovalMKLink.csproj",
"--report", "--report",
".vscode", ".vscode",
"--verbosity", "--verbosity",
@ -63,7 +79,8 @@
"type": "process", "type": "process",
"args": [ "args": [
"format", "format",
"whitespace" "whitespace",
"${workspaceFolder}/Fab2ApprovalMKLink/Fab2ApprovalMKLink.csproj"
], ],
"problemMatcher": "$msCompile" "problemMatcher": "$msCompile"
}, },
@ -79,6 +96,18 @@
], ],
"problemMatcher": "$msCompile" "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", "label": "Fab2ApprovalMKLink-publish",
"command": "dotnet", "command": "dotnet",

View File

@ -367,6 +367,7 @@ dotnet_diagnostic.IDE0065.severity = none # Question -
dotnet_diagnostic.IDE0066.severity = none # Question - Use dotnet_diagnostic.IDE0066.severity = none # Question - Use
dotnet_diagnostic.IDE0078.severity = none # Question - Use pattern matching (may change code meaning) dotnet_diagnostic.IDE0078.severity = none # Question - Use pattern matching (may change code meaning)
dotnet_diagnostic.IDE0090.severity = warning # Question - Simplify new expression dotnet_diagnostic.IDE0090.severity = warning # Question - Simplify new expression
dotnet_diagnostic.IDE0100.severity = error # Question - Remove redundant equality
dotnet_diagnostic.IDE0160.severity = warning # Question - Use block-scoped namespace dotnet_diagnostic.IDE0160.severity = warning # Question - Use block-scoped namespace
dotnet_diagnostic.IDE0161.severity = warning # Question - Namespace declaration preferences dotnet_diagnostic.IDE0161.severity = warning # Question - Namespace declaration preferences
dotnet_diagnostic.IDE0270.severity = none # Question - Null check can be simplified dotnet_diagnostic.IDE0270.severity = none # Question - Null check can be simplified

View File

@ -35,3 +35,37 @@ mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\PdfGenerator" "L
mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\Jobs" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\Jobs" mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\Jobs" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\Jobs"
mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\JobSchedules" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\JobSchedules" mklink /J "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalMKLink\JobSchedules" "L:\DevOps\Mesa_FI\MesaFabApproval\Fab2ApprovalSystem\JobSchedules"
``` ```
```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"
```

View File

@ -18,12 +18,19 @@
<PropertyGroup Condition="'$(TargetFramework)' == 'net8.0'"> <PropertyGroup Condition="'$(TargetFramework)' == 'net8.0'">
<DefineConstants>NET8</DefineConstants> <DefineConstants>NET8</DefineConstants>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>Fab2ApprovalTests</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Dapper.Contrib" Version="2.0.78" /> <PackageReference Include="Dapper.Contrib" Version="2.0.78" />
<PackageReference Include="Dapper" Version="2.1.44" /> <PackageReference Include="Dapper" Version="2.1.44" />
<PackageReference Include="DocumentFormat.OpenXml" Version="3.3.0" />
<PackageReference Include="EntityFramework" Version="6.5.1" /> <PackageReference Include="EntityFramework" Version="6.5.1" />
<PackageReference Include="ExcelDataReader" Version="3.7.0" /> <PackageReference Include="ExcelDataReader" Version="3.7.0" />
<PackageReference Include="jQuery" Version="3.7.1" /> <PackageReference Include="jQuery" Version="3.7.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.8" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Server" Version="8.0.10" /> <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Server" Version="8.0.10" />
<PackageReference Include="Microsoft.Data.SqlClient" Version="5.2.0" /> <PackageReference Include="Microsoft.Data.SqlClient" Version="5.2.0" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="8.0.2" /> <PackageReference Include="Microsoft.Data.Sqlite" Version="8.0.2" />

View File

@ -1,15 +1,23 @@
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using System.Text;
using Fab2ApprovalSystem.Misc;
using Fab2ApprovalSystem.Models; using Fab2ApprovalSystem.Models;
using Fab2ApprovalSystem.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Hosting.WindowsServices; using Microsoft.Extensions.Hosting.WindowsServices;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
namespace Fab2ApprovalMKLink; namespace Fab2ApprovalMKLink;
@ -24,12 +32,36 @@ public class Program {
throw new Exception("Company name must have a value!"); throw new Exception("Company name must have a value!");
if (string.IsNullOrEmpty(appSettings.WorkingDirectoryName)) if (string.IsNullOrEmpty(appSettings.WorkingDirectoryName))
throw new Exception("Working directory name must have a value!"); 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 { try {
_ = webApplicationBuilder.Services.Configure<ApiBehaviorOptions>(options => options.SuppressModelStateInvalidFilter = true); _ = webApplicationBuilder.Services.Configure<ApiBehaviorOptions>(options => options.SuppressModelStateInvalidFilter = true);
_ = webApplicationBuilder.Services.AddControllers(); _ = webApplicationBuilder.Services.AddControllers();
_ = webApplicationBuilder.Services.AddControllersWithViews();
_ = webApplicationBuilder.Services.AddDistributedMemoryCache(); _ = webApplicationBuilder.Services.AddDistributedMemoryCache();
_ = webApplicationBuilder.Services.AddHttpClient(); _ = webApplicationBuilder.Services.AddHttpClient();
_ = webApplicationBuilder.Services.AddMemoryCache();
_ = webApplicationBuilder.Services.AddSingleton(_ => appSettings); _ = webApplicationBuilder.Services.AddSingleton(_ => appSettings);
_ = webApplicationBuilder.Services.AddSingleton<ICompositeViewEngine, CompositeViewEngine>();
// _ = webApplicationBuilder.Services.AddTransient<IViewRenderingService, ViewRenderingService>();
// _ = webApplicationBuilder.Services.AddScoped<IViewRenderService, ViewRenderService>();
// _ = webApplicationBuilder.Services.AddSingleton<ITempDataProvider, ITempDataProvider>();
_ = webApplicationBuilder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
_ = webApplicationBuilder.Services.AddScoped<IAuthenticationService, AuthenticationService>();
_ = webApplicationBuilder.Services.AddScoped<IDalService, DalService>();
_ = webApplicationBuilder.Services.AddScoped<IDbConnectionService, DbConnectionService>();
_ = webApplicationBuilder.Services.AddScoped<IUserService, UserService>();
_ = webApplicationBuilder.Services.AddSwaggerGen(); _ = webApplicationBuilder.Services.AddSwaggerGen();
_ = webApplicationBuilder.Services.AddSession(sessionOptions => { _ = webApplicationBuilder.Services.AddSession(sessionOptions => {
sessionOptions.IdleTimeout = TimeSpan.FromSeconds(2000); sessionOptions.IdleTimeout = TimeSpan.FromSeconds(2000);
@ -37,6 +69,29 @@ public class Program {
sessionOptions.Cookie.IsEssential = true; 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()) { if (WindowsServiceHelpers.IsWindowsService()) {
_ = webApplicationBuilder.Services.AddSingleton<IHostLifetime, WindowsServiceLifetime>(); _ = webApplicationBuilder.Services.AddSingleton<IHostLifetime, WindowsServiceLifetime>();
_ = webApplicationBuilder.Logging.AddEventLog(settings => { _ = webApplicationBuilder.Logging.AddEventLog(settings => {
@ -65,6 +120,8 @@ public class Program {
} }
_ = webApplication.UseSession(); _ = webApplication.UseSession();
_ = webApplication.MapControllers(); _ = webApplication.MapControllers();
_ = webApplication.UseAuthentication();
_ = webApplication.UseAuthorization();
logger.LogInformation("Starting Web Application"); logger.LogInformation("Starting Web Application");
webApplication.Run(); webApplication.Run();
return 0; return 0;

View File

@ -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<LoginResult> AuthenticateUser(AuthAttempt login);
public Task<LoginResult> AttemptLocalUserAuth(WindowsIdentity identity);
public AuthTokens GenerateAuthTokens(AuthAttempt authAttempt, IEnumerable<string> roles);
public Task<LoginResult> RefreshAuthTokens(AuthAttempt authAttempt);
}
public class AuthenticationService : IAuthenticationService {
private readonly ILogger<AuthenticationService> _logger;
private readonly IMemoryCache _cache;
private readonly IUserService _userService;
private readonly string? _jwtIssuer;
private readonly string? _jwtAudience;
private readonly string? _jwtKey;
public AuthenticationService(ILogger<AuthenticationService> 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<LoginResult> 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>($"user{login.LoginID}");
if (user is null) {
user = await _userService.GetUserByLoginId(login.LoginID);
_cache.Set($"user{login.LoginID}", user, DateTimeOffset.Now.AddDays(1));
}
List<string> 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<LoginResult> 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<string> 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<string> 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<Claim> 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<string>? refreshTokensForUser = _cache.Get<List<string>>(authAttempt.LoginID);
refreshTokensForUser ??= new List<string>();
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<LoginResult> 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>($"user{authAttempt.LoginID}");
if (user is null) {
user = await _userService.GetUserByLoginId(authAttempt.LoginID);
_cache.Set($"user{authAttempt.LoginID}", user, DateTimeOffset.Now.AddDays(1));
}
List<string> 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<string>? cachedRefreshTokensForUser = _cache.Get<List<string>>(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;
}
}
}

View File

@ -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<IEnumerable<T>> QueryAsync<T>(string sql);
Task<IEnumerable<T>> QueryAsync<T>(string sql, object parameters);
Task<int> ExecuteAsync(string sql);
Task<int> ExecuteAsync<T>(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<DalService> _logger;
private readonly IDbConnectionService _dbConnectionService;
public DalService(IDbConnectionService dbConnectionService, ILogger<DalService> logger) {
_dbConnectionService = dbConnectionService ??
throw new ArgumentNullException("IDbConnectionService not injected");
_logger = logger ??
throw new ArgumentNullException("ILogger not injected");
}
public async Task<IEnumerable<T>> QueryAsync<T>(string sql) {
if (sql is null) throw new ArgumentNullException("sql cannot be null");
int remainingRetries = RETRIES;
bool queryWasSuccessful = false;
Exception exception = null;
IEnumerable<T> result = new List<T>();
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<T>(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<IEnumerable<T>> QueryAsync<T>(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<T> result = new List<T>();
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<T>(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<int> 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<int> ExecuteAsync<T>(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;
}
}

View File

@ -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);
}

View File

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

View File

@ -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

View File

@ -0,0 +1,3 @@
@{
Layout = null;
}

View File

@ -1,105 +0,0 @@
trigger:
branches:
include:
- Development
paths:
include:
- "Fab2ApprovalSystem/*"
exclude:
- "**/*.yaml"
- "**/*.yml"
- "SQL/*"
- "references/*"
- "packages/*"
- "Kendo/*"
pool:
name: Mesa-IIS
demands: Fab2ApprovalSystem-Development
variables:
# solution: '**/*.sln'
# buildPlatform: 'Any CPU'
buildConfiguration: "Debug"
ASPNETCORE_ENVIRONMENT: "Development"
steps:
- script: |
set assemblyTitle=Fab2ApprovalSystem
echo %assemblyTitle%
echo ##vso[task.setvariable variable=AssemblyTitle;]%assemblyTitle%
echo $(AssemblyTitle)
displayName: AssemblyTitle
- script: |
set targetFrameworkVersion=v4.8
echo %targetFrameworkVersion%
echo ##vso[task.setvariable variable=TargetFrameworkVersion;]%targetFrameworkVersion%
echo $(TargetFrameworkVersion)
displayName: TargetFrameworkVersion
- script: |
set coreVersion=na
echo %coreVersion%
echo ##vso[task.setvariable variable=CoreVersion;]%coreVersion%
echo $(CoreVersion)
displayName: CoreVersion
- script: |
set configuration=Debug
echo %configuration%
echo ##vso[task.setvariable variable=Configuration;]%configuration%
echo $(Configuration)
displayName: Configuration
- script: |
REM set nugetSource=https://messa017.infineon.com/v3/index.json
set nugetSource=https://eaf-prod.mes.infineon.com/v3/index.json
echo %nugetSource%
echo ##vso[task.setvariable variable=NugetSource;]%nugetSource%
echo $(NugetSource)
displayName: NugetSource
- script: |
set gitCommit=$(Build.SourceVersion)
set gitCommitSeven=%gitCommit:~0,7%
echo %gitCommitSeven%
echo ##vso[task.setvariable variable=GitCommitSeven;]%gitCommitSeven%
echo $(GitCommitSeven)
displayName: GitCommitSeven
- script: |
echo $(AssemblyTitle)
echo $(Build.BuildId)
echo $(Build.Reason)
echo $(Build.Repository.Id)
echo $(Build.Repository.Name)
echo $(Build.SourceVersion)
echo $(CoreVersion)
echo $(Configuration)
echo $(NugetSource)
echo $(GitCommitSeven)
echo $(TargetFrameworkVersion)
REM echo $(pipelinePassword)
displayName: "Echo Check"
- script: '"C:/Program Files (x86)/Microsoft Visual Studio/2022/BuildTools/MSBuild/Current/Bin/MSBuild.exe" /target:Restore /DetailedSummary /ConsoleLoggerParameters:PerformanceSummary;ErrorsOnly; /p:Configuration=$(Configuration);TargetFrameworkVersion=$(TargetFrameworkVersion) /p:RestoreSources=$(NugetSource) $(AssemblyTitle).csproj'
workingDirectory: Fab2ApprovalSystem
displayName: "Framework Restore"
- script: '"C:/Program Files (x86)/Microsoft Visual Studio/2022/BuildTools/MSBuild/Current/Bin/MSBuild.exe" /target:Build /DetailedSummary /ConsoleLoggerParameters:PerformanceSummary;ErrorsOnly; /p:Configuration=$(Configuration);TargetFrameworkVersion=$(TargetFrameworkVersion) $(AssemblyTitle).csproj'
workingDirectory: Fab2ApprovalSystem
displayName: "Framework Build"
- script: '"C:/Program Files (x86)/Microsoft Visual Studio/2022/BuildTools/MSBuild/Current/Bin/MSBuild.exe" /DetailedSummary /ConsoleLoggerParameters:PerformanceSummary;ErrorsOnly; /p:Configuration=$(Configuration);TargetFrameworkVersion=$(TargetFrameworkVersion) /p:DebugSymbols=false /p:DeleteExistingFiles=true /p:DeployOnBuild=true /p:EnableUpdateAble=true /p:ExcludeApp_Data=true /p:LastUsedBuildConfiguration=$(Configuration) /p:LastUsedPlatform="Any CPU" /p:LaunchSiteAfterPublish=true /p:OutputPath="D:\$(TargetFrameworkVersion)\$(Build.Repository.Name)\$(GitCommitSeven)-$(Build.BuildId)-$(Build.Repository.Name)-$(Configuration)" /p:PreCompileBeforePublish=true /p:PublishProvider=FileSystem /p:PublishUrl="D:/PublishUrl" /p:SiteUrlToLaunchAfterPublish="" /p:WDPMergeOption=DoNotMerge /p:WebPublishMethod=FileSystem $(AssemblyTitle).csproj'
workingDirectory: Fab2ApprovalSystem
displayName: "Framework Pack"
- script: '"C:/Program Files (x86)/IIS/Microsoft Web Deploy V3/MSDeploy.exe" -AllowUntrusted -dest:auto -disableLink:AppPoolExtension -disableLink:CertificateExtension -disableLink:ContentExtension -setParam:name="IIS Web Application Name",value=$(Build.Repository.Name) -setParamFile:"D:\$(TargetFrameworkVersion)\$(Build.Repository.Name)\$(GitCommitSeven)-$(Build.BuildId)-$(Build.Repository.Name)-$(Configuration)" "/_PublishedWebsites/$(Build.Repository.Name)_Package/$(Build.Repository.Name).SetParameters.xml" -source:package="D:\$(TargetFrameworkVersion)\$(Build.Repository.Name)\$(GitCommitSeven)-$(Build.BuildId)-$(Build.Repository.Name)-$(Configuration)" "/_PublishedWebsites/$(AssemblyTitle)_Package/$(AssemblyTitle).zip" -verb:sync'
workingDirectory: Fab2ApprovalSystem
displayName: "Framework Deploy"
enabled: false
- script: 'echo $(Build.SourceVersion)-$(Build.BuildId)>bin_x_x_\$(Configuration)\$(CoreVersion)\win-x64\$(Build.Repository.Name).txt'
displayName: "Force Fail"
enabled: false

View File

@ -6,6 +6,9 @@ MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Fab2ApprovalSystem", "Fab2ApprovalSystem\Fab2ApprovalSystem.csproj", "{AAE52608-4DD1-4732-92BD-CC8915DEC71E}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Fab2ApprovalSystem", "Fab2ApprovalSystem\Fab2ApprovalSystem.csproj", "{AAE52608-4DD1-4732-92BD-CC8915DEC71E}"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MesaFabApproval.API", "MesaFabApproval.API\MesaFabApproval.API.csproj", "{852E528D-015A-43B5-999D-F281E3359E5E}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MesaFabApproval.API", "MesaFabApproval.API\MesaFabApproval.API.csproj", "{852E528D-015A-43B5-999D-F281E3359E5E}"
ProjectSection(ProjectDependencies) = postProject
{2C16014D-B04E-46AF-AB4C-D2691D44A339} = {2C16014D-B04E-46AF-AB4C-D2691D44A339}
EndProjectSection
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MesaFabApproval.Shared", "MesaFabApproval.Shared\MesaFabApproval.Shared.csproj", "{2C16014D-B04E-46AF-AB4C-D2691D44A339}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MesaFabApproval.Shared", "MesaFabApproval.Shared\MesaFabApproval.Shared.csproj", "{2C16014D-B04E-46AF-AB4C-D2691D44A339}"
EndProject EndProject
@ -14,6 +17,18 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MesaFabApproval.Client", "M
{2C16014D-B04E-46AF-AB4C-D2691D44A339} = {2C16014D-B04E-46AF-AB4C-D2691D44A339} {2C16014D-B04E-46AF-AB4C-D2691D44A339} = {2C16014D-B04E-46AF-AB4C-D2691D44A339}
EndProjectSection EndProjectSection
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MesaFabApproval.API.Test", "MesaFabApproval.API.Test\MesaFabApproval.API.Test.csproj", "{D03AB305-BA29-4EB1-AC66-ABBF76FBF5C1}"
ProjectSection(ProjectDependencies) = postProject
{2C16014D-B04E-46AF-AB4C-D2691D44A339} = {2C16014D-B04E-46AF-AB4C-D2691D44A339}
{852E528D-015A-43B5-999D-F281E3359E5E} = {852E528D-015A-43B5-999D-F281E3359E5E}
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MesaFabApproval.Client.Test", "MesaFabApproval.Client.Test\MesaFabApproval.Client.Test.csproj", "{A0E5BD7D-3910-43BD-BBA3-3820AD524423}"
ProjectSection(ProjectDependencies) = postProject
{2C16014D-B04E-46AF-AB4C-D2691D44A339} = {2C16014D-B04E-46AF-AB4C-D2691D44A339}
{34D52F44-A81F-4247-8180-16E204824A07} = {34D52F44-A81F-4247-8180-16E204824A07}
EndProjectSection
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@ -36,6 +51,14 @@ Global
{34D52F44-A81F-4247-8180-16E204824A07}.Debug|Any CPU.Build.0 = Debug|Any CPU {34D52F44-A81F-4247-8180-16E204824A07}.Debug|Any CPU.Build.0 = Debug|Any CPU
{34D52F44-A81F-4247-8180-16E204824A07}.Release|Any CPU.ActiveCfg = Release|Any CPU {34D52F44-A81F-4247-8180-16E204824A07}.Release|Any CPU.ActiveCfg = Release|Any CPU
{34D52F44-A81F-4247-8180-16E204824A07}.Release|Any CPU.Build.0 = Release|Any CPU {34D52F44-A81F-4247-8180-16E204824A07}.Release|Any CPU.Build.0 = Release|Any CPU
{D03AB305-BA29-4EB1-AC66-ABBF76FBF5C1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D03AB305-BA29-4EB1-AC66-ABBF76FBF5C1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D03AB305-BA29-4EB1-AC66-ABBF76FBF5C1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D03AB305-BA29-4EB1-AC66-ABBF76FBF5C1}.Release|Any CPU.Build.0 = Release|Any CPU
{A0E5BD7D-3910-43BD-BBA3-3820AD524423}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A0E5BD7D-3910-43BD-BBA3-3820AD524423}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A0E5BD7D-3910-43BD-BBA3-3820AD524423}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A0E5BD7D-3910-43BD-BBA3-3820AD524423}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View File

@ -1,5 +1,7 @@
using System.Web; using System.Web;
#if !NET8
using System.Web.Mvc; using System.Web.Mvc;
#endif
namespace Fab2ApprovalSystem; namespace Fab2ApprovalSystem;

View File

@ -3,13 +3,16 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Web; using System.Web;
using System.Web.Http; using System.Web.Http;
#if !NET8
using System.Web.Mvc; using System.Web.Mvc;
#endif
using System.Web.Routing; using System.Web.Routing;
namespace Fab2ApprovalSystem; namespace Fab2ApprovalSystem;
public class RouteConfig { public class RouteConfig {
public static void RegisterRoutes(RouteCollection routes) { public static void RegisterRoutes(RouteCollection routes) {
#if !NET8
routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute( routes.MapRoute(
@ -20,5 +23,6 @@ public class RouteConfig {
// otherwise MVC generates the wrong form action url // otherwise MVC generates the wrong form action url
defaults: new { controller = "Home", action = "MyTasks", id = UrlParameter.Optional } defaults: new { controller = "Home", action = "MyTasks", id = UrlParameter.Optional }
); );
#endif
} }
} }

View File

@ -6,10 +6,12 @@ public static class WebApiConfig {
public static void Register(HttpConfiguration config) { public static void Register(HttpConfiguration config) {
config.MapHttpAttributeRoutes(); config.MapHttpAttributeRoutes();
#if !NET8
config.Routes.MapHttpRoute( config.Routes.MapHttpRoute(
name: "DefaultApi", name: "DefaultApi",
routeTemplate: "api/{controller}/{id}", routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional } defaults: new { id = RouteParameter.Optional }
); );
#endif
} }
} }

View File

@ -1,9 +1,9 @@
 /*vertical height between form-groups*/ /*vertical height between form-groups*/
.my-form .form-group { .my-form .form-group {
margin-bottom: 4px; margin-bottom: 4px;
} }
@media (min-width:768px) { @media (min-width:768px) {
.my-form .row { .my-form .row {
margin-left: -1px; margin-left: -1px;
margin-right: -1px; margin-right: -1px;
@ -12,7 +12,8 @@
.my-form [class*="col-"] { .my-form [class*="col-"] {
padding: 0 2px; padding: 0 2px;
} }
} }
body { body {
padding-top: 50px; padding-top: 50px;
padding-bottom: 20px; padding-bottom: 20px;
@ -29,10 +30,10 @@ body {
/*input, /*input,
select select
{ {
max-width: 280px; max-width: 280px;
}*/ }*/
.row{ .row {
margin-top: 2px; margin-top: 2px;
margin-bottom: 2px margin-bottom: 2px
} }
@ -71,10 +72,10 @@ input[type="checkbox"].input-validation-error {
padding-left: 20px; padding-left: 20px;
padding-right: 20px; padding-right: 20px;
background-color: #87b3de; background-color: #87b3de;
background-image: -moz-linear-gradient(top,#87b3de, #4d79a5); background-image: -moz-linear-gradient(top, #87b3de, #4d79a5);
background-image: -ms-linear-gradient(top,#87b3de, #4d79a5); background-image: -ms-linear-gradient(top, #87b3de, #4d79a5);
background-image: -webkit-gradient(linear, 0 0, 0 50%, from( #87b3de), to(#4d79a5)); background-image: -webkit-gradient(linear, 0 0, 0 50%, from(#87b3de), to(#4d79a5));
background-image: -webkit-linear-gradient(top,#87b3de, #4d79a5); background-image: -webkit-linear-gradient(top, #87b3de, #4d79a5);
background-image: -o-linear-gradient(top, #87b3de, #4d79a5); background-image: -o-linear-gradient(top, #87b3de, #4d79a5);
background-image: linear-gradient(top, #87b3de, #4d79a5); background-image: linear-gradient(top, #87b3de, #4d79a5);
background-repeat: repeat-x; background-repeat: repeat-x;
@ -89,7 +90,7 @@ input[type="checkbox"].input-validation-error {
.label-color { .label-color {
background-color: #e5e0e0; background-color: #e5e0e0;
} }
.linkbutton { .linkbutton {
display: inline-block; display: inline-block;
@ -101,6 +102,21 @@ input[type="checkbox"].input-validation-error {
border: 0; border: 0;
vertical-align: middle; vertical-align: middle;
} }
.linkbutton.edit { .linkbutton.edit {
background: url('/Content/icons/edit.gif'); background: url('/Content/icons/edit.gif');
} }
.modal-dialog {
margin-top: 80px;
}
.affix {
position: fixed;
top: 55px;
left: 25px;
}
.navbar-header-hidden {
display: none;
}

View File

@ -1,35 +1,49 @@
#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;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Security.Claims; using System.Security.Claims;
using System.Text;
using System.Threading.Tasks; 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; using Newtonsoft.Json;
#endif
namespace Fab2ApprovalSystem.Controllers; namespace Fab2ApprovalSystem.Controllers;
[Authorize] [Authorize]
#if NET8
[Route("[controller]")]
#endif
public class AccountController : Controller { public class AccountController : Controller {
private string _apiBaseUrl;
#if !NET8
public AccountController() public AccountController()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()))) { : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()))) {
_apiBaseUrl = Environment.GetEnvironmentVariable("FabApprovalApiBaseUrl") ??
throw new ArgumentNullException("FabApprovalApiBaseUrl environment variable not found");
} }
public AccountController(UserManager<ApplicationUser> userManager) { public AccountController(UserManager<ApplicationUser> userManager) {
@ -38,25 +52,23 @@ public class AccountController : Controller {
public UserManager<ApplicationUser> UserManager { get; private set; } public UserManager<ApplicationUser> UserManager { get; private set; }
#endif
#if !NET8
// GET: /Account/Login // GET: /Account/Login
[AllowAnonymous] [AllowAnonymous]
// try to make the browser refresh the login page every time, to prevent issues with changing usernames and the anti-forgery token validation // 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 = "*")] [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
#endif
public ActionResult Login(string returnUrl) { public ActionResult Login(string returnUrl) {
ViewBag.ReturnUrl = returnUrl; ViewBag.ReturnUrl = returnUrl;
return View(); return View();
} }
private void SetSessionParameters(LoginResult loginResult, LoginModel user) { #if !NET8
Session["JWT"] = loginResult.AuthTokens.JwtToken;
Session["RefreshToken"] = loginResult.AuthTokens.RefreshToken;
Session[GlobalVars.SESSION_USERID] = user.UserID; private void SetSessionParameters(LoginResult loginResult, LoginModel user) {
Session[GlobalVars.SESSION_USERNAME] = user.FullName; GlobalVars.SetSessionParameters(GetSession(), loginResult, user);
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);
FormsAuthentication.SetAuthCookie(user.LoginID, true); FormsAuthentication.SetAuthCookie(user.LoginID, true);
} }
@ -69,7 +81,7 @@ public class AccountController : Controller {
bool isLoginValid; bool isLoginValid;
HttpClient httpClient = HttpClientFactory.Create(); HttpClient httpClient = HttpClientFactory.Create();
httpClient.BaseAddress = new Uri(_apiBaseUrl); httpClient.BaseAddress = new Uri(GlobalVars.AppSettings.ApiBaseUrl);
LoginResult loginResult = await AccountDMO.LoginAsync(httpClient, model); LoginResult loginResult = await AccountDMO.LoginAsync(httpClient, model);
@ -105,8 +117,8 @@ public class AccountController : Controller {
ModelState.AddModelError("", "The user name or password provided is incorrect."); ModelState.AddModelError("", "The user name or password provided is incorrect.");
} }
} catch (Exception ex) { } catch (Exception ex) {
Functions.WriteEvent(GlobalVars.AppSettings, @User.Identity.Name + " " + ex.InnerException, System.Diagnostics.EventLogEntryType.Error); Functions.WriteEvent(GlobalVars.AppSettings, GetUserIdentityName() + " " + ex.InnerException, System.Diagnostics.EventLogEntryType.Error);
EventLogDMO.Add(new WinEventLog() { IssueID = 99999, UserID = @User.Identity.Name, DocumentType = "Login", OperationType = "Error", Comments = "Reject - " + ex.Message }); EventLogDMO.Add(new WinEventLog() { IssueID = 99999, UserID = GetUserIdentityName(), DocumentType = "Login", OperationType = "Error", Comments = "Reject - " + ex.Message });
ModelState.AddModelError("", ex.Message); ModelState.AddModelError("", ex.Message);
} }
@ -121,7 +133,7 @@ public class AccountController : Controller {
bool isLoginValid; bool isLoginValid;
HttpClient httpClient = HttpClientFactory.Create(); HttpClient httpClient = HttpClientFactory.Create();
httpClient.BaseAddress = new Uri(_apiBaseUrl); httpClient.BaseAddress = new Uri(GlobalVars.AppSettings.ApiBaseUrl);
LoginResult loginResult = await AccountDMO.ExternalAuthSetupAsync(httpClient, authAttempt); LoginResult loginResult = await AccountDMO.ExternalAuthSetupAsync(httpClient, authAttempt);
@ -161,20 +173,24 @@ public class AccountController : Controller {
return new HttpResponseMessage(HttpStatusCode.Unauthorized); return new HttpResponseMessage(HttpStatusCode.Unauthorized);
} }
} catch (Exception ex) { } catch (Exception ex) {
Functions.WriteEvent(GlobalVars.AppSettings, @User.Identity.Name + " " + ex.InnerException, System.Diagnostics.EventLogEntryType.Error); Functions.WriteEvent(GlobalVars.AppSettings, GetUserIdentityName() + " " + ex.InnerException, System.Diagnostics.EventLogEntryType.Error);
EventLogDMO.Add(new WinEventLog() { IssueID = 99999, UserID = @User.Identity.Name, DocumentType = "Login", OperationType = "Error", Comments = "Reject - " + ex.Message }); EventLogDMO.Add(new WinEventLog() { IssueID = 99999, UserID = GetUserIdentityName(), DocumentType = "Login", OperationType = "Error", Comments = "Reject - " + ex.Message });
ModelState.AddModelError("", ex.Message); ModelState.AddModelError("", ex.Message);
return new HttpResponseMessage(HttpStatusCode.InternalServerError); return new HttpResponseMessage(HttpStatusCode.InternalServerError);
} }
} }
#endif
// GET: /Account/Register // GET: /Account/Register
[AllowAnonymous] [AllowAnonymous]
public ActionResult Register() { public ActionResult Register() {
return View(); return View();
} }
#if !NET8
// POST: /Account/Disassociate // POST: /Account/Disassociate
[HttpPost] [HttpPost]
[ValidateAntiForgeryToken] [ValidateAntiForgeryToken]
@ -189,6 +205,8 @@ public class AccountController : Controller {
return RedirectToAction("Manage", new { Message = message }); return RedirectToAction("Manage", new { Message = message });
} }
#endif
// GET: /Account/Manage // GET: /Account/Manage
#pragma warning disable IDE0060 // Remove unused parameter #pragma warning disable IDE0060 // Remove unused parameter
public ActionResult Manage(ManageMessageId? message) { public ActionResult Manage(ManageMessageId? message) {
@ -196,6 +214,8 @@ public class AccountController : Controller {
} }
#pragma warning restore IDE0060 // Remove unused parameter #pragma warning restore IDE0060 // Remove unused parameter
#if !NET8
// POST: /Account/ExternalLogin // POST: /Account/ExternalLogin
[HttpPost] [HttpPost]
[AllowAnonymous] [AllowAnonymous]
@ -226,7 +246,6 @@ public class AccountController : Controller {
return RedirectToAction("Manage", new { Message = ManageMessageId.Error }); return RedirectToAction("Manage", new { Message = ManageMessageId.Error });
} }
// POST: /Account/LogOff
[HttpPost] [HttpPost]
[ValidateAntiForgeryToken] [ValidateAntiForgeryToken]
public ActionResult LogOff() { public ActionResult LogOff() {
@ -234,12 +253,15 @@ public class AccountController : Controller {
return RedirectToAction("Login", "Account"); return RedirectToAction("Login", "Account");
} }
// GET: /Account/ExternalLoginFailure #endif
[AllowAnonymous] [AllowAnonymous]
public ActionResult ExternalLoginFailure() { public ActionResult ExternalLoginFailure() {
return View(); return View();
} }
#if !NET8
[ChildActionOnly] [ChildActionOnly]
public ActionResult RemoveAccountList() { public ActionResult RemoveAccountList() {
IList<UserLoginInfo> linkedAccounts = UserManager.GetLogins(User.Identity.GetUserId()); IList<UserLoginInfo> linkedAccounts = UserManager.GetLogins(User.Identity.GetUserId());
@ -255,10 +277,14 @@ public class AccountController : Controller {
base.Dispose(disposing); base.Dispose(disposing);
} }
#endif
#region Helpers #region Helpers
// Used for XSRF protection when adding external logins // Used for XSRF protection when adding external logins
private const string XsrfKey = "XsrfId"; private const string XsrfKey = "XsrfId";
#if !NET8
private IAuthenticationManager AuthenticationManager { private IAuthenticationManager AuthenticationManager {
get { get {
return HttpContext.GetOwinContext().Authentication; return HttpContext.GetOwinContext().Authentication;
@ -285,6 +311,8 @@ public class AccountController : Controller {
return false; return false;
} }
#endif
public enum ManageMessageId { public enum ManageMessageId {
ChangePasswordSuccess, ChangePasswordSuccess,
SetPasswordSuccess, SetPasswordSuccess,
@ -300,7 +328,18 @@ public class AccountController : Controller {
} }
} }
#if !NET8
private class ChallengeResult : HttpUnauthorizedResult { private class ChallengeResult : HttpUnauthorizedResult {
#endif
#if NET8
private class ChallengeResult {
#endif
public ChallengeResult(string provider, string redirectUri) : this(provider, redirectUri, null) { public ChallengeResult(string provider, string redirectUri) : this(provider, redirectUri, null) {
} }
@ -314,6 +353,8 @@ public class AccountController : Controller {
public string RedirectUri { get; set; } public string RedirectUri { get; set; }
public string UserId { get; set; } public string UserId { get; set; }
#if !NET8
public override void ExecuteResult(ControllerContext context) { public override void ExecuteResult(ControllerContext context) {
AuthenticationProperties properties = new AuthenticationProperties() { RedirectUri = RedirectUri }; AuthenticationProperties properties = new AuthenticationProperties() { RedirectUri = RedirectUri };
if (UserId != null) { if (UserId != null) {
@ -321,6 +362,40 @@ public class AccountController : Controller {
} }
context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider); context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
} }
#endif
} }
#endregion #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;
} }

View File

@ -1,31 +1,47 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; #if !NET8
using System.Web; using System.Web;
using System.Web.Mvc; using System.Web.Mvc;
#endif
#if NET8
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
#endif
using Fab2ApprovalSystem.DMO; using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Misc; using Fab2ApprovalSystem.Misc;
using Fab2ApprovalSystem.Models; using Fab2ApprovalSystem.Models;
#if !NET8
using System.Linq;
using Fab2ApprovalSystem.ViewModels; using Fab2ApprovalSystem.ViewModels;
#endif
#if !NET8
using Kendo.Mvc.Extensions; using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI; using Kendo.Mvc.UI;
#endif
namespace Fab2ApprovalSystem.Controllers; namespace Fab2ApprovalSystem.Controllers;
[Authorize] [Authorize]
#if !NET8
[SessionExpireFilter] [SessionExpireFilter]
#endif
#if NET8
[Route("[controller]")]
#endif
public class AdminController : Controller { public class AdminController : Controller {
// GET: /Admin/ // GET: /Admin/
UserAccountDMO userDMO = new UserAccountDMO(); private readonly UserAccountDMO userDMO = new();
AdminDMO adminDMO = new AdminDMO(); private readonly AdminDMO adminDMO = new();
TrainingDMO trainingDMO = new TrainingDMO(); private readonly TrainingDMO trainingDMO = new();
LotDispositionDMO ldDMO = new LotDispositionDMO(); private readonly LotDispositionDMO ldDMO = new();
private readonly AppSettings _AppSettings = GlobalVars.AppSettings; private readonly AppSettings? _AppSettings = GlobalVars.AppSettings;
public ActionResult Index() { public ActionResult Index() {
if ((bool)Session[GlobalVars.IS_ADMIN]) { if (GlobalVars.IsAdmin(GetSession())) {
var model = userDMO.GetAllUsers(); var model = userDMO.GetAllUsers();
ViewBag.AllActiveUsers = userDMO.GetAllActiveUsers(); ViewBag.AllActiveUsers = userDMO.GetAllActiveUsers();
return View(model); return View(model);
@ -33,8 +49,10 @@ public class AdminController : Controller {
return Content("Not Autthorized"); return Content("Not Autthorized");
} }
#if !NET8
public ActionResult AssignRoles() { public ActionResult AssignRoles() {
if ((bool)Session[GlobalVars.IS_ADMIN]) { if (GlobalVars.IsAdmin(GetSession())) {
ViewBag.ToplevelNode = GetRoles_SubRolesList(); ViewBag.ToplevelNode = GetRoles_SubRolesList();
return View(); return View();
} else } else
@ -43,36 +61,33 @@ public class AdminController : Controller {
public ActionResult GetAllUserList([DataSourceRequest] DataSourceRequest request) { public ActionResult GetAllUserList([DataSourceRequest] DataSourceRequest request) {
IEnumerable<LoginModel> userlist = userDMO.GetAllActiveUsers(); IEnumerable<LoginModel> userlist = userDMO.GetAllActiveUsers();
return Json(userlist, JsonRequestBehavior.AllowGet); return GetJsonResult(userlist);
} }
/// <summary>
/// For the Administration of the Users
/// </summary>
public ActionResult GetGridUserList([DataSourceRequest] DataSourceRequest request) { public ActionResult GetGridUserList([DataSourceRequest] DataSourceRequest request) {
return Json(userDMO.GetAllUsers().ToDataSourceResult(request)); return GetJsonResult(userDMO.GetAllUsers().ToDataSourceResult(request));
} }
#endif
public JsonResult GetAllUserListBySubRole(int subRole) { public JsonResult GetAllUserListBySubRole(int subRole) {
IEnumerable<LoginModel> userlist = adminDMO.GetAllUsersBySubRole(subRole); IEnumerable<LoginModel> userlist = adminDMO.GetAllUsersBySubRole(subRole);
return Json(userlist, JsonRequestBehavior.AllowGet); return GetJsonResult(userlist);
} }
public JsonResult AllSubRoles(string showInactiveRoles = "") { public JsonResult AllSubRoles(string showInactiveRoles = "") {
List<ParentChildModel> newRoles = adminDMO.GetAllSubRoles(showInactiveRoles); List<ParentChildModel> newRoles = adminDMO.GetAllSubRoles(showInactiveRoles);
return GetJsonResult(newRoles);
return Json(newRoles, JsonRequestBehavior.AllowGet);
} }
#if !NET8
public ActionResult GetSubRoleListByUserId([DataSourceRequest] DataSourceRequest request, string userId) { public ActionResult GetSubRoleListByUserId([DataSourceRequest] DataSourceRequest request, string userId) {
int userIdInt = Convert.ToInt32(userId); int userIdInt = Convert.ToInt32(userId);
return Json(adminDMO.GetUserSubRoles(userIdInt).ToDataSourceResult(request)); return Json(adminDMO.GetUserSubRoles(userIdInt).ToDataSourceResult(request));
} }
/// <summary>
/// OBSOLETE FUNCTION BELOW FOR THE KENDO TREEVIEW
/// </summary>
private IEnumerable<TreeViewItemModel> GetRoles_SubRolesList() { private IEnumerable<TreeViewItemModel> GetRoles_SubRolesList() {
List<Role> roles = adminDMO.GetSubRoles(); List<Role> roles = adminDMO.GetSubRoles();
@ -103,6 +118,8 @@ public class AdminController : Controller {
return ToplevelNode; return ToplevelNode;
} }
#endif
public ActionResult AddUserRoles(int subRole, string users) { public ActionResult AddUserRoles(int subRole, string users) {
adminDMO.AddUserRoles(subRole, users); adminDMO.AddUserRoles(subRole, users);
return View(); return View();
@ -128,6 +145,8 @@ public class AdminController : Controller {
return View(); return View();
} }
#if !NET8
// POST: /Workflow/Create // POST: /Workflow/Create
[HttpPost] [HttpPost]
public ActionResult Create(FormCollection collection) { public ActionResult Create(FormCollection collection) {
@ -154,12 +173,16 @@ public class AdminController : Controller {
return Json(new[] { model }.ToDataSourceResult(request, ModelState)); return Json(new[] { model }.ToDataSourceResult(request, ModelState));
} }
#endif
public ActionResult DeleteUser(string userId) { public ActionResult DeleteUser(string userId) {
LoginModel loginModel = userDMO.GetUserByID(Convert.ToInt32(userId)); LoginModel loginModel = userDMO.GetUserByID(Convert.ToInt32(userId));
adminDMO.DeleteUser(userDMO, trainingDMO, loginModel); adminDMO.DeleteUser(userDMO, trainingDMO, loginModel);
return Content("Success"); return Content("Success");
} }
#if !NET8
[AcceptVerbs(HttpVerbs.Post)] [AcceptVerbs(HttpVerbs.Post)]
public ActionResult InsertUser([DataSourceRequest] DataSourceRequest request, LoginModel model) { public ActionResult InsertUser([DataSourceRequest] DataSourceRequest request, LoginModel model) {
try { try {
@ -174,6 +197,8 @@ public class AdminController : Controller {
return Json(new[] { model }.ToDataSourceResult(request, ModelState)); return Json(new[] { model }.ToDataSourceResult(request, ModelState));
} }
#endif
public ActionResult EnableOOOStatus(int oooUserID, int delegatedTo, DateTime startDate, DateTime endDate) { public ActionResult EnableOOOStatus(int oooUserID, int delegatedTo, DateTime startDate, DateTime endDate) {
int returnValue = MiscDMO.EnableOOOStatus(oooUserID, delegatedTo, startDate, endDate); int returnValue = MiscDMO.EnableOOOStatus(oooUserID, delegatedTo, startDate, endDate);
if (returnValue == 3) // the delegator is already a delegator to someone else if (returnValue == 3) // the delegator is already a delegator to someone else
@ -191,7 +216,7 @@ public class AdminController : Controller {
} }
public ActionResult ManageTrainingGroups() { public ActionResult ManageTrainingGroups() {
if ((bool)Session[GlobalVars.IS_ADMIN]) { if (GlobalVars.IsAdmin(GetSession())) {
ViewBag.AllGroups = GetTrainingGroups(); ViewBag.AllGroups = GetTrainingGroups();
return View(); return View();
} else } else
@ -212,15 +237,17 @@ public class AdminController : Controller {
return TrainingGroups; return TrainingGroups;
} }
#if !NET8
public ActionResult GetTaskListByUser([DataSourceRequest] DataSourceRequest request, string userId) { public ActionResult GetTaskListByUser([DataSourceRequest] DataSourceRequest request, string userId) {
IEnumerable<IssuesViewModel> data = ldDMO.GetTaskList(Convert.ToInt32(userId)); IEnumerable<IssuesViewModel> data = ldDMO.GetTaskList(Convert.ToInt32(userId));
data = from a in data where a.PendingApprovers != null select a; 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) { public ActionResult GetOpenActionItemsByUser([DataSourceRequest] DataSourceRequest request, string userId) {
IEnumerable<OpenActionItemViewModel> data = ldDMO.GetMyOpenActionItems(Convert.ToInt32(userId)); IEnumerable<OpenActionItemViewModel> data = ldDMO.GetMyOpenActionItems(Convert.ToInt32(userId));
return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet); return GetJsonResult(data.ToDataSourceResult(request));
} }
public ActionResult AddNewTrainingGroup(string groupName) { public ActionResult AddNewTrainingGroup(string groupName) {
@ -232,6 +259,8 @@ public class AdminController : Controller {
} }
} }
#endif
public ActionResult DeleteTrainingGroup(int groupID) { public ActionResult DeleteTrainingGroup(int groupID) {
try { try {
adminDMO.DeleteTrainingGroup(groupID); adminDMO.DeleteTrainingGroup(groupID);
@ -246,6 +275,8 @@ public class AdminController : Controller {
return View(); return View();
} }
#if !NET8
public ActionResult TrainingGroupPartial(int TrainingGroupID) { public ActionResult TrainingGroupPartial(int TrainingGroupID) {
ViewBag.AllUsers = userDMO.GetAllActiveUsers(); ViewBag.AllUsers = userDMO.GetAllActiveUsers();
ViewBag.TrainingGroupId = TrainingGroupID; ViewBag.TrainingGroupId = TrainingGroupID;
@ -263,6 +294,8 @@ public class AdminController : Controller {
return Json(new { test = "Succesfully saved" }); return Json(new { test = "Succesfully saved" });
} }
#endif
public ActionResult DeleteFromGroup(int userId, int groupId) { public ActionResult DeleteFromGroup(int userId, int groupId) {
try { try {
adminDMO.DeleteFromGroup(userId, groupId); adminDMO.DeleteFromGroup(userId, groupId);
@ -274,7 +307,7 @@ public class AdminController : Controller {
} }
public ActionResult JobSchedulerConfiguration() { public ActionResult JobSchedulerConfiguration() {
if ((bool)Session[GlobalVars.IS_ADMIN]) { if (GlobalVars.IsAdmin(GetSession())) {
return View(); return View();
} else } else
return Content("Not Autthorized"); return Content("Not Autthorized");
@ -283,7 +316,7 @@ public class AdminController : Controller {
public ActionResult TrainingReportConfig() { public ActionResult TrainingReportConfig() {
ViewBag.AllUsers = userDMO.GetAllActiveUsers(); ViewBag.AllUsers = userDMO.GetAllActiveUsers();
List<TrainingReportUser> currentTrainingReportUsersIds = adminDMO.GetTrainingReportUsers(); List<TrainingReportUser> currentTrainingReportUsersIds = adminDMO.GetTrainingReportUsers();
List<LoginModel> currentTrainingReportUsers = new List<LoginModel>(); List<LoginModel> currentTrainingReportUsers = new();
foreach (TrainingReportUser id in currentTrainingReportUsersIds) { foreach (TrainingReportUser id in currentTrainingReportUsersIds) {
currentTrainingReportUsers.Add(userDMO.GetUserByID(id.UserId)); currentTrainingReportUsers.Add(userDMO.GetUserByID(id.UserId));
@ -292,10 +325,12 @@ public class AdminController : Controller {
return PartialView(); return PartialView();
} }
#if !NET8
public ActionResult TECNNotificationConfig() { public ActionResult TECNNotificationConfig() {
ViewBag.AllUsers = userDMO.GetAllActiveUsers(); ViewBag.AllUsers = userDMO.GetAllActiveUsers();
List<TECNNotificationsUser> currentTECNNotificationUsersIds = adminDMO.GetTECNNotificationUsers(); List<TECNNotificationsUser> currentTECNNotificationUsersIds = adminDMO.GetTECNNotificationUsers();
List<LoginModel> currentTECNNotificationUsers = new List<LoginModel>(); List<LoginModel> currentTECNNotificationUsers = new();
foreach (TECNNotificationsUser id in currentTECNNotificationUsersIds) { foreach (TECNNotificationsUser id in currentTECNNotificationUsersIds) {
currentTECNNotificationUsers.Add(userDMO.GetUserByID(id.UserId)); currentTECNNotificationUsers.Add(userDMO.GetUserByID(id.UserId));
@ -304,8 +339,10 @@ public class AdminController : Controller {
return PartialView(); return PartialView();
} }
#endif
public ActionResult AddToTrainingReport(int userId) { 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 // Check to make sure user is not apart of the group already
bool userExists = false; bool userExists = false;
List<TrainingReportUser> existingUsers = adminDMO.GetTrainingReportUsers(); List<TrainingReportUser> existingUsers = adminDMO.GetTrainingReportUsers();
@ -329,8 +366,10 @@ public class AdminController : Controller {
} }
} }
#if !NET8
public ActionResult AddToTECNNotification(int userId) { 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 // Check to make sure user is not apart of the group already
bool userExists = false; bool userExists = false;
List<TECNNotificationsUser> existingUsers = adminDMO.GetTECNNotificationUsers(); List<TECNNotificationsUser> existingUsers = adminDMO.GetTECNNotificationUsers();
@ -360,8 +399,10 @@ public class AdminController : Controller {
} }
} }
#endif
public ActionResult DeleteFromTrainingReport(int userId) { public ActionResult DeleteFromTrainingReport(int userId) {
if ((bool)Session[GlobalVars.IS_ADMIN]) { if (GlobalVars.IsAdmin(GetSession())) {
try { try {
adminDMO.TrainingReportDeleteUser(userId); adminDMO.TrainingReportDeleteUser(userId);
return Content("Successfully Deleted"); return Content("Successfully Deleted");
@ -374,7 +415,7 @@ public class AdminController : Controller {
} }
public ActionResult DeleteFromTECNNotification(int userId) { public ActionResult DeleteFromTECNNotification(int userId) {
if ((bool)Session[GlobalVars.IS_ADMIN]) { if (GlobalVars.IsAdmin(GetSession())) {
try { try {
adminDMO.TECNExpirationDeleteUser(userId); adminDMO.TECNExpirationDeleteUser(userId);
return Content("Successfully Deleted"); 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;
} }

View File

@ -1,27 +1,43 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Configuration; #if !NET8
using System.Linq;
using System.Web; using System.Web;
using System.Web.Mvc; using System.Web.Mvc;
#endif
#if NET8
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
#endif
using Fab2ApprovalSystem.DMO; using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Misc; using Fab2ApprovalSystem.Misc;
using Fab2ApprovalSystem.Models; using Fab2ApprovalSystem.Models;
#if !NET8
using System.Configuration;
using System.Linq;
using Fab2ApprovalSystem.Utilities; using Fab2ApprovalSystem.Utilities;
#endif
#if !NET8
using Kendo.Mvc.Extensions; using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI; using Kendo.Mvc.UI;
#endif
namespace Fab2ApprovalSystem.Controllers; namespace Fab2ApprovalSystem.Controllers;
[Authorize] [Authorize]
#if !NET8
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
[SessionExpireFilter] [SessionExpireFilter]
#endif
#if NET8
[Route("[controller]")]
#endif
public class AuditController : Controller { public class AuditController : Controller {
AuditDMO auditDMO = new AuditDMO(GlobalVars.AppSettings); private readonly AuditDMO auditDMO = new(GlobalVars.AppSettings);
CorrectiveActionDMO caDMO = new CorrectiveActionDMO(); private readonly CorrectiveActionDMO caDMO = new();
private readonly AppSettings _AppSettings = GlobalVars.AppSettings; private readonly AppSettings _AppSettings = GlobalVars.AppSettings;
// GET: Audit // GET: Audit
@ -30,11 +46,11 @@ public class AuditController : Controller {
} }
public ActionResult Create() { public ActionResult Create() {
Audit audit = new Audit(); Audit audit = new();
try { try {
// TODO: Add insert logic here // TODO: Add insert logic here
audit.OriginatorID = (int)Session[GlobalVars.SESSION_USERID]; audit.OriginatorID = GlobalVars.GetUserId(GetSession());
auditDMO.InsertAudit(audit); auditDMO.InsertAudit(audit);
return RedirectToAction("Edit", new { issueID = audit.AuditNo }); return RedirectToAction("Edit", new { issueID = audit.AuditNo });
} catch (Exception e) { } catch (Exception e) {
@ -45,19 +61,20 @@ public class AuditController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + audit.AuditNo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); 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 = @User.Identity.Name, DocumentType = "Audit", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); EventLogDMO.Add(new WinEventLog() { IssueID = audit.AuditNo, UserID = GetUserIdentityName(), DocumentType = "Audit", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
} }
public ActionResult Edit(int issueID) { public ActionResult Edit(int issueID) {
int isITARCompliant = 1; int isITARCompliant = 1;
Audit audit = new Audit(); Audit audit = new();
try { try {
bool isAdmin = (bool)Session[GlobalVars.IS_ADMIN]; bool isAdmin = GlobalVars.IsAdmin(GetSession());
int userId = (int)Session[GlobalVars.SESSION_USERID]; int userId = GlobalVars.GetUserId(GetSession());
audit = auditDMO.GetAuditItem(issueID, userId);
AuditEdit auditEdit = auditDMO.GetAuditEdit(issueID, audit, isAdmin, userId); AuditEdit auditEdit = auditDMO.GetAuditEdit(issueID, audit, isAdmin, userId);
if (auditEdit.RedirectToAction) if (auditEdit.RedirectToAction)
return RedirectToAction("ReadOnlyAudit", new { auditNo = audit.AuditNo }); return RedirectToAction("ReadOnlyAudit", new { auditNo = audit.AuditNo });
@ -80,8 +97,8 @@ public class AuditController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + audit.AuditNo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); 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 = @User.Identity.Name, DocumentType = "Audit", OperationType = "Error", Comments = "Edit - " + exceptionString }); EventLogDMO.Add(new WinEventLog() { IssueID = audit.AuditNo, UserID = GetUserIdentityName(), DocumentType = "Audit", OperationType = "Error", Comments = "Edit - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
@ -92,7 +109,7 @@ public class AuditController : Controller {
public ActionResult Edit(Audit model) { public ActionResult Edit(Audit model) {
try { try {
var data = model; var data = model;
auditDMO.UpdateAudit(model, (int)Session[GlobalVars.SESSION_USERID]); auditDMO.UpdateAudit(model, GlobalVars.GetUserId(GetSession()));
} catch (Exception ex) { } catch (Exception ex) {
return Content(ex.Message); return Content(ex.Message);
} }
@ -112,8 +129,8 @@ public class AuditController : Controller {
} }
public ActionResult ReadOnlyAudit(int auditNo) { public ActionResult ReadOnlyAudit(int auditNo) {
Audit audit = new Audit(); Audit audit = new();
audit = auditDMO.GetAuditItemReadOnly(auditNo, (int)Session[GlobalVars.SESSION_USERID]); audit = auditDMO.GetAuditItemReadOnly(auditNo, GlobalVars.GetUserId(GetSession()));
ViewBag.AuditTypeList = auditDMO.GetAuditTypeList(); ViewBag.AuditTypeList = auditDMO.GetAuditTypeList();
ViewBag.AuditorList = auditDMO.GetAuditorList(); ViewBag.AuditorList = auditDMO.GetAuditorList();
@ -123,11 +140,13 @@ public class AuditController : Controller {
return View(audit); return View(audit);
} }
#if !NET8
public ActionResult AuditReportAttachSave(IEnumerable<HttpPostedFileBase> AuditReportFiles, int auditNo) { public ActionResult AuditReportAttachSave(IEnumerable<HttpPostedFileBase> AuditReportFiles, int auditNo) {
try { try {
// The Name of the Upload component is "files" // The Name of the Upload component is "files"
if (AuditReportFiles != null) { if (AuditReportFiles != null) {
int userId = (int)Session[GlobalVars.SESSION_USERID]; int userId = GlobalVars.GetUserId(GetSession());
foreach (var file in AuditReportFiles) { foreach (var file in AuditReportFiles) {
AuditHelper.AuditReportAttachSave(_AppSettings, auditDMO, auditNo, userId, file.FileName, file.InputStream); AuditHelper.AuditReportAttachSave(_AppSettings, auditDMO, auditNo, userId, file.FileName, file.InputStream);
} }
@ -144,6 +163,8 @@ public class AuditController : Controller {
return Json(auditDMO.GetAuditReportAttachments(auditNo).ToDataSourceResult(request)); return Json(auditDMO.GetAuditReportAttachments(auditNo).ToDataSourceResult(request));
} }
#endif
[HttpPost] [HttpPost]
public void DeleteAuditReportAttachment(int attachID) { public void DeleteAuditReportAttachment(int attachID) {
auditDMO.DeleteAuditReportAttachment(attachID); auditDMO.DeleteAuditReportAttachment(attachID);
@ -172,18 +193,21 @@ public class AuditController : Controller {
} }
} }
#if !NET8
public ActionResult GetAuditFindingsList([DataSourceRequest] DataSourceRequest request, int auditNo) { public ActionResult GetAuditFindingsList([DataSourceRequest] DataSourceRequest request, int auditNo) {
return Json(auditDMO.GetAuditFindingsList(auditNo).ToDataSourceResult(request)); return Json(auditDMO.GetAuditFindingsList(auditNo).ToDataSourceResult(request));
} }
#endif
public ActionResult InsertAuditFindingsItem(AuditFindings data) { public ActionResult InsertAuditFindingsItem(AuditFindings data) {
if ((data.FindingType == "Major" || data.FindingType == "Minor") && data.CANo == 0) { 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."); throw new ArgumentException("You must select add a CA for a Major or Minor finding.");
} else { } else {
int userId = (int)Session[GlobalVars.SESSION_USERID]; int userId = GlobalVars.GetUserId(GetSession());
Audit audit = auditDMO.InsertAndGetAudit(caDMO, data, userId); Audit audit = auditDMO.InsertAndGetAudit(caDMO, data, userId);
return GetJsonResult(audit);
return Json(audit, JsonRequestBehavior.AllowGet);
} }
} }
@ -191,25 +215,24 @@ public class AuditController : Controller {
if ((data.FindingType == "Major" || data.FindingType == "Minor") && data.CANo == 0) { 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."); throw new ArgumentException("You must select add a CA for a Major or Minor finding.");
} else { } else {
int userId = (int)Session[GlobalVars.SESSION_USERID]; int userId = GlobalVars.GetUserId(GetSession());
Audit audit = auditDMO.UpdateAndGetAudit(caDMO, data, userId); Audit audit = auditDMO.UpdateAndGetAudit(caDMO, data, userId);
return GetJsonResult(audit);
return Json(audit, JsonRequestBehavior.AllowGet);
} }
} }
public ActionResult DeleteAuditFindingsItem(int auditFindingsID) { public ActionResult DeleteAuditFindingsItem(int auditFindingsID) {
int userId = (int)Session[GlobalVars.SESSION_USERID]; int userId = GlobalVars.GetUserId(GetSession());
Audit audit = auditDMO.DeleteAndGetAudit(auditFindingsID, userId); Audit audit = auditDMO.DeleteAndGetAudit(auditFindingsID, userId);
return Json(audit, JsonRequestBehavior.AllowGet); return GetJsonResult(audit);
} }
public void ReleaseLockOnDocument(int issueID) { public void ReleaseLockOnDocument(int issueID) {
try { try {
auditDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], issueID); auditDMO.ReleaseLockOnDocument(GlobalVars.GetUserId(GetSession()), issueID);
} catch (Exception e) { } catch (Exception e) {
try { 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 { } } catch { }
auditDMO.ReleaseLockOnDocument(-1, issueID); auditDMO.ReleaseLockOnDocument(-1, issueID);
} }
@ -236,6 +259,8 @@ public class AuditController : Controller {
return Content(""); return Content("");
} }
#if !NET8
public ActionResult GetCAFindingsList([DataSourceRequest] DataSourceRequest request, int auditNo) { public ActionResult GetCAFindingsList([DataSourceRequest] DataSourceRequest request, int auditNo) {
return Json(auditDMO.GetCAFindingsList(auditNo).ToDataSourceResult(request)); return Json(auditDMO.GetCAFindingsList(auditNo).ToDataSourceResult(request));
} }
@ -244,8 +269,10 @@ public class AuditController : Controller {
return Json(auditDMO.GetCAFindingsItemAttachments(caFindingsID).ToDataSourceResult(request)); return Json(auditDMO.GetCAFindingsItemAttachments(caFindingsID).ToDataSourceResult(request));
} }
#endif
public ActionResult GetCAFindingsItem(int caFindingsID) { public ActionResult GetCAFindingsItem(int caFindingsID) {
var model = new CAFindings(); CAFindings model = new();
model = auditDMO.GetCAFindingsItem(caFindingsID); model = auditDMO.GetCAFindingsItem(caFindingsID);
return PartialView("_CAFindingsAttachment", model); return PartialView("_CAFindingsAttachment", model);
@ -256,11 +283,13 @@ public class AuditController : Controller {
auditDMO.DeleteCAFindingsItem(caFindingsID); auditDMO.DeleteCAFindingsItem(caFindingsID);
} }
#if !NET8
public ActionResult SaveCAFindings_Attachemnt(IEnumerable<HttpPostedFileBase> CAFindings_Attachemnt, int caFindingsID, int auditNo) { public ActionResult SaveCAFindings_Attachemnt(IEnumerable<HttpPostedFileBase> CAFindings_Attachemnt, int caFindingsID, int auditNo) {
try { try {
// The Name of the Upload component is "files" // The Name of the Upload component is "files"
if (CAFindings_Attachemnt != null) { if (CAFindings_Attachemnt != null) {
int userId = (int)Session[GlobalVars.SESSION_USERID]; int userId = GlobalVars.GetUserId(GetSession());
foreach (var file in CAFindings_Attachemnt) { foreach (var file in CAFindings_Attachemnt) {
AuditHelper.SaveAndInsert(_AppSettings, auditDMO, caFindingsID, auditNo, userId, file.FileName, file.InputStream); AuditHelper.SaveAndInsert(_AppSettings, auditDMO, caFindingsID, auditNo, userId, file.FileName, file.InputStream);
} }
@ -272,12 +301,14 @@ public class AuditController : Controller {
return Content(""); return Content("");
} }
#endif
public void NotifyActionItemOwner(int issueID, DateTime? dueDate, int? responsibleOwnerID) { public void NotifyActionItemOwner(int issueID, DateTime? dueDate, int? responsibleOwnerID) {
try { try {
string email = auditDMO.NotifyActionItemOwner(issueID, dueDate, responsibleOwnerID, _AppSettings.EmailTemplatesPath); string email = auditDMO.NotifyActionItemOwner(issueID, dueDate, responsibleOwnerID, _AppSettings.EmailTemplatesPath);
try { 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 { }
} catch (Exception e) { } catch (Exception e) {
string detailedException = ""; string detailedException = "";
@ -288,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(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "5s/CAFindings Notification - " + exceptionString });
} }
} }
@ -297,4 +328,33 @@ public class AuditController : Controller {
return Content(auditDMO.IsCAAssignedToAudit(caNo, auditNo).ToString()); 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;
} }

View File

@ -1,36 +1,50 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
#if !NET8
using System.Web; using System.Web;
using System.Web.Mvc; using System.Web.Mvc;
using System.Web.Services; using System.Web.Services;
#endif
#if NET8
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
#endif
using Fab2ApprovalSystem.DMO; using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Misc; using Fab2ApprovalSystem.Misc;
using Fab2ApprovalSystem.Models; using Fab2ApprovalSystem.Models;
using Fab2ApprovalSystem.ViewModels; using Fab2ApprovalSystem.ViewModels;
#if !NET8
using Kendo.Mvc.Extensions; using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI; using Kendo.Mvc.UI;
#endif
namespace Fab2ApprovalSystem.Controllers; namespace Fab2ApprovalSystem.Controllers;
[Authorize] [Authorize]
#if !NET8
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
[SessionExpireFilter] [SessionExpireFilter]
#endif
#if NET8
[Route("[controller]")]
#endif
public class ChangeControlController : Controller { public class ChangeControlController : Controller {
ChangeControlDMO ccDMO = new ChangeControlDMO(); private readonly ChangeControlDMO ccDMO = new();
private readonly AppSettings _AppSettings = GlobalVars.AppSettings; private readonly AppSettings? _AppSettings = GlobalVars.AppSettings;
public ActionResult Index() { public ActionResult Index() {
return View(); return View();
} }
public ActionResult Create() { public ActionResult Create() {
ChangeControlViewModel cc = new ChangeControlViewModel(); ChangeControlViewModel cc = new();
try { try {
cc.OwnerID = (int)Session[GlobalVars.SESSION_USERID]; cc.OwnerID = GlobalVars.GetUserId(GetSession());
ccDMO.InsertChangeControl(cc); ccDMO.InsertChangeControl(cc);
return RedirectToAction("Edit", new { issueID = cc.PlanNumber }); return RedirectToAction("Edit", new { issueID = cc.PlanNumber });
} catch (Exception e) { } catch (Exception e) {
@ -41,74 +55,37 @@ public class ChangeControlController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + cc.PlanNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); 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 = @User.Identity.Name, DocumentType = "Change Control", OperationType = "Error", Comments = "Create - " + exceptionString }); EventLogDMO.Add(new WinEventLog() { IssueID = cc.PlanNumber, UserID = GetUserIdentityName(), DocumentType = "Change Control", OperationType = "Error", Comments = "Create - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
} }
public ActionResult Edit(int issueID) { public ActionResult Edit(int issueID) {
int isITARCompliant = 1; string jwt = GlobalVars.GetJWT(GetSession());
ChangeControlViewModel cc = new ChangeControlViewModel(); string encodedJwt = System.Net.WebUtility.UrlEncode(jwt);
cc = ccDMO.GetChangeControlRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); 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}";
List<ApproversListViewModel> userList = MiscDMO.GetApproversListByDocument(cc.PlanNumber, cc.CurrentStep, (int)GlobalVars.DocumentType.ChangeControl); return Redirect(mrbUrl);
ApproversListViewModel appUser = userList.Find(delegate (ApproversListViewModel al) { return al.UserID == (int)Session[GlobalVars.SESSION_USERID]; });
if (appUser != null) {
ViewBag.IsApprover = "true";
}
// TODO locked functionality
if (isITARCompliant == 0) // not ITAR Compliant
{
return View("UnAuthorizedAccess");
} else {
if ((int)Session[GlobalVars.SESSION_USERID] == cc.OwnerID)
ViewBag.IsOriginator = "true";
else
ViewBag.IsOriginator = "false";
if ((cc.RecordLockIndicator && cc.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) ||
cc.ClosedDate != null) {
return RedirectToAction("ReadOnlyCC", new { issueID = issueID });
} else {
cc = ccDMO.GetChangeControl(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]);
ViewBag.Attendees = ccDMO.GetUsers();
ViewBag.Generations = ccDMO.GetGenerations();
ViewBag.PartNumbers = ccDMO.GetPartNumbers();
ViewBag.Processes = ccDMO.GetProcesses();
ViewBag.Logistics = ccDMO.GetLogistics();
ViewBag.AIResponsibles = ccDMO.GetActionItemResponsible();
ViewBag.Sites = ccDMO.GetSites();
return View(cc);
}
}
} }
public ActionResult ReadOnlyCC(int issueID) { public ActionResult ReadOnlyCC(int issueID) {
int isITARCompliant = 1; string jwt = GlobalVars.GetJWT(GetSession());
ChangeControlViewModel cc = new ChangeControlViewModel(); string encodedJwt = System.Net.WebUtility.UrlEncode(jwt);
cc = ccDMO.GetChangeControlRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); string refreshToken = GlobalVars.GetRefreshToken(GetSession());
// TODO locked functionality string encodedRefreshToken = System.Net.WebUtility.UrlEncode(refreshToken);
string mrbUrl = $"{GlobalVars.AppSettings.WasmClientUrl}/redirect?jwt={encodedJwt}&refreshToken={encodedRefreshToken}&redirectPath=pcrb/{issueID}";
if (isITARCompliant == 0) // not ITAR Compliant return Redirect(mrbUrl);
{
return View("UnAuthorizedAccess");
} else {
ViewBag.MeetingList = ccDMO.GetMeetingList(issueID);
ViewBag.Generations = ccDMO.GetGenerations();
ViewBag.PartNumbers = ccDMO.GetPartNumbers();
ViewBag.Processes = ccDMO.GetProcesses();
ViewBag.Logistics = ccDMO.GetLogistics();
return View(cc);
}
} }
[HttpPost] [HttpPost]
public ActionResult Edit(ChangeControlViewModel model) { public ActionResult Edit(ChangeControlViewModel model) {
try { try {
var data = model; var data = model;
ccDMO.UpdateChangeControl(model, (int)Session[GlobalVars.SESSION_USERID]); ccDMO.UpdateChangeControl(model, GlobalVars.GetUserId(GetSession()));
ViewBag.AIResponsibles = ccDMO.GetActionItemResponsible(); ViewBag.AIResponsibles = ccDMO.GetActionItemResponsible();
} catch (Exception ex) { } catch (Exception ex) {
return Content(ex.Message); return Content(ex.Message);
@ -130,10 +107,12 @@ public class ChangeControlController : Controller {
} }
public JsonResult SearchParts(string searchText) { public JsonResult SearchParts(string searchText) {
List<String> partList = MiscDMO.SearchLTParts(searchText.Trim()).Select(x => x.WIPPartData).ToList<String>(); List<string> partList = MiscDMO.SearchLTParts(searchText.Trim()).Select(x => x.WIPPartData).ToList();
return Json(partList, JsonRequestBehavior.AllowGet); return GetJsonResult(partList);
} }
#if !NET8
public ActionResult GetCCAttachments([DataSourceRequest] DataSourceRequest request, int planNumber) { public ActionResult GetCCAttachments([DataSourceRequest] DataSourceRequest request, int planNumber) {
return Json(ccDMO.GetCCAttachment(planNumber).ToDataSourceResult(request)); return Json(ccDMO.GetCCAttachment(planNumber).ToDataSourceResult(request));
} }
@ -167,7 +146,7 @@ public class ChangeControlController : Controller {
public ActionResult AttachSaveCC(IEnumerable<HttpPostedFileBase> files, int planNumber, int attachID) { public ActionResult AttachSaveCC(IEnumerable<HttpPostedFileBase> files, int planNumber, int attachID) {
// The Name of the Upload component is "files" // The Name of the Upload component is "files"
if (files != null) { if (files != null) {
int userId = (int)Session[GlobalVars.SESSION_USERID]; int userId = GlobalVars.GetUserId(GetSession());
foreach (var file in files) { foreach (var file in files) {
ChangeControlHelper.AttachSaveCC(_AppSettings, ccDMO, planNumber, attachID, userId, file.FileName, file.InputStream); ChangeControlHelper.AttachSaveCC(_AppSettings, ccDMO, planNumber, attachID, userId, file.FileName, file.InputStream);
} }
@ -182,6 +161,7 @@ public class ChangeControlController : Controller {
public ActionResult GetMeetingAttachments([DataSourceRequest] DataSourceRequest request, int meetingID) { public ActionResult GetMeetingAttachments([DataSourceRequest] DataSourceRequest request, int meetingID) {
return Json(ccDMO.GetMeetingAttachments(meetingID).ToDataSourceResult(request)); return Json(ccDMO.GetMeetingAttachments(meetingID).ToDataSourceResult(request));
} }
public ActionResult GetPCRB([DataSourceRequest] DataSourceRequest request, int PlanNumber, string PCRB) { public ActionResult GetPCRB([DataSourceRequest] DataSourceRequest request, int PlanNumber, string PCRB) {
return Json(ccDMO.GetPCRB(PlanNumber, PCRB).ToDataSourceResult(request)); return Json(ccDMO.GetPCRB(PlanNumber, PCRB).ToDataSourceResult(request));
} }
@ -214,7 +194,7 @@ public class ChangeControlController : Controller {
public ActionResult AttachSaveMeeting(IEnumerable<HttpPostedFileBase> files, int planNumber, int meetingID, int attachID) { public ActionResult AttachSaveMeeting(IEnumerable<HttpPostedFileBase> files, int planNumber, int meetingID, int attachID) {
// The Name of the Upload component is "files" // The Name of the Upload component is "files"
if (files != null) { if (files != null) {
int userId = (int)Session[GlobalVars.SESSION_USERID]; int userId = GlobalVars.GetUserId(GetSession());
foreach (var file in files) { foreach (var file in files) {
ChangeControlHelper.AttachSaveMeeting(_AppSettings, ccDMO, planNumber, attachID, userId, file.FileName, file.InputStream); ChangeControlHelper.AttachSaveMeeting(_AppSettings, ccDMO, planNumber, attachID, userId, file.FileName, file.InputStream);
} }
@ -222,6 +202,8 @@ public class ChangeControlController : Controller {
return Content(""); return Content("");
} }
#endif
public FileResult DownloadCCFile(string fileGuid, int planNumber) { public FileResult DownloadCCFile(string fileGuid, int planNumber) {
string fileName = ccDMO.GetCCFileName(fileGuid); string fileName = ccDMO.GetCCFileName(fileGuid);
@ -256,20 +238,20 @@ public class ChangeControlController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + planNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); 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 = @User.Identity.Name, DocumentType = "Meeting", OperationType = "Error", Comments = "Create - " + exceptionString }); EventLogDMO.Add(new WinEventLog() { IssueID = planNumber, UserID = GetUserIdentityName(), DocumentType = "Meeting", OperationType = "Error", Comments = "Create - " + exceptionString });
throw new Exception("Error: " + e.Message); throw new Exception("Error: " + e.Message);
} }
} }
public ActionResult EditMeeting(int meetingID) { public ActionResult EditMeeting(int meetingID) {
int isITARCompliant = 1; int isITARCompliant = 1;
CCMeeting meeting = new CCMeeting(); CCMeeting meeting = new();
meeting = ccDMO.GetMeetingRead(meetingID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); meeting = ccDMO.GetMeetingRead(meetingID, out isITARCompliant, GlobalVars.GetUserId(GetSession()));
ViewBag.MeetingList = ccDMO.GetMeetingList(meeting.PlanNumber); ViewBag.MeetingList = ccDMO.GetMeetingList(meeting.PlanNumber);
// TODO locked functionality // TODO locked functionality
List<ApproversListViewModel> userList = MiscDMO.GetApproversListByDocument(meeting.PlanNumber, meeting.CurrentStep, (int)GlobalVars.DocumentType.ChangeControl); List<ApproversListViewModel> 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) { if (appUser != null) {
ViewBag.IsApprover = "true"; ViewBag.IsApprover = "true";
} }
@ -278,7 +260,7 @@ public class ChangeControlController : Controller {
{ {
return View("UnAuthorizedAccess"); return View("UnAuthorizedAccess");
} else { } else {
if ((meeting.RecordLockIndicator && meeting.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) if ((meeting.RecordLockIndicator && meeting.RecordLockedBy != GlobalVars.GetUserId(GetSession()))
|| (meeting.PCRBClosed)) { || (meeting.PCRBClosed)) {
return RedirectToAction("ReadOnlyMeeting", new { meetingID = meetingID }); return RedirectToAction("ReadOnlyMeeting", new { meetingID = meetingID });
} else if (meeting.Decision != -1) { } else if (meeting.Decision != -1) {
@ -288,7 +270,7 @@ public class ChangeControlController : Controller {
ViewBag.Attendees = ccDMO.GetUsers(); ViewBag.Attendees = ccDMO.GetUsers();
ViewBag.Sites = ccDMO.GetSites(); ViewBag.Sites = ccDMO.GetSites();
ViewBag.PCRValues = ccDMO.GetPCRValues(); 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); return View(meeting);
} }
@ -297,8 +279,8 @@ public class ChangeControlController : Controller {
public ActionResult ReadOnlyMeeting(int meetingID) { public ActionResult ReadOnlyMeeting(int meetingID) {
int isITARCompliant = 1; int isITARCompliant = 1;
CCMeeting meeting = new CCMeeting(); CCMeeting meeting = new();
meeting = ccDMO.GetMeetingRead(meetingID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); meeting = ccDMO.GetMeetingRead(meetingID, out isITARCompliant, GlobalVars.GetUserId(GetSession()));
ViewBag.MeetingList = ccDMO.GetMeetingList(meeting.PlanNumber); ViewBag.MeetingList = ccDMO.GetMeetingList(meeting.PlanNumber);
ViewBag.PCRValues = ccDMO.GetPCRValues(); ViewBag.PCRValues = ccDMO.GetPCRValues();
@ -323,13 +305,13 @@ public class ChangeControlController : Controller {
public ActionResult EditMeetingUpdate(int meetingID) { public ActionResult EditMeetingUpdate(int meetingID) {
int isITARCompliant = 1; int isITARCompliant = 1;
CCMeeting meeting = new CCMeeting(); CCMeeting meeting = new();
meeting = ccDMO.GetMeetingRead(meetingID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); meeting = ccDMO.GetMeetingRead(meetingID, out isITARCompliant, GlobalVars.GetUserId(GetSession()));
ViewBag.MeetingList = ccDMO.GetMeetingList(meeting.PlanNumber); ViewBag.MeetingList = ccDMO.GetMeetingList(meeting.PlanNumber);
ViewBag.PCRValues = ccDMO.GetPCRValues(); ViewBag.PCRValues = ccDMO.GetPCRValues();
// TODO locked functionality // TODO locked functionality
List<ApproversListViewModel> userList = MiscDMO.GetApproversListByDocument(meeting.PlanNumber, meeting.CurrentStep, (int)GlobalVars.DocumentType.ChangeControl); List<ApproversListViewModel> 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) { if (appUser != null) {
ViewBag.IsApprover = "true"; ViewBag.IsApprover = "true";
} }
@ -338,11 +320,11 @@ public class ChangeControlController : Controller {
{ {
return View("UnAuthorizedAccess"); return View("UnAuthorizedAccess");
} else { } else {
if ((meeting.RecordLockIndicator && meeting.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID]) if ((meeting.RecordLockIndicator && meeting.RecordLockedBy != GlobalVars.GetUserId(GetSession()))
|| (meeting.PCRBClosed)) { || (meeting.PCRBClosed)) {
return RedirectToAction("ReadOnlyMeeting", new { meetingID = meetingID }); return RedirectToAction("ReadOnlyMeeting", new { meetingID = meetingID });
} else { } 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(); ViewBag.AIResponsibles = ccDMO.GetActionItemResponsible();
@ -373,10 +355,14 @@ public class ChangeControlController : Controller {
return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
} }
#if !NET8
public ActionResult GetDecisionsSummaryList([DataSourceRequest] DataSourceRequest request, int meetingID) { public ActionResult GetDecisionsSummaryList([DataSourceRequest] DataSourceRequest request, int meetingID) {
return Json(ccDMO.GetDecisionsSummaryList(meetingID).ToDataSourceResult(request)); return Json(ccDMO.GetDecisionsSummaryList(meetingID).ToDataSourceResult(request));
} }
#endif
public ActionResult UpdateMeetingDecisionNotes(CCDecisionSummary model) { public ActionResult UpdateMeetingDecisionNotes(CCDecisionSummary model) {
try { try {
ccDMO.UpdateDecisionSummary(model); ccDMO.UpdateDecisionSummary(model);
@ -386,6 +372,8 @@ public class ChangeControlController : Controller {
return Content("Saved Succesfully"); return Content("Saved Succesfully");
} }
#if !NET8
[AcceptVerbs(HttpVerbs.Post)] [AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteDecisionsSummary([DataSourceRequest] DataSourceRequest request, CCDecisionSummary model) { public ActionResult DeleteDecisionsSummary([DataSourceRequest] DataSourceRequest request, CCDecisionSummary model) {
if (model != null && ModelState.IsValid) { if (model != null && ModelState.IsValid) {
@ -394,6 +382,8 @@ public class ChangeControlController : Controller {
return Json(new[] { model }.ToDataSourceResult(request, ModelState)); return Json(new[] { model }.ToDataSourceResult(request, ModelState));
} }
#endif
public ActionResult InsertDecisionsSummary(CCDecisionSummary model) { public ActionResult InsertDecisionsSummary(CCDecisionSummary model) {
try { try {
ccDMO.InsertDecisionSummary(model); ccDMO.InsertDecisionSummary(model);
@ -412,19 +402,23 @@ public class ChangeControlController : Controller {
return Content("Saved Succesfully", "application/json"); return Content("Saved Succesfully", "application/json");
} }
#if !NET8
public ActionResult GetMeetingList([DataSourceRequest] DataSourceRequest request, int planNumber) { public ActionResult GetMeetingList([DataSourceRequest] DataSourceRequest request, int planNumber) {
var meetingList = ccDMO.GetMeetingList(planNumber); var meetingList = ccDMO.GetMeetingList(planNumber);
return Json(meetingList.ToDataSourceResult(request)); return Json(meetingList.ToDataSourceResult(request));
} }
///
public ActionResult GetMeetingAttendees([DataSourceRequest] DataSourceRequest request, int meetingID) { public ActionResult GetMeetingAttendees([DataSourceRequest] DataSourceRequest request, int meetingID) {
return Json(ccDMO.GetMeetingAttendees(meetingID).ToDataSourceResult(request)); return Json(ccDMO.GetMeetingAttendees(meetingID).ToDataSourceResult(request));
} }
public ActionResult GetPCRBAttendees([DataSourceRequest] DataSourceRequest request, int PCRBID) { public ActionResult GetPCRBAttendees([DataSourceRequest] DataSourceRequest request, int PCRBID) {
return Json(ccDMO.GetPCRBAttendees(PCRBID).ToDataSourceResult(request)); return Json(ccDMO.GetPCRBAttendees(PCRBID).ToDataSourceResult(request));
} }
#endif
public void InsertNewMeetingAttendee(string attendeeName, string jobTitle, string siteName) { public void InsertNewMeetingAttendee(string attendeeName, string jobTitle, string siteName) {
try { try {
} catch (Exception e) { } catch (Exception e) {
@ -449,8 +443,8 @@ public class ChangeControlController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + docid.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); 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 = @User.Identity.Name, DocumentType = "Change Control", OperationType = "Error", Comments = "UpdateMeetingAttendee - " + exceptionString }); EventLogDMO.Add(new WinEventLog() { IssueID = docid, UserID = GetUserIdentityName(), DocumentType = "Change Control", OperationType = "Error", Comments = "UpdateMeetingAttendee - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
} }
@ -469,12 +463,14 @@ public class ChangeControlController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + docid.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); 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 = @User.Identity.Name, DocumentType = "Change Control", OperationType = "Error", Comments = "UpdateMeetingAttendee - " + exceptionString }); EventLogDMO.Add(new WinEventLog() { IssueID = docid, UserID = GetUserIdentityName(), DocumentType = "Change Control", OperationType = "Error", Comments = "UpdateMeetingAttendee - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
} }
#if !NET8
[AcceptVerbs(HttpVerbs.Post)] [AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteMeetingAttendee([DataSourceRequest] DataSourceRequest request, CCMeetingAttendee model) { public ActionResult DeleteMeetingAttendee([DataSourceRequest] DataSourceRequest request, CCMeetingAttendee model) {
if (model != null && ModelState.IsValid) { if (model != null && ModelState.IsValid) {
@ -512,6 +508,8 @@ public class ChangeControlController : Controller {
return Json(ccDMO.GetMeetingActionItems_All(planNumber).ToDataSourceResult(request)); return Json(ccDMO.GetMeetingActionItems_All(planNumber).ToDataSourceResult(request));
} }
#endif
public ActionResult InsertPCRBActionItem(CCPCRBActionItem model) { public ActionResult InsertPCRBActionItem(CCPCRBActionItem model) {
try { try {
if (model != null) { if (model != null) {
@ -538,6 +536,8 @@ public class ChangeControlController : Controller {
return Content("1"); return Content("1");
} }
#if !NET8
public ActionResult InsertPCRBAttendee([DataSourceRequest] DataSourceRequest request, int pcrId, int attendeeId, string jobTitle, string siteName) { public ActionResult InsertPCRBAttendee([DataSourceRequest] DataSourceRequest request, int pcrId, int attendeeId, string jobTitle, string siteName) {
CCPCRBAttendee newAttendee = new CCPCRBAttendee(); CCPCRBAttendee newAttendee = new CCPCRBAttendee();
newAttendee.AttendeeID = attendeeId; newAttendee.AttendeeID = attendeeId;
@ -554,6 +554,8 @@ public class ChangeControlController : Controller {
return Content("1"); return Content("1");
} }
#endif
public ActionResult UpdatePCRBActionItem(CCPCRBActionItem model) { public ActionResult UpdatePCRBActionItem(CCPCRBActionItem model) {
try { try {
if (model != null) { if (model != null) {
@ -566,10 +568,12 @@ public class ChangeControlController : Controller {
return Content("1"); return Content("1");
} }
#if !NET8
[AcceptVerbs(HttpVerbs.Post)] [AcceptVerbs(HttpVerbs.Post)]
public ActionResult UpdateMeetingActionItemAll([DataSourceRequest] DataSourceRequest request, CCMeetingActionItemAll model) { public ActionResult UpdateMeetingActionItemAll([DataSourceRequest] DataSourceRequest request, CCMeetingActionItemAll model) {
if (model != null && ModelState.IsValid) { if (model != null && ModelState.IsValid) {
model.ClosedBy = (int)Session[GlobalVars.SESSION_USERID]; model.ClosedBy = GlobalVars.GetUserId(GetSession());
ccDMO.UpdateMeetingActionItem_All(model); ccDMO.UpdateMeetingActionItem_All(model);
} }
if (model.ClosedStatus) if (model.ClosedStatus)
@ -580,6 +584,8 @@ public class ChangeControlController : Controller {
return Json(new[] { model }.ToDataSourceResult(request, ModelState)); return Json(new[] { model }.ToDataSourceResult(request, ModelState));
} }
#endif
public ActionResult UpdateMeetingActionItem(CCMeetingActionItem model) { public ActionResult UpdateMeetingActionItem(CCMeetingActionItem model) {
try { try {
if (model != null) { if (model != null) {
@ -594,11 +600,11 @@ public class ChangeControlController : Controller {
[HttpPost] [HttpPost]
public ActionResult ReassignMeetingActionItemResponsiblePersons(int meetingActionItemId, string newResponsiblePersonIDs, string comments) { public ActionResult ReassignMeetingActionItemResponsiblePersons(int meetingActionItemId, string newResponsiblePersonIDs, string comments) {
if (Session[GlobalVars.IS_ADMIN] == null) if (GlobalVars.IsAdminValueNull(GetSession()))
throw new Exception("Permission denied"); throw new Exception("Permission denied");
try { try {
ccDMO.ReassignMeetingActionItemResponsiblePersons(meetingActionItemId, newResponsiblePersonIDs, comments, (int)Session[GlobalVars.SESSION_USERID]); ccDMO.ReassignMeetingActionItemResponsiblePersons(meetingActionItemId, newResponsiblePersonIDs, comments, GlobalVars.GetUserId(GetSession()));
} catch (Exception ex) { } catch (Exception ex) {
return Content(ex.Message.ToString()); return Content(ex.Message.ToString());
} }
@ -606,6 +612,8 @@ public class ChangeControlController : Controller {
return Content("1"); return Content("1");
} }
#if !NET8
[AcceptVerbs(HttpVerbs.Post)] [AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteMeetingActionItem([DataSourceRequest] DataSourceRequest request, CCMeetingActionItem model) { public ActionResult DeleteMeetingActionItem([DataSourceRequest] DataSourceRequest request, CCMeetingActionItem model) {
if (model != null && ModelState.IsValid) { if (model != null && ModelState.IsValid) {
@ -621,6 +629,8 @@ public class ChangeControlController : Controller {
return Json(new[] { model }.ToDataSourceResult(request, ModelState)); return Json(new[] { model }.ToDataSourceResult(request, ModelState));
} }
#endif
public void CompleteCC(int planNumber) { public void CompleteCC(int planNumber) {
int docid = planNumber; int docid = planNumber;
try { try {
@ -633,8 +643,8 @@ public class ChangeControlController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + docid.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); 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 = @User.Identity.Name, DocumentType = "Change Control", OperationType = "Error", Comments = "CompleteCC - " + exceptionString }); EventLogDMO.Add(new WinEventLog() { IssueID = docid, UserID = GetUserIdentityName(), DocumentType = "Change Control", OperationType = "Error", Comments = "CompleteCC - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
} }
@ -651,16 +661,18 @@ public class ChangeControlController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + docid.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); 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 = @User.Identity.Name, DocumentType = "Change Control", OperationType = "Error", Comments = "CancelCC - " + exceptionString }); EventLogDMO.Add(new WinEventLog() { IssueID = docid, UserID = GetUserIdentityName(), DocumentType = "Change Control", OperationType = "Error", Comments = "CancelCC - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
} }
#if !NET8
public ActionResult AttachSaveActionItem(IEnumerable<HttpPostedFileBase> AIfiles, int planNumber, int attachID) { public ActionResult AttachSaveActionItem(IEnumerable<HttpPostedFileBase> AIfiles, int planNumber, int attachID) {
// The Name of the Upload component is "files" // The Name of the Upload component is "files"
if (AIfiles != null) { if (AIfiles != null) {
int userId = (int)Session[GlobalVars.SESSION_USERID]; int userId = GlobalVars.GetUserId(GetSession());
foreach (var file in AIfiles) { foreach (var file in AIfiles) {
ChangeControlHelper.AttachSaveActionItem(_AppSettings, ccDMO, planNumber, attachID, userId, file.FileName, file.InputStream); ChangeControlHelper.AttachSaveActionItem(_AppSettings, ccDMO, planNumber, attachID, userId, file.FileName, file.InputStream);
} }
@ -668,6 +680,8 @@ public class ChangeControlController : Controller {
return Content(""); return Content("");
} }
#endif
public FileResult DownloadActionItemFile(string fileGuid, int planNumber) { public FileResult DownloadActionItemFile(string fileGuid, int planNumber) {
string fileName = ccDMO.GetActionItemFileName(fileGuid); string fileName = ccDMO.GetActionItemFileName(fileGuid);
@ -695,36 +709,36 @@ public class ChangeControlController : Controller {
} }
public void ReleaseLockOnDocument(int planNumber) { public void ReleaseLockOnDocument(int planNumber) {
ccDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], planNumber); ccDMO.ReleaseLockOnDocument(GlobalVars.GetUserId(GetSession()), planNumber);
try { try {
ccDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], planNumber); ccDMO.ReleaseLockOnDocument(GlobalVars.GetUserId(GetSession()), planNumber);
} catch (Exception e) { } catch (Exception e) {
try { 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 { } } catch { }
ccDMO.ReleaseLockOnDocument(-1, planNumber); ccDMO.ReleaseLockOnDocument(-1, planNumber);
} }
} }
public JsonResult GetAllUsersList() { public JsonResult GetAllUsersList() {
UserAccountDMO userDMO = new UserAccountDMO(); UserAccountDMO userDMO = new();
IEnumerable<LoginModel> userlist = userDMO.GetAllUsers(); IEnumerable<LoginModel> userlist = userDMO.GetAllUsers();
return Json(userlist, JsonRequestBehavior.AllowGet); return GetJsonResult(userlist);
} }
[HttpPost] [HttpPost]
public void ReAssignOwnerByAdmin(string planNumber, string comments, int newOwnerId) { public void ReAssignOwnerByAdmin(string planNumber, string comments, int newOwnerId) {
if (Session[GlobalVars.IS_ADMIN] == null) if (GlobalVars.IsAdminValueNull(GetSession()))
throw new Exception("Permission denied"); throw new Exception("Permission denied");
int planNumberInt = 0; int planNumberInt = 0;
try { try {
// remove non-numeric characters from Plan # then convert to int // remove non-numeric characters from Plan # then convert to int
planNumberInt = Int32.Parse(new String(planNumber.Where<char>(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) { } catch (Exception e) {
string detailedException = ""; string detailedException = "";
try { try {
@ -735,17 +749,46 @@ public class ChangeControlController : Controller {
string exceptionString = e.Message.ToString().Trim(); string exceptionString = e.Message.ToString().Trim();
if (exceptionString.Length > 450) if (exceptionString.Length > 450)
exceptionString = exceptionString.Substring(0, 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); 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 = @User.Identity.Name, DocumentType = "ChangeControl", OperationType = "Error", Comments = "ReAssignOwnerByAdmin - " + exceptionString }); EventLogDMO.Add(new WinEventLog() { IssueID = planNumberInt, UserID = GetUserIdentityName(), DocumentType = "ChangeControl", OperationType = "Error", Comments = "ReAssignOwnerByAdmin - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
} }
public ActionResult GetPCRBMesaTitle(int issueID) { public ActionResult GetPCRBMesaTitle(int issueID) {
int isItarCompliant = 1; 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; string content = cc.PlanTitle;
return Content(content); 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;
} }

View File

@ -1,43 +1,63 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Configuration;
using System.Linq; using System.Linq;
#if !NET8
using System.Web; using System.Web;
using System.Web.Mvc; using System.Web.Mvc;
#endif
#if NET8
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
#endif
using Fab2ApprovalSystem.DMO; using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Misc; using Fab2ApprovalSystem.Misc;
using Fab2ApprovalSystem.Models; using Fab2ApprovalSystem.Models;
#if !NET8
using Fab2ApprovalSystem.Utilities; using Fab2ApprovalSystem.Utilities;
#endif
using Fab2ApprovalSystem.ViewModels; using Fab2ApprovalSystem.ViewModels;
#if !NET8
using Kendo.Mvc.Extensions; using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI; using Kendo.Mvc.UI;
#endif
namespace Fab2ApprovalSystem.Controllers; namespace Fab2ApprovalSystem.Controllers;
[Authorize] [Authorize]
#if !NET8
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
[SessionExpireFilter] [SessionExpireFilter]
#endif
#if NET8
[Route("[controller]")]
#endif
public class CorrectiveActionController : Controller { public class CorrectiveActionController : Controller {
AuditDMO auditDMO = new AuditDMO(GlobalVars.AppSettings); private readonly AuditDMO auditDMO = new(GlobalVars.AppSettings);
CorrectiveActionDMO caDMO = new CorrectiveActionDMO(); private readonly CorrectiveActionDMO caDMO = new();
WorkflowDMO wfDMO = new WorkflowDMO(); private readonly WorkflowDMO wfDMO = new();
private readonly AppSettings _AppSettings = GlobalVars.AppSettings; private readonly AppSettings _AppSettings = GlobalVars.AppSettings;
UserAccountDMO userDMO = new UserAccountDMO(); private readonly UserAccountDMO userDMO = new();
#if !NET8
FileUtilities<System.Web.Mvc.FileContentResult> fileUtilities = new FileUtilities<System.Web.Mvc.FileContentResult>(); FileUtilities<System.Web.Mvc.FileContentResult> fileUtilities = new FileUtilities<System.Web.Mvc.FileContentResult>();
#endif
public ActionResult Index() { public ActionResult Index() {
return View(); return View();
} }
public ActionResult Create() { public ActionResult Create() {
CorrectiveAction ca = new CorrectiveAction(); CorrectiveAction ca = new();
try { try {
// TODO: Add insert logic here // TODO: Add insert logic here
ca.RequestorID = (int)Session[GlobalVars.SESSION_USERID]; ca.RequestorID = GlobalVars.GetUserId(GetSession());
caDMO.InsertCA(ca); caDMO.InsertCA(ca);
return RedirectToAction("Edit", new { issueID = ca.CANo }); return RedirectToAction("Edit", new { issueID = ca.CANo });
} catch (Exception e) { } catch (Exception e) {
@ -48,18 +68,18 @@ public class CorrectiveActionController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ca.CANo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); 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 = @User.Identity.Name, DocumentType = "CA", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); EventLogDMO.Add(new WinEventLog() { IssueID = ca.CANo, UserID = GetUserIdentityName(), DocumentType = "CA", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
} }
public ActionResult CreateFromAudit(string title) { public ActionResult CreateFromAudit(string title) {
CorrectiveAction ca = new CorrectiveAction(); CorrectiveAction ca = new();
try { try {
// TODO: Add insert logic here // TODO: Add insert logic here
ca.RequestorID = (int)Session[GlobalVars.SESSION_USERID]; ca.RequestorID = GlobalVars.GetUserId(GetSession());
ca.CASource = "Audit"; ca.CASource = "Audit";
caDMO.InsertCA(ca); caDMO.InsertCA(ca);
string test = ca.CANoDisp; string test = ca.CANoDisp;
@ -72,43 +92,43 @@ public class CorrectiveActionController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ca.CANo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); 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 = @User.Identity.Name, DocumentType = "CA", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); EventLogDMO.Add(new WinEventLog() { IssueID = ca.CANo, UserID = GetUserIdentityName(), DocumentType = "CA", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
} }
public ActionResult Edit(int issueID) { public ActionResult Edit(int issueID) {
CorrectiveAction ca = new CorrectiveAction(); CorrectiveAction ca = new();
string s = Functions.ReturnCANoStringFormat(issueID); string s = Functions.ReturnCANoStringFormat(issueID);
try { try {
List<int> _8DQAList = caDMO.Get8DQA(); List<int> _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"; ViewBag.Is8DQA = "false";
if (QAs != 0) { if (QAs != 0) {
ViewBag.Is8DQA = "true"; ViewBag.Is8DQA = "true";
} }
ca = caDMO.GetCAItem(issueID, (int)Session[GlobalVars.SESSION_USERID]); ca = caDMO.GetCAItem(issueID, GlobalVars.GetUserId(GetSession()));
ViewBag.CanCompleteCA = "false"; ViewBag.CanCompleteCA = "false";
if (ca.D1AssigneeID == (int)Session[GlobalVars.SESSION_USERID]) if (ca.D1AssigneeID == GlobalVars.GetUserId(GetSession()))
ViewBag.CanCompleteCA = "true"; ViewBag.CanCompleteCA = "true";
List<ApproversListViewModel> userList = MiscDMO.GetPendingApproversListByDocument(issueID, ca.CurrentStep, (int)GlobalVars.DocumentType.CorrectiveAction); List<ApproversListViewModel> 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) if (approver == null)
ViewBag.IsApprover = "false"; ViewBag.IsApprover = "false";
else else
ViewBag.IsApprover = "true"; ViewBag.IsApprover = "true";
ViewBag.IsAIAssignee = caDMO.IsAIAssignee((int)Session[GlobalVars.SESSION_USERID], issueID); ViewBag.IsAIAssignee = caDMO.IsAIAssignee(GlobalVars.GetUserId(GetSession()), issueID);
ViewBag.IsSectionApprover = caDMO.IsUserSectionApprover(ca.CANo, (int)Session[GlobalVars.SESSION_USERID]); ViewBag.IsSectionApprover = caDMO.IsUserSectionApprover(ca.CANo, GlobalVars.GetUserId(GetSession()));
ViewBag.AuditFindingCategoriesOptions = auditDMO.GetAuditFindingCategories().ToList(); ViewBag.AuditFindingCategoriesOptions = auditDMO.GetAuditFindingCategories().ToList();
if (ca.RelatedAudit != null && ca.RelatedAudit > 0) { if (ca.RelatedAudit > 0) {
Audit audit = auditDMO.GetAuditItem(ca.RelatedAudit, (int)Session[GlobalVars.SESSION_USERID]); Audit audit = auditDMO.GetAuditItem(ca.RelatedAudit, GlobalVars.GetUserId(GetSession()));
IEnumerable<AuditFindings> auditFindings = auditDMO.GetAuditFindingsList(audit.AuditNo); IEnumerable<AuditFindings> auditFindings = auditDMO.GetAuditFindingsList(audit.AuditNo);
AuditFindings relatedFinding = (from a in auditFindings where a.CANo == ca.CANo select a).First(); 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) || if ((ca.ClosedDate != null) ||
// TODO Aproverslist================================================================ // TODO Aproverslist================================================================
(ca.ClosedDate != null && ViewBag.IsApprover == "false" && ViewBag.IsAIAssignee == "false") || (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 }); return RedirectToAction("ReadOnlyCA", new { caNo = ca.CANo });
} else { } else {
ViewBag.ECNList = caDMO.GetECNList(); ViewBag.ECNList = caDMO.GetECNList();
@ -154,8 +174,8 @@ public class CorrectiveActionController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + ca.CANo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); 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 = @User.Identity.Name, DocumentType = "Audit", OperationType = "Error", Comments = "Edit - " + exceptionString }); EventLogDMO.Add(new WinEventLog() { IssueID = ca.CANo, UserID = GetUserIdentityName(), DocumentType = "Audit", OperationType = "Error", Comments = "Edit - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
@ -164,7 +184,7 @@ public class CorrectiveActionController : Controller {
[HttpPost] [HttpPost]
public ActionResult Edit(CorrectiveAction model) { public ActionResult Edit(CorrectiveAction model) {
int currentUserId = (int)Session[GlobalVars.SESSION_USERID]; int currentUserId = GlobalVars.GetUserId(GetSession());
CorrectiveAction caPrevious = caDMO.GetCAItemReadOnly(model.CANo, currentUserId); CorrectiveAction caPrevious = caDMO.GetCAItemReadOnly(model.CANo, currentUserId);
if ((currentUserId != caPrevious.D1AssigneeID && currentUserId != caPrevious.QAID && currentUserId != caPrevious.RequestorID)) { if ((currentUserId != caPrevious.D1AssigneeID && currentUserId != caPrevious.QAID && currentUserId != caPrevious.RequestorID)) {
return Content("User is not authorized to save the CA."); return Content("User is not authorized to save the CA.");
@ -201,7 +221,7 @@ public class CorrectiveActionController : Controller {
return Content("Successfully Saved...Approval initiated!"); return Content("Successfully Saved...Approval initiated!");
} }
if (model.TriggerApproval) { 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); NotifyApprovers(model.CANo, 1);
return Content("Successfully Saved...Approval initiated!"); return Content("Successfully Saved...Approval initiated!");
} }
@ -213,9 +233,9 @@ public class CorrectiveActionController : Controller {
} }
public ActionResult ReadOnlyCA(int caNo) { 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) { if (ca.Status == 1 || ca.Status == 2 || ca.Status == 11 || ca.ClosedDate != null) {
ViewBag.UserList = caDMO.GetAllUserList(); ViewBag.UserList = caDMO.GetAllUserList();
} else { } else {
@ -227,8 +247,8 @@ public class CorrectiveActionController : Controller {
ViewBag.D5D6ImprovementIDs = caDMO.GetD5D6Improvement(); ViewBag.D5D6ImprovementIDs = caDMO.GetD5D6Improvement();
ViewBag.AuditFindingCategoriesOptions = auditDMO.GetAuditFindingCategories().ToList(); ViewBag.AuditFindingCategoriesOptions = auditDMO.GetAuditFindingCategories().ToList();
if (ca.RelatedAudit != null && ca.RelatedAudit > 0) { if (ca.RelatedAudit > 0) {
Audit audit = auditDMO.GetAuditItem(ca.RelatedAudit, (int)Session[GlobalVars.SESSION_USERID]); Audit audit = auditDMO.GetAuditItem(ca.RelatedAudit, GlobalVars.GetUserId(GetSession()));
IEnumerable<AuditFindings> auditFindings = auditDMO.GetAuditFindingsList(audit.AuditNo); IEnumerable<AuditFindings> auditFindings = auditDMO.GetAuditFindingsList(audit.AuditNo);
AuditFindings relatedFinding = (from a in auditFindings where a.CANo == ca.CANo select a).First(); 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); caDMO.ReleaseLockOnDocument(-1, issueID);
} catch (Exception e) { } catch (Exception e) {
try { 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 { } } catch { }
caDMO.ReleaseLockOnDocument(-1, issueID); caDMO.ReleaseLockOnDocument(-1, issueID);
} }
} }
#if !NET8
public ActionResult GetD2AttachmentList([DataSourceRequest] DataSourceRequest request, int caNo) { public ActionResult GetD2AttachmentList([DataSourceRequest] DataSourceRequest request, int caNo) {
return Json(caDMO.GetCAAttachmentsList(caNo, Functions.CASectionMapper(GlobalVars.CASection.D2)).ToDataSourceResult(request)); return Json(caDMO.GetCAAttachmentsList(caNo, Functions.CASectionMapper(GlobalVars.CASection.D2)).ToDataSourceResult(request));
} }
public ActionResult Attachment_Read([DataSourceRequest] DataSourceRequest request, int caNO) { 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] [HttpPost]
public void DeleteCAAttachment(int attachmentID) { public void DeleteCAAttachment(int attachmentID) {
caDMO.DeleteCAAttachment(attachmentID); caDMO.DeleteCAAttachment(attachmentID);
} }
#if !NET8
public ActionResult DownloadCAAttachment(string fileGuid, int caNo) { public ActionResult DownloadCAAttachment(string fileGuid, int caNo) {
try { try {
string fileName = caDMO.GetCAAttachmentFileName(fileGuid); string fileName = caDMO.GetCAAttachmentFileName(fileGuid);
@ -312,7 +338,7 @@ public class CorrectiveActionController : Controller {
try { try {
// The Name of the Upload component is "files" // The Name of the Upload component is "files"
if (files != null) { if (files != null) {
int userId = (int)Session[GlobalVars.SESSION_USERID]; int userId = GlobalVars.GetUserId(GetSession());
foreach (var file in files) { foreach (var file in files) {
CorrectiveActionHelper.AttachSave(_AppSettings, caDMO, caNo, userId, file.FileName, file.InputStream); 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)); return Json(caDMO.GetD3ContainmentActions(caNo).ToDataSourceResult(request));
} }
#endif
public ActionResult UpdateD3ContainmentAction(D3ContainmentAction data) { public ActionResult UpdateD3ContainmentAction(D3ContainmentAction data) {
caDMO.UpdateD3ContainmentAction(data); caDMO.UpdateD3ContainmentAction(data);
if (data.ResponsibilityOwnerID != data.CurrentResponsibilityOwnerID && data.ResponsibilityOwnerID != 0) { if (data.ResponsibilityOwnerID != data.CurrentResponsibilityOwnerID && data.ResponsibilityOwnerID != 0) {
@ -339,7 +367,7 @@ public class CorrectiveActionController : Controller {
public ActionResult InsertD3ContainmentAction(D3ContainmentAction data) { public ActionResult InsertD3ContainmentAction(D3ContainmentAction data) {
caDMO.InsertD3ContainmentAction(data); caDMO.InsertD3ContainmentAction(data);
if (data.ResponsibilityOwnerID != null && data.ResponsibilityOwnerID != 0) { if (data.ResponsibilityOwnerID != 0) {
NotifyActionItemOwner(data.CANo, data.ECD, data.ResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt"); NotifyActionItemOwner(data.CANo, data.ECD, data.ResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt");
} }
return Content(""); return Content("");
@ -350,6 +378,8 @@ public class CorrectiveActionController : Controller {
caDMO.DeleteD3ContainmentActionItem(d3ContainmentActionID); caDMO.DeleteD3ContainmentActionItem(d3ContainmentActionID);
} }
#if !NET8
public ActionResult GetD4AttachmentList([DataSourceRequest] DataSourceRequest request, int caNo) { public ActionResult GetD4AttachmentList([DataSourceRequest] DataSourceRequest request, int caNo) {
return Json(caDMO.GetCAAttachmentsList(caNo, Functions.CASectionMapper(GlobalVars.CASection.D4)).ToDataSourceResult(request)); return Json(caDMO.GetCAAttachmentsList(caNo, Functions.CASectionMapper(GlobalVars.CASection.D4)).ToDataSourceResult(request));
} }
@ -358,7 +388,7 @@ public class CorrectiveActionController : Controller {
try { try {
// The Name of the Upload component is "files" // The Name of the Upload component is "files"
if (D4Files != null) { if (D4Files != null) {
int userId = (int)Session[GlobalVars.SESSION_USERID]; int userId = GlobalVars.GetUserId(GetSession());
foreach (var file in D4Files) { foreach (var file in D4Files) {
CorrectiveActionHelper.D4FilesAttachSave(_AppSettings, caDMO, caNo, userId, file.FileName, file.InputStream); 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)); return Json(caDMO.GetD5D6CorrectivetActions(caNo).ToDataSourceResult(request));
} }
#endif
public ActionResult InsertD5D6CAItem(D5D6CorrectivetAction data) { public ActionResult InsertD5D6CAItem(D5D6CorrectivetAction data) {
try { try {
caDMO.InsertD5D6CorrectivetAction(data); caDMO.InsertD5D6CorrectivetAction(data);
@ -385,7 +417,7 @@ public class CorrectiveActionController : Controller {
public ActionResult UpdateD5D6CAItem(D5D6CorrectivetAction data) { public ActionResult UpdateD5D6CAItem(D5D6CorrectivetAction data) {
D5D6CorrectivetAction previousData = caDMO.GetD5D5CAItem(data.ID); 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 { try {
caDMO.UpdateD5D6CorrectivetAction(data); caDMO.UpdateD5D6CorrectivetAction(data);
} catch (Exception e) { } catch (Exception e) {
@ -404,26 +436,32 @@ public class CorrectiveActionController : Controller {
} }
public ActionResult GetD5D6CAItem(int d5d6CAID) { public ActionResult GetD5D6CAItem(int d5d6CAID) {
var model = new D5D6CorrectivetAction(); D5D6CorrectivetAction model = new();
model = caDMO.GetD5D5CAItem(d5d6CAID); model = caDMO.GetD5D5CAItem(d5d6CAID);
return PartialView("_D5D6CAAttachment", model); return PartialView("_D5D6CAAttachment", model);
} }
#if !NET8
public ActionResult GetD5D6ItemAttachments([DataSourceRequest] DataSourceRequest request, int d5d6CAID) { public ActionResult GetD5D6ItemAttachments([DataSourceRequest] DataSourceRequest request, int d5d6CAID) {
return Json(caDMO.GetD5D6ItemAttachments(d5d6CAID).ToDataSourceResult(request)); return Json(caDMO.GetD5D6ItemAttachments(d5d6CAID).ToDataSourceResult(request));
} }
#endif
[HttpPost] [HttpPost]
public void DeleteD5D6CAItem(int d5d6CAID) { public void DeleteD5D6CAItem(int d5d6CAID) {
caDMO.DeleteD5D6CorrectivetAction(d5d6CAID); caDMO.DeleteD5D6CorrectivetAction(d5d6CAID);
} }
#if !NET8
public ActionResult SaveD5D6CA_Attachemnt(IEnumerable<HttpPostedFileBase> D5D6CA_Attachemnt, int d5d6CAID, int caNo) { public ActionResult SaveD5D6CA_Attachemnt(IEnumerable<HttpPostedFileBase> D5D6CA_Attachemnt, int d5d6CAID, int caNo) {
try { try {
// The Name of the Upload component is "files" // The Name of the Upload component is "files"
if (D5D6CA_Attachemnt != null) { if (D5D6CA_Attachemnt != null) {
int userId = (int)Session[GlobalVars.SESSION_USERID]; int userId = GlobalVars.GetUserId(GetSession());
foreach (var file in D5D6CA_Attachemnt) { foreach (var file in D5D6CA_Attachemnt) {
CorrectiveActionHelper.SaveD5D6CA_Attachemnt(_AppSettings, caDMO, d5d6CAID, caNo, userId, file.FileName, file.InputStream); CorrectiveActionHelper.SaveD5D6CA_Attachemnt(_AppSettings, caDMO, d5d6CAID, caNo, userId, file.FileName, file.InputStream);
} }
@ -435,14 +473,15 @@ public class CorrectiveActionController : Controller {
return Content(""); return Content("");
} }
// D7 ====================================================================================
public ActionResult GetD7PreventiveActionList([DataSourceRequest] DataSourceRequest request, int caNo) { public ActionResult GetD7PreventiveActionList([DataSourceRequest] DataSourceRequest request, int caNo) {
return Json(caDMO.GetD7PreventiveActions(caNo).ToDataSourceResult(request)); return Json(caDMO.GetD7PreventiveActions(caNo).ToDataSourceResult(request));
} }
#endif
public ActionResult InsertD7PAItem(D7PreventiveAction data) { public ActionResult InsertD7PAItem(D7PreventiveAction data) {
caDMO.InsertD7PreventiveAction(data); caDMO.InsertD7PreventiveAction(data);
if (data.ResponsibilityOwnerID != null && data.ResponsibilityOwnerID != 0) { if (data.ResponsibilityOwnerID != 0) {
NotifyActionItemOwner(data.CANo, data.ECD, data.ResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt"); NotifyActionItemOwner(data.CANo, data.ECD, data.ResponsibilityOwnerID, "CorrectiveActionAIAssigned.txt");
} }
@ -459,26 +498,32 @@ public class CorrectiveActionController : Controller {
} }
public ActionResult GetD7PAItem(int d7paID) { public ActionResult GetD7PAItem(int d7paID) {
var model = new D7PreventiveAction(); D7PreventiveAction model = new();
model = caDMO.GetD7PAItem(d7paID); model = caDMO.GetD7PAItem(d7paID);
return PartialView("_D7PAAttachment", model); return PartialView("_D7PAAttachment", model);
} }
#if !NET8
public ActionResult GetD7ItemAttachments([DataSourceRequest] DataSourceRequest request, int d7PAID) { public ActionResult GetD7ItemAttachments([DataSourceRequest] DataSourceRequest request, int d7PAID) {
return Json(caDMO.GetD7ItemAttachments(d7PAID).ToDataSourceResult(request)); return Json(caDMO.GetD7ItemAttachments(d7PAID).ToDataSourceResult(request));
} }
#endif
[HttpPost] [HttpPost]
public void DeleteD7PAItem(int d7PAID) { public void DeleteD7PAItem(int d7PAID) {
caDMO.DeleteD7PreventiveActionItem(d7PAID); caDMO.DeleteD7PreventiveActionItem(d7PAID);
} }
#if !NET8
public ActionResult SaveD7PA_Attachemnt(IEnumerable<HttpPostedFileBase> D7PA_Attachemnt, int d7PAID, int caNo) { public ActionResult SaveD7PA_Attachemnt(IEnumerable<HttpPostedFileBase> D7PA_Attachemnt, int d7PAID, int caNo) {
try { try {
// The Name of the Upload component is "files" // The Name of the Upload component is "files"
if (D7PA_Attachemnt != null) { if (D7PA_Attachemnt != null) {
int userId = (int)Session[GlobalVars.SESSION_USERID]; int userId = GlobalVars.GetUserId(GetSession());
foreach (var file in D7PA_Attachemnt) { foreach (var file in D7PA_Attachemnt) {
CorrectiveActionHelper.SaveD7PA_Attachemnt(_AppSettings, caDMO, d7PAID, caNo, userId, file.FileName, file.InputStream); CorrectiveActionHelper.SaveD7PA_Attachemnt(_AppSettings, caDMO, d7PAID, caNo, userId, file.FileName, file.InputStream);
} }
@ -490,21 +535,23 @@ public class CorrectiveActionController : Controller {
return Content(""); return Content("");
} }
#endif
public void ReleaseLockOnDocument(int issueID) { public void ReleaseLockOnDocument(int issueID) {
try { try {
caDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], issueID); caDMO.ReleaseLockOnDocument(GlobalVars.GetUserId(GetSession()), issueID);
} catch (Exception e) { } catch (Exception e) {
try { 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 { } } catch { }
caDMO.ReleaseLockOnDocument(-1, issueID); caDMO.ReleaseLockOnDocument(-1, issueID);
} }
} }
public JsonResult GetAllUsersList() { public JsonResult GetAllUsersList() {
UserAccountDMO userDMO = new UserAccountDMO(); UserAccountDMO userDMO = new();
IEnumerable<LoginModel> userlist = userDMO.GetAllUsers(); IEnumerable<LoginModel> userlist = userDMO.GetAllUsers();
return Json(userlist, JsonRequestBehavior.AllowGet); return GetJsonResult(userlist);
} }
public void ReAssignApproverByAdmin(int issueID, int reAssignApproverFrom, int reAssignApproverTo, byte step, int docType) { public void ReAssignApproverByAdmin(int issueID, int reAssignApproverFrom, int reAssignApproverTo, byte step, int docType) {
@ -519,20 +566,20 @@ public class CorrectiveActionController : Controller {
detailedException = e.Message; 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(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "CA", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
CorrectiveActionHelper.ReAssignApproverByAdmin(_AppSettings, issueID, email); CorrectiveActionHelper.ReAssignApproverByAdmin(_AppSettings, issueID, email);
try { 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 { } } catch { }
} }
public void ReAssignApproval(int issueID, int userIDs, byte step) { public void ReAssignApproval(int issueID, int userIDs, byte step) {
var email = ""; var email = "";
try { 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) { } catch (Exception e) {
string detailedException = ""; string detailedException = "";
try { try {
@ -541,20 +588,20 @@ public class CorrectiveActionController : Controller {
detailedException = e.Message; 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(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
CorrectiveActionHelper.ReAssignApproval(_AppSettings, issueID, email); CorrectiveActionHelper.ReAssignApproval(_AppSettings, issueID, email);
try { 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 { } } catch { }
} }
public void Reject(int issueID, byte currentStep, string comments) { public void Reject(int issueID, byte currentStep, string comments) {
try { try {
if (Session[GlobalVars.SESSION_USERID] != null) { if (GlobalVars.IsUserIdValueNotNull(GetSession())) {
wfDMO.Reject(issueID, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.CorrectiveAction); wfDMO.Reject(issueID, currentStep, comments, GlobalVars.GetUserId(GetSession()), (int)GlobalVars.DocumentType.CorrectiveAction);
NotifyRejectionToAssignee(issueID, comments); NotifyRejectionToAssignee(issueID, comments);
} else { } else {
Response.Redirect("~/Account/Login"); Response.Redirect("~/Account/Login");
@ -567,18 +614,18 @@ public class CorrectiveActionController : Controller {
detailedException = e.Message; 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(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "Reject - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
} }
public void NotifyRejectionToAssignee(int issueID, string comments) { public void NotifyRejectionToAssignee(int issueID, string comments) {
string username = Session[GlobalVars.SESSION_USERNAME].ToString(); string username = GlobalVars.GetUserName(GetSession());
List<string> emailIst = caDMO.GetRejectionAssigneeEmailList(@issueID).Distinct().ToList(); List<string> emailIst = caDMO.GetRejectionAssigneeEmailList(@issueID).Distinct().ToList();
string userEmail = CorrectiveActionHelper.NotifyRejectionToAssignee(_AppSettings, issueID, comments, username, emailIst); string userEmail = CorrectiveActionHelper.NotifyRejectionToAssignee(_AppSettings, issueID, comments, username, emailIst);
try { 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 { } } catch { }
} }
@ -586,9 +633,9 @@ public class CorrectiveActionController : Controller {
int isITARCompliant = 1; int isITARCompliant = 1;
try { try {
bool lastStep = false; 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) { if (lastApprover && !lastStep) {
// Set to complete // Set to complete
@ -610,8 +657,8 @@ public class CorrectiveActionController : Controller {
detailedException = e.Message; 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(); 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); 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 = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Approve - " + exceptionString }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "Approve - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
} }
@ -621,7 +668,7 @@ public class CorrectiveActionController : Controller {
string userEmail = userDMO.GetUserEmailByID(userId); string userEmail = userDMO.GetUserEmailByID(userId);
CorrectiveActionHelper.NotifySectionApprover(_AppSettings, issueID, section, userEmail); CorrectiveActionHelper.NotifySectionApprover(_AppSettings, issueID, section, userEmail);
try { 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 { }
} catch (Exception e) { } catch (Exception e) {
string detailedException = ""; string detailedException = "";
@ -631,9 +678,9 @@ public class CorrectiveActionController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString });
throw e; throw;
} }
} }
@ -642,7 +689,7 @@ public class CorrectiveActionController : Controller {
List<string> emailIst = MiscDMO.GetApproverEmailListByDocument(@issueID, currentStep, (int)GlobalVars.DocumentType.CorrectiveAction).Distinct().ToList(); List<string> emailIst = MiscDMO.GetApproverEmailListByDocument(@issueID, currentStep, (int)GlobalVars.DocumentType.CorrectiveAction).Distinct().ToList();
string emailSentList = CorrectiveActionHelper.NotifyApprovers(_AppSettings, issueID, emailIst); string emailSentList = CorrectiveActionHelper.NotifyApprovers(_AppSettings, issueID, emailIst);
try { 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 { }
} catch (Exception e) { } catch (Exception e) {
string detailedException = ""; string detailedException = "";
@ -652,9 +699,9 @@ public class CorrectiveActionController : Controller {
detailedException = e.Message; 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(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString });
throw e; throw;
} }
} }
@ -673,18 +720,20 @@ public class CorrectiveActionController : Controller {
detailedException = e.Message; 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(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
emailSentList = CorrectiveActionHelper.AddAdditionalApproval(_AppSettings, issueID, emailSentList, emailArray); emailSentList = CorrectiveActionHelper.AddAdditionalApproval(_AppSettings, issueID, emailSentList, emailArray);
try { 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 { } } catch { }
} }
#endregion #endregion
#if !NET8
public ActionResult GetApproversList([DataSourceRequest] DataSourceRequest request, int issueID, byte step) { public ActionResult GetApproversList([DataSourceRequest] DataSourceRequest request, int issueID, byte step) {
return Json(MiscDMO.GetApproversListByDocument(issueID, step, (int)GlobalVars.DocumentType.CorrectiveAction).ToDataSourceResult(request)); 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)); return Json(caDMO.GetCASectionApprovalLog(caNo).ToDataSourceResult(request));
} }
#endif
public void NotifyRequestor(int issueID, DateTime? dueDate, int? responsibleOwnerID, string template) { public void NotifyRequestor(int issueID, DateTime? dueDate, int? responsibleOwnerID, string template) {
try { try {
string email = MiscDMO.GetEmail(responsibleOwnerID); string email = MiscDMO.GetEmail(responsibleOwnerID);
CorrectiveActionHelper.NotifyRequestor(_AppSettings, issueID, dueDate, template, email); CorrectiveActionHelper.NotifyRequestor(_AppSettings, issueID, dueDate, template, email);
try { 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 { }
} catch (Exception e) { } catch (Exception e) {
string detailedException = ""; 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(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); 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); string email = MiscDMO.GetEmail(responsibleOwnerID);
CorrectiveActionHelper.NotifyAssignee(_AppSettings, issueID, template, D3DueDate, D5D7DueDate, email); CorrectiveActionHelper.NotifyAssignee(_AppSettings, issueID, template, D3DueDate, D5D7DueDate, email);
try { 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 { }
} catch (Exception e) { } catch (Exception e) {
string detailedException = ""; 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(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); 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 { try {
string email = CorrectiveActionHelper.NotifyActionItemOwner(_AppSettings, issueID, dueDate, responsibleOwnerID, template); string email = CorrectiveActionHelper.NotifyActionItemOwner(_AppSettings, issueID, dueDate, responsibleOwnerID, template);
try { 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 { }
} catch (Exception e) { } catch (Exception e) {
string detailedException = ""; 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(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); 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 { try {
string email = CorrectiveActionHelper.NotifyActionItemCompletion(_AppSettings, issueID, dueDate, recipientId, template); string email = CorrectiveActionHelper.NotifyActionItemCompletion(_AppSettings, issueID, dueDate, recipientId, template);
try { 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 { }
} catch (Exception e) { } catch (Exception e) {
string detailedException = ""; 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(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); 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 { try {
string emailSentList = CorrectiveActionHelper.NotifyClosureOf8D(_AppSettings, issueID); string emailSentList = CorrectiveActionHelper.NotifyClosureOf8D(_AppSettings, issueID);
try { 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 { }
} catch (Exception e) { } catch (Exception e) {
string detailedException = ""; 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(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); 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 { try {
string emailSentList = CorrectiveActionHelper.NotifyCompletionOf8D(_AppSettings, issueID, followUpDate); string emailSentList = CorrectiveActionHelper.NotifyCompletionOf8D(_AppSettings, issueID, followUpDate);
try { 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 { }
} catch (Exception e) { } catch (Exception e) {
string detailedException = ""; 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(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); 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) { public void StartSectionApproval(int issueID, string dSection) {
try { try {
CorrectiveAction ca = caDMO.GetCAItem(issueID, (int)Session[GlobalVars.SESSION_USERID]); CorrectiveAction ca = caDMO.GetCAItem(issueID, GlobalVars.GetUserId(GetSession()));
int requestorId = ca.RequestorID; int requestorId = ca.RequestorID;
int qaId = ca.QAID; int qaId = ca.QAID;
@ -834,16 +885,16 @@ public class CorrectiveActionController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); 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 = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Approve - " + exceptionString }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "Approve - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
} }
[HttpPost] [HttpPost]
public ActionResult ApproveSection(int issueID, string dSection) { public ActionResult ApproveSection(int issueID, string dSection) {
try { try {
int userID = (int)Session[GlobalVars.SESSION_USERID]; int userID = GlobalVars.GetUserId(GetSession());
CorrectiveAction caItem = caDMO.GetCAItem(issueID, (int)Session[GlobalVars.SESSION_USERID]); CorrectiveAction caItem = caDMO.GetCAItem(issueID, GlobalVars.GetUserId(GetSession()));
caDMO.ApproveSection(issueID, userID, dSection); caDMO.ApproveSection(issueID, userID, dSection);
bool isLastApprover = caDMO.IsLastSectionApprover(issueID, dSection); bool isLastApprover = caDMO.IsLastSectionApprover(issueID, dSection);
if (isLastApprover) { if (isLastApprover) {
@ -876,8 +927,8 @@ public class CorrectiveActionController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); 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 = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Approve - " + exceptionString }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "Approve - " + exceptionString });
return Content(e.Message); return Content(e.Message);
} }
} }
@ -885,7 +936,7 @@ public class CorrectiveActionController : Controller {
public ActionResult RejectSection(int issueID, string dSection, string comments) { public ActionResult RejectSection(int issueID, string dSection, string comments) {
try { try {
int userID = (int)Session[GlobalVars.SESSION_USERID]; int userID = GlobalVars.GetUserId(GetSession());
CorrectiveAction ca = caDMO.GetCAItem(issueID, userID); CorrectiveAction ca = caDMO.GetCAItem(issueID, userID);
caDMO.RejectSection(issueID, userID, dSection, comments); caDMO.RejectSection(issueID, userID, dSection, comments);
// Notify Rejection to assignee and requestor // Notify Rejection to assignee and requestor
@ -905,18 +956,19 @@ public class CorrectiveActionController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " Step:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); 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 = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "Reject - " + exceptionString }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "Reject - " + exceptionString });
return Content(e.Message); return Content(e.Message);
} }
} }
public void NotifySectionRejection(int issueID, int recipientUserId, int loggedInUserId, string section, string comment) { public void NotifySectionRejection(int issueID, int recipientUserId, int loggedInUserId, string section, string comment) {
try { try {
LoginModel recipient = userDMO.GetUserByID(recipientUserId); LoginModel recipient = userDMO.GetUserByID(recipientUserId);
LoginModel loggedInUser = userDMO.GetUserByID(loggedInUserId); LoginModel loggedInUser = userDMO.GetUserByID(loggedInUserId);
CorrectiveActionHelper.NotifySectionRejection(_AppSettings, issueID, section, comment, recipient, loggedInUser); CorrectiveActionHelper.NotifySectionRejection(_AppSettings, issueID, section, comment, recipient, loggedInUser);
try { 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 { }
} catch (Exception e) { } catch (Exception e) {
string detailedException = ""; string detailedException = "";
@ -926,9 +978,9 @@ public class CorrectiveActionController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString });
throw e; throw;
} }
} }
@ -937,7 +989,7 @@ public class CorrectiveActionController : Controller {
string userEmail = userDMO.GetUserEmailByID(userId); string userEmail = userDMO.GetUserEmailByID(userId);
CorrectiveActionHelper.NotifyForD5D6D7Validation(_AppSettings, issueID, dSection, userEmail); CorrectiveActionHelper.NotifyForD5D6D7Validation(_AppSettings, issueID, dSection, userEmail);
try { 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 { }
} catch (Exception e) { } catch (Exception e) {
string detailedException = ""; string detailedException = "";
@ -947,9 +999,9 @@ public class CorrectiveActionController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString });
throw e; throw;
} }
} }
@ -958,7 +1010,7 @@ public class CorrectiveActionController : Controller {
string userEmail = userDMO.GetUserEmailByID(userId); string userEmail = userDMO.GetUserEmailByID(userId);
CorrectiveActionHelper.NotifyUsersDSectionApproved(_AppSettings, issueID, dSection, userEmail); CorrectiveActionHelper.NotifyUsersDSectionApproved(_AppSettings, issueID, dSection, userEmail);
try { 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 { }
} catch (Exception e) { } catch (Exception e) {
string detailedException = ""; string detailedException = "";
@ -968,9 +1020,9 @@ public class CorrectiveActionController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Corrective Action", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString });
throw e; throw;
} }
} }
@ -979,10 +1031,12 @@ public class CorrectiveActionController : Controller {
return d3DueDate; return d3DueDate;
} }
public DateTime SetD5D7DueDate(int caNo) { public DateTime SetD5D7DueDate(int caNo) {
DateTime d5d7DueDate = caDMO.SetCAD5D7DueDate(caNo); DateTime d5d7DueDate = caDMO.SetCAD5D7DueDate(caNo);
return d5d7DueDate; return d5d7DueDate;
} }
public bool ProcessCARDueDates() { public bool ProcessCARDueDates() {
bool isSuccess = false; bool isSuccess = false;
List<CAD3D5D7Due> dueCAs = caDMO.GetCAD3D5D7Due().ToList(); List<CAD3D5D7Due> dueCAs = caDMO.GetCAD3D5D7Due().ToList();
@ -1006,8 +1060,8 @@ public class CorrectiveActionController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + dueCA.CANo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); 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() { 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;
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,35 +1,53 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Configuration; #if !NET8
using System.Linq;
using System.Web; using System.Web;
using System.Web.Mvc; using System.Web.Mvc;
#endif
#if NET8
using Microsoft.AspNetCore.Mvc;
#endif
using Fab2ApprovalSystem.DMO; using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Misc; using Fab2ApprovalSystem.Misc;
using Fab2ApprovalSystem.Models; using Fab2ApprovalSystem.Models;
using Fab2ApprovalSystem.Utilities; 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.Extensions;
using Kendo.Mvc.UI; using Kendo.Mvc.UI;
#endif
namespace Fab2ApprovalSystem.Controllers; namespace Fab2ApprovalSystem.Controllers;
#if !NET8
[Authorize] [Authorize]
#if !NET8
[SessionExpireFilter] [SessionExpireFilter]
#endif
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
#endif
#if NET8
[Route("[controller]")]
#endif
public class HomeController : Controller { public class HomeController : Controller {
MRB_DMO mrbDMO = new MRB_DMO(GlobalVars.AppSettings); private readonly MRB_DMO mrbDMO = new(GlobalVars.AppSettings);
PartsRequestDMO prDMO = new PartsRequestDMO(); private readonly PartsRequestDMO prDMO = new();
LotDispositionDMO ldDMO = new LotDispositionDMO(); private readonly LotDispositionDMO ldDMO = new();
WorkflowDMO wfDMO = new WorkflowDMO(); private readonly WorkflowDMO wfDMO = new();
ECN_DMO ecnDMO = new ECN_DMO(); private readonly ECN_DMO ecnDMO = new();
UserUtilities userDMO = new UserUtilities(); private readonly UserUtilities userDMO = new();
UserAccountDMO originalUserDMO = new UserAccountDMO(); private readonly UserAccountDMO originalUserDMO = new();
TrainingDMO trainingDMO = new TrainingDMO(); private readonly TrainingDMO trainingDMO = new();
MiscDMO miscDMO = new MiscDMO(); private readonly MiscDMO miscDMO = new();
private readonly AppSettings _AppSettings = GlobalVars.AppSettings; private readonly AppSettings _AppSettings = GlobalVars.AppSettings;
public ActionResult Index(string tabName) { public ActionResult Index(string tabName) {
@ -57,6 +75,7 @@ public class HomeController : Controller {
public ActionResult ECNList() { public ActionResult ECNList() {
return View(); return View();
} }
public ActionResult TrainingList() { public ActionResult TrainingList() {
return View(); return View();
} }
@ -82,25 +101,25 @@ public class HomeController : Controller {
return View(); return View();
} }
#if !NET8
public ActionResult GetTaskList([DataSourceRequest] DataSourceRequest request, string tabName) { public ActionResult GetTaskList([DataSourceRequest] DataSourceRequest request, string tabName) {
try { try {
ViewBag.ActiveTabName = tabName; ViewBag.ActiveTabName = tabName;
List<IssuesViewModel> data = ldDMO.GetTaskList((int)Session[GlobalVars.SESSION_USERID]).Distinct().ToList(); List<IssuesViewModel> data = ldDMO.GetTaskList(GlobalVars.GetUserId(GetSession())).Distinct().ToList();
return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet); return GetJsonResult(data.ToDataSourceResult(request));
} catch (Exception ex) { } catch (Exception ex) {
// TODO record the error throw;
throw ex;
} }
} }
public ActionResult GetMyOpenActionItems([DataSourceRequest] DataSourceRequest request, string tabName) { public ActionResult GetMyOpenActionItems([DataSourceRequest] DataSourceRequest request, string tabName) {
try { try {
ViewBag.ActiveTabName = tabName; ViewBag.ActiveTabName = tabName;
List<OpenActionItemViewModel> data = ldDMO.GetMyOpenActionItems((int)Session[GlobalVars.SESSION_USERID]).Distinct().ToList(); List<OpenActionItemViewModel> data = ldDMO.GetMyOpenActionItems(GlobalVars.GetUserId(GetSession())).Distinct().ToList();
return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet); return GetJsonResult(data.ToDataSourceResult(request));
} catch (Exception ex) { } catch (Exception ex) {
// TODO record the error throw;
throw ex;
} }
} }
@ -116,76 +135,82 @@ public class HomeController : Controller {
} }
public ActionResult GetChangeControlList([DataSourceRequest] DataSourceRequest request) { public ActionResult GetChangeControlList([DataSourceRequest] DataSourceRequest request) {
IEnumerable<ChangeControlList> data = ldDMO.GetChangeControls(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); IEnumerable<ChangeControlList> data = ldDMO.GetChangeControls(GlobalVars.GetUserId(GetSession()));
return Json(data.ToDataSourceResult(request)); return Json(data.ToDataSourceResult(request));
} }
public ActionResult GetAuditList([DataSourceRequest] DataSourceRequest request) { public ActionResult GetAuditList([DataSourceRequest] DataSourceRequest request) {
IEnumerable<AuditList> data = ldDMO.GetAuditList(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); IEnumerable<AuditList> data = ldDMO.GetAuditList(GlobalVars.GetUserId(GetSession()));
return Json(data.ToDataSourceResult(request)); return Json(data.ToDataSourceResult(request));
} }
public ActionResult GetCorrectiveActionList([DataSourceRequest] DataSourceRequest request) { public ActionResult GetCorrectiveActionList([DataSourceRequest] DataSourceRequest request) {
IEnumerable<CorrectiveAction> data = ldDMO.GetCorrectiveActionList(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); IEnumerable<CorrectiveAction> data = ldDMO.GetCorrectiveActionList(GlobalVars.GetUserId(GetSession()));
return Json(data.ToDataSourceResult(request)); return Json(data.ToDataSourceResult(request));
} }
public ActionResult GetMRBList([DataSourceRequest] DataSourceRequest request) { public ActionResult GetMRBList([DataSourceRequest] DataSourceRequest request) {
IEnumerable<IssuesViewModel> data = ldDMO.GetMRBList(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); IEnumerable<IssuesViewModel> data = ldDMO.GetMRBList(GlobalVars.GetUserId(GetSession()));
return Json(data.ToDataSourceResult(request)); return Json(data.ToDataSourceResult(request));
} }
public ActionResult GetLotDispositionList([DataSourceRequest] DataSourceRequest request) { public ActionResult GetLotDispositionList([DataSourceRequest] DataSourceRequest request) {
IEnumerable<IssuesViewModel> data = ldDMO.GetLotDispositionList(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); IEnumerable<IssuesViewModel> data = ldDMO.GetLotDispositionList(GlobalVars.GetUserId(GetSession()));
return Json(data.ToDataSourceResult(request)); return Json(data.ToDataSourceResult(request));
} }
public ActionResult GetECNList([DataSourceRequest] DataSourceRequest request) { public ActionResult GetECNList([DataSourceRequest] DataSourceRequest request) {
IEnumerable<IssuesViewModel> data = ldDMO.GetECNList(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); IEnumerable<IssuesViewModel> data = ldDMO.GetECNList(GlobalVars.GetUserId(GetSession()));
return Json(data.ToDataSourceResult(request)); return Json(data.ToDataSourceResult(request));
} }
public ActionResult GetTrainingList([DataSourceRequest] DataSourceRequest request) { public ActionResult GetTrainingList([DataSourceRequest] DataSourceRequest request) {
IEnumerable<Training> data = trainingDMO.GetAllTrainings(); IEnumerable<Training> data = trainingDMO.GetAllTrainings();
return Json(data.ToDataSourceResult(request)); return Json(data.ToDataSourceResult(request));
} }
#endif
public ActionResult MyECNsTECNs(string dataType) { public ActionResult MyECNsTECNs(string dataType) {
ViewBag.ActiveTabName = dataType; ViewBag.ActiveTabName = dataType;
return View(); return View();
} }
#if !NET8
public ActionResult GetECN_TECNsPendingApproval([DataSourceRequest] DataSourceRequest request) { public ActionResult GetECN_TECNsPendingApproval([DataSourceRequest] DataSourceRequest request) {
IEnumerable<IssuesViewModel> data = ecnDMO.GetECN_TECNPendingApprovals(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); IEnumerable<IssuesViewModel> data = ecnDMO.GetECN_TECNPendingApprovals(GlobalVars.GetUserId(GetSession()));
ViewBag.ViewOption = "Pending Approvals"; ViewBag.ViewOption = "Pending Approvals";
Session[GlobalVars.ECN_VIEW_OPTION] = ViewBag.ViewOption; GlobalVars.SetECNViewOption(GetSession(), ViewBag.ViewOption);
return Json(data.ToDataSourceResult(request)); return Json(data.ToDataSourceResult(request));
} }
public ActionResult GetMyExpiredTECNs([DataSourceRequest] DataSourceRequest request) { public ActionResult GetMyExpiredTECNs([DataSourceRequest] DataSourceRequest request) {
IEnumerable<IssuesViewModel> data = ecnDMO.GetMyExpiredTECNs(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), 7); IEnumerable<IssuesViewModel> data = ecnDMO.GetMyExpiredTECNs(GlobalVars.GetUserId(GetSession()), 7);
ViewBag.ViewOption = "Expired TECNs"; ViewBag.ViewOption = "Expired TECNs";
Session[GlobalVars.ECN_VIEW_OPTION] = ViewBag.ViewOption; GlobalVars.SetECNViewOption(GetSession(), ViewBag.ViewOption);
return Json(data.ToDataSourceResult(request)); return Json(data.ToDataSourceResult(request));
} }
public ActionResult GetAllTECNs([DataSourceRequest] DataSourceRequest request) { public ActionResult GetAllTECNs([DataSourceRequest] DataSourceRequest request) {
IEnumerable<IssuesViewModel> data = ecnDMO.GetAllTECNs(); IEnumerable<IssuesViewModel> data = ecnDMO.GetAllTECNs();
ViewBag.ViewOption = "All TECNs"; ViewBag.ViewOption = "All TECNs";
Session[GlobalVars.ECN_VIEW_OPTION] = ViewBag.ViewOption; GlobalVars.SetECNViewOption(GetSession(), ViewBag.ViewOption);
return Json(data.ToDataSourceResult(request)); return Json(data.ToDataSourceResult(request));
} }
public ActionResult GetMyConvertedTECNsToECNs([DataSourceRequest] DataSourceRequest request) { public ActionResult GetMyConvertedTECNsToECNs([DataSourceRequest] DataSourceRequest request) {
IEnumerable<IssuesViewModel> data = ecnDMO.GetMyConvertedTECNsToECNs(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), 7); IEnumerable<IssuesViewModel> data = ecnDMO.GetMyConvertedTECNsToECNs(GlobalVars.GetUserId(GetSession()), 7);
ViewBag.ViewOption = "Converted TECNs"; ViewBag.ViewOption = "Converted TECNs";
Session[GlobalVars.ECN_VIEW_OPTION] = ViewBag.ViewOption; GlobalVars.SetECNViewOption(GetSession(), ViewBag.ViewOption);
return Json(data.ToDataSourceResult(request)); return Json(data.ToDataSourceResult(request));
} }
public ActionResult GetMyExpiringTECNs([DataSourceRequest] DataSourceRequest request) { public ActionResult GetMyExpiringTECNs([DataSourceRequest] DataSourceRequest request) {
IEnumerable<IssuesViewModel> data = ecnDMO.GetMyExpiringTECNs(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), 7); IEnumerable<IssuesViewModel> data = ecnDMO.GetMyExpiringTECNs(GlobalVars.GetUserId(GetSession()), 7);
ViewBag.ViewOption = "Expiring TECNs"; ViewBag.ViewOption = "Expiring TECNs";
Session[GlobalVars.ECN_VIEW_OPTION] = ViewBag.ViewOption; GlobalVars.SetECNViewOption(GetSession(), ViewBag.ViewOption);
return Json(data.ToDataSourceResult(request)); return Json(data.ToDataSourceResult(request));
} }
@ -194,17 +219,17 @@ public class HomeController : Controller {
return Json(LotTravDMO.GetLotListBasedOnSWRNumber(workRequestID).ToDataSourceResult(request)); return Json(LotTravDMO.GetLotListBasedOnSWRNumber(workRequestID).ToDataSourceResult(request));
} }
/// <returns></returns> #endif
public ActionResult SetOOOStatus(int delegatedTo, DateTime startDate, DateTime endDate, string tab) { public ActionResult SetOOOStatus(int delegatedTo, DateTime startDate, DateTime endDate, string tab) {
if (Session[GlobalVars.SESSION_USERID] != null) { if (GlobalVars.IsUserIdValueNotNull(GetSession())) {
int returnValue = MiscDMO.EnableOOOStatus(int.Parse(Session[GlobalVars.SESSION_USERID].ToString()), delegatedTo, startDate, endDate); int returnValue = MiscDMO.EnableOOOStatus(GlobalVars.GetUserId(GetSession()), delegatedTo, startDate, endDate);
if (returnValue == 3) // the delegator is already a delegator to someone else if (returnValue == 3) // the delegator is already a delegator to someone else
{ {
return Content("3"); return Content("3");
} }
if (startDate <= DateTime.Today) if (startDate <= DateTime.Today)
Session[GlobalVars.OOO] = true; GlobalVars.SetOOO(GetSession(), true);
NotifyDelegation(delegatedTo, startDate, endDate); NotifyDelegation(delegatedTo, startDate, endDate);
} }
@ -213,12 +238,14 @@ public class HomeController : Controller {
} }
public void ExpireOOOStatus(string tab) { public void ExpireOOOStatus(string tab) {
if (Session[GlobalVars.SESSION_USERID] != null) { if (GlobalVars.IsUserIdValueNotNull(GetSession())) {
MiscDMO.ExpireOOOStatus(int.Parse(Session[GlobalVars.SESSION_USERID].ToString())); MiscDMO.ExpireOOOStatus(GlobalVars.GetUserId(GetSession()));
Session[GlobalVars.OOO] = false; GlobalVars.SetOOO(GetSession(), false);
} }
} }
#if !NET8
[AcceptVerbs(HttpVerbs.Post)] [AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteItem([DataSourceRequest] DataSourceRequest request, IssuesViewModel issue) { public ActionResult DeleteItem([DataSourceRequest] DataSourceRequest request, IssuesViewModel issue) {
GlobalVars.DocumentType dType; GlobalVars.DocumentType dType;
@ -228,20 +255,22 @@ public class HomeController : Controller {
else if (dType == GlobalVars.DocumentType.LotDisposition) else if (dType == GlobalVars.DocumentType.LotDisposition)
ldDMO.DeleteLotDisposition(issue.IssueID); ldDMO.DeleteLotDisposition(issue.IssueID);
else if (dType == GlobalVars.DocumentType.ECN) 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) 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)); return Json(new[] { issue }.ToDataSourceResult(request, ModelState));
} }
[AcceptVerbs(HttpVerbs.Post)] [AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteCAItem([DataSourceRequest] DataSourceRequest request, CorrectiveAction ca) { 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)); return Json(new[] { ca }.ToDataSourceResult(request, ModelState));
} }
#endif
public ActionResult About() { public ActionResult About() {
ViewBag.Message = "Your application description page."; 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) { public void DelegateDocumentApproval(int issueID, int delegateTo, string ecnTypeString, string title) {
var email = ""; var email = "";
int delegateFrom = (int)Session[GlobalVars.SESSION_USERID]; int delegateFrom = GlobalVars.GetUserId(GetSession());
try { try {
email = wfDMO.DelegateDocumentApproval(issueID, delegateFrom, delegateTo); 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) { } catch (Exception e) {
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = " + ecnTypeString + ", OperationType = "Error", Comments = "DelegateApproval - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
HomeHelper.DelegateDocumentApproval(_AppSettings, issueID, ecnTypeString, title, email); HomeHelper.DelegateDocumentApproval(_AppSettings, issueID, ecnTypeString, title, email);
try { 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 { } } catch { }
} }
public JsonResult GetAllUsersList() { public JsonResult GetAllUsersList() {
UserAccountDMO userDMO = new UserAccountDMO(); UserAccountDMO userDMO = new();
IEnumerable<LoginModel> userlist = userDMO.GetAllUsers(); IEnumerable<LoginModel> userlist = userDMO.GetAllUsers();
return Json(userlist, JsonRequestBehavior.AllowGet); return GetJsonResult(userlist);
} }
public ActionResult SaveAllDocumentsFilter(string data) { public ActionResult SaveAllDocumentsFilter(string data) {
Session["AllDocumentsFilterData"] = data; GlobalVars.SetAllDocumentsFilterData(GetSession(), data);
return new EmptyResult(); return new EmptyResult();
} }
public ActionResult LoadAllDocumentsFilter() { public ActionResult LoadAllDocumentsFilter() {
return Json(Session["AllDocumentsFilterData"], JsonRequestBehavior.AllowGet); return GetJsonResult(GlobalVars.GetAllDocumentsFilterData(GetSession()));
} }
public ActionResult SaveSWRFilter(string data) { public ActionResult SaveSWRFilter(string data) {
Session["SWRFilterData"] = data; GlobalVars.SetSWRFilterData(GetSession(), data);
return new EmptyResult(); return new EmptyResult();
} }
public ActionResult LoadSWRFilter() { public ActionResult LoadSWRFilter() {
return Json(Session["SWRFilterData"], JsonRequestBehavior.AllowGet); return GetJsonResult(GlobalVars.GetSWRFilterData(GetSession()));
} }
public ActionResult SavePCRBFilter(string data) { public ActionResult SavePCRBFilter(string data) {
Session["PCRBFilterData"] = data; GlobalVars.SetPCRBFilterData(GetSession(), data);
return new EmptyResult(); return new EmptyResult();
} }
public ActionResult LoadPCRBFilter() { public ActionResult LoadPCRBFilter() {
return Json(Session["PCRBFilterData"], JsonRequestBehavior.AllowGet); return GetJsonResult(GlobalVars.GetPCRBFilterData(GetSession()));
} }
public ActionResult PartsRequestList() { public ActionResult PartsRequestList() {
ViewBag.CanDeletePR = Session[GlobalVars.CAN_CREATE_PARTS_REQUEST]; ViewBag.CanDeletePR = GlobalVars.GetCanCreatePartsRequest(GetSession());
return View(); return View();
} }
#if !NET8
public ActionResult GetPartsRequestList([DataSourceRequest] DataSourceRequest request) { public ActionResult GetPartsRequestList([DataSourceRequest] DataSourceRequest request) {
IEnumerable<PartsRequestList> data = prDMO.GetPartsRequestList(); IEnumerable<PartsRequestList> data = prDMO.GetPartsRequestList();
return Json(data.ToDataSourceResult(request)); return Json(data.ToDataSourceResult(request));
@ -346,31 +377,32 @@ public class HomeController : Controller {
public ActionResult GetMyPartsRequestsList([DataSourceRequest] DataSourceRequest request, string tabName) { public ActionResult GetMyPartsRequestsList([DataSourceRequest] DataSourceRequest request, string tabName) {
try { try {
ViewBag.ActiveTabName = tabName; ViewBag.ActiveTabName = tabName;
var data = prDMO.GetMyPartsRequests((int)Session[GlobalVars.SESSION_USERID]); var data = prDMO.GetMyPartsRequests(GlobalVars.GetUserId(GetSession()));
return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet); return GetJsonResult(data.ToDataSourceResult(request));
} catch (Exception ex) { } catch (Exception ex) {
// TODO record the error throw;
throw ex;
} }
} }
[AcceptVerbs(HttpVerbs.Post)] [AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeletePR([DataSourceRequest] DataSourceRequest request, MyPartsRequestList pr) { public ActionResult DeletePR([DataSourceRequest] DataSourceRequest request, MyPartsRequestList pr) {
try { try {
if (Convert.ToBoolean(Session[GlobalVars.CAN_CREATE_PARTS_REQUEST]) == false) if (!GlobalVars.GetCanCreatePartsRequest(GetSession()))
throw new Exception("Permission denied"); 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)); return Json(new[] { pr }.ToDataSourceResult(request, ModelState));
} catch (Exception ex) { } catch (Exception ex) {
return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, ex.Message); return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, ex.Message);
} }
} }
#endif
public void NotifyDelegation(int delegatedUser, DateTime startDate, DateTime endDate) { 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); LoginModel delegateTo = originalUserDMO.GetUserByID(delegatedUser);
List<string> emailList = new List<string>(); List<string> emailList = new();
emailList.Add(delegateFrom.Email); emailList.Add(delegateFrom.Email);
emailList.Add(delegateTo.Email); emailList.Add(delegateTo.Email);
HomeHelper.NotifyDelegation(_AppSettings, startDate, endDate, delegateFrom, delegateTo, emailList); HomeHelper.NotifyDelegation(_AppSettings, startDate, endDate, delegateFrom, delegateTo, emailList);
@ -381,22 +413,24 @@ public class HomeController : Controller {
public bool ProcessOoO() { public bool ProcessOoO() {
try { try {
UserAccountDMO userDMO = new UserAccountDMO(); UserAccountDMO userDMO = new();
userDMO.ProcessOoO(); userDMO.ProcessOoO();
return true; return true;
} catch { } catch {
return false; return false;
} }
} }
public bool ExpireOoO() { public bool ExpireOoO() {
try { try {
UserAccountDMO userDMO = new UserAccountDMO(); UserAccountDMO userDMO = new();
userDMO.ExpireOoO(); userDMO.ExpireOoO();
return true; return true;
} catch { } catch {
return false; return false;
} }
} }
public bool ApprovalsReminderNotifications() { public bool ApprovalsReminderNotifications() {
try { try {
// Get list of approvals // Get list of approvals
@ -417,12 +451,13 @@ public class HomeController : Controller {
return false; return false;
} }
} }
public void NotifyApprover(string toEmail, string title, int issueId, string docType) { public void NotifyApprover(string toEmail, string title, int issueId, string docType) {
try { try {
HomeHelper.NotifyApprover(_AppSettings, toEmail, title, issueId, docType); HomeHelper.NotifyApprover(_AppSettings, toEmail, title, issueId, docType);
try { 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 { }
} catch (Exception e) { } catch (Exception e) {
@ -432,9 +467,38 @@ public class HomeController : Controller {
} catch { } catch {
detailedException = e.Message; detailedException = e.Message;
} }
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" });
throw e; 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;
} }

View File

@ -1,39 +1,57 @@
using System; using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Configuration;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Runtime.Serialization; #if !NET8
using System.Web; using System.Web;
using System.Web.Mvc; 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.DMO;
using Fab2ApprovalSystem.Misc; using Fab2ApprovalSystem.Misc;
using Fab2ApprovalSystem.Models; using Fab2ApprovalSystem.Models;
using Fab2ApprovalSystem.ViewModels; using Fab2ApprovalSystem.ViewModels;
#if !NET8
using Kendo.Mvc.Extensions; using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI; using Kendo.Mvc.UI;
#endif
#if !NET8
using System.Collections;
using System.Configuration;
using System.Runtime.Serialization;
#endif
namespace Fab2ApprovalSystem.Controllers; namespace Fab2ApprovalSystem.Controllers;
[Authorize] [Authorize]
#if !NET8
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
[SessionExpireFilter] [SessionExpireFilter]
#endif
#if NET8
[Route("[controller]")]
#endif
public class LotDispositionController : Controller { public class LotDispositionController : Controller {
LotDispositionDMO ldDMO = new LotDispositionDMO(); private readonly LotDispositionDMO ldDMO = new();
WorkflowDMO wfDMO = new WorkflowDMO(); private readonly WorkflowDMO wfDMO = new();
private readonly AppSettings _AppSettings = GlobalVars.AppSettings; private readonly AppSettings? _AppSettings = GlobalVars.AppSettings;
// GET: /LotDisposition/Create // GET: /LotDisposition/Create
public ActionResult Create() { public ActionResult Create() {
LotDisposition lotDispo = new LotDisposition(); LotDisposition lotDispo = new();
try { try {
// insert a records to get the issueID // insert a records to get the issueID
lotDispo.OriginatorID = (int)Session[GlobalVars.SESSION_USERID]; lotDispo.OriginatorID = GlobalVars.GetUserId(GetSession());
ldDMO.InsertLotDisposition(lotDispo); ldDMO.InsertLotDisposition(lotDispo);
return RedirectToAction("Edit", new { issueID = lotDispo.IssueID.ToString() }); return RedirectToAction("Edit", new { issueID = lotDispo.IssueID.ToString() });
} catch (Exception e) { } catch (Exception e) {
@ -44,16 +62,16 @@ public class LotDispositionController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = lotDispo.IssueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString });
return View("Error"); return View("Error");
} }
} }
public JsonResult AddLot(Lot lot) { public JsonResult AddLot(Lot lot) {
Lot l = lot; Lot l = lot;
MRB_DMO mrbDMO = new MRB_DMO(_AppSettings); MRB_DMO mrbDMO = new(_AppSettings);
IssueWithExistingLotsViewModel issueWEL = new IssueWithExistingLotsViewModel(); IssueWithExistingLotsViewModel issueWEL = new();
try { try {
lot.LotStatusOption.LotStatusOptionID = l.LotStatusOptionID; lot.LotStatusOption.LotStatusOptionID = l.LotStatusOptionID;
@ -67,22 +85,22 @@ public class LotDispositionController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + lot.IssueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = l.IssueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
return Json(l, JsonRequestBehavior.AllowGet); return GetJsonResult(l);
} }
public JsonResult AddLots(string lotNumbers, int issueID) { public JsonResult AddLots(string lotNumbers, int issueID) {
MRB_DMO mrbDMO = new MRB_DMO(_AppSettings); MRB_DMO mrbDMO = new(_AppSettings);
bool existingLotUpdated; bool existingLotUpdated;
IssueWithExistingLotsViewModel issueWEL = new IssueWithExistingLotsViewModel(); IssueWithExistingLotsViewModel issueWEL = new();
try { try {
if (lotNumbers.Length > 0) { if (lotNumbers.Length > 0) {
string[] tempLots = lotNumbers.Split(new char[] { '~' }); string[] tempLots = lotNumbers.Split(new char[] { '~' });
foreach (string lotNumber in tempLots) { foreach (string lotNumber in tempLots) {
Lot l = new Lot(); Lot l = new();
l.LotNumber = lotNumber; l.LotNumber = lotNumber;
l.IssueID = issueID; l.IssueID = issueID;
l.LotStatusOption.LotStatusOptionID = (int)GlobalVars.LotStatusOption.NotAvailable; l.LotStatusOption.LotStatusOptionID = (int)GlobalVars.LotStatusOption.NotAvailable;
@ -104,20 +122,19 @@ public class LotDispositionController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
return GetJsonResult(issueWEL);
return Json(issueWEL, JsonRequestBehavior.AllowGet);
} }
// GET: /LotDisposition/Edit/5 // GET: /LotDisposition/Edit/5
public ActionResult Edit(int issueID) { public ActionResult Edit(int issueID) {
int isITARCompliant = 1; int isITARCompliant = 1;
try { try {
LotDisposition lotDispo = new LotDisposition(); LotDisposition lotDispo = new();
lotDispo = ldDMO.GetLotDispositionItemForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); lotDispo = ldDMO.GetLotDispositionItemForRead(issueID, out isITARCompliant, GlobalVars.GetUserId(GetSession()));
if (isITARCompliant == 0) // not ITAR Compliant if (isITARCompliant == 0) // not ITAR Compliant
{ {
@ -128,20 +145,20 @@ public class LotDispositionController : Controller {
} }
if (lotDispo.CurrentStep == 1) { if (lotDispo.CurrentStep == 1) {
List<ApproversListViewModel> userList = MiscDMO.GetPendingApproversListByDocument(issueID, lotDispo.CurrentStep, (int)GlobalVars.DocumentType.LotDisposition); List<ApproversListViewModel> 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) if (approver == null)
ViewBag.IsApprover = "false"; ViewBag.IsApprover = "false";
else else
ViewBag.IsApprover = "true"; 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 }); return RedirectToAction("ReadOnly", new { issueID = issueID });
} else { } else {
if ((ViewBag.IsApprover == "true" || (bool)Session[GlobalVars.IS_ADMIN]) if ((ViewBag.IsApprover == "true" || GlobalVars.IsAdmin(GetSession()))
|| (int)Session[GlobalVars.SESSION_USERID] == lotDispo.OriginatorID) { || GlobalVars.GetUserId(GetSession()) == lotDispo.OriginatorID) {
lotDispo = ldDMO.GetLotDispositionItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); 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(); PopulateLotStatusOptions();
ViewBag.OriginatorList = ldDMO.GetUserList(); ViewBag.OriginatorList = ldDMO.GetUserList();
ViewBag.deps = ldDMO.GetDepartments(); ViewBag.deps = ldDMO.GetDepartments();
@ -159,7 +176,7 @@ public class LotDispositionController : Controller {
} else if (lotDispo.CurrentStep > 1) { } else if (lotDispo.CurrentStep > 1) {
List<ApproversListViewModel> userList = MiscDMO.GetPendingApproversListByDocument(issueID, lotDispo.CurrentStep, (int)GlobalVars.DocumentType.LotDisposition); List<ApproversListViewModel> 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) { if (approver == null) {
ViewBag.IsApprover = "false"; 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 }); return RedirectToAction("ReadOnly", new { issueID = issueID });
} else { } else {
if ((ViewBag.IsApprover == "true" || (bool)Session[GlobalVars.IS_ADMIN]) if ((ViewBag.IsApprover == "true" || GlobalVars.IsAdmin(GetSession()))
|| (int)Session[GlobalVars.SESSION_USERID] == lotDispo.OriginatorID) { || GlobalVars.GetUserId(GetSession()) == lotDispo.OriginatorID) {
return RedirectToAction("EditStep", new { issueID = issueID }); return RedirectToAction("EditStep", new { issueID = issueID });
} else { } else {
@ -185,10 +202,10 @@ public class LotDispositionController : Controller {
} else { } else {
// TODO // TODO
// Check the recordlock indicator // 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 }); return RedirectToAction("ReadOnly", new { issueID = issueID });
} else { } else {
lotDispo = ldDMO.GetLotDispositionItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); lotDispo = ldDMO.GetLotDispositionItem(issueID, out isITARCompliant, GlobalVars.GetUserId(GetSession()));
PopulateLotStatusOptions(); PopulateLotStatusOptions();
ViewBag.OriginatorList = ldDMO.GetUserList(); ViewBag.OriginatorList = ldDMO.GetUserList();
ViewBag.deps = ldDMO.GetDepartments(); ViewBag.deps = ldDMO.GetDepartments();
@ -207,8 +224,8 @@ public class LotDispositionController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString });
return View("Error"); return View("Error");
} }
} }
@ -227,8 +244,8 @@ public class LotDispositionController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + lotDispo.IssueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = lotDispo.IssueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
} }
@ -236,8 +253,8 @@ public class LotDispositionController : Controller {
public ActionResult ReadOnly(int issueID) { public ActionResult ReadOnly(int issueID) {
int isITARCompliant = 1; int isITARCompliant = 1;
try { try {
LotDisposition lotDispo = new LotDisposition(); LotDisposition lotDispo = new();
lotDispo = ldDMO.GetLotDispositionItemForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); lotDispo = ldDMO.GetLotDispositionItemForRead(issueID, out isITARCompliant, GlobalVars.GetUserId(GetSession()));
PopulateLotStatusOptions(); PopulateLotStatusOptions();
ViewBag.OriginatorList = ldDMO.GetUserList(); ViewBag.OriginatorList = ldDMO.GetUserList();
@ -254,8 +271,8 @@ public class LotDispositionController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
} }
@ -264,10 +281,10 @@ public class LotDispositionController : Controller {
int isITARCompliant = 1; int isITARCompliant = 1;
try { try {
LotDisposition lotDispo = new LotDisposition(); LotDisposition lotDispo = new();
lotDispo = ldDMO.GetLotDispositionItemForRead(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); lotDispo = ldDMO.GetLotDispositionItemForRead(issueID, out isITARCompliant, GlobalVars.GetUserId(GetSession()));
List<ApproversListViewModel> userList = MiscDMO.GetPendingApproversListByDocument(issueID, lotDispo.CurrentStep, (int)GlobalVars.DocumentType.LotDisposition); List<ApproversListViewModel> 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) if (appUser == null)
ViewBag.IsApprover = "false"; ViewBag.IsApprover = "false";
else else
@ -275,10 +292,10 @@ public class LotDispositionController : Controller {
// Check the recordlock indicator // Check the recordlock indicator
if ((ViewBag.IsApprover == "true" || (bool)Session[GlobalVars.IS_ADMIN])) { if ((ViewBag.IsApprover == "true" || GlobalVars.IsAdmin(GetSession()))) {
lotDispo = ldDMO.GetLotDispositionItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); 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(); PopulateLotStatusOptions();
ViewBag.OriginatorList = ldDMO.GetUserList(); ViewBag.OriginatorList = ldDMO.GetUserList();
ViewBag.deps = ldDMO.GetDepartments(); ViewBag.deps = ldDMO.GetDepartments();
@ -301,8 +318,8 @@ public class LotDispositionController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + issueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
} }
@ -315,30 +332,32 @@ public class LotDispositionController : Controller {
public JsonResult GetResponsibilityIssue(int responsibilityID) { public JsonResult GetResponsibilityIssue(int responsibilityID) {
List<ResponsibilityIssue> respIssue = ldDMO.GetResponsibilityIssueList(responsibilityID); List<ResponsibilityIssue> respIssue = ldDMO.GetResponsibilityIssueList(responsibilityID);
var data = respIssue.Select(s => new SelectListItem { Value = s.ResponsibilityIssueID.ToString(), Text = s.Issue }); var data = respIssue.Select(s => new SelectListItem() { Value = s.ResponsibilityIssueID.ToString(), Text = s.Issue });
return Json(data, JsonRequestBehavior.AllowGet); return GetJsonResult(data);
} }
#if !NET8
public JsonResult GetDepartments([DataSourceRequest] DataSourceRequest request) { public JsonResult GetDepartments([DataSourceRequest] DataSourceRequest request) {
var departments = ldDMO.GetDepartments(); var departments = ldDMO.GetDepartments();
return Json(departments, JsonRequestBehavior.AllowGet); return GetJsonResult(departments);
} }
#endif
public void PopulateLotStatusOptions() { public void PopulateLotStatusOptions() {
var lotStatusOptions = ldDMO.GetLotStatusOptions(); var lotStatusOptions = ldDMO.GetLotStatusOptions();
ViewData["LotStatusOptions"] = lotStatusOptions; ViewData["LotStatusOptions"] = lotStatusOptions;
} }
#if !NET8
public ActionResult EditingCustom_Read([DataSourceRequest] DataSourceRequest request, int issueID) { public ActionResult EditingCustom_Read([DataSourceRequest] DataSourceRequest request, int issueID) {
return Json(ldDMO.GetLotDispositionLots(issueID).ToDataSourceResult(request)); return Json(ldDMO.GetLotDispositionLots(issueID).ToDataSourceResult(request));
} }
/// <summary>
/// Updates the lot tables
/// </summary>
[AcceptVerbs(HttpVerbs.Post)] [AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditingCustom_Update([DataSourceRequest] DataSourceRequest request, Lot lot) { public ActionResult EditingCustom_Update([DataSourceRequest] DataSourceRequest request, Lot lot) {
if (lot != null && ModelState.IsValid) { if (lot != null && ModelState.IsValid) {
ldDMO.UpdateLotDispoLot(lot); ldDMO.UpdateLotDispoLot(lot);
} }
@ -347,10 +366,6 @@ public class LotDispositionController : Controller {
return Json(new[] { lot }.ToDataSourceResult(request, ModelState)); return Json(new[] { lot }.ToDataSourceResult(request, ModelState));
} }
/// <summary>
/// Deletes record from the lot table
/// </summary>
[AcceptVerbs(HttpVerbs.Post)] [AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditingCustom_Destroy([DataSourceRequest] DataSourceRequest request, Lot lot) { public ActionResult EditingCustom_Destroy([DataSourceRequest] DataSourceRequest request, Lot lot) {
try { try {
@ -366,8 +381,6 @@ public class LotDispositionController : Controller {
return Json(new[] { lot }.ToDataSourceResult(request, ModelState)); return Json(new[] { lot }.ToDataSourceResult(request, ModelState));
} }
// REGION ATTACHMENT
public ActionResult Attachment_Read([DataSourceRequest] DataSourceRequest request, int issueID) { public ActionResult Attachment_Read([DataSourceRequest] DataSourceRequest request, int issueID) {
return Json(ldDMO.GetLotDispoAttachments(issueID).ToDataSourceResult(request)); return Json(ldDMO.GetLotDispoAttachments(issueID).ToDataSourceResult(request));
} }
@ -385,6 +398,8 @@ public class LotDispositionController : Controller {
return Json(new[] { attachment }.ToDataSourceResult(request, ModelState)); return Json(new[] { attachment }.ToDataSourceResult(request, ModelState));
} }
#endif
[HttpPost] [HttpPost]
public void DeleteAttachment(int attachmentID, string fileName) { public void DeleteAttachment(int attachmentID, string fileName) {
try { try {
@ -392,7 +407,7 @@ public class LotDispositionController : Controller {
ldDMO.DeleteLotDispoAttachment(attachmentID); ldDMO.DeleteLotDispoAttachment(attachmentID);
var physicalPath = System.IO.Path.Combine(_AppSettings.AttachmentFolder + "LotDisposition", fileName); 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) if (f.Exists)
f.Delete(); f.Delete();
@ -406,21 +421,23 @@ public class LotDispositionController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "AttachmentID=" + attachmentID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = 999, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "AttachmentID Disposition " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
} }
public JsonResult GetLotDispoAttachments(int issueID) { public JsonResult GetLotDispoAttachments(int issueID) {
var model = ldDMO.GetLotDispoAttachments(issueID); var model = ldDMO.GetLotDispoAttachments(issueID);
return Json(model, JsonRequestBehavior.AllowGet); return GetJsonResult(model);
} }
#if !NET8
public ActionResult AttachSave(IEnumerable<HttpPostedFileBase> files, int issueID) { public ActionResult AttachSave(IEnumerable<HttpPostedFileBase> files, int issueID) {
// The Name of the Upload component is "files" // The Name of the Upload component is "files"
if (files != null) { if (files != null) {
int userId = (int)Session[GlobalVars.SESSION_USERID]; int userId = GlobalVars.GetUserId(GetSession());
foreach (var file in files) { foreach (var file in files) {
LotDispositionHelper.AttachSave(_AppSettings, ldDMO, issueID, userId, file.FileName, file.InputStream); LotDispositionHelper.AttachSave(_AppSettings, ldDMO, issueID, userId, file.FileName, file.InputStream);
} }
@ -429,10 +446,11 @@ public class LotDispositionController : Controller {
return Content(""); return Content("");
} }
public JsonResult SearchLots(string searchText, string searchBy) { #endif
List<String> lotlist = MiscDMO.SearchLots(searchText, searchBy).Select(x => x.LotNumber).ToList<String>();
return Json(lotlist, JsonRequestBehavior.AllowGet); public JsonResult SearchLots(string searchText, string searchBy) {
List<string> lotlist = MiscDMO.SearchLots(searchText, searchBy).Select(x => x.LotNumber).ToList();
return GetJsonResult(lotlist);
} }
public void DeleteAllLots(int issueID) { public void DeleteAllLots(int issueID) {
@ -440,10 +458,12 @@ public class LotDispositionController : Controller {
ldDMO.DeleteAllLotDispoLot(issueID); ldDMO.DeleteAllLotDispoLot(issueID);
} }
#if !NET8
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
#endif
public ActionResult LotStatusDetail(int issueID, string lotNumber, bool readonlyView, string lotLocation = "") { public ActionResult LotStatusDetail(int issueID, string lotNumber, bool readonlyView, string lotLocation = "") {
ViewBag.LotLocation = lotLocation; ViewBag.LotLocation = lotLocation;
var model = new ScrapLot(); ScrapLot model = new();
var data = ldDMO.GetLotStausDetail(issueID, lotNumber); var data = ldDMO.GetLotStausDetail(issueID, lotNumber);
if (data != null) if (data != null)
model = data; model = data;
@ -470,7 +490,8 @@ public class LotDispositionController : Controller {
try { try {
foreach (PropertyInfo pi in sl.GetType().GetProperties()) { foreach (PropertyInfo pi in sl.GetType().GetProperties()) {
if (pi.Name.ToLower().StartsWith("lot") && pi.Name.ToLower().EndsWith("state")) { 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) { if (currentValue == (int)GlobalVars.LotStatusOption.Release || currentValue == (int)GlobalVars.LotStatusOption.CloseToQDB) {
releaseCount++; releaseCount++;
// required to update the lot status option // required to update the lot status option
@ -498,8 +519,8 @@ public class LotDispositionController : Controller {
detailedException = e.Message; 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(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = sl.IssueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "UpdateLotScrapReleaseStatus - " + exceptionString });
throw new Exception(e.Message); 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 /// Update the all the lots to "RELEASE" Status for a given Lot disposition document
/// </summary> /// </summary>
public void ReleaseAll(int issueID) { public void ReleaseAll(int issueID) {
ScrapLot sl = new ScrapLot(); ScrapLot sl = new();
try { try {
sl.IssueID = issueID; sl.IssueID = issueID;
foreach (PropertyInfo pi in sl.GetType().GetProperties()) { foreach (PropertyInfo pi in sl.GetType().GetProperties()) {
@ -526,8 +547,8 @@ public class LotDispositionController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + sl.IssueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = sl.IssueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "ReleaseAll - " + exceptionString });
throw new Exception(e.Message); 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 /// Update the all the lots to "SCRAP" Status for a given Lot disposition document
/// </summary> /// </summary>
public void ScrapAll(int issueID) { public void ScrapAll(int issueID) {
ScrapLot sl = new ScrapLot(); ScrapLot sl = new();
try { try {
sl.IssueID = issueID; sl.IssueID = issueID;
foreach (PropertyInfo pi in sl.GetType().GetProperties()) { foreach (PropertyInfo pi in sl.GetType().GetProperties()) {
@ -554,20 +575,20 @@ public class LotDispositionController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + sl.IssueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = sl.IssueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "ScrapAll - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
} }
public JsonResult GetLotDispositionLotSummary(int issueID) { 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) { public ActionResult SubmitDocument(int issueID, bool peRequired, bool mrbRequired) {
try { 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) if (appoverCount > 0)
NotifyApprovers(issueID, (byte)GlobalVars.WorkFLowStepNumber.Step1); NotifyApprovers(issueID, (byte)GlobalVars.WorkFLowStepNumber.Step1);
else { else {
@ -576,10 +597,11 @@ public class LotDispositionController : Controller {
} }
if (Request.IsAjaxRequest()) { if (IsAjaxRequest()) {
return Content("Redirect"); return Content("Redirect");
} else } else {
return Content("Invalid"); return Content("Invalid");
}
} catch (Exception e) { } catch (Exception e) {
string detailedException = ""; string detailedException = "";
try { try {
@ -588,11 +610,11 @@ public class LotDispositionController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString });
Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError; 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; int isITARCompliant = 1;
try { try {
bool lastStep = false; 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) { while (lastApprover && !lastStep) {
currentStep++; 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); NotifyApprovers(issueID, currentStep);
} }
} catch (Exception e) { } catch (Exception e) {
@ -617,16 +639,16 @@ public class LotDispositionController : Controller {
detailedException = e.Message; 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(); 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); 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 = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "Approve - " + exceptionString }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "Approve - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
} }
public void Reject(int issueID, byte currentStep, string comments) { public void Reject(int issueID, byte currentStep, string comments) {
try { try {
if (Session[GlobalVars.SESSION_USERID] != null) { if (GlobalVars.IsUserIdValueNotNull(GetSession())) {
wfDMO.Reject(issueID, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.LotDisposition); wfDMO.Reject(issueID, currentStep, comments, GlobalVars.GetUserId(GetSession()), (int)GlobalVars.DocumentType.LotDisposition);
NotifyRejectionToOrginator(issueID); NotifyRejectionToOrginator(issueID);
} else { } else {
@ -640,29 +662,30 @@ public class LotDispositionController : Controller {
detailedException = e.Message; 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(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "Reject - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
} }
/// <summary> #if !NET8
/// Get a list of Approvers and the status
/// </summary>
public ActionResult GetApproversList([DataSourceRequest] DataSourceRequest request, int issueID, byte step) { public ActionResult GetApproversList([DataSourceRequest] DataSourceRequest request, int issueID, byte step) {
return Json(MiscDMO.GetApproversListByDocument(issueID, step, (int)GlobalVars.DocumentType.LotDisposition).ToDataSourceResult(request)); return Json(MiscDMO.GetApproversListByDocument(issueID, step, (int)GlobalVars.DocumentType.LotDisposition).ToDataSourceResult(request));
} }
#endif
public JsonResult GetAllUsersList() { public JsonResult GetAllUsersList() {
UserAccountDMO userDMO = new UserAccountDMO(); UserAccountDMO userDMO = new();
IEnumerable<LoginModel> userlist = userDMO.GetAllUsers(); IEnumerable<LoginModel> userlist = userDMO.GetAllUsers();
return Json(userlist, JsonRequestBehavior.AllowGet); return GetJsonResult(userlist);
} }
public void ReAssignApproval(int issueID, int userIDs, byte step) { public void ReAssignApproval(int issueID, int userIDs, byte step) {
var email = ""; var email = "";
try { 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) { } catch (Exception e) {
string detailedException = ""; string detailedException = "";
try { try {
@ -671,13 +694,13 @@ public class LotDispositionController : Controller {
detailedException = e.Message; 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(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
LotDispositionHelper.ReAssignApproval(_AppSettings, issueID, email); LotDispositionHelper.ReAssignApproval(_AppSettings, issueID, email);
try { 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 { } } catch { }
} }
@ -693,22 +716,22 @@ public class LotDispositionController : Controller {
detailedException = e.Message; 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(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "ReAssignApproval - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
LotDispositionHelper.ReAssignApproverByAdmin(_AppSettings, issueID, email); LotDispositionHelper.ReAssignApproverByAdmin(_AppSettings, issueID, email);
try { 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 { } } catch { }
} }
#region Additional Approvers #region Additional Approvers
public JsonResult GetUserListForAdditionalAppprrovers() { public JsonResult GetUserListForAdditionalAppprrovers() {
UserAccountDMO userDMO = new UserAccountDMO(); UserAccountDMO userDMO = new();
IEnumerable<LoginModel> userlist = userDMO.GetAllUsers(); IEnumerable<LoginModel> userlist = userDMO.GetAllUsers();
return Json(userlist, JsonRequestBehavior.AllowGet); return GetJsonResult(userlist);
} }
public void AddAdditionalApproval(int issueID, byte step, string userIDs) { public void AddAdditionalApproval(int issueID, byte step, string userIDs) {
@ -724,13 +747,13 @@ public class LotDispositionController : Controller {
detailedException = e.Message; 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(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
emailSentList = LotDispositionHelper.AddAdditionalApproval(_AppSettings, issueID, emailSentList, emailArray); emailSentList = LotDispositionHelper.AddAdditionalApproval(_AppSettings, issueID, emailSentList, emailArray);
try { 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 { } } catch { }
} }
@ -741,7 +764,7 @@ public class LotDispositionController : Controller {
List<string> emailIst = MiscDMO.GetApproverEmailListByDocument(@issueID, currentStep, (int)GlobalVars.DocumentType.LotDisposition).Distinct().ToList(); List<string> emailIst = MiscDMO.GetApproverEmailListByDocument(@issueID, currentStep, (int)GlobalVars.DocumentType.LotDisposition).Distinct().ToList();
string emailSentList = LotDispositionHelper.NotifyApprovers(_AppSettings, issueID, emailIst); string emailSentList = LotDispositionHelper.NotifyApprovers(_AppSettings, issueID, emailIst);
try { 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 { }
} catch (Exception e) { } catch (Exception e) {
string detailedException = ""; string detailedException = "";
@ -751,19 +774,19 @@ public class LotDispositionController : Controller {
detailedException = e.Message; 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(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "AddAdditionalApproval - " + exceptionString });
throw e; throw;
} }
} }
public void NotifyRejectionToOrginator(int issueID) { public void NotifyRejectionToOrginator(int issueID) {
string username = Session[GlobalVars.SESSION_USERNAME].ToString(); string username = GlobalVars.GetUserName(GetSession());
List<string> emailIst = ldDMO.GetRejectionOrginatorEmailList(@issueID).Distinct().ToList(); List<string> emailIst = ldDMO.GetRejectionOrginatorEmailList(@issueID).Distinct().ToList();
string userEmail = LotDispositionHelper.NotifyRejectionToOrginator(_AppSettings, issueID, username, emailIst); string userEmail = LotDispositionHelper.NotifyRejectionToOrginator(_AppSettings, issueID, username, emailIst);
try { 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 { } } catch { }
} }
@ -778,19 +801,23 @@ public class LotDispositionController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim(); string exceptionString = e.Message.ToString().Trim();
Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n UpdateReasonForDisposition\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "UpdateReasonForDisposition - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
} }
#if !NET8
public ActionResult GetComments([DataSourceRequest] DataSourceRequest request, int issueID) { public ActionResult GetComments([DataSourceRequest] DataSourceRequest request, int issueID) {
return Json(ldDMO.GetComments(issueID).ToDataSourceResult(request)); return Json(ldDMO.GetComments(issueID).ToDataSourceResult(request));
} }
#endif
public void InsertComments(int issueID, string Comments) { public void InsertComments(int issueID, string Comments) {
try { try {
ldDMO.InsertComments(issueID, Comments, (int)Session[GlobalVars.SESSION_USERID]); ldDMO.InsertComments(issueID, Comments, GlobalVars.GetUserId(GetSession()));
} catch (Exception e) { } catch (Exception e) {
string detailedException = ""; string detailedException = "";
try { try {
@ -799,17 +826,19 @@ public class LotDispositionController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim(); string exceptionString = e.Message.ToString().Trim();
Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n UpdateCopmments\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\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 }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "UpdateCopmments - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
} }
#if !NET8
public ActionResult ExcelLotOpen(IEnumerable<HttpPostedFileBase> Lotfile, int issueID) { public ActionResult ExcelLotOpen(IEnumerable<HttpPostedFileBase> Lotfile, int issueID) {
MRB_DMO mrbDMO = new MRB_DMO(_AppSettings); MRB_DMO mrbDMO = new MRB_DMO(_AppSettings);
var physicalPath = ""; var physicalPath = "";
try { try {
string userIdentityName = @User.Identity.Name; string userIdentityName = GetUserIdentityName();
foreach (var file in Lotfile) { foreach (var file in Lotfile) {
physicalPath = LotDispositionHelper.ExcelLotOpen(ldDMO, issueID, userIdentityName, _AppSettings.LotTempPipeLine, file.FileName, file.InputStream); 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) { public void ReleaseLockOnDocument(int issueID) {
try { try {
ldDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], issueID); ldDMO.ReleaseLockOnDocument(GlobalVars.GetUserId(GetSession()), issueID);
} catch (Exception e) { } catch (Exception e) {
try { 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 { } } catch { }
ldDMO.ReleaseLockOnDocument(-1, issueID); ldDMO.ReleaseLockOnDocument(-1, issueID);
} }
@ -857,4 +888,34 @@ public class LotDispositionController : Controller {
return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); 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;
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,33 +1,50 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics; using System.Diagnostics;
using System.Dynamic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading; #if !NET8
using System.Web; using System.Web;
using System.Web.Mvc; using System.Web.Mvc;
using System.Web.Script.Serialization; using System.Web.Script.Serialization;
#endif
#if NET8
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
#endif
using Fab2ApprovalSystem.DMO; using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Misc; using Fab2ApprovalSystem.Misc;
using Fab2ApprovalSystem.Models; using Fab2ApprovalSystem.Models;
using Fab2ApprovalSystem.ViewModels; using Fab2ApprovalSystem.ViewModels;
#if !NET8
using System.Dynamic;
using System.Threading;
using System.Configuration;
#endif
#if !NET8
using Kendo.Mvc.Extensions; using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI; using Kendo.Mvc.UI;
#endif
namespace Fab2ApprovalSystem.Controllers; namespace Fab2ApprovalSystem.Controllers;
[Authorize] [Authorize]
#if !NET8
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
[SessionExpireFilter] [SessionExpireFilter]
#endif
#if NET8
[Route("[controller]")]
#endif
public class MRBController : Controller { public class MRBController : Controller {
MRB_DMO mrbDMO = new MRB_DMO(GlobalVars.AppSettings); private readonly MRB_DMO mrbDMO = new(GlobalVars.AppSettings);
WorkflowDMO wfDMO = new WorkflowDMO(); private readonly WorkflowDMO wfDMO = new();
CredentialsStorage credentialsStorage = new CredentialsStorage(); private readonly CredentialsStorage credentialsStorage = new();
private readonly AppSettings _AppSettings = GlobalVars.AppSettings; private readonly AppSettings _AppSettings = GlobalVars.AppSettings;
// GET: /MRB/ // GET: /MRB/
@ -42,25 +59,27 @@ public class MRBController : Controller {
// GET: /MRB/Create // GET: /MRB/Create
public ActionResult Create() { public ActionResult Create() {
MRB mrb = new MRB(); MRB mrb = new();
MRB_DMO mrbDMO = new MRB_DMO(_AppSettings); MRB_DMO mrbDMO = new(_AppSettings);
mrb.OriginatorID = (int)Session[GlobalVars.SESSION_USERID]; mrb.OriginatorID = GlobalVars.GetUserId(GetSession());
mrbDMO.InsertMRB(mrb); mrbDMO.InsertMRB(mrb);
// Automatically Submit the Document as soon as an MRB is created // Automatically Submit the Document as soon as an MRB is created
try { try {
PopulateCloseToQDB(); PopulateCloseToQDB();
mrbDMO.SubmitDocument(mrb.MRBNumber, (int)Session[GlobalVars.SESSION_USERID]); mrbDMO.SubmitDocument(mrb.MRBNumber, GlobalVars.GetUserId(GetSession()));
} catch (Exception e) { } catch (Exception e) {
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + mrb.MRBNumber.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n SubmitDocument - MRB\r\n" + e.Message.ToString(), EventLogEntryType.Error);
EventLogDMO.Add(new WinEventLog() { IssueID = mrb.MRBNumber, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString }); EventLogDMO.Add(new WinEventLog() { IssueID = mrb.MRBNumber, UserID = GetUserIdentityName(), DocumentType = "MRB", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
return RedirectToAction("Edit", new { IssueID = mrb.MRBNumber }); return RedirectToAction("Edit", new { IssueID = mrb.MRBNumber });
} }
#if !NET8
// POST: /MRB/Create // POST: /MRB/Create
[HttpPost] [HttpPost]
public ActionResult Create(FormCollection collection) { public ActionResult Create(FormCollection collection) {
@ -73,15 +92,15 @@ public class MRBController : Controller {
} }
} }
#endif
// GET: /MRB/Edit/5 // GET: /MRB/Edit/5
public ActionResult Edit(int issueID) { public ActionResult Edit(int issueID) {
string jwt = Session["JWT"].ToString(); string jwt = GlobalVars.GetJWT(GetSession());
string encodedJwt = System.Net.WebUtility.UrlEncode(jwt); 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 encodedRefreshToken = System.Net.WebUtility.UrlEncode(refreshToken);
string wasmClientUrl = Environment.GetEnvironmentVariable("FabApprovalWasmClientUrl") ?? string mrbUrl = $"{GlobalVars.AppSettings.WasmClientUrl}/redirect?jwt={encodedJwt}&refreshToken={encodedRefreshToken}&redirectPath=mrb/{issueID}";
"https://localhost:7255";
string mrbUrl = $"{wasmClientUrl}/redirect?jwt={encodedJwt}&refreshToken={encodedRefreshToken}&redirectPath=/mrb/{issueID}";
return Redirect(mrbUrl); return Redirect(mrbUrl);
} }
@ -93,20 +112,18 @@ public class MRBController : Controller {
mrbDMO.UpdateMRB(mrb); mrbDMO.UpdateMRB(mrb);
} catch (Exception e) { } catch (Exception e) {
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + mrb.MRBNumber.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n UpdateEdit MRB\r\n" + e.Message.ToString(), EventLogEntryType.Error);
EventLogDMO.Add(new WinEventLog() { IssueID = mrb.MRBNumber, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); EventLogDMO.Add(new WinEventLog() { IssueID = mrb.MRBNumber, UserID = GetUserIdentityName(), DocumentType = "MRB", OperationType = "Error", Comments = exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
} }
public ActionResult ReadOnly(int issueID) { public ActionResult ReadOnly(int issueID) {
string jwt = Session["JWT"].ToString(); string jwt = GlobalVars.GetJWT(GetSession());
string encodedJwt = System.Net.WebUtility.UrlEncode(jwt); 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 encodedRefreshToken = System.Net.WebUtility.UrlEncode(refreshToken);
string wasmClientUrl = Environment.GetEnvironmentVariable("FabApprovalWasmClientUrl") ?? string mrbUrl = $"{GlobalVars.AppSettings.WasmClientUrl}/redirect?jwt={encodedJwt}&refreshToken={encodedRefreshToken}&redirectPath=mrb/{issueID}";
"https://localhost:7255";
string mrbUrl = $"{wasmClientUrl}/redirect?jwt={encodedJwt}&refreshToken={encodedRefreshToken}&redirectPath=/mrb/{issueID}";
return Redirect(mrbUrl); return Redirect(mrbUrl);
} }
@ -116,6 +133,8 @@ public class MRBController : Controller {
return View(); return View();
} }
#if !NET8
// POST: /MRB/Delete/5 // POST: /MRB/Delete/5
[HttpPost] [HttpPost]
public ActionResult Delete(int id, FormCollection collection) { public ActionResult Delete(int id, FormCollection collection) {
@ -128,23 +147,31 @@ public class MRBController : Controller {
} }
} }
#endif
public JsonResult SearchLots(string searchText, string searchBy) { public JsonResult SearchLots(string searchText, string searchBy) {
List<String> lotlist = MiscDMO.SearchLots(searchText, searchBy).Select(x => x.LotNumber).ToList<String>(); List<string> lotlist = MiscDMO.SearchLots(searchText, searchBy).Select(x => x.LotNumber).ToList();
return Json(lotlist, JsonRequestBehavior.AllowGet); return GetJsonResult(lotlist);
} }
#if !NET8
public ActionResult GetMRBLots([DataSourceRequest] DataSourceRequest request, int mrbNumber) { public ActionResult GetMRBLots([DataSourceRequest] DataSourceRequest request, int mrbNumber) {
return Json(mrbDMO.GetMRBLots(mrbNumber).ToDataSourceResult(request)); return Json(mrbDMO.GetMRBLots(mrbNumber).ToDataSourceResult(request));
} }
#endif
[HttpGet] [HttpGet]
public ActionResult GetTools() { public ActionResult GetTools() {
return Json(mrbDMO.GetTools(), JsonRequestBehavior.AllowGet); return GetJsonResult(mrbDMO.GetTools());
} }
/// <summary> /// <summary>
/// Updates the lot tables /// Updates the lot tables
/// </summary> /// </summary>
#if !NET8
[AcceptVerbs(HttpVerbs.Post)] [AcceptVerbs(HttpVerbs.Post)]
public ActionResult UpdateMRBLot([DataSourceRequest] DataSourceRequest request, Lot lot) { public ActionResult UpdateMRBLot([DataSourceRequest] DataSourceRequest request, Lot lot) {
if (lot != null && ModelState.IsValid) { if (lot != null && ModelState.IsValid) {
@ -172,6 +199,8 @@ public class MRBController : Controller {
return Json(new[] { lot }.ToDataSourceResult(request, ModelState)); return Json(new[] { lot }.ToDataSourceResult(request, ModelState));
} }
#endif
public void DeleteAllMRBLots(int issueID) { public void DeleteAllMRBLots(int issueID) {
// trap the error on then client side // trap the error on then client side
mrbDMO.DeleteAllMRBLot(issueID); mrbDMO.DeleteAllMRBLot(issueID);
@ -187,24 +216,24 @@ public class MRBController : Controller {
mrbDMO.InsertLot(lot, false, out existingRowUpdated); mrbDMO.InsertLot(lot, false, out existingRowUpdated);
} catch (Exception e) { } catch (Exception e) {
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + lot.IssueID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Add Lot Disposition\r\n" + e.Message.ToString(), EventLogEntryType.Error);
EventLogDMO.Add(new WinEventLog() { IssueID = l.IssueID, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); EventLogDMO.Add(new WinEventLog() { IssueID = l.IssueID, UserID = GetUserIdentityName(), DocumentType = "MRB", OperationType = "Error", Comments = exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
return Json(l, JsonRequestBehavior.AllowGet); return GetJsonResult(l);
} }
public ActionResult AddLots(string lotNumbers, int mrbNumber) { public ActionResult AddLots(string lotNumbers, int mrbNumber) {
// This is for adding lot(s) via search // This is for adding lot(s) via search
try { try {
var warnings = new StringBuilder(); StringBuilder warnings = new();
if (lotNumbers.Length > 0) { if (lotNumbers.Length > 0) {
string[] tempLots = lotNumbers.Split(new char[] { '~' }); string[] tempLots = lotNumbers.Split(new char[] { '~' });
foreach (string lotNumber in tempLots) { foreach (string lotNumber in tempLots) {
bool existingRowUpdated; bool existingRowUpdated;
Lot l = new Lot(); Lot l = new();
l.LotNumber = lotNumber; l.LotNumber = lotNumber;
l.MRBNumber = mrbNumber; l.MRBNumber = mrbNumber;
mrbDMO.InsertLot(l, true, out existingRowUpdated); mrbDMO.InsertLot(l, true, out existingRowUpdated);
@ -214,8 +243,8 @@ public class MRBController : Controller {
return Content(warnings.ToString()); return Content(warnings.ToString());
} catch (Exception e) { } catch (Exception e) {
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "MRBNumber=" + mrbNumber.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n AddLots MRB\r\n" + e.Message.ToString(), EventLogEntryType.Error);
EventLogDMO.Add(new WinEventLog() { UserID = @User.Identity.Name, OperationType = "Error", DocumentType = "MRB", Comments = exceptionString }); EventLogDMO.Add(new WinEventLog() { UserID = GetUserIdentityName(), OperationType = "Error", DocumentType = "MRB", Comments = exceptionString });
Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError; Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
return Content(e.Message); return Content(e.Message);
@ -224,10 +253,14 @@ public class MRBController : Controller {
#region ATTACHMENT #region ATTACHMENT
#if !NET8
public ActionResult Attachment_Read([DataSourceRequest] DataSourceRequest request, int mrbNumber) { public ActionResult Attachment_Read([DataSourceRequest] DataSourceRequest request, int mrbNumber) {
return Json(mrbDMO.GetMRBAttachments(mrbNumber).ToDataSourceResult(request)); return Json(mrbDMO.GetMRBAttachments(mrbNumber).ToDataSourceResult(request));
} }
#endif
[HttpPost] [HttpPost]
public void DeleteAttachment(int attachmentID) { public void DeleteAttachment(int attachmentID) {
try { try {
@ -237,16 +270,16 @@ public class MRBController : Controller {
if (attachment == null) if (attachment == null)
return; return;
String fileName = attachment.Path; string fileName = attachment.Path;
if (String.IsNullOrEmpty(fileName)) if (string.IsNullOrEmpty(fileName))
fileName = attachment.FileName; fileName = attachment.FileName;
mrbDMO.DeleteMRBAttachment(attachmentID); mrbDMO.DeleteMRBAttachment(attachmentID);
if (!String.IsNullOrWhiteSpace(fileName)) { if (!string.IsNullOrWhiteSpace(fileName)) {
var physicalPath = System.IO.Path.Combine(_AppSettings.AttachmentFolder + "MRB", 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) if (f.Exists)
f.Delete(); f.Delete();
@ -254,18 +287,20 @@ public class MRBController : Controller {
} }
} catch (Exception e) { } catch (Exception e) {
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "AttachmentID=" + attachmentID.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n AttachmentID MRB\r\n" + e.Message.ToString(), EventLogEntryType.Error);
EventLogDMO.Add(new WinEventLog() { IssueID = 999, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = "AttachmentID Disposition " + exceptionString }); EventLogDMO.Add(new WinEventLog() { IssueID = 999, UserID = GetUserIdentityName(), DocumentType = "MRB", OperationType = "Error", Comments = "AttachmentID Disposition " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
} }
#if !NET8
public ActionResult AttachSave(IEnumerable<HttpPostedFileBase> files, int mrbNumber) { public ActionResult AttachSave(IEnumerable<HttpPostedFileBase> files, int mrbNumber) {
var errorList = new List<String>(); var errorList = new List<String>();
// The Name of the Upload component is "files" // The Name of the Upload component is "files"
if (files != null) { if (files != null) {
int userId = (int)Session[GlobalVars.SESSION_USERID]; int userId = GlobalVars.GetUserId(GetSession());
foreach (var file in files) { foreach (var file in files) {
MRBHelper.AttachSave(_AppSettings, mrbDMO, mrbNumber, userId, file.FileName, file.InputStream); MRBHelper.AttachSave(_AppSettings, mrbDMO, mrbNumber, userId, file.FileName, file.InputStream);
} }
@ -273,13 +308,17 @@ public class MRBController : Controller {
return Json(new { errors = errorList }); return Json(new { errors = errorList });
} }
#endif
#endregion #endregion
#if !NET8
public ActionResult ExcelLotOpen(IEnumerable<HttpPostedFileBase> Lotfile, int mrbNumber) { public ActionResult ExcelLotOpen(IEnumerable<HttpPostedFileBase> Lotfile, int mrbNumber) {
var warnings = new StringBuilder(); var warnings = new StringBuilder();
var physicalPath = ""; var physicalPath = "";
try { try {
string userIdentityName = @User.Identity.Name; string userIdentityName = GetUserIdentityName();
var dispos = mrbDMO.GetDispositions(mrbNumber); var dispos = mrbDMO.GetDispositions(mrbNumber);
foreach (var file in Lotfile) { foreach (var file in Lotfile) {
physicalPath = MRBHelper.ExcelLotOpen(mrbDMO, mrbNumber, warnings, dispos, userIdentityName, _AppSettings.LotTempPipeLine, file.FileName, file.InputStream); physicalPath = MRBHelper.ExcelLotOpen(mrbDMO, mrbNumber, warnings, dispos, userIdentityName, _AppSettings.LotTempPipeLine, file.FileName, file.InputStream);
@ -294,8 +333,8 @@ public class MRBController : Controller {
detailedException = e.Message; detailedException = e.Message;
} }
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "IssueID=" + mrbNumber.ToString() + " " + e.Message.ToString().Substring(0, 250) : e.Message.ToString(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n MRB Excel\r\n" + detailedException, EventLogEntryType.Error);
EventLogDMO.Add(new WinEventLog() { IssueID = mrbNumber, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString }); EventLogDMO.Add(new WinEventLog() { IssueID = mrbNumber, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = exceptionString });
System.IO.FileInfo f = new System.IO.FileInfo(physicalPath); System.IO.FileInfo f = new System.IO.FileInfo(physicalPath);
if (f.Exists) if (f.Exists)
@ -311,7 +350,7 @@ public class MRBController : Controller {
try { try {
string message; string message;
string c = Server.MapPath("/FTPBatch/"); string c = Server.MapPath("/FTPBatch/");
string userIdentityName = @User.Identity.Name; string userIdentityName = GetUserIdentityName();
string b = Server.MapPath("/FTPBatch/" + _AppSettings.FTPSPNBatchFileName); string b = Server.MapPath("/FTPBatch/" + _AppSettings.FTPSPNBatchFileName);
string a = Server.MapPath("/FTPBatch/" + _AppSettings.FTPSPNBatchFileName_Test); string a = Server.MapPath("/FTPBatch/" + _AppSettings.FTPSPNBatchFileName_Test);
foreach (var file in AddQDBFlag) { foreach (var file in AddQDBFlag) {
@ -336,7 +375,7 @@ public class MRBController : Controller {
try { try {
string message; string message;
string c = Server.MapPath("/FTPBatch/"); string c = Server.MapPath("/FTPBatch/");
string userIdentityName = @User.Identity.Name; string userIdentityName = GetUserIdentityName();
string b = Server.MapPath("/FTPBatch/" + _AppSettings.FTPSPNBatchFileName); string b = Server.MapPath("/FTPBatch/" + _AppSettings.FTPSPNBatchFileName);
string a = Server.MapPath("/FTPBatch/" + _AppSettings.FTPSPNBatchFileName_Test); string a = Server.MapPath("/FTPBatch/" + _AppSettings.FTPSPNBatchFileName_Test);
foreach (var file in RemoveQDBFlag) { foreach (var file in RemoveQDBFlag) {
@ -356,11 +395,19 @@ public class MRBController : Controller {
} }
} }
#if !NET8
public ActionResult GetContainmentActions([DataSourceRequest] DataSourceRequest request, int mrbNumber) { public ActionResult GetContainmentActions([DataSourceRequest] DataSourceRequest request, int mrbNumber) {
return Json(mrbDMO.GetContainmentActions(mrbNumber).ToDataSourceResult(request)); return Json(mrbDMO.GetContainmentActions(mrbNumber).ToDataSourceResult(request));
} }
#endif
#endif
#if !NET8
[AcceptVerbs(HttpVerbs.Post)] [AcceptVerbs(HttpVerbs.Post)]
#endif
public ActionResult UpdateContainmentAction(ContainmentActionObj model) { public ActionResult UpdateContainmentAction(ContainmentActionObj model) {
if (model != null && ModelState.IsValid) { if (model != null && ModelState.IsValid) {
mrbDMO.UpdateContainmentAction(model); mrbDMO.UpdateContainmentAction(model);
@ -369,7 +416,9 @@ public class MRBController : Controller {
return Content(""); return Content("");
} }
#if !NET8
[AcceptVerbs(HttpVerbs.Post)] [AcceptVerbs(HttpVerbs.Post)]
#endif
public ActionResult InsertContainmentAction(ContainmentActionObj model) { public ActionResult InsertContainmentAction(ContainmentActionObj model) {
if (model != null && ModelState.IsValid) { if (model != null && ModelState.IsValid) {
mrbDMO.InsertContainmentAction(model); mrbDMO.InsertContainmentAction(model);
@ -378,6 +427,8 @@ public class MRBController : Controller {
return Content(""); return Content("");
} }
#if !NET8
[AcceptVerbs(HttpVerbs.Post)] [AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteContainmentAction([DataSourceRequest] DataSourceRequest request, ContainmentActionObj model) { public ActionResult DeleteContainmentAction([DataSourceRequest] DataSourceRequest request, ContainmentActionObj model) {
if (model != null && ModelState.IsValid) { if (model != null && ModelState.IsValid) {
@ -387,19 +438,25 @@ public class MRBController : Controller {
return Json(new[] { model }.ToDataSourceResult(request, ModelState)); return Json(new[] { model }.ToDataSourceResult(request, ModelState));
} }
#endif
#region #region
#if !NET8
public ActionResult GetDispostions([DataSourceRequest] DataSourceRequest request, int mrbNumber) { public ActionResult GetDispostions([DataSourceRequest] DataSourceRequest request, int mrbNumber) {
return Json(mrbDMO.GetDispositions(mrbNumber).ToDataSourceResult(request)); return Json(mrbDMO.GetDispositions(mrbNumber).ToDataSourceResult(request));
} }
#endif
#if !NET8
[AcceptVerbs(HttpVerbs.Post)] [AcceptVerbs(HttpVerbs.Post)]
public ActionResult UpdateDisposition(Disposition model) { public ActionResult UpdateDisposition(Disposition model) {
if (model != null && ModelState.IsValid) { if (model != null && ModelState.IsValid) {
mrbDMO.UpdateDisposition(model); mrbDMO.UpdateDisposition(model);
} }
return GetJsonResult(model);
return Json(model, JsonRequestBehavior.AllowGet);
} }
[AcceptVerbs(HttpVerbs.Post)] [AcceptVerbs(HttpVerbs.Post)]
@ -415,13 +472,15 @@ public class MRBController : Controller {
mrbDMO.DeleteDisposition(model); mrbDMO.DeleteDisposition(model);
} }
return Json(model, JsonRequestBehavior.AllowGet); return GetJsonResult(model);
} }
#endif
#endregion #endregion
public void PopulateCloseToQDB() { public void PopulateCloseToQDB() {
List<CloseToQDBOptionViewModel> options = new List<CloseToQDBOptionViewModel>(); List<CloseToQDBOptionViewModel> options = new();
options.Add(new CloseToQDBOptionViewModel { CloseToQDBOptionID = 0, CloseToQDBOption = "No" }); options.Add(new CloseToQDBOptionViewModel { CloseToQDBOptionID = 0, CloseToQDBOption = "No" });
options.Add(new CloseToQDBOptionViewModel { CloseToQDBOptionID = 1, CloseToQDBOption = "Yes" }); options.Add(new CloseToQDBOptionViewModel { CloseToQDBOptionID = 1, CloseToQDBOption = "Yes" });
ViewData["CloseToQDBOptions"] = options; ViewData["CloseToQDBOptions"] = options;
@ -432,28 +491,28 @@ public class MRBController : Controller {
List<string> emailIst = MiscDMO.GetApproverEmailListByDocument(mrbNumber, currentStep, (int)GlobalVars.DocumentType.MRB).Distinct().ToList(); List<string> emailIst = MiscDMO.GetApproverEmailListByDocument(mrbNumber, currentStep, (int)GlobalVars.DocumentType.MRB).Distinct().ToList();
string emailSentList = MRBHelper.NotifyApprovers(_AppSettings, mrbNumber, emailIst); string emailSentList = MRBHelper.NotifyApprovers(_AppSettings, mrbNumber, emailIst);
try { 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 { } } catch { }
} }
public void Approve(int issueID, byte currentStep, string comments) { public void Approve(int issueID, byte currentStep, string comments) {
int isITARCompliant = 1; int isITARCompliant = 1;
MRB mrb = new MRB(); MRB mrb = new();
mrb = mrbDMO.GetMRBItem(issueID, out isITARCompliant, (int)Session[GlobalVars.SESSION_USERID]); mrb = mrbDMO.GetMRBItem(issueID, out isITARCompliant, GlobalVars.GetUserId(GetSession()));
try { try {
bool lastStep = false; 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) { while (lastApprover && !lastStep) {
currentStep++; 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); NotifyApprovers(issueID, currentStep);
} }
} catch (Exception e) { } 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(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Approve\r\n" + e.Message.ToString(), EventLogEntryType.Error);
EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Lot Disposition", OperationType = "Error", Comments = "Approve - " + exceptionString }); EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = GetUserIdentityName(), DocumentType = "Lot Disposition", OperationType = "Error", Comments = "Approve - " + exceptionString });
throw new Exception(e.Message); throw new Exception(e.Message);
} }
} }
@ -471,9 +530,11 @@ public class MRBController : Controller {
int waferCount = 0; int waferCount = 0;
int dieCount = 0; int dieCount = 0;
mrbDMO.GetLotWaferDieCount(mrbNumber, out lotCount, out waferCount, out dieCount); 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) { public ActionResult SendMRBHoldFlagToSPN(int mrbNumber) {
MRB mrbInfo; MRB mrbInfo;
try { try {
@ -484,7 +545,7 @@ public class MRBController : Controller {
} }
if (!mrbInfo.ToolCSV.ToUpper().Equals("NA")) { if (!mrbInfo.ToolCSV.ToUpper().Equals("NA")) {
Lot l = new Lot(); Lot l = new();
var mrbLotInfo = mrbDMO.GetLotsToFindNewChildLots(mrbNumber); var mrbLotInfo = mrbDMO.GetLotsToFindNewChildLots(mrbNumber);
foreach (Lot lot in mrbLotInfo) { foreach (Lot lot in mrbLotInfo) {
@ -497,10 +558,10 @@ public class MRBController : Controller {
// SEND DATA to SPN // SEND DATA to SPN
StringBuilder output = new StringBuilder(); StringBuilder output = new();
try { try {
string c = Server.MapPath("/FTPBatch/"); string c = Server.MapPath("/FTPBatch/");
string userIdentityName = @User.Identity.Name; string userIdentityName = GetUserIdentityName();
string b = Server.MapPath("/FTPBatch/" + _AppSettings.FTPSPNBatchFileName); string b = Server.MapPath("/FTPBatch/" + _AppSettings.FTPSPNBatchFileName);
string a = Server.MapPath("/FTPBatch/" + _AppSettings.FTPSPNBatchFileName_Test); string a = Server.MapPath("/FTPBatch/" + _AppSettings.FTPSPNBatchFileName_Test);
IEnumerable<string> data = mrbDMO.GetMRBHoldLots(mrbNumber); IEnumerable<string> data = mrbDMO.GetMRBHoldLots(mrbNumber);
@ -530,33 +591,33 @@ public class MRBController : Controller {
} }
} catch (Exception e) { } 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(); 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 }); EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = GetUserIdentityName(), DocumentType = "MRB", OperationType = "Error", Comments = exceptionString });
return Json(new { Error = true, Message = e.Message }, JsonRequestBehavior.AllowGet); return GetJsonResult(new { Error = true, Message = e.Message });
} }
} }
} catch (Exception e) { } 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(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Approve\r\n" + e.Message.ToString(), EventLogEntryType.Error);
EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = GetUserIdentityName(), DocumentType = "MRB", OperationType = "Error", Comments = exceptionString });
return Json(new { Error = true, Message = e.Message }, JsonRequestBehavior.AllowGet); 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) { } 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(); 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); Functions.WriteEvent(_AppSettings, GetUserIdentityName() + "\r\n Approve\r\n" + e.Message.ToString(), EventLogEntryType.Error);
EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = @User.Identity.Name, DocumentType = "MRB", OperationType = "Error", Comments = exceptionString }); EventLogDMO.Add(new WinEventLog() { IssueID = -1, UserID = GetUserIdentityName(), DocumentType = "MRB", OperationType = "Error", Comments = exceptionString });
return Json(new { Error = true, Message = e.Message }, JsonRequestBehavior.AllowGet); return GetJsonResult(new { Error = true, Message = e.Message });
} }
} }
public bool BatchFTP_Old(string sourceFile, string destFile) { public bool BatchFTP_Old(string sourceFile, string destFile) {
System.IO.FileInfo sourcefile = new System.IO.FileInfo(sourceFile); System.IO.FileInfo sourcefile = new(sourceFile);
try { try {
ProcessStartInfo psiFab1 = new ProcessStartInfo(); ProcessStartInfo psiFab1 = new();
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") { if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") {
psiFab1.FileName = Server.MapPath("/FTPBatch/" + _AppSettings.FTPSPNBatchFileName_Test); psiFab1.FileName = Server.MapPath("/FTPBatch/" + _AppSettings.FTPSPNBatchFileName_Test);
} else { } else {
@ -565,24 +626,26 @@ public class MRBController : Controller {
psiFab1.Arguments = sourcefile.FullName + " " + destFile; psiFab1.Arguments = sourcefile.FullName + " " + destFile;
Process procFab1 = new Process(); Process procFab1 = new();
procFab1.StartInfo = psiFab1; procFab1.StartInfo = psiFab1;
procFab1.Start(); procFab1.Start();
return true; return true;
} catch (Exception e) { } 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; return false;
} }
} }
#endif
public FileResult DownloadFile(string attachmentID) { public FileResult DownloadFile(string attachmentID) {
var attachment = mrbDMO.GetMRBAttachment(Convert.ToInt32(attachmentID)); var attachment = mrbDMO.GetMRBAttachment(Convert.ToInt32(attachmentID));
if (attachment == null) if (attachment == null)
throw new Exception("Invalid attachment ID"); throw new Exception("Invalid attachment ID");
String fileName = attachment.Path; string fileName = attachment.Path;
if (String.IsNullOrEmpty(fileName)) if (string.IsNullOrEmpty(fileName))
fileName = attachment.FileName; fileName = attachment.FileName;
var sDocument = System.IO.Path.Combine(_AppSettings.AttachmentFolder + "MRB", fileName); var sDocument = System.IO.Path.Combine(_AppSettings.AttachmentFolder + "MRB", fileName);
@ -601,7 +664,7 @@ public class MRBController : Controller {
} }
public FileResult ExportMRBHoldFlagReport(int mrbNumber) { 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"); 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)) { foreach (var report in mrbDMO.GetMRBHoldFlagReport(mrbNumber)) {
sb.AppendLine(MRB_DMO.FormCSV( sb.AppendLine(MRB_DMO.FormCSV(
@ -630,7 +693,7 @@ public class MRBController : Controller {
} }
public FileResult PreviewMRBHoldFlagTobeSentToSPN(int mrbNumber) { 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"); sb.AppendLine("LotNumber,MRBNumber,DispoType,MRB Flag,Modified,Sent To SPN,Last Sent to SPN");
foreach (var lot in mrbDMO.GetMRHoldFlagSentHistory(mrbNumber)) { foreach (var lot in mrbDMO.GetMRHoldFlagSentHistory(mrbNumber)) {
sb.AppendLine(MRB_DMO.FormCSV( sb.AppendLine(MRB_DMO.FormCSV(
@ -648,7 +711,7 @@ public class MRBController : Controller {
} }
public FileResult ExportLots(int mrbNumber) { 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"); 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)) { foreach (var lot in mrbDMO.GetMRBLots(mrbNumber)) {
sb.AppendLine(MRB_DMO.FormCSV( sb.AppendLine(MRB_DMO.FormCSV(
@ -675,4 +738,33 @@ public class MRBController : Controller {
return File(b, "application/octet-stream", "mrb_lots_" + mrbNumber.ToString() + ".csv"); 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;
} }

View File

@ -1,31 +1,75 @@
using System; #if !NET8
using System.Collections.Generic;
using System.Linq;
using System.Web; using System.Web;
using System.Web.Mvc; using System.Web.Mvc;
#endif
#if NET8
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
#endif
using Fab2ApprovalSystem.DMO; using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Misc; using Fab2ApprovalSystem.Misc;
#if !NET8
using System;
using System.Collections.Generic;
using System.Linq;
using Fab2ApprovalSystem.Models; using Fab2ApprovalSystem.Models;
#endif
namespace Fab2ApprovalSystem.Controllers; namespace Fab2ApprovalSystem.Controllers;
[Authorize] [Authorize]
#if !NET8
[SessionExpireFilter] [SessionExpireFilter]
#endif
#if NET8
[Route("[controller]")]
#endif
public class ManagerController : Controller { public class ManagerController : Controller {
UserAccountDMO userDMO = new UserAccountDMO(); private readonly UserAccountDMO userDMO = new();
AdminDMO adminDMO = new AdminDMO(); private readonly AdminDMO adminDMO = new();
TrainingDMO trainingDMO = new TrainingDMO(); private readonly TrainingDMO trainingDMO = new();
LotDispositionDMO ldDMO = new LotDispositionDMO(); private readonly LotDispositionDMO ldDMO = new();
private readonly AppSettings _AppSettings = GlobalVars.AppSettings;
public ActionResult Index() { public ActionResult Index() {
if ((bool)Session[GlobalVars.IS_MANAGER]) { if (GlobalVars.IsManager(GetSession())) {
var model = userDMO.GetAllUsers(); var model = userDMO.GetAllUsers();
ViewBag.AllActiveUsers = userDMO.GetAllActiveUsers(); ViewBag.AllActiveUsers = userDMO.GetAllActiveUsers();
return View(model); return View(model);
} else } else
return Content("Not Autthorized"); 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;
} }

View File

@ -0,0 +1,62 @@
#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 = GlobalVars.GetJWT(GetSession());
string encodedJwt = System.Net.WebUtility.UrlEncode(jwt);
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;
}

View File

@ -1,29 +1,42 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
#if !NET8
using System.Web; using System.Web;
using System.Web.Mvc; using System.Web.Mvc;
#endif
#if NET8
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
#endif
using Fab2ApprovalSystem.DMO; using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Misc; using Fab2ApprovalSystem.Misc;
using Fab2ApprovalSystem.Models; using Fab2ApprovalSystem.Models;
#if !NET8
using Kendo.Mvc.Extensions; using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI; using Kendo.Mvc.UI;
#endif
namespace Fab2ApprovalSystem.Controllers; namespace Fab2ApprovalSystem.Controllers;
[Authorize] [Authorize]
#if !NET8
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
[SessionExpireFilter] [SessionExpireFilter]
#endif
#if NET8
[Route("[controller]")]
#endif
public class PartsRequestController : Controller { public class PartsRequestController : Controller {
private const int WorkflowNumber = 1;
const int WorkflowNumber = 1; private readonly PartsRequestDMO prDMO = new();
PartsRequestDMO prDMO = new PartsRequestDMO(); private readonly UserAccountDMO userDMO = new();
UserAccountDMO userDMO = new UserAccountDMO(); private readonly WorkflowDMO wfDMO = new();
WorkflowDMO wfDMO = new WorkflowDMO(); private readonly AppSettings? _AppSettings = GlobalVars.AppSettings;
private readonly AppSettings _AppSettings = GlobalVars.AppSettings;
public PartsRequestController() { public PartsRequestController() {
ViewBag.ShowReAssignApprovers = false; ViewBag.ShowReAssignApprovers = false;
@ -42,13 +55,13 @@ public class PartsRequestController : Controller {
} }
protected void HandleException(int issueID, Exception ex, string additionalKeys = "") { protected void HandleException(int issueID, Exception ex, string additionalKeys = "") {
var st = new System.Diagnostics.StackTrace(); System.Diagnostics.StackTrace st = new();
var sf = st.GetFrame(1); System.Diagnostics.StackFrame? sf = st.GetFrame(1);
String controller = sf.GetMethod().DeclaringType.Name.Replace("Controller", ""); string controller = sf.GetMethod().DeclaringType.Name.Replace("Controller", "");
String method = sf.GetMethod().Name; string method = sf.GetMethod().Name;
string detailedException = String.Format( string detailedException = string.Format(
"Exception for issue # {0}\r\n" + "Exception for issue # {0}\r\n" +
"Controller: {1}, Method: {2}, User: {3}, Keys: {4}\r\n" + "Controller: {1}, Method: {2}, User: {3}, Keys: {4}\r\n" +
"=====\r\n", "=====\r\n",
@ -69,20 +82,19 @@ public class PartsRequestController : Controller {
EventLogDMO.Add(new WinEventLog() { EventLogDMO.Add(new WinEventLog() {
IssueID = issueID, IssueID = issueID,
UserID = @User.Identity.Name, UserID = GetUserIdentityName(),
DocumentType = controller, DocumentType = controller,
OperationType = "Error", OperationType = "Error",
Comments = detailedException Comments = detailedException
}); });
} }
// GET: PartsRequest
public ActionResult Index() { public ActionResult Index() {
return View(); return View();
} }
public ActionResult Edit(int issueID) { public ActionResult Edit(int issueID) {
var pr = new PartsRequest(); PartsRequest pr = new();
try { try {
pr = prDMO.Get(issueID); pr = prDMO.Get(issueID);
@ -95,8 +107,8 @@ public class PartsRequestController : Controller {
} else if (pr.CurrentStep >= 1) { } else if (pr.CurrentStep >= 1) {
return RedirectToAction("EditApproval", new { issueID = issueID }); return RedirectToAction("EditApproval", new { issueID = issueID });
} else { } else {
if (pr.OriginatorID != (int)Session[GlobalVars.SESSION_USERID]) { if (pr.OriginatorID != GlobalVars.GetUserId(GetSession())) {
if (Convert.ToBoolean(Session[GlobalVars.IS_ADMIN]) == false) { if (!GlobalVars.IsAdmin(GetSession())) {
return RedirectToAction("ReadOnly", new { issueID = issueID }); return RedirectToAction("ReadOnly", new { issueID = issueID });
} }
} }
@ -110,6 +122,8 @@ public class PartsRequestController : Controller {
} }
} }
#if !NET8
[HttpPost] [HttpPost]
public ActionResult Edit(PartsRequest pr) { public ActionResult Edit(PartsRequest pr) {
try { try {
@ -133,10 +147,12 @@ public class PartsRequestController : Controller {
} }
} }
#endif
public ActionResult EditApproval(int issueID) { public ActionResult EditApproval(int issueID) {
var pr = new PartsRequest(); PartsRequest pr = new();
try { try {
int myUserID = (int)Session[GlobalVars.SESSION_USERID]; int myUserID = GlobalVars.GetUserId(GetSession());
pr = prDMO.Get(issueID); pr = prDMO.Get(issueID);
@ -156,15 +172,15 @@ public class PartsRequestController : Controller {
if (ViewBag.IsApprover == false) { if (ViewBag.IsApprover == false) {
if (pr.OriginatorID != myUserID) { if (pr.OriginatorID != myUserID) {
if (Convert.ToBoolean(Session[GlobalVars.IS_ADMIN]) == false) { if (!GlobalVars.IsAdmin(GetSession())) {
return RedirectToAction("ReadOnly", new { issueID = issueID }); 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.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.ShowReAssignApprovers = ViewBag.IsAdmin || ViewBag.IsOriginator;
ViewBag.ShowAddApprovers = ViewBag.IsAdmin || ViewBag.IsApprover || ViewBag.IsOriginator; ViewBag.ShowAddApprovers = ViewBag.IsAdmin || ViewBag.IsApprover || ViewBag.IsOriginator;
ViewBag.UserList = userDMO.GetAllUsers(); ViewBag.UserList = userDMO.GetAllUsers();
@ -176,9 +192,9 @@ public class PartsRequestController : Controller {
} }
public ActionResult ReadOnly(int issueID) { public ActionResult ReadOnly(int issueID) {
var pr = new PartsRequest(); PartsRequest pr = new();
try { try {
int myUserID = (int)Session[GlobalVars.SESSION_USERID]; int myUserID = GlobalVars.GetUserId(GetSession());
pr = prDMO.Get(issueID); pr = prDMO.Get(issueID);
@ -191,7 +207,7 @@ public class PartsRequestController : Controller {
return View("Error"); return View("Error");
} }
ViewBag.IsAdmin = Convert.ToBoolean(Session[GlobalVars.IS_ADMIN]); ViewBag.IsAdmin = GlobalVars.IsAdmin(GetSession());
ViewBag.IsOriginator = (pr.OriginatorID == myUserID); ViewBag.IsOriginator = (pr.OriginatorID == myUserID);
ViewBag.UserList = userDMO.GetAllUsers(); ViewBag.UserList = userDMO.GetAllUsers();
return View(pr); return View(pr);
@ -202,11 +218,11 @@ public class PartsRequestController : Controller {
} }
public ActionResult Create() { public ActionResult Create() {
var pr = new PartsRequest(); PartsRequest pr = new();
try { 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"); throw new Exception("User does not have permission to create Parts Request");
prDMO.Insert(pr); prDMO.Insert(pr);
@ -218,8 +234,8 @@ public class PartsRequestController : Controller {
} }
public static bool CanCreatePartsRequest(int userID) { public static bool CanCreatePartsRequest(int userID) {
var adminDMO = new AdminDMO(); AdminDMO adminDMO = new();
var role = adminDMO.GetSubRoles().Where(r => string.Equals(r.RoleName, "Parts Request", StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); Role? role = adminDMO.GetSubRoles().FirstOrDefault(r => string.Equals(r.RoleName, "Parts Request", StringComparison.OrdinalIgnoreCase));
if (role != null) { if (role != null) {
var subrole = role.SubRoles.FirstOrDefault(sr => string.Equals(sr.SubRoleCategoryItem, "Originator", StringComparison.OrdinalIgnoreCase)); var subrole = role.SubRoles.FirstOrDefault(sr => string.Equals(sr.SubRoleCategoryItem, "Originator", StringComparison.OrdinalIgnoreCase));
if (subrole != null) { if (subrole != null) {
@ -232,9 +248,11 @@ public class PartsRequestController : Controller {
return false; return false;
} }
#if !NET8
public ActionResult Attachment_Read([DataSourceRequest] DataSourceRequest request, int prNumber) { public ActionResult Attachment_Read([DataSourceRequest] DataSourceRequest request, int prNumber) {
try { try {
return Json(prDMO.GetAttachments(prNumber).ToDataSourceResult(request), JsonRequestBehavior.AllowGet); return GetJsonResult(prDMO.GetAttachments(prNumber).ToDataSourceResult(request));
} catch (Exception ex) { } catch (Exception ex) {
return HandleAPIException(prNumber, ex); return HandleAPIException(prNumber, ex);
} }
@ -244,7 +262,7 @@ public class PartsRequestController : Controller {
public ActionResult AttachSave(IEnumerable<HttpPostedFileBase> files, int prNumber) { public ActionResult AttachSave(IEnumerable<HttpPostedFileBase> files, int prNumber) {
// The Name of the Upload component is "files" // The Name of the Upload component is "files"
if (files != null) { if (files != null) {
int userId = (int)Session[GlobalVars.SESSION_USERID]; int userId = GlobalVars.GetUserId(GetSession());
foreach (var file in files) { foreach (var file in files) {
PartsRequestHelper.AttachSave(_AppSettings, prDMO, prNumber, userId, file.FileName, file.InputStream); PartsRequestHelper.AttachSave(_AppSettings, prDMO, prNumber, userId, file.FileName, file.InputStream);
} }
@ -253,6 +271,8 @@ public class PartsRequestController : Controller {
return Content(""); return Content("");
} }
#endif
public FileResult DownloadFile(string attachmentID, string prNumber) { public FileResult DownloadFile(string attachmentID, string prNumber) {
string fileName = prDMO.GetFileName(attachmentID); string fileName = prDMO.GetFileName(attachmentID);
@ -289,17 +309,19 @@ public class PartsRequestController : Controller {
} }
} }
#if !NET8
[HttpPost] [HttpPost]
public ActionResult Submit(int prNumber) { public ActionResult Submit(int prNumber) {
try { try {
int myUserID = (int)Session[GlobalVars.SESSION_USERID]; int myUserID = GlobalVars.GetUserId(GetSession());
var pr = prDMO.Get(prNumber); var pr = prDMO.Get(prNumber);
if (pr == null) if (pr == null)
return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "Document does not exist"); 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"); return HandleValidationError("Title is required");
if (pr.RequestorID <= 0) if (pr.RequestorID <= 0)
return HandleValidationError("Requestor is required"); 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) { 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 // Auto-Approve if the user is an approver for workflow step 1
var c = Approve(prNumber, 1, "Auto-Approve"); var c = Approve(prNumber, 1, "Auto-Approve");
if (c != null && c is ContentResult) { if (c != null && c is ContentResult contentResult) {
var result = ((ContentResult)c).Content; var result = contentResult.Content;
if (!String.Equals(result, "OK")) if (!string.Equals(result, "OK"))
throw new Exception(result); throw new Exception(result);
} }
if (c != null && c is JsonResult) if (c != null && c is JsonResult)
@ -325,7 +347,7 @@ public class PartsRequestController : Controller {
NotifyApprovers(prNumber, 1); NotifyApprovers(prNumber, 1);
} }
if (Request.IsAjaxRequest()) { if (IsAjaxRequest()) {
return Content("Redirect"); return Content("Redirect");
} else { } else {
return Content("Invalid"); return Content("Invalid");
@ -348,16 +370,18 @@ public class PartsRequestController : Controller {
try { try {
UserAccountDMO userDMO = new UserAccountDMO(); UserAccountDMO userDMO = new UserAccountDMO();
IEnumerable<LoginModel> userlist = userDMO.GetAllUsers(); IEnumerable<LoginModel> userlist = userDMO.GetAllUsers();
return Json(userlist, JsonRequestBehavior.AllowGet); return GetJsonResult(userlist);
} catch (Exception e) { } catch (Exception e) {
return HandleAPIException(0, e); return HandleAPIException(0, e);
} }
} }
#endif
[HttpPost] [HttpPost]
public ActionResult ReAssignApproval(int issueID, int fromUserID, int userIDs, byte step) { public ActionResult ReAssignApproval(int issueID, int fromUserID, int userIDs, byte step) {
try { try {
String email = wfDMO.ReAssignApproval( string email = wfDMO.ReAssignApproval(
issueID, fromUserID, userIDs, step, (int)GlobalVars.DocumentType.PartsRequest); issueID, fromUserID, userIDs, step, (int)GlobalVars.DocumentType.PartsRequest);
NotifyReAssignment(issueID, email); NotifyReAssignment(issueID, email);
@ -368,12 +392,14 @@ public class PartsRequestController : Controller {
} }
} }
#if !NET8
[HttpPost] [HttpPost]
public ActionResult Approve(int prNumber, byte currentStep, string comments) { public ActionResult Approve(int prNumber, byte currentStep, string comments) {
try { try {
bool lastStep = false; bool lastStep = false;
bool lastApproverInCurrentStep = false; bool lastApproverInCurrentStep = false;
int myUserID = (int)Session[GlobalVars.SESSION_USERID]; int myUserID = GlobalVars.GetUserId(GetSession());
var pr = prDMO.Get(prNumber); var pr = prDMO.Get(prNumber);
@ -387,7 +413,7 @@ public class PartsRequestController : Controller {
currentStep, currentStep,
comments, comments,
out lastStep, out lastStep,
(int)Session[GlobalVars.SESSION_USERID], GlobalVars.GetUserId(GetSession()),
(int)GlobalVars.DocumentType.PartsRequest, (int)GlobalVars.DocumentType.PartsRequest,
WorkflowNumber); WorkflowNumber);
@ -417,22 +443,24 @@ public class PartsRequestController : Controller {
} }
} }
#endif
protected void NotifyReAssignment(int prNumber, string email) { protected void NotifyReAssignment(int prNumber, string email) {
var pr = prDMO.Get(prNumber); var pr = prDMO.Get(prNumber);
if (pr == null) if (pr == null)
return; return;
string username = Session[GlobalVars.SESSION_USERNAME].ToString(); string username = GlobalVars.GetUserName(GetSession());
PartsRequestHelper.SendEmailNotification(_AppSettings, username, 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, prNumber: prNumber,
toEmail: email, toEmail: email,
emailTemplate: "PRReAssigned.txt"); emailTemplate: "PRReAssigned.txt");
EventLogDMO.Add(new WinEventLog() { EventLogDMO.Add(new WinEventLog() {
IssueID = prNumber, IssueID = prNumber,
UserID = @User.Identity.Name, UserID = GetUserIdentityName(),
DocumentType = "PR", DocumentType = "PR",
OperationType = "Email", OperationType = "Email",
Comments = "ReAssigned Approver: " + email Comments = "ReAssigned Approver: " + email
@ -446,17 +474,17 @@ public class PartsRequestController : Controller {
return; return;
var u = userDMO.GetUserByID(pr.RequestorID); var u = userDMO.GetUserByID(pr.RequestorID);
if ((u != null) && (!String.IsNullOrWhiteSpace(u.Email))) { if ((u != null) && (!string.IsNullOrWhiteSpace(u.Email))) {
string username = Session[GlobalVars.SESSION_USERNAME].ToString(); string username = GlobalVars.GetUserName(GetSession());
PartsRequestHelper.SendEmailNotification(_AppSettings, username, 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, prNumber: prNumber,
toEmail: u.Email, toEmail: u.Email,
emailTemplate: "PRCompleted.txt"); emailTemplate: "PRCompleted.txt");
EventLogDMO.Add(new WinEventLog() { EventLogDMO.Add(new WinEventLog() {
IssueID = prNumber, IssueID = prNumber,
UserID = @User.Identity.Name, UserID = GetUserIdentityName(),
DocumentType = "PR", DocumentType = "PR",
OperationType = "Email", OperationType = "Email",
Comments = "Completed: " + u.Email Comments = "Completed: " + u.Email
@ -471,17 +499,17 @@ public class PartsRequestController : Controller {
return; return;
var u = userDMO.GetUserByID(pr.OriginatorID); var u = userDMO.GetUserByID(pr.OriginatorID);
if ((u != null) && (!String.IsNullOrWhiteSpace(u.Email))) { if ((u != null) && (!string.IsNullOrWhiteSpace(u.Email))) {
string username = Session[GlobalVars.SESSION_USERNAME].ToString(); string username = GlobalVars.GetUserName(GetSession());
PartsRequestHelper.SendEmailNotification(_AppSettings, username, 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, prNumber: prNumber,
toEmail: u.Email, toEmail: u.Email,
emailTemplate: "PRReject.txt"); emailTemplate: "PRReject.txt");
EventLogDMO.Add(new WinEventLog() { EventLogDMO.Add(new WinEventLog() {
IssueID = prNumber, IssueID = prNumber,
UserID = @User.Identity.Name, UserID = GetUserIdentityName(),
DocumentType = "PR", DocumentType = "PR",
OperationType = "Email", OperationType = "Email",
Comments = "Rejected: " + u.Email Comments = "Rejected: " + u.Email
@ -503,9 +531,9 @@ public class PartsRequestController : Controller {
foreach (string email in emailList) { foreach (string email in emailList) {
try { try {
string username = Session[GlobalVars.SESSION_USERNAME].ToString(); string username = GlobalVars.GetUserName(GetSession());
PartsRequestHelper.SendEmailNotification(_AppSettings, username, 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, prNumber: prNumber,
toEmail: email, toEmail: email,
emailTemplate: "PRAssigned.txt"); emailTemplate: "PRAssigned.txt");
@ -519,7 +547,7 @@ public class PartsRequestController : Controller {
try { try {
EventLogDMO.Add(new WinEventLog() { EventLogDMO.Add(new WinEventLog() {
IssueID = prNumber, IssueID = prNumber,
UserID = @User.Identity.Name, UserID = GetUserIdentityName(),
DocumentType = "PR", DocumentType = "PR",
OperationType = "Email", OperationType = "Email",
Comments = "Approvers for Step " + step.ToString() + ":" + emailSentList Comments = "Approvers for Step " + step.ToString() + ":" + emailSentList
@ -533,8 +561,8 @@ public class PartsRequestController : Controller {
[HttpPost] [HttpPost]
public ActionResult Reject(int prNumber, byte currentStep, string comments) { public ActionResult Reject(int prNumber, byte currentStep, string comments) {
try { try {
if (Session[GlobalVars.SESSION_USERID] != null) { if (GlobalVars.IsUserIdValueNotNull(GetSession())) {
wfDMO.Reject(prNumber, currentStep, comments, (int)Session[GlobalVars.SESSION_USERID], (int)GlobalVars.DocumentType.PartsRequest); wfDMO.Reject(prNumber, currentStep, comments, GlobalVars.GetUserId(GetSession()), (int)GlobalVars.DocumentType.PartsRequest);
NotifyRejection(prNumber); NotifyRejection(prNumber);
} else { } else {
Response.Redirect("~/Account/Login"); Response.Redirect("~/Account/Login");
@ -546,26 +574,30 @@ public class PartsRequestController : Controller {
} }
} }
#if !NET8
public ActionResult ApprovalLogHistory_Read([DataSourceRequest] DataSourceRequest request, int prNumber) { 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) { protected void NotifyAssignment(int prNumber, string email) {
var pr = prDMO.Get(prNumber); var pr = prDMO.Get(prNumber);
if (pr == null) if (pr == null)
return; return;
string username = Session[GlobalVars.SESSION_USERNAME].ToString(); string username = GlobalVars.GetUserName(GetSession());
PartsRequestHelper.SendEmailNotification(_AppSettings, username, 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, prNumber: prNumber,
toEmail: email, toEmail: email,
emailTemplate: "PRAssigned.txt"); emailTemplate: "PRAssigned.txt");
EventLogDMO.Add(new WinEventLog() { EventLogDMO.Add(new WinEventLog() {
IssueID = prNumber, IssueID = prNumber,
UserID = @User.Identity.Name, UserID = GetUserIdentityName(),
DocumentType = "PR", DocumentType = "PR",
OperationType = "Email", OperationType = "Email",
Comments = "Assigned Approver: " + email Comments = "Assigned Approver: " + email
@ -594,7 +626,7 @@ public class PartsRequestController : Controller {
try { try {
EventLogDMO.Add(new WinEventLog() { EventLogDMO.Add(new WinEventLog() {
IssueID = issueID, IssueID = issueID,
UserID = @User.Identity.Name, UserID = GetUserIdentityName(),
DocumentType = "PR", DocumentType = "PR",
OperationType = "Email", OperationType = "Email",
Comments = "Additional Approver: " + emailSentList Comments = "Additional Approver: " + emailSentList
@ -602,4 +634,33 @@ public class PartsRequestController : Controller {
} catch { } } 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;
} }

View File

@ -1,43 +1,60 @@
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
#if !NET8
using System.Web; using System.Web;
using System.Web.Mvc; using System.Web.Mvc;
#endif
#if NET8
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
#endif
using Fab2ApprovalSystem.DMO; using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Misc; using Fab2ApprovalSystem.Misc;
using Fab2ApprovalSystem.Models; using Fab2ApprovalSystem.Models;
#if !NET8
using System.Collections.Generic;
using Fab2ApprovalSystem.ViewModels; using Fab2ApprovalSystem.ViewModels;
#endif
namespace Fab2ApprovalSystem.Controllers; namespace Fab2ApprovalSystem.Controllers;
[Authorize] [Authorize]
#if !NET8
[SessionExpireFilter] [SessionExpireFilter]
#endif
#if NET8
[Route("[controller]")]
#endif
public class ReportsController : Controller { public class ReportsController : Controller {
public const String specialNullString = "~NULL~"; public const string specialNullString = "~NULL~";
private readonly AppSettings _AppSettings = GlobalVars.AppSettings; private readonly AppSettings? _AppSettings = GlobalVars.AppSettings;
// GET: Export // GET: Export
public ActionResult Index() { public ActionResult Index() {
UserAccountDMO userDMO = new UserAccountDMO(); UserAccountDMO userDMO = new();
ViewBag.HasITARAccess = userDMO.GetITARAccess((int)Session[GlobalVars.SESSION_USERID]); ViewBag.HasITARAccess = userDMO.GetITARAccess(GlobalVars.GetUserId(GetSession()));
return View(); return View();
} }
public ActionResult Report(String id, String docType = "") { #if !NET8
if (String.IsNullOrEmpty(id))
public ActionResult Report(string id, string docType = "") {
if (string.IsNullOrEmpty(id))
return RedirectToAction("Index"); return RedirectToAction("Index");
UserAccountDMO userDMO = new UserAccountDMO(); UserAccountDMO userDMO = new();
if (!userDMO.GetITARAccess((int)Session[GlobalVars.SESSION_USERID])) if (!userDMO.GetITARAccess(GlobalVars.GetUserId(GetSession())))
return View("UnAuthorizedAccess"); return View("UnAuthorizedAccess");
var m = new ReportViewModel<System.Web.Mvc.SelectListItem>(); ReportViewModel<SelectListItem> m = new();
var reports = GetReportList(docType); var reports = GetReportList(docType);
foreach (var report in reports) { 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.ReportID = report.ReportID;
m.ReportName = report.Name; m.ReportName = report.Name;
m.Description = report.Description; m.Description = report.Description;
@ -46,8 +63,8 @@ public class ReportsController : Controller {
var c = SetupSSRSHelperClient(); var c = SetupSSRSHelperClient();
m.Parameters = c.GetReportParameters(report.FullPath).Select(parm => { m.Parameters = c.GetReportParameters(report.FullPath).Select(parm => {
var r = new ReportParameterViewModel<System.Web.Mvc.SelectListItem>(); ReportParameterViewModel<SelectListItem> r = new();
r.Visible = (parm.PromptUser.HasValue == false || parm.PromptUser == true) && !String.IsNullOrEmpty(parm.Prompt); r.Visible = (parm.PromptUser.HasValue == false || parm.PromptUser == true) && !string.IsNullOrEmpty(parm.Prompt);
r.Prompt = parm.Prompt; r.Prompt = parm.Prompt;
r.Name = parm.Name; r.Name = parm.Name;
r.HtmlID = "parm_" + parm.Name; r.HtmlID = "parm_" + parm.Name;
@ -87,7 +104,7 @@ public class ReportsController : Controller {
public SSRSHelper.SSRSClient SetupSSRSHelperClient() { public SSRSHelper.SSRSClient SetupSSRSHelperClient() {
var useCfgForBindings = false; var useCfgForBindings = false;
if (String.Equals(_AppSettings.SSRSBindingsByConfiguration, "true", StringComparison.OrdinalIgnoreCase)) if (string.Equals(_AppSettings.SSRSBindingsByConfiguration, "true", StringComparison.OrdinalIgnoreCase))
useCfgForBindings = true; useCfgForBindings = true;
var c = new SSRSHelper.SSRSClient( var c = new SSRSHelper.SSRSClient(
@ -112,27 +129,26 @@ public class ReportsController : Controller {
return c.ListReports(folderName); return c.ListReports(folderName);
} }
public ActionResult GetReports(String docType) { public ActionResult GetReports(string docType) {
var reports = GetReportList(docType); var reports = GetReportList(docType);
return Json(new { return GetJsonResult(new {
Data = Data =
reports.Select(r => new ReportViewModel<System.Web.Mvc.SelectListItem>() { reports.Select(r => new ReportViewModel<SelectListItem>() {
ReportName = r.Name ?? "", ReportName = r.Name ?? "",
Description = r.Description ?? "", Description = r.Description ?? "",
ReportID = r.ReportID ?? "", ReportID = r.ReportID ?? "",
DocType = docType DocType = docType
}) })
}, });
JsonRequestBehavior.AllowGet);
} }
[HttpPost] [HttpPost]
public ActionResult ExportReport(String DocType, String ReportID) { public ActionResult ExportReport(string DocType, string ReportID) {
var c = SetupSSRSHelperClient(); var c = SetupSSRSHelperClient();
var reports = GetReportList(DocType); 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) if (report == null)
return Content("Invalid report ID"); return Content("Invalid report ID");
@ -140,16 +156,16 @@ public class ReportsController : Controller {
var parms = new SSRSHelper.ReportParameterCollection(); var parms = new SSRSHelper.ReportParameterCollection();
parms.Add("DocType", DocType); parms.Add("DocType", DocType);
parms.Add("UserID", Convert.ToString(Session[GlobalVars.SESSION_USERID])); parms.Add("UserID", GlobalVars.GetUserIdValue(GetSession()));
parms.Add("BaseURL", GlobalVars.hostURL); parms.Add("BaseURL", GlobalVars.hostURL);
foreach (var rp in reportParms) { foreach (var rp in reportParms) {
if (rp.MultiValue.HasValue && rp.MultiValue.Value) { 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); parms.Add(rp.Name, v);
} }
} else { } else {
String value = null; string value = null;
if (Request.Params.AllKeys.Contains("parm_" + rp.Name)) if (Request.Params.AllKeys.Contains("parm_" + rp.Name))
value = Request.Params.GetValues("parm_" + rp.Name).FirstOrDefault(); 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 { try {
var b2 = c.FreezeExcelHeaders(b); var b2 = c.FreezeExcelHeaders(b);
return File(b2, "application/octet-stream", MakeFilename(report.Name) + ".xlsx"); 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"); return File(b, "application/octet-stream", MakeFilename(report.Name) + ".xlsx");
} }
protected String MakeFilename(String reportName) { #endif
String r = "";
protected string MakeFilename(string reportName) {
string r = "";
char[] invalidChars = System.IO.Path.GetInvalidFileNameChars(); char[] invalidChars = System.IO.Path.GetInvalidFileNameChars();
foreach (char c in reportName) { foreach (char c in reportName) {
if (invalidChars.Contains(c)) if (invalidChars.Contains(c))
@ -194,4 +212,33 @@ public class ReportsController : Controller {
return r; 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;
} }

View File

@ -1,8 +1,14 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Configuration;
using System.Linq; using System.Linq;
#if !NET8
using System.Web.Mvc; using System.Web.Mvc;
#endif
#if NET8
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
#endif
using Fab2ApprovalSystem.DMO; using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Misc; using Fab2ApprovalSystem.Misc;
@ -10,19 +16,26 @@ using Fab2ApprovalSystem.Models;
using Fab2ApprovalSystem.Utilities; using Fab2ApprovalSystem.Utilities;
using Fab2ApprovalSystem.ViewModels; using Fab2ApprovalSystem.ViewModels;
#if !NET8
using Kendo.Mvc.Extensions; using Kendo.Mvc.Extensions;
#endif
namespace Fab2ApprovalSystem.Controllers; namespace Fab2ApprovalSystem.Controllers;
[Authorize] [Authorize]
#if !NET8
[SessionExpireFilter] [SessionExpireFilter]
#endif
#if NET8
[Route("[controller]")]
#endif
public class TrainingController : Controller { public class TrainingController : Controller {
UserAccountDMO userDMO = new UserAccountDMO(); private readonly UserAccountDMO userDMO = new();
AdminDMO adminDMO = new AdminDMO(); private readonly AdminDMO adminDMO = new();
TrainingDMO trainingDMO = new TrainingDMO(); private readonly TrainingDMO trainingDMO = new();
ECN_DMO ecnDMO = new ECN_DMO(); private readonly ECN_DMO ecnDMO = new();
private readonly AppSettings _AppSettings = GlobalVars.AppSettings; private readonly AppSettings? _AppSettings = GlobalVars.AppSettings;
// GET: Training // GET: Training
public ActionResult Index() { public ActionResult Index() {
@ -30,19 +43,19 @@ public class TrainingController : Controller {
} }
public int Create(int ecnId) { public int Create(int ecnId) {
ECN_DMO ecnDMO = new ECN_DMO(); ECN_DMO ecnDMO = new();
// Delete old training if exists // Delete old training if exists
int oldTrainingId = trainingDMO.GetTrainingId(ecnId); int oldTrainingId = trainingDMO.GetTrainingId(ecnId);
if (oldTrainingId != null && oldTrainingId != 0) { if (oldTrainingId != 0) {
trainingDMO.DeleteTraining(oldTrainingId); trainingDMO.DeleteTraining(oldTrainingId);
} }
int trainingId = trainingDMO.Create(ecnId); int trainingId = trainingDMO.Create(ecnId);
List<int> TrainingGroups = new List<int>(); List<int> TrainingGroups = new();
TrainingGroups = trainingDMO.GetECNAssignedTrainingGroups(ecnId); TrainingGroups = trainingDMO.GetECNAssignedTrainingGroups(ecnId);
string ECNTitle = ecnDMO.GetECN(ecnId).Title; string ECNTitle = ecnDMO.GetECN(ecnId).Title;
List<int> Trainees = new List<int>(); List<int> Trainees = new();
foreach (int group in TrainingGroups) { foreach (int group in TrainingGroups) {
Trainees.AddRange(trainingDMO.GetTrainees(group)); Trainees.AddRange(trainingDMO.GetTrainees(group));
} }
@ -55,8 +68,9 @@ public class TrainingController : Controller {
return trainingId; return trainingId;
} }
public ActionResult AddUserToTrainingAdHoc(int trainingId, int traineeId, int ecnId) { public ActionResult AddUserToTrainingAdHoc(int trainingId, int traineeId, int ecnId) {
if ((bool)Session[GlobalVars.IS_ADMIN]) { if (GlobalVars.IsAdmin(GetSession())) {
// Get ECN // Get ECN
ECN ecn = ecnDMO.GetECN(ecnId); ECN ecn = ecnDMO.GetECN(ecnId);
@ -105,7 +119,7 @@ public class TrainingController : Controller {
} }
public ActionResult AddGroupToTrainingAdHoc(int trainingId, int groupId, int ecnId) { public ActionResult AddGroupToTrainingAdHoc(int trainingId, int groupId, int ecnId) {
if ((bool)Session[GlobalVars.IS_ADMIN]) { if (GlobalVars.IsAdmin(GetSession())) {
ECN ecn = ecnDMO.GetECN(ecnId); ECN ecn = ecnDMO.GetECN(ecnId);
Training training = trainingDMO.GetTraining(trainingId); Training training = trainingDMO.GetTraining(trainingId);
TrainingGroup group = trainingDMO.GetTrainingGroupByID(groupId); TrainingGroup group = trainingDMO.GetTrainingGroupByID(groupId);
@ -163,14 +177,14 @@ public class TrainingController : Controller {
public ActionResult DeleteTrainingByECN(int ECNNumber) { public ActionResult DeleteTrainingByECN(int ECNNumber) {
int trainingId = trainingDMO.GetTrainingId(ECNNumber); int trainingId = trainingDMO.GetTrainingId(ECNNumber);
if (trainingId != null && trainingId != 0) { if (trainingId != 0) {
trainingDMO.DeleteTraining(trainingId); trainingDMO.DeleteTraining(trainingId);
} }
return RedirectToAction("ViewTrainings"); return RedirectToAction("ViewTrainings");
} }
public ActionResult DeleteTrainingByID(int trainingId) { public ActionResult DeleteTrainingByID(int trainingId) {
if (trainingId != null && trainingId != 0) { if (trainingId != 0) {
trainingDMO.DeleteTraining(trainingId); trainingDMO.DeleteTraining(trainingId);
} }
return RedirectToAction("ViewTrainings"); return RedirectToAction("ViewTrainings");
@ -254,7 +268,7 @@ public class TrainingController : Controller {
// Group Filter // Group Filter
if (filterType == 1 && filterValue != "") { if (filterType == 1 && filterValue != "") {
ViewBag.GroupFilter = filterValue; ViewBag.GroupFilter = filterValue;
List<Training> filteredTraining = new List<Training>(); List<Training> filteredTraining = new();
foreach (Training item in trainingList) { foreach (Training item in trainingList) {
List<int> assignedTrainingGroups = trainingDMO.GetECNAssignedTrainingGroups(item.ECN); List<int> assignedTrainingGroups = trainingDMO.GetECNAssignedTrainingGroups(item.ECN);
foreach (int id in assignedTrainingGroups) { foreach (int id in assignedTrainingGroups) {
@ -268,7 +282,7 @@ public class TrainingController : Controller {
} }
// Status Filter // Status Filter
if (filterType == 2 && filterValue != "") { if (filterType == 2 && filterValue != "") {
List<Training> filteredTraining = new List<Training>(); List<Training> filteredTraining = new();
switch (filterValue) { switch (filterValue) {
case "1": case "1":
// Completed // Completed
@ -307,7 +321,7 @@ public class TrainingController : Controller {
float assignmentCount = (from a in trainingAssignments where a.Deleted != true select a).Count(); float assignmentCount = (from a in trainingAssignments where a.Deleted != true select a).Count();
float totalCompleted = 0; float totalCompleted = 0;
foreach (TrainingAssignment assignment in trainingAssignments) { foreach (TrainingAssignment assignment in trainingAssignments) {
if (assignment.status == true && assignment.Deleted != true) { if (assignment.status && assignment.Deleted != true) {
totalCompleted++; totalCompleted++;
} }
} }
@ -316,7 +330,7 @@ public class TrainingController : Controller {
if (groupFilter != "" && groupFilter != null) { if (groupFilter != "" && groupFilter != null) {
ViewBag.GroupFilter = groupFilter; ViewBag.GroupFilter = groupFilter;
List<TrainingAssignment> groupFilteredTraining = new List<TrainingAssignment>(); List<TrainingAssignment> groupFilteredTraining = new();
List<int> groupMemberIds = trainingDMO.GetTrainees(Convert.ToInt32(groupFilter)); List<int> groupMemberIds = trainingDMO.GetTrainees(Convert.ToInt32(groupFilter));
foreach (TrainingAssignment assignment in trainingAssignments) { foreach (TrainingAssignment assignment in trainingAssignments) {
if (trainingDMO.isUserTrainingMember(Convert.ToInt32(groupFilter), assignment.UserID)) { if (trainingDMO.isUserTrainingMember(Convert.ToInt32(groupFilter), assignment.UserID)) {
@ -326,15 +340,15 @@ public class TrainingController : Controller {
trainingAssignments = groupFilteredTraining; trainingAssignments = groupFilteredTraining;
} }
if (statusFilter != "" && statusFilter != null) { if (statusFilter != "" && statusFilter != null) {
List<TrainingAssignment> filteredTraining = new List<TrainingAssignment>(); List<TrainingAssignment> filteredTraining = new();
switch (statusFilter) { switch (statusFilter) {
case "1": case "1":
// Completed // 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; break;
case "2": case "2":
// In Progress // 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; break;
case "3": case "3":
// Cancelled // Cancelled
@ -369,9 +383,9 @@ public class TrainingController : Controller {
/// Method to return all the training assignments for a specified user /// Method to return all the training assignments for a specified user
/// </summary> /// </summary>
public ActionResult ViewMyTrainingAssignments() { public ActionResult ViewMyTrainingAssignments() {
int userID = (int)Session[GlobalVars.SESSION_USERID]; int userID = GlobalVars.GetUserId(GetSession());
List<TrainingAssignment> assignments = trainingDMO.GetTrainingAssignmentsByUserID(userID); List<TrainingAssignment> assignments = trainingDMO.GetTrainingAssignmentsByUserID(userID);
List<ECNTrainingAssignments> ViewData = new List<ECNTrainingAssignments>(); List<ECNTrainingAssignments> ViewData = new();
foreach (TrainingAssignment assignment in assignments) { foreach (TrainingAssignment assignment in assignments) {
Training training = trainingDMO.GetTraining(assignment.TrainingID); Training training = trainingDMO.GetTraining(assignment.TrainingID);
if (training != null && !assignment.status) { if (training != null && !assignment.status) {
@ -407,7 +421,7 @@ public class TrainingController : Controller {
// Group Filter // Group Filter
if (filterType == 1 && filterValue != "") { if (filterType == 1 && filterValue != "") {
ViewBag.GroupFilter = filterValue; ViewBag.GroupFilter = filterValue;
List<Training> filteredTraining = new List<Training>(); List<Training> filteredTraining = new();
foreach (Training item in AllTrainings) { foreach (Training item in AllTrainings) {
List<int> assignedTrainingGroups = trainingDMO.GetECNAssignedTrainingGroups(item.ECN); List<int> assignedTrainingGroups = trainingDMO.GetECNAssignedTrainingGroups(item.ECN);
foreach (int id in assignedTrainingGroups) { foreach (int id in assignedTrainingGroups) {
@ -454,8 +468,8 @@ public class TrainingController : Controller {
} }
public ActionResult ManuallyExecuteECNTraining(int ecnId, int[] trainingGroupsIn) { public ActionResult ManuallyExecuteECNTraining(int ecnId, int[] trainingGroupsIn) {
if ((bool)Session[GlobalVars.IS_ADMIN]) { if (GlobalVars.IsAdmin(GetSession())) {
List<int> newTrainingGroupIds = new List<int>(trainingGroupsIn); List<int> newTrainingGroupIds = new(trainingGroupsIn);
ECN ecn = ecnDMO.GetECN(ecnId); ECN ecn = ecnDMO.GetECN(ecnId);
if (ecn != null) { if (ecn != null) {
if (ecn.CloseDate != null) { if (ecn.CloseDate != null) {
@ -493,7 +507,7 @@ public class TrainingController : Controller {
if (ecn != null) { if (ecn != null) {
if (ecn.CloseDate != null) { if (ecn.CloseDate != null) {
List<int> trainingGroupIds = trainingDMO.GetECNAssignedTrainingGroups(ecnId); List<int> trainingGroupIds = trainingDMO.GetECNAssignedTrainingGroups(ecnId);
List<TrainingGroup> assignedGroups = new List<TrainingGroup>(); List<TrainingGroup> assignedGroups = new();
foreach (int trainingGroupId in trainingGroupIds) { foreach (int trainingGroupId in trainingGroupIds) {
TrainingGroup trainingGroup = trainingDMO.GetTrainingGroupByID(trainingGroupId); TrainingGroup trainingGroup = trainingDMO.GetTrainingGroupByID(trainingGroupId);
assignedGroups.Add(trainingGroup); assignedGroups.Add(trainingGroup);
@ -517,7 +531,7 @@ public class TrainingController : Controller {
emailBody += "<style>table,th,td{border: 1px solid black;}</style>"; emailBody += "<style>table,th,td{border: 1px solid black;}</style>";
// Get all users set up to receive the training report email. // Get all users set up to receive the training report email.
List<TrainingReportUser> trainingReportUsers = adminDMO.GetTrainingReportUsers(); List<TrainingReportUser> trainingReportUsers = adminDMO.GetTrainingReportUsers();
List<string> emailList = new List<string>(); List<string> emailList = new();
foreach (TrainingReportUser user in trainingReportUsers) { foreach (TrainingReportUser user in trainingReportUsers) {
string userEmail = userDMO.GetUserByID(user.UserId).Email; string userEmail = userDMO.GetUserByID(user.UserId).Email;
emailList.Add(userEmail); emailList.Add(userEmail);
@ -564,4 +578,34 @@ public class TrainingController : Controller {
} }
return isSuccess; 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;
} }

View File

@ -1,34 +1,56 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; #if !NET8
using System.Net;
using System.Net.Http;
using System.Web.Http; using System.Web.Http;
#endif
#if NET8
using Microsoft.AspNetCore.Mvc;
#endif
using Fab2ApprovalSystem.Misc; using Fab2ApprovalSystem.Misc;
using Fab2ApprovalSystem.Models; using Fab2ApprovalSystem.Models;
#if !NET8
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
#endif
namespace Fab2ApprovalSystem.Controllers; namespace Fab2ApprovalSystem.Controllers;
#if !NET8
public class WebAPIController : ApiController { public class WebAPIController : ApiController {
public TrainingController trainingFunctions = new TrainingController(); #endif
public CorrectiveActionController carFunctions = new CorrectiveActionController();
public AccountController accountFunctions = new AccountController(); #if NET8
public HomeController homeFunctions = new HomeController(); [ApiController]
private readonly AppSettings _AppSettings = GlobalVars.AppSettings; [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() { public string Get() {
return "Welcome To Web API"; return "Welcome To Web API";
} }
public List<string> Get(int Id) { public List<string> Get(int Id) {
return new List<string> { return new List<string> {
"Data1", "Data1",
"Data2" "Data2"
}; };
} }
public void Post() { public void Post() {
} }
#if !NET8
public HttpResponseMessage Post(HttpRequestMessage request, string action) { public HttpResponseMessage Post(HttpRequestMessage request, string action) {
switch (action) { switch (action) {
case "TrainingReport": case "TrainingReport":
@ -65,4 +87,7 @@ public class WebAPIController : ApiController {
return request.CreateResponse(HttpStatusCode.InternalServerError, "Action Not Found"); return request.CreateResponse(HttpStatusCode.InternalServerError, "Action Not Found");
} }
} }
#endif
} }

View File

@ -1,17 +1,30 @@
using System; #if !NET8
using System.Collections.Generic;
using System.Linq;
using System.Web; using System.Web;
using System.Web.Mvc; 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.DMO;
using Fab2ApprovalSystem.Models; using Fab2ApprovalSystem.Models;
#endif
#if !NET8
using Kendo.Mvc.Extensions; using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI; using Kendo.Mvc.UI;
#endif
namespace Fab2ApprovalSystem.Controllers; namespace Fab2ApprovalSystem.Controllers;
#if NET8
[Route("[controller]")]
#endif
public class WorkflowController : Controller { public class WorkflowController : Controller {
// GET: /Workflow/Details/5 // GET: /Workflow/Details/5
@ -24,6 +37,8 @@ public class WorkflowController : Controller {
return View(); return View();
} }
#if !NET8
// POST: /Workflow/Create // POST: /Workflow/Create
[HttpPost] [HttpPost]
public ActionResult Create(FormCollection collection) { public ActionResult Create(FormCollection collection) {
@ -36,11 +51,15 @@ public class WorkflowController : Controller {
} }
} }
#endif
// GET: /Workflow/Edit/5 // GET: /Workflow/Edit/5
public ActionResult Edit(int id) { public ActionResult Edit(int id) {
return View(); return View();
} }
#if !NET8
// POST: /Workflow/Edit/5 // POST: /Workflow/Edit/5
[HttpPost] [HttpPost]
public ActionResult Edit(int id, FormCollection collection) { public ActionResult Edit(int id, FormCollection collection) {
@ -53,11 +72,15 @@ public class WorkflowController : Controller {
} }
} }
#endif
// GET: /Workflow/Delete/5 // GET: /Workflow/Delete/5
public ActionResult Delete(int id) { public ActionResult Delete(int id) {
return View(); return View();
} }
#if !NET8
// POST: /Workflow/Delete/5 // POST: /Workflow/Delete/5
[HttpPost] [HttpPost]
public ActionResult Delete(int id, FormCollection collection) { 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;
} }

View File

@ -37,7 +37,7 @@ public class AdminDMO {
foreach (SubRole sr in r.SubRoles) { foreach (SubRole sr in r.SubRoles) {
if (sr.Inactive) { if (sr.Inactive) {
// hide inactive roles unless parameter says otherwise // hide inactive roles unless parameter says otherwise
if (showInactiveRoles.Equals("true") == false) if (!showInactiveRoles.Equals("true"))
continue; continue;
} }
@ -130,13 +130,19 @@ public class AdminDMO {
} }
#if !NET8 #if !NET8
public List<TrainingReportUser> GetTrainingReportUsers() { public List<TrainingReportUser> GetTrainingReportUsers() {
List<TrainingReportUser> CurrentReportUsers = (from a in FabApprovalDB.TrainingReportUsers select a).ToList(); List<TrainingReportUser> CurrentReportUsers = (from a in FabApprovalDB.TrainingReportUsers select a).ToList();
return CurrentReportUsers; return CurrentReportUsers;
} }
#else
#endif
#if NET8
public List<TrainingReportUser> GetTrainingReportUsers() => public List<TrainingReportUser> GetTrainingReportUsers() =>
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
#if !NET8 #if !NET8
@ -179,14 +185,20 @@ public class AdminDMO {
return; return;
} }
#if !NET8
public List<TrainingGroup> GetTrainingGroups() { public List<TrainingGroup> GetTrainingGroups() {
#if !NET8
var TrainingGroups = from a in FabApprovalDB.TrainingGroups select a; var TrainingGroups = from a in FabApprovalDB.TrainingGroups select a;
List<TrainingGroup> GroupsToReturn = TrainingGroups.ToList(); List<TrainingGroup> GroupsToReturn = TrainingGroups.ToList();
return GroupsToReturn; return GroupsToReturn;
#endif
#if NET8
throw new NotImplementedException();
#endif
} }
#if !NET8
public void AddNewTrainingGroup(string groupName) { public void AddNewTrainingGroup(string groupName) {
TrainingGroup existing = null; TrainingGroup existing = null;
// Check to see that the group name doesn't exist. // Check to see that the group name doesn't exist.

View File

@ -401,7 +401,6 @@ public class AuditDMO {
result.Is8DQA = "true"; result.Is8DQA = "true";
} }
audit = GetAuditItem(issueID, userId);
// transform audit users from string to list, delimited by a comma. // transform audit users from string to list, delimited by a comma.
if (audit.Auditees == null) { if (audit.Auditees == null) {
result.AuditeeNames = new List<string>(); result.AuditeeNames = new List<string>();
@ -414,7 +413,7 @@ public class AuditDMO {
if (audit.OriginatorID == userId) { if (audit.OriginatorID == userId) {
result.IsSubmitter = true; result.IsSubmitter = true;
} }
if (isAdmin != true) { if (!isAdmin) {
result.IsAdmin = false; result.IsAdmin = false;
} else { } else {
result.IsAdmin = true; result.IsAdmin = true;
@ -424,7 +423,7 @@ public class AuditDMO {
{ {
result.RedirectToAction = true; result.RedirectToAction = true;
} }
if (result.IsAdmin == false && result.IsSubmitter == false) { if (!result.IsAdmin && !result.IsSubmitter) {
result.RedirectToAction = true; result.RedirectToAction = true;
} else { } else {
result.UserList = GetUserList(); result.UserList = GetUserList();

View File

@ -90,6 +90,7 @@ public class CorrectiveActionDMO {
parameters.Add("@EscapePoint", model.EscapePoint); parameters.Add("@EscapePoint", model.EscapePoint);
parameters.Add("@FollowUpDate", model.FollowUpDate); parameters.Add("@FollowUpDate", model.FollowUpDate);
parameters.Add("@CASubmitted", model.CASubmitted); parameters.Add("@CASubmitted", model.CASubmitted);
parameters.Add("@CAStandardType", model.CAStandardType);
db.Execute("_8DUpdateCorrectiveAction", parameters, commandType: CommandType.StoredProcedure); db.Execute("_8DUpdateCorrectiveAction", parameters, commandType: CommandType.StoredProcedure);
EventLogDMO.Add(new WinEventLog { UserID = "System", Comments = "Saved Corrective Action", DocumentType = "9", IssueID = model.CANo, OperationType = "Status", SysDocumentID = 1 }); EventLogDMO.Add(new WinEventLog { UserID = "System", Comments = "Saved Corrective Action", DocumentType = "9", IssueID = model.CANo, OperationType = "Status", SysDocumentID = 1 });
@ -323,7 +324,7 @@ public class CorrectiveActionDMO {
bool isAssignee = false; bool isAssignee = false;
int aiIndex = 0; int aiIndex = 0;
List<D5D6CorrectivetAction> actionItems = GetD5D6CorrectivetActions(caId).ToList(); List<D5D6CorrectivetAction> actionItems = GetD5D6CorrectivetActions(caId).ToList();
while (isAssignee == false && aiIndex < actionItems.Count) { while (!isAssignee && aiIndex < actionItems.Count) {
D5D6CorrectivetAction actionItem = actionItems[aiIndex]; D5D6CorrectivetAction actionItem = actionItems[aiIndex];
if (actionItem.ResponsibilityOwnerID == userId && actionItem.ImplementedDate == null && actionItem.Approved) { if (actionItem.ResponsibilityOwnerID == userId && actionItem.ImplementedDate == null && actionItem.Approved) {
isAssignee = true; isAssignee = true;

View File

@ -15,6 +15,7 @@ using Fab2ApprovalSystem.ViewModels;
namespace Fab2ApprovalSystem.DMO; namespace Fab2ApprovalSystem.DMO;
public class ECN_DMO { public class ECN_DMO {
private readonly IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); private readonly IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
private readonly WorkflowDMO wfDMO = new(); private readonly WorkflowDMO wfDMO = new();
@ -41,6 +42,9 @@ public class ECN_DMO {
parameters.Add("@ExpirationDate", ecn.ExpirationDate); parameters.Add("@ExpirationDate", ecn.ExpirationDate);
parameters.Add("@ExtensionDate", ecn.ExtensionDate); parameters.Add("@ExtensionDate", ecn.ExtensionDate);
parameters.Add("@CancellationDate", ecn.CancellationDate); parameters.Add("@CancellationDate", ecn.CancellationDate);
parameters.Add("@CancellationApprovalDate", ecn.CancellationApprovalDate);
parameters.Add("@CancellationApproved", ecn.CancellationApproved);
parameters.Add("@Cancelled", ecn.Cancelled);
parameters.Add("@AcknowledgementRequired", ecn.AcknowledgementRequired); parameters.Add("@AcknowledgementRequired", ecn.AcknowledgementRequired);
parameters.Add("@TrainingRequired", ecn.TrainingRequired); parameters.Add("@TrainingRequired", ecn.TrainingRequired);
parameters.Add("@AreaID", ecn.AreaID); parameters.Add("@AreaID", ecn.AreaID);
@ -352,14 +356,17 @@ public class ECN_DMO {
List<string> affectedAreas = multipleResultItems.Read<string>().ToList(); List<string> affectedAreas = multipleResultItems.Read<string>().ToList();
List<string> affectedTechnologies = multipleResultItems.Read<string>().ToList(); List<string> affectedTechnologies = multipleResultItems.Read<string>().ToList();
List<string> acknowledgementBy = multipleResultItems.Read<string>().ToList(); List<string> acknowledgementBy = multipleResultItems.Read<string>().ToList();
List<string> trainingBy = multipleResultItems.Read<string>().ToList(); List<int> trainingby = multipleResultItems.Read<int>().ToList();
if (ecnItem != null && trainingby != null) {
if (trainingby.Count > 0)
ecnItem.TrainingByIDs.AddRange(trainingby);
}
List<string> productfamilies = multipleResultItems.Read<string>().ToList(); List<string> productfamilies = multipleResultItems.Read<string>().ToList();
ecnItem.AffectedModules = string.Join(", ", modules); ecnItem.AffectedModules = string.Join(", ", modules);
ecnItem.AffectedDepartments = string.Join(", ", departments); ecnItem.AffectedDepartments = string.Join(", ", departments);
ecnItem.AffectedAreas = string.Join(",", affectedAreas); ecnItem.AffectedAreas = string.Join(",", affectedAreas);
ecnItem.AffectedTechnologies = string.Join(",", affectedTechnologies); ecnItem.AffectedTechnologies = string.Join(",", affectedTechnologies);
ecnItem.TrainingBy = string.Join(",", trainingBy);
ecnItem.AcknowledgementBy = string.Join(",", acknowledgementBy); ecnItem.AcknowledgementBy = string.Join(",", acknowledgementBy);
ecnItem.AffectedProductFamilies = string.Join(",", productfamilies); ecnItem.AffectedProductFamilies = string.Join(",", productfamilies);
@ -367,7 +374,7 @@ public class ECN_DMO {
return ecnItem; return ecnItem;
} }
internal ECN GetECN(int ecnNumber) { public ECN GetECN(int ecnNumber) {
ECN ecnItem = new(); ECN ecnItem = new();
DynamicParameters parameters = new(); DynamicParameters parameters = new();
parameters.Add("@ECNNumber", value: ecnNumber); parameters.Add("@ECNNumber", value: ecnNumber);
@ -389,7 +396,7 @@ public class ECN_DMO {
internal List<ECNCategory> GetCategories() { internal List<ECNCategory> GetCategories() {
List<ECNCategory> r = db.Query<ECNCategory>("ECNGetCategories", null, commandType: CommandType.StoredProcedure).ToList(); List<ECNCategory> r = db.Query<ECNCategory>("ECNGetCategories", null, commandType: CommandType.StoredProcedure).ToList();
return r; return r.OrderBy(l => l.CategoryName).ToList();
} }
internal List<ECNArea> GetECNAreas() { internal List<ECNArea> GetECNAreas() {
@ -710,4 +717,26 @@ public class ECN_DMO {
return r; return r;
} }
internal string GetCategoryID(ECNPdf ecn) {
string result;
if (ecn.CategoryID is null) {
result = string.Empty;
} else {
List<ECNCategory> categories = GetCategories();
result = (from l in categories where l.CategoryID == ecn.CategoryID.Value select l.CategoryName).FirstOrDefault();
}
return result;
}
internal string GetTrainingNotificationTo(ECNPdf ecn, TrainingDMO trainingDMO) {
string result;
if (ecn.TrainingByIDs is null) {
result = string.Empty;
} else {
List<TrainingGroup> trainingGroups = trainingDMO.GetTrainingGroups();
result = string.Join(", ", (from l in trainingGroups where ecn.TrainingByIDs.Contains(l.TrainingGroupID) select l.TrainingGroupName).ToArray());
}
return result;
}
} }

View File

@ -266,9 +266,9 @@ public class MRB_DMO {
DateTime? issueStartDate = tempMRBInfo.IssueStartDate; DateTime? issueStartDate = tempMRBInfo.IssueStartDate;
DateTime? issueEndDate = tempMRBInfo.IssueEndDate; DateTime? issueEndDate = tempMRBInfo.IssueEndDate;
if (issueStartDate.HasValue == false) if (!issueStartDate.HasValue)
throw new Exception("MRB Issue Start Date cannot be blank"); throw new Exception("MRB Issue Start Date cannot be blank");
if (issueEndDate.HasValue == false) if (!issueEndDate.HasValue)
throw new Exception("MRB Issue End Date cannot be blank"); throw new Exception("MRB Issue End Date cannot be blank");
MRB mrbData = new() { MRBNumber = mrbNumber, ToolCSV = tempMRBInfo.ToolCSV, IssueStartDate = tempMRBInfo.IssueStartDate, IssueEndDate = tempMRBInfo.IssueEndDate }; MRB mrbData = new() { MRBNumber = mrbNumber, ToolCSV = tempMRBInfo.ToolCSV, IssueStartDate = tempMRBInfo.IssueStartDate, IssueEndDate = tempMRBInfo.IssueEndDate };

View File

@ -46,7 +46,9 @@ public class TrainingDMO {
IEnumerable<Training> allTrainings = (from a in db.Trainings select a).ToList(); IEnumerable<Training> allTrainings = (from a in db.Trainings select a).ToList();
return allTrainings; return allTrainings;
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -57,7 +59,9 @@ public class TrainingDMO {
Training trainingRecord = new Training(); Training trainingRecord = new Training();
trainingRecord = (from a in db.Trainings where a.TrainingID == trainingId select a).FirstOrDefault(); trainingRecord = (from a in db.Trainings where a.TrainingID == trainingId select a).FirstOrDefault();
return trainingRecord; return trainingRecord;
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -67,7 +71,9 @@ public class TrainingDMO {
FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); FabApprovalTrainingEntities db = new FabApprovalTrainingEntities();
TrainingAssignment assignmentRecord = (from a in db.TrainingAssignments where a.ID == assignmentId select a).FirstOrDefault(); TrainingAssignment assignmentRecord = (from a in db.TrainingAssignments where a.ID == assignmentId select a).FirstOrDefault();
return assignmentRecord; return assignmentRecord;
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -79,7 +85,9 @@ public class TrainingDMO {
int trainingId = (from a in db.Trainings where a.ECN == ECNId select a.TrainingID).FirstOrDefault(); int trainingId = (from a in db.Trainings where a.ECN == ECNId select a.TrainingID).FirstOrDefault();
return trainingId; return trainingId;
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -90,7 +98,9 @@ public class TrainingDMO {
var users = (from a in db.TrainingGroupMembers where a.TrainingGroupID == groupId select a.UserID).ToList(); var users = (from a in db.TrainingGroupMembers where a.TrainingGroupID == groupId select a.UserID).ToList();
return users; return users;
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -105,7 +115,9 @@ public class TrainingDMO {
} else { } else {
return true; return true;
} }
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -114,8 +126,11 @@ public class TrainingDMO {
#if !NET8 #if !NET8
FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); FabApprovalTrainingEntities db = new FabApprovalTrainingEntities();
return (from a in db.TrainingGroups select a).ToList(); return (from a in db.TrainingGroups select a).ToList();
#else #endif
throw new NotImplementedException();
#if NET8
System.Text.StringBuilder query = new("SELECT TrainingGroupID, TrainingGroupName FROM TrainingGroups ORDER BY TrainingGroupID");
return db.Query<TrainingGroup>(query.ToString()).ToList();
#endif #endif
} }
@ -124,7 +139,9 @@ public class TrainingDMO {
FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); FabApprovalTrainingEntities db = new FabApprovalTrainingEntities();
TrainingGroup groups = (from a in db.TrainingGroups where a.TrainingGroupID == groupId select a).FirstOrDefault(); TrainingGroup groups = (from a in db.TrainingGroups where a.TrainingGroupID == groupId select a).FirstOrDefault();
return groups; return groups;
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -134,7 +151,9 @@ public class TrainingDMO {
List<int> trainingGroups = (from a in FabApprovalDB.ECNTrainingBies where a.ECNNumber == ECNNumber select a.AcknowledgementTrainingByID).ToList(); List<int> trainingGroups = (from a in FabApprovalDB.ECNTrainingBies where a.ECNNumber == ECNNumber select a.AcknowledgementTrainingByID).ToList();
return trainingGroups; return trainingGroups;
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -149,7 +168,9 @@ public class TrainingDMO {
this.db.Execute("ECNInsertTrainingBy", parameters, commandType: CommandType.StoredProcedure); this.db.Execute("ECNInsertTrainingBy", parameters, commandType: CommandType.StoredProcedure);
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -162,7 +183,9 @@ public class TrainingDMO {
this.db.Execute("ECNSetTrainingFlag", parameters, commandType: CommandType.StoredProcedure); this.db.Execute("ECNSetTrainingFlag", parameters, commandType: CommandType.StoredProcedure);
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -177,7 +200,9 @@ public class TrainingDMO {
TrainingData = from a in db.TrainingAssignments where a.TrainingID == TrainingID select a; TrainingData = from a in db.TrainingAssignments where a.TrainingID == TrainingID select a;
return TrainingData.ToList(); return TrainingData.ToList();
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -192,7 +217,9 @@ public class TrainingDMO {
TrainingData = from a in db.TrainingAssignments where a.TrainingID == TrainingID select a; TrainingData = from a in db.TrainingAssignments where a.TrainingID == TrainingID select a;
return TrainingData.ToList(); return TrainingData.ToList();
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -203,7 +230,9 @@ public class TrainingDMO {
var TrainingData = from a in db.TrainingAssignments where a.TrainingID == TrainingID && a.UserID == userID select a; var TrainingData = from a in db.TrainingAssignments where a.TrainingID == TrainingID && a.UserID == userID select a;
return TrainingData.ToList(); return TrainingData.ToList();
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #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(); var docs = (from a in db.TrainingDocAcks where a.TrainingAssignmentID == trainingAssignmentId && a.Deleted != true select a).ToList();
return docs; return docs;
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -240,7 +271,9 @@ public class TrainingDMO {
Console.WriteLine(e); Console.WriteLine(e);
} }
} }
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -251,7 +284,9 @@ public class TrainingDMO {
int trainingID = (from a in db.TrainingAssignments where a.ID == trainingAssignmentID select a.TrainingID).SingleOrDefault(); int trainingID = (from a in db.TrainingAssignments where a.ID == trainingAssignmentID select a.TrainingID).SingleOrDefault();
return trainingID; return trainingID;
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -272,7 +307,9 @@ public class TrainingDMO {
Console.WriteLine(e); Console.WriteLine(e);
} }
} }
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -293,7 +330,9 @@ public class TrainingDMO {
Console.WriteLine(e); Console.WriteLine(e);
} }
} }
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -311,7 +350,9 @@ public class TrainingDMO {
} }
} }
return isFinished; return isFinished;
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -331,7 +372,9 @@ public class TrainingDMO {
} }
return isFinished; return isFinished;
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -348,7 +391,9 @@ public class TrainingDMO {
} }
return userHasAssignment; return userHasAssignment;
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -359,7 +404,9 @@ public class TrainingDMO {
var trainings = from a in db.Trainings select a; var trainings = from a in db.Trainings select a;
return trainings.ToList(); return trainings.ToList();
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -370,7 +417,9 @@ public class TrainingDMO {
var trainingAssignments = from a in db.TrainingAssignments where a.UserID == userID && a.Deleted != true select a; var trainingAssignments = from a in db.TrainingAssignments where a.UserID == userID && a.Deleted != true select a;
return trainingAssignments.ToList(); return trainingAssignments.ToList();
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -390,7 +439,9 @@ public class TrainingDMO {
string exception = e.ToString(); string exception = e.ToString();
Console.WriteLine(e); Console.WriteLine(e);
} }
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -410,7 +461,9 @@ public class TrainingDMO {
string exception = e.ToString(); string exception = e.ToString();
Console.WriteLine(e); Console.WriteLine(e);
} }
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -431,7 +484,9 @@ public class TrainingDMO {
DeleteTrainingAssignment(trainingAssignment.ID); DeleteTrainingAssignment(trainingAssignment.ID);
DeleteTrainingDocAck(trainingAssignment.ID); DeleteTrainingDocAck(trainingAssignment.ID);
} }
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -451,7 +506,9 @@ public class TrainingDMO {
} }
DeleteTrainingAssignment(item.ID); DeleteTrainingAssignment(item.ID);
} }
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -478,7 +535,9 @@ public class TrainingDMO {
} else { } else {
return false; return false;
} }
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -488,7 +547,9 @@ public class TrainingDMO {
FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); FabApprovalTrainingEntities db = new FabApprovalTrainingEntities();
List<Training> openTrainings = (from a in db.Trainings where a.Status != true && a.Deleted != true select a).ToList(); List<Training> openTrainings = (from a in db.Trainings where a.Status != true && a.Deleted != true select a).ToList();
return openTrainings; return openTrainings;
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }
@ -498,7 +559,9 @@ public class TrainingDMO {
FabApprovalTrainingEntities db = new FabApprovalTrainingEntities(); FabApprovalTrainingEntities db = new FabApprovalTrainingEntities();
List<TrainingAssignment> openAssignments = (from a in FabApprovalDB.TrainingAssignments where a.TrainingID == trainingID && a.status != true && a.Deleted != true select a).ToList(); List<TrainingAssignment> openAssignments = (from a in FabApprovalDB.TrainingAssignments where a.TrainingID == trainingID && a.status != true && a.Deleted != true select a).ToList();
return openAssignments; return openAssignments;
#else #endif
#if NET8
throw new NotImplementedException(); throw new NotImplementedException();
#endif #endif
} }

View File

@ -166,7 +166,7 @@ public class WorkflowDMO {
sqlString.Append("SELECT COUNT(*) FROM LotDisposition LD INNER JOIN Lot L ON LD.IssueID = L.IssueID "); sqlString.Append("SELECT COUNT(*) FROM LotDisposition LD INNER JOIN Lot L ON LD.IssueID = L.IssueID ");
sqlString.Append("WHERE (PERequired = 1 OR Location = 'QDB' OR Location = 'EDB' ) AND LD.IssueID = @IssueID "); sqlString.Append("WHERE (PERequired = 1 OR Location = 'QDB' OR Location = 'EDB' ) AND LD.IssueID = @IssueID ");
recordCount = db.Query<int>(sqlString.ToString(), new { IssueID = issueID }).Single(); recordCount = db.Query<int>(sqlString.ToString(), new { IssueID = issueID }).Single();
if ((recordCount > 0) && (allLotsAreScrap == false)) { if ((recordCount > 0) && (!allLotsAreScrap)) {
// check if there any IG Medical products // check if there any IG Medical products
if (recordCountForIG_MA > 0) { if (recordCountForIG_MA > 0) {
sqlString = new StringBuilder(); sqlString = new StringBuilder();

View File

@ -2,10 +2,12 @@
*****Please DO NOT reply to this email***** *****Please DO NOT reply to this email*****
<br/><br/> <br/><br/>
{3}# {0} has been Cancelled. Please remove posted TECN from point of use. The cancellation date is {4} {3}# {0} has been Cancelled. Please remove posted TECN from point of use. The cancellation date is {4}
Please review the cancelled TECN form in the attachment. Please review comments below and ensure process has been returned to normal.
<br/><br/> <br/><br/>
https://messa016ec.infineon.com/ECN/Edit?issueID={1} https://messa016ec.infineon.com/ECN/Edit?issueID={1}
<br/><br/> <br/><br/>
Comments: {5}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator. If you have any questions or trouble logging on please contact a site administrator.
<br/><br/> <br/><br/>

View File

@ -0,0 +1,17 @@
<font size="2" face="verdana">
*****Please DO NOT reply to this email*****
<br/><br/>
{3}# {0} has been returned to process. Please remove posted TECN from point of use. The returned to process date is {4}
Please review comments below and ensure process has been returned to normal.
<br/><br/>
https://messa016ec.infineon.com/ECN/Edit?issueID={1}
<br/><br/>
Comments: {5}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.
<br/><br/>
Thank you!
</font>

View File

@ -255,6 +255,7 @@
<Compile Include="Controllers\TrainingController.cs" /> <Compile Include="Controllers\TrainingController.cs" />
<Compile Include="Controllers\WebAPIController.cs" /> <Compile Include="Controllers\WebAPIController.cs" />
<Compile Include="Controllers\WorkflowController.cs" /> <Compile Include="Controllers\WorkflowController.cs" />
<Compile Include="Controllers\PCRBController.cs" />
<Compile Include="DMO\AccountDMO.cs" /> <Compile Include="DMO\AccountDMO.cs" />
<Compile Include="DMO\AdminDMO.cs" /> <Compile Include="DMO\AdminDMO.cs" />
<Compile Include="DMO\ApprovalLogDMO.cs" /> <Compile Include="DMO\ApprovalLogDMO.cs" />
@ -320,13 +321,11 @@
<Compile Include="Models\PartsRequestModels.cs" /> <Compile Include="Models\PartsRequestModels.cs" />
<Compile Include="Models\ProductViewModel.cs" /> <Compile Include="Models\ProductViewModel.cs" />
<Compile Include="Models\TestModels.cs" /> <Compile Include="Models\TestModels.cs" />
<Compile Include="Models\User.cs" />
<Compile Include="Models\UserSubRoles.cs" /> <Compile Include="Models\UserSubRoles.cs" />
<Compile Include="Models\WinEventLogModel.cs" /> <Compile Include="Models\WinEventLogModel.cs" />
<Compile Include="Models\WorkFlowModels.cs" /> <Compile Include="Models\WorkFlowModels.cs" />
<Compile Include="PdfGenerator\BinaryContentResult.cs" /> <Compile Include="PdfGenerator\BinaryContentResult.cs" />
<Compile Include="PdfGenerator\FakeView.cs" />
<Compile Include="PdfGenerator\HtmlViewRenderer.cs" />
<Compile Include="PdfGenerator\PdfViewController.cs" />
<Compile Include="PdfGenerator\PrintHeaderFooter.cs" /> <Compile Include="PdfGenerator\PrintHeaderFooter.cs" />
<Compile Include="PdfGenerator\StandardPdfRenderer.cs" /> <Compile Include="PdfGenerator\StandardPdfRenderer.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
@ -387,8 +386,10 @@
<Content Include="Views\CorrectiveAction\_D7PAAttachment.cshtml" /> <Content Include="Views\CorrectiveAction\_D7PAAttachment.cshtml" />
<Content Include="Views\CorrectiveAction\Edit.cshtml" /> <Content Include="Views\CorrectiveAction\Edit.cshtml" />
<Content Include="Views\CorrectiveAction\ReadOnlyCA.cshtml" /> <Content Include="Views\CorrectiveAction\ReadOnlyCA.cshtml" />
<Content Include="Views\ECN\_ECNCancel.cshtml" />
<Content Include="Views\ECN\_ECNLayout.cshtml" /> <Content Include="Views\ECN\_ECNLayout.cshtml" />
<Content Include="Views\ECN\_ECNReassignOriginator.cshtml" /> <Content Include="Views\ECN\_ECNReassignOriginator.cshtml" />
<Content Include="Views\ECN\_ECNReturnToProcess.cshtml" />
<Content Include="Views\ECN\Acknowledge.cshtml" /> <Content Include="Views\ECN\Acknowledge.cshtml" />
<Content Include="Views\ECN\ECNApprovalPdf.cshtml" /> <Content Include="Views\ECN\ECNApprovalPdf.cshtml" />
<Content Include="Views\ECN\ECNPdf.cshtml" /> <Content Include="Views\ECN\ECNPdf.cshtml" />
@ -513,6 +514,7 @@
<Content Include="EmailTemplates\TECNExpirationApproval.txt" /> <Content Include="EmailTemplates\TECNExpirationApproval.txt" />
<Content Include="EmailTemplates\TECNExpired.txt" /> <Content Include="EmailTemplates\TECNExpired.txt" />
<Content Include="EmailTemplates\TECNExtensionReject.txt" /> <Content Include="EmailTemplates\TECNExtensionReject.txt" />
<Content Include="EmailTemplates\TECNReturnedToProcess.txt" />
<Content Include="EmailTemplates\WorkRequestApproval.txt" /> <Content Include="EmailTemplates\WorkRequestApproval.txt" />
<Content Include="EmailTemplates\WorkRequestAssigned.txt" /> <Content Include="EmailTemplates\WorkRequestAssigned.txt" />
<Content Include="EmailTemplates\WorkRequestReAssigned.txt" /> <Content Include="EmailTemplates\WorkRequestReAssigned.txt" />

View File

@ -5,7 +5,9 @@ using System.Linq;
using System.Web; using System.Web;
using System.Web.Hosting; using System.Web.Hosting;
using System.Web.Http; using System.Web.Http;
#if !NET8
using System.Web.Mvc; using System.Web.Mvc;
#endif
using System.Web.Optimization; using System.Web.Optimization;
using System.Web.Routing; using System.Web.Routing;
using System.Web.Security; using System.Web.Security;
@ -63,7 +65,7 @@ public class MvcApplication : System.Web.HttpApplication {
protected void Application_EndRequest() { protected void Application_EndRequest() {
var context = new HttpContextWrapper(Context); var context = new HttpContextWrapper(Context);
// Do a direct 401 unauthorized #if !NET8
if (Context.Response.StatusCode == 301 && context.Request.IsAjaxRequest()) { if (Context.Response.StatusCode == 301 && context.Request.IsAjaxRequest()) {
Context.Response.Clear(); Context.Response.Clear();
Context.Response.StatusCode = 401; Context.Response.StatusCode = 401;
@ -72,18 +74,27 @@ public class MvcApplication : System.Web.HttpApplication {
context.Response.Clear(); context.Response.Clear();
context.Response.StatusCode = 401; 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) { 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) { protected void Session_End(object sender, EventArgs e) {
// FormsAuthentication.SignOut(); // FormsAuthentication.SignOut();
try { try {
Session[GlobalVars.SESSION_USERNAME] = ""; GlobalVars.EndSession(Session);
Session[GlobalVars.SESSION_USERID] = "";
Session[GlobalVars.IS_ADMIN] = null;
} catch (Exception ex) { } catch (Exception ex) {
Functions.WriteEvent(null, @User.Identity.Name + "\r\n Session Closed - \r\n" + ex.Message.ToString(), System.Diagnostics.EventLogEntryType.Error); Functions.WriteEvent(null, @User.Identity.Name + "\r\n Session Closed - \r\n" + ex.Message.ToString(), System.Diagnostics.EventLogEntryType.Error);
} }

View File

@ -126,7 +126,7 @@ public class ECNHelper {
return emailSentList; return emailSentList;
} }
public static string NotifyTECNCancellation(AppSettings appSettings, UserAccountDMO userDMO, int ecnNumber, string ecnFolderPath, ECN ecn, List<int> notificationUserList) { public static string NotifyTECNCancellation(AppSettings appSettings, UserAccountDMO userDMO, int ecnNumber, string ecnFolderPath, string comments, ECN ecn, List<int> notificationUserList) {
string emailSentList = ""; string emailSentList = "";
List<string> emailIst = MiscDMO.GetTECNCancelledApprovalNotifyList(ecnNumber).Distinct().ToList(); List<string> emailIst = MiscDMO.GetTECNCancelledApprovalNotifyList(ecnNumber).Distinct().ToList();
foreach (int userId in notificationUserList) { foreach (int userId in notificationUserList) {
@ -135,23 +135,27 @@ public class ECNHelper {
emailIst.Add(email); emailIst.Add(email);
} }
string subject = string.Empty; string subject;
string userEmail = string.Empty; string emailTemplate;
string emailTemplate = "TECNCancelled.txt";
if (ecn.CancellationApprovalDate == null) {
subject = "TECN Cancellation Initiated Notice - " + ecnNumber + " for " + ecn.Title + ", Cancellation Initiated on:" + DateTime.Now;
} else {
subject = "TECN Cancellation Approved Notice - " + ecnNumber + " for " + ecn.Title + ", Cancelled:" + ecn.CancellationApprovalDate;
}
string senderName = "ECN"; string senderName = "ECN";
string userEmail = string.Empty;
DateTime dateTime = ecn.CancellationApprovalDate is null ? DateTime.Now : ecn.CancellationApprovalDate.Value;
if (ecn.ExpirationDate > DateTime.Today || ecn.ExtensionDate > DateTime.Today) {
emailTemplate = "TECNCancelled.txt";
subject = "TECN Cancellation Approved Notice - " + ecnNumber + " for " + ecn.Title + ", Cancelled:" + dateTime;
} else {
emailTemplate = "TECNReturnedToProcess.txt";
subject = "TECN Return to Process Approved Notice - " + ecnNumber + " for " + ecn.Title + ", Returned:" + dateTime;
}
EmailNotification en = new(appSettings, subject); EmailNotification en = new(appSettings, subject);
string[] emailparams = new string[5]; string[] emailparams = new string[6];
emailparams[0] = ecnNumber.ToString(); emailparams[0] = ecnNumber.ToString();
emailparams[1] = ecnNumber.ToString(); emailparams[1] = ecnNumber.ToString();
emailparams[2] = GlobalVars.hostURL; emailparams[2] = GlobalVars.hostURL;
emailparams[3] = "TECN"; emailparams[3] = "TECN";
emailparams[4] = DateTime.Now.ToString(); emailparams[4] = DateTime.Now.ToString();
emailparams[5] = comments;
#if (DEBUG) #if (DEBUG)
userEmail = GlobalVars.SENDER_EMAIL; userEmail = GlobalVars.SENDER_EMAIL;

View File

@ -1,53 +1,56 @@
#if !NET8 #if NET8
using ExcelDataReader;
#endif
#if !NET8
using Excel; using Excel;
#endif
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data; using System.Data;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Web;
namespace Fab2ApprovalSystem.Misc { namespace Fab2ApprovalSystem.Misc;
public class ExcelData {
private readonly string _Path;
public class ExcelData {
string _path;
public ExcelData(string path) { public ExcelData(string path) {
_path = path; _Path = path;
} }
public IExcelDataReader getExcelReader() { public IExcelDataReader getExcelReader() {
// ExcelDataReader works with the binary Excel file, so it needs a FileStream FileStream stream = File.Open(_Path, FileMode.Open, FileAccess.Read);
// to get started. This is how we avoid dependencies on ACE or Interop:
FileStream stream = File.Open(_path, FileMode.Open, FileAccess.Read);
// We return the interface, so that
IExcelDataReader reader = null; IExcelDataReader reader = null;
try { try {
if (_path.EndsWith(".xls")) { if (_Path.EndsWith(".xls")) {
reader = ExcelReaderFactory.CreateBinaryReader(stream); reader = ExcelReaderFactory.CreateBinaryReader(stream);
} }
if (_path.EndsWith(".xlsx")) { if (_Path.EndsWith(".xlsx")) {
reader = ExcelReaderFactory.CreateOpenXmlReader(stream); reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
} }
return reader; return reader;
} catch (Exception) { } catch (Exception) {
throw; throw;
} }
} }
public class ExcelLotInfo { public class ExcelLotInfo {
public string LotNo { get; set; } public string? LotNo { get; set; }
public string LotDispo { get; set; } public string? LotDispo { get; set; }
} }
public IEnumerable<ExcelLotInfo> ReadData() { public IEnumerable<ExcelLotInfo> ReadData() {
var r = new List<ExcelLotInfo>(); List<ExcelLotInfo> r = new();
var excelData = new ExcelData(_path); ExcelData excelData = new(_Path);
var lots = excelData.getData().ToList(); List<DataRow> lots = excelData.getData().ToList();
int lotDispoColumnIndex = -1; int lotDispoColumnIndex = -1;
foreach (DataColumn col in lots[0].Table.Columns) { foreach (DataColumn col in lots[0].Table.Columns) {
@ -57,7 +60,7 @@ namespace Fab2ApprovalSystem.Misc {
} }
} }
foreach (var row in lots) { foreach (DataRow row in lots) {
string temValue = row[0].ToString(); string temValue = row[0].ToString();
if (temValue.Trim().Length > 0 && temValue.Trim().Length <= 10) { if (temValue.Trim().Length > 0 && temValue.Trim().Length <= 10) {
r.Add(new ExcelLotInfo() { r.Add(new ExcelLotInfo() {
@ -71,11 +74,10 @@ namespace Fab2ApprovalSystem.Misc {
} }
public IEnumerable<string> ReadQDBFlagData() { public IEnumerable<string> ReadQDBFlagData() {
List<string> s = new List<string>(); List<string> s = new();
// We return the interface, so that ExcelData excelData = new(_Path);
var excelData = new ExcelData(_path); IEnumerable<DataRow> lotNos = excelData.getData();
var lotNos = excelData.getData(); foreach (DataRow row in lotNos) {
foreach (var row in lotNos) {
string temValue = row[0].ToString(); string temValue = row[0].ToString();
if (temValue.Trim().Length > 0 && temValue.Trim().Length == 9) { if (temValue.Trim().Length > 0 && temValue.Trim().Length == 9) {
if (row[2].ToString().ToUpper() != "YES" && row[2].ToString().ToUpper() != "NO") { if (row[2].ToString().ToUpper() != "YES" && row[2].ToString().ToUpper() != "NO") {
@ -89,16 +91,23 @@ namespace Fab2ApprovalSystem.Misc {
return s; return s;
} }
#if NET8
public IEnumerable<DataRow> getData(bool firstRowIsColumnNames = true) =>
throw new NotImplementedException();
#endif
#if !NET8
public IEnumerable<DataRow> getData(bool firstRowIsColumnNames = true) { public IEnumerable<DataRow> getData(bool firstRowIsColumnNames = true) {
var reader = this.getExcelReader(); IExcelDataReader reader = getExcelReader();
reader.IsFirstRowAsColumnNames = firstRowIsColumnNames; reader.IsFirstRowAsColumnNames = firstRowIsColumnNames;
var workSheet = reader.AsDataSet().Tables[0]; var workSheet = reader.AsDataSet().Tables[0];
var rows = from DataRow a in workSheet.Rows select a; var rows = from DataRow a in workSheet.Rows select a;
return rows; return rows;
} }
}
}
#endif #endif
}

View File

@ -6,10 +6,15 @@ namespace Fab2ApprovalSystem.Misc;
public class GlobalVars { public class GlobalVars {
public int USER_ID; public int USER_ID;
#else
#endif
#if NET8
public static class GlobalVars { public static class GlobalVars {
public static int USER_ID = 0; public static int USER_ID = 0;
#endif #endif
public const string SESSION_USERNAME = "UserName"; public const string SESSION_USERNAME = "UserName";
public const string ApplicationName = "LotDisposition"; public const string ApplicationName = "LotDisposition";
@ -98,4 +103,268 @@ public static class GlobalVars {
Main, D1, D2, D3, D4, D5, D6, D7, D8, CF 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
} }

View File

@ -117,8 +117,8 @@ public class LotDispositionHelper {
public static void AttachSave(AppSettings appSettings, LotDispositionDMO lotDispositionDMO, int issueID, int userId, string fullFileName, Stream stream) { public static void AttachSave(AppSettings appSettings, LotDispositionDMO lotDispositionDMO, int issueID, int userId, string fullFileName, Stream stream) {
// Some browsers send file names with full path. // Some browsers send file names with full path.
// We are only interested in the file name. // We are only interested in the file name.
var fileName = Path.GetFileName(fullFileName); string fileName = Path.GetFileName(fullFileName);
var physicalPath = Path.Combine(appSettings.AttachmentFolder + "LotDisposition", fileName); string physicalPath = Path.Combine(appSettings.AttachmentFolder + "LotDisposition", fileName);
using (FileStream fileStream = new(physicalPath, FileMode.Create, FileAccess.Write)) { using (FileStream fileStream = new(physicalPath, FileMode.Create, FileAccess.Write)) {
stream.CopyTo(fileStream); stream.CopyTo(fileStream);
@ -134,7 +134,7 @@ public class LotDispositionHelper {
public static string ExcelLotOpen(LotDispositionDMO lotDispositionDMO, int issueID, string userIdentityName, string lotTempPipeLine, string fullFileName, Stream stream) { public static string ExcelLotOpen(LotDispositionDMO lotDispositionDMO, int issueID, string userIdentityName, string lotTempPipeLine, string fullFileName, Stream stream) {
string physicalPath; string physicalPath;
var fileExtension = Path.GetExtension(fullFileName); string fileExtension = Path.GetExtension(fullFileName);
string fName = userIdentityName + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString(); string fName = userIdentityName + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
physicalPath = Path.Combine(lotTempPipeLine, fName + "." + fileExtension); physicalPath = Path.Combine(lotTempPipeLine, fName + "." + fileExtension);
@ -142,20 +142,18 @@ public class LotDispositionHelper {
stream.CopyTo(fileStream); stream.CopyTo(fileStream);
} }
#if !NET8 ExcelData x = new (physicalPath);
ExcelData x = new ExcelData(physicalPath); IEnumerable<ExcelData.ExcelLotInfo> lotNumbers = x.ReadData();
var lotNumbers = x.ReadData();
foreach (var lotInfo in lotNumbers) { foreach (ExcelData.ExcelLotInfo lotInfo in lotNumbers) {
Lot l = new Lot(); Lot l = new();
l.LotNumber = lotInfo.LotNo; l.LotNumber = lotInfo.LotNo ?? string.Empty;
l.IssueID = issueID; l.IssueID = issueID;
if (l.LotStatusOptionID == 0) if (l.LotStatusOptionID == 0)
l.LotStatusOption.LotStatusOptionID = (int)GlobalVars.LotStatusOption.Release; l.LotStatusOption.LotStatusOptionID = (int)GlobalVars.LotStatusOption.Release;
lotDispositionDMO.InsertLot(l, true); lotDispositionDMO.InsertLot(l, true);
} }
#endif
FileInfo f = new(physicalPath); FileInfo f = new(physicalPath);
if (f.Exists) if (f.Exists)

View File

@ -46,14 +46,12 @@ public class MRBHelper {
stream.CopyTo(fileStream); stream.CopyTo(fileStream);
} }
#if !NET8 ExcelData x = new(physicalPath);
ExcelData x = new ExcelData(physicalPath);
lotDataList = x.ReadQDBFlagData(); lotDataList = x.ReadQDBFlagData();
foreach (string lotData in lotDataList) { foreach (string lotData in lotDataList) {
mrbDMO.InsertMRB_QDB_HoldFlag(guid, lotData, operation); mrbDMO.InsertMRB_QDB_HoldFlag(guid, lotData, operation);
} }
#endif
FileInfo f = new(physicalPath); FileInfo f = new(physicalPath);
if (f.Exists) if (f.Exists)
@ -170,14 +168,12 @@ public class MRBHelper {
stream.CopyTo(fileStream); stream.CopyTo(fileStream);
} }
#if !NET8 ExcelData x = new(physicalPath);
ExcelData x = new ExcelData(physicalPath);
lotDataList = x.ReadQDBFlagData(); lotDataList = x.ReadQDBFlagData();
foreach (string lotData in lotDataList) { foreach (string lotData in lotDataList) {
mrbDMO.InsertMRB_QDB_HoldFlag(guid, lotData, operation); mrbDMO.InsertMRB_QDB_HoldFlag(guid, lotData, operation);
} }
#endif
FileInfo f = new(physicalPath); FileInfo f = new(physicalPath);
if (f.Exists) if (f.Exists)
@ -246,17 +242,16 @@ public class MRBHelper {
string fName = userIdentityName + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString(); string fName = userIdentityName + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
string physicalPath = Path.Combine(lotTempPipeLine, fName + "." + fileExtension); string physicalPath = Path.Combine(lotTempPipeLine, fName + "." + fileExtension);
#if !NET8
IEnumerable<ExcelData.ExcelLotInfo> lotNumbers; IEnumerable<ExcelData.ExcelLotInfo> lotNumbers;
try { try {
using (var fileStream = new FileStream(physicalPath, FileMode.Create, FileAccess.Write)) { using (FileStream fileStream = new(physicalPath, FileMode.Create, FileAccess.Write)) {
stream.CopyTo(fileStream); stream.CopyTo(fileStream);
} }
ExcelData x = new ExcelData(physicalPath); ExcelData x = new(physicalPath);
lotNumbers = x.ReadData(); lotNumbers = x.ReadData();
} catch (Exception ex) { } catch (Exception ex) {
throw new Exception(String.Format("Invalid file format for {0}: {1}", fileName, ex.Message)); throw new Exception(string.Format("Invalid file format for {0}: {1}", fileName, ex.Message));
} }
// Get Tool, Issue Start and End Date // Get Tool, Issue Start and End Date
@ -266,7 +261,7 @@ public class MRBHelper {
foreach (var lotInfo in lotNumbers) { foreach (var lotInfo in lotNumbers) {
if (lotInfo.LotDispo.Length == 1) { if (lotInfo.LotDispo.Length == 1) {
if (dispos.Count(d => d.DispositionType.Trim().ToUpper() == lotInfo.LotDispo.Trim().ToUpper()) == 0) { if (dispos.Count(d => d.DispositionType.Trim().ToUpper() == lotInfo.LotDispo.Trim().ToUpper()) == 0) {
throw new Exception(String.Format("Invalid lot disposition {0} for lot no {1}", throw new Exception(string.Format("Invalid lot disposition {0} for lot no {1}",
lotInfo.LotDispo, lotInfo.LotNo)); lotInfo.LotDispo, lotInfo.LotNo));
} }
} }
@ -276,8 +271,8 @@ public class MRBHelper {
if (!mrbInfo.ToolCSV.ToUpper().Equals("NA")) { if (!mrbInfo.ToolCSV.ToUpper().Equals("NA")) {
foreach (var lotInfo in lotNumbers) { foreach (var lotInfo in lotNumbers) {
bool existingLotUpdated; bool existingLotUpdated;
Lot l = new Lot(); Lot l = new();
l.LotNumber = lotInfo.LotNo; l.LotNumber = lotInfo.LotNo ?? string.Empty;
if (lotInfo.LotDispo.Length == 1) { if (lotInfo.LotDispo.Length == 1) {
l.DispoType = lotInfo.LotDispo[0]; l.DispoType = lotInfo.LotDispo[0];
} }
@ -298,8 +293,8 @@ public class MRBHelper {
// Only find the child Splits when a Tool or a list of Tools is provided // Only find the child Splits when a Tool or a list of Tools is provided
foreach (var lotInfo in lotNumbers) { foreach (var lotInfo in lotNumbers) {
bool existingLotUpdated; bool existingLotUpdated;
Lot l = new Lot(); Lot l = new();
l.LotNumber = lotInfo.LotNo; l.LotNumber = lotInfo.LotNo ?? string.Empty;
if (lotInfo.LotDispo.Length == 1) { if (lotInfo.LotDispo.Length == 1) {
l.DispoType = lotInfo.LotDispo[0]; l.DispoType = lotInfo.LotDispo[0];
} }
@ -308,7 +303,6 @@ public class MRBHelper {
mrbDMO.InsertLot(l, true, out existingLotUpdated); mrbDMO.InsertLot(l, true, out existingLotUpdated);
} }
} }
#endif
FileInfo f = new(physicalPath); FileInfo f = new(physicalPath);
if (f.Exists) if (f.Exists)

View File

@ -4,7 +4,9 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Web; using System.Web;
#if !NET8
using System.Web.Mvc; using System.Web.Mvc;
#endif
namespace Fab2ApprovalSystem.Misc { namespace Fab2ApprovalSystem.Misc {
@ -16,7 +18,7 @@ namespace Fab2ApprovalSystem.Misc {
// check if session is supported // check if session is supported
if (session[GlobalVars.SESSION_USERNAME] == null) { if (GlobalVars.IsUserNameNull(session)) {
// check if a new session id was generated // check if a new session id was generated
// this will force MVC to use the standard login redirect, enabling ReturnURL functionality // this will force MVC to use the standard login redirect, enabling ReturnURL functionality

View File

@ -8,7 +8,7 @@ namespace Fab2ApprovalSystem.Models;
public class AppSettings { public class AppSettings {
public AppSettings(string adminNotificationRecepient, public AppSettings(string adminNotificationRecepient,
string? apiBaseUrl, string apiBaseUrl,
string attachmentFolder, string attachmentFolder,
string? attachmentUrl, string? attachmentUrl,
string caBlankFormsLocation, string caBlankFormsLocation,
@ -26,6 +26,9 @@ public class AppSettings {
string ifxContainer, string ifxContainer,
string ifxDomain, string ifxDomain,
bool isInfineonDomain, bool isInfineonDomain,
string? jwtAudience,
string? jwtIssuer,
string? jwtKey,
string lotTempPipeLine, string lotTempPipeLine,
string mesaTemplateFiles, string mesaTemplateFiles,
string nDriveURL, string nDriveURL,
@ -46,6 +49,7 @@ public class AppSettings {
string urls, string urls,
int userId, int userId,
bool userIsAdmin, bool userIsAdmin,
string wasmClientUrl,
string wsr_URL, string wsr_URL,
string? workingDirectoryName) { string? workingDirectoryName) {
AdminNotificationRecepient = adminNotificationRecepient; AdminNotificationRecepient = adminNotificationRecepient;
@ -67,6 +71,9 @@ public class AppSettings {
IFXContainer = ifxContainer; IFXContainer = ifxContainer;
IFXDomain = ifxDomain; IFXDomain = ifxDomain;
IsInfineonDomain = isInfineonDomain; IsInfineonDomain = isInfineonDomain;
JwtAudience = jwtAudience;
JwtIssuer = jwtIssuer;
JwtKey = jwtKey;
LotTempPipeLine = lotTempPipeLine; LotTempPipeLine = lotTempPipeLine;
MesaTemplateFiles = mesaTemplateFiles; MesaTemplateFiles = mesaTemplateFiles;
NDriveURL = nDriveURL; NDriveURL = nDriveURL;
@ -88,11 +95,12 @@ public class AppSettings {
UserId = userId; UserId = userId;
UserIsAdmin = userIsAdmin; UserIsAdmin = userIsAdmin;
WSR_URL = wsr_URL; WSR_URL = wsr_URL;
WasmClientUrl = wasmClientUrl;
WorkingDirectoryName = workingDirectoryName; WorkingDirectoryName = workingDirectoryName;
} }
public string AdminNotificationRecepient { get; } public string AdminNotificationRecepient { get; }
public string? ApiBaseUrl { get; } public string ApiBaseUrl { get; }
public string AttachmentFolder { get; } public string AttachmentFolder { get; }
public string? AttachmentUrl { get; } public string? AttachmentUrl { get; }
public string CABlankFormsLocation { get; } public string CABlankFormsLocation { get; }
@ -110,6 +118,9 @@ public class AppSettings {
public string IFXContainer { get; } public string IFXContainer { get; }
public string IFXDomain { get; } public string IFXDomain { get; }
public bool IsInfineonDomain { get; } public bool IsInfineonDomain { get; }
public string? JwtAudience { get; }
public string? JwtIssuer { get; }
public string? JwtKey { get; }
public string LotTempPipeLine { get; } public string LotTempPipeLine { get; }
public string MesaTemplateFiles { get; } public string MesaTemplateFiles { get; }
public string NAContainer { get; } public string NAContainer { get; }
@ -130,6 +141,7 @@ public class AppSettings {
public string URLs { get; } public string URLs { get; }
public int UserId { get; } public int UserId { get; }
public bool UserIsAdmin { get; } public bool UserIsAdmin { get; }
public string WasmClientUrl { get; }
public string WSR_URL { get; } public string WSR_URL { get; }
public string? WorkingDirectoryName { get; } public string? WorkingDirectoryName { get; }
@ -211,12 +223,18 @@ public class AppSettings {
throw new ArgumentNullException("SSRSPassword environment variable not found"); throw new ArgumentNullException("SSRSPassword environment variable not found");
string testEmailRecipients = ConfigurationManager.AppSettings["Test Email Recipients"] ?? string testEmailRecipients = ConfigurationManager.AppSettings["Test Email Recipients"] ??
throw new ArgumentNullException("Test Email Recipients environment variable not found"); throw new ArgumentNullException("Test Email Recipients environment variable not found");
string? apiBaseUrl = ConfigurationManager.AppSettings["FabApprovalApiBaseUrl"]?.ToString(); string apiBaseUrl = Environment.GetEnvironmentVariable("FabApprovalApiBaseUrl") ??
throw new ArgumentNullException("FabApprovalApiBaseUrl environment variable not found");
string? attachmentUrl = ConfigurationManager.AppSettings["AttachmentUrl"]?.ToString(); string? attachmentUrl = ConfigurationManager.AppSettings["AttachmentUrl"]?.ToString();
string? company = ConfigurationManager.AppSettings["Company"]?.ToString(); string? company = ConfigurationManager.AppSettings["Company"]?.ToString();
string? smtpServer = ConfigurationManager.AppSettings["SMTP Server"]?.ToString(); string? smtpServer = ConfigurationManager.AppSettings["SMTP Server"]?.ToString();
string? urls = ConfigurationManager.AppSettings["URLs"]?.ToString(); string? urls = ConfigurationManager.AppSettings["URLs"]?.ToString();
string? workingDirectoryName = ConfigurationManager.AppSettings["WorkingDirectoryName"]?.ToString(); 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, result = new(adminNotificationRecepient: adminNotificationRecepient,
apiBaseUrl: apiBaseUrl, apiBaseUrl: apiBaseUrl,
attachmentFolder: attachmentFolder, attachmentFolder: attachmentFolder,
@ -236,6 +254,9 @@ public class AppSettings {
ifxContainer: ifxContainer, ifxContainer: ifxContainer,
ifxDomain: ifxDomain, ifxDomain: ifxDomain,
isInfineonDomain: Misc.GlobalVars.IS_INFINEON_DOMAIN, isInfineonDomain: Misc.GlobalVars.IS_INFINEON_DOMAIN,
jwtAudience: jwtAudience,
jwtIssuer: jwtIssuer,
jwtKey: jwtKey,
lotTempPipeLine: lotTempPipeLine, lotTempPipeLine: lotTempPipeLine,
mesaTemplateFiles: Misc.GlobalVars.MesaTemplateFiles, mesaTemplateFiles: Misc.GlobalVars.MesaTemplateFiles,
naContainer: naContainer, naContainer: naContainer,
@ -256,6 +277,7 @@ public class AppSettings {
urls: urls, urls: urls,
userId: userId, userId: userId,
userIsAdmin: Misc.GlobalVars.USER_ISADMIN, userIsAdmin: Misc.GlobalVars.USER_ISADMIN,
wasmClientUrl: wasmClientUrl,
wsr_URL: Misc.GlobalVars.WSR_URL, wsr_URL: Misc.GlobalVars.WSR_URL,
workingDirectoryName: workingDirectoryName); workingDirectoryName: workingDirectoryName);
return result; return result;

View File

@ -231,6 +231,7 @@ public class CorrectiveAction {
public DateTime? NextDueDate { get; set; } public DateTime? NextDueDate { get; set; }
public DateTime? FollowUpDate { get; set; } public DateTime? FollowUpDate { get; set; }
public bool CASubmitted { get; set; } public bool CASubmitted { get; set; }
public string CAStandardType { get; set; }
public DateTime? ClosedDate { get; set; } public DateTime? ClosedDate { get; set; }
public CorrectiveAction() { public CorrectiveAction() {
TeamMemberIDs = new List<int>(); TeamMemberIDs = new List<int>();

View File

@ -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

View File

@ -3,6 +3,7 @@
public class LoginResult { public class LoginResult {
public bool IsAuthenticated { get; set; } public bool IsAuthenticated { get; set; }
public User User { get; set; }
public AuthTokens AuthTokens { get; set; } public AuthTokens AuthTokens { get; set; }
} }

View File

@ -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();
}

View File

@ -1,23 +1,26 @@
#if !NET8 #if !NET8
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
#endif
// -------------------------------------------------------------------------------------------------------------------- #if NET8
// <copyright file="BinaryContentResult.cs" company="SemanticArchitecture"> using Microsoft.AspNetCore.Mvc;
// http://www.SemanticArchitecture.net pkalkie@gmail.com #endif
// </copyright>
// <summary>
// An ActionResult used to send binary data to the browser.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Fab2ApprovalSystem.PdfGenerator { #if !NET8
using System.IO; using System;
using System.Web; using System.Collections.Generic;
using System.Web.Mvc; using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Threading.Tasks;
using System.IO;
#endif
/// <summary> namespace Fab2ApprovalSystem.PdfGenerator;
/// An ActionResult used to send binary data to the browser.
/// </summary> public class BinaryContentResult : ActionResult {
public class BinaryContentResult : ActionResult {
private readonly string contentType; private readonly string contentType;
private readonly byte[] contentBytes; private readonly byte[] contentBytes;
@ -26,18 +29,19 @@ namespace Fab2ApprovalSystem.PdfGenerator {
this.contentType = contentType; this.contentType = contentType;
} }
#if !NET8
public override void ExecuteResult(ControllerContext context) { public override void ExecuteResult(ControllerContext context) {
var response = context.HttpContext.Response; var response = context.HttpContext.Response;
response.Clear(); response.Clear();
response.Cache.SetCacheability(HttpCacheability.Public); response.Cache.SetCacheability(HttpCacheability.Public);
response.ContentType = this.contentType; response.ContentType = contentType;
using (var stream = new MemoryStream(this.contentBytes)) { using (var stream = new MemoryStream(contentBytes)) {
stream.WriteTo(response.OutputStream); stream.WriteTo(response.OutputStream);
stream.Flush(); stream.Flush();
} }
} }
}
}
#endif #endif
}

View File

@ -1,28 +0,0 @@
#if !NET8
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="FakeView.cs" company="SemanticArchitecture">
// http://www.SemanticArchitecture.net pkalkie@gmail.com
// </copyright>
// <summary>
// Defines the FakeView type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Fab2ApprovalSystem.PdfGenerator {
using System;
using System.IO;
using System.Web.Mvc;
public class FakeView : IView {
#region IView Members
public void Render(ViewContext viewContext, TextWriter writer) {
throw new NotImplementedException();
}
#endregion
}
}
#endif

View File

@ -1,49 +0,0 @@
#if !NET8
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="HtmlViewRenderer.cs" company="SemanticArchitecture">
// http://www.SemanticArchitecture.net pkalkie@gmail.com
// </copyright>
// <summary>
// This class is responsible for rendering a HTML view to a string.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Fab2ApprovalSystem.PdfGenerator {
using System.IO;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
/// <summary>
/// This class is responsible for rendering a HTML view into a string.
/// </summary>
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);
}
}
}
#endif

View File

@ -1,54 +0,0 @@
#if !NET8
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PdfViewController.cs" company="SemanticArchitecture">
// http://www.SemanticArchitecture.net pkalkie@gmail.com
// </copyright>
// <summary>
// Extends the controller with functionality for rendering PDF views
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Fab2ApprovalSystem.PdfGenerator {
using System.Web.Mvc;
using System.IO;
/// <summary>
/// Extends the controller with functionality for rendering PDF views
/// </summary>
public class PdfViewController : Controller {
private readonly HtmlViewRenderer htmlViewRenderer;
private readonly StandardPdfRenderer standardPdfRenderer;
public PdfViewController() {
this.htmlViewRenderer = new HtmlViewRenderer();
this.standardPdfRenderer = new StandardPdfRenderer();
}
protected ActionResult ViewPdf(string pageTitle, 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);
// Return the PDF as a binary stream to the client.
return new BinaryContentResult(buffer, "application/pdf");
}
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, "");
using (FileStream fs = new FileStream(fileName, FileMode.Create)) {
fs.Write(buffer, 0, buffer.Length);
}
}
}
}
#endif

View File

@ -1,23 +1,45 @@
#if !NET8
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
#endif
#if !NET8 #if !NET8
namespace Fab2ApprovalSystem.PdfGenerator { using iTextSharp.text;
using iTextSharp.text; using iTextSharp.text.pdf;
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
namespace Fab2ApprovalSystem.PdfGenerator;
#if !NET8
public class PrintHeaderFooter : PdfPageEventHelper {
/// <summary>
/// This class represents the standard header and footer for a PDF print.
/// application.
/// </summary>
public class PrintHeaderFooter : PdfPageEventHelper {
private PdfContentByte pdfContent; private PdfContentByte pdfContent;
private PdfTemplate pageNumberTemplate; private PdfTemplate pageNumberTemplate;
private BaseFont baseFont; private BaseFont baseFont;
private DateTime printTime; private DateTime printTime;
#endif
#if NET8
public class PrintHeaderFooter {
#endif
public string Title { get; set; } public string Title { get; set; }
#if !NET8
public override void OnOpenDocument(PdfWriter writer, Document document) { public override void OnOpenDocument(PdfWriter writer, Document document) {
printTime = DateTime.Now; printTime = DateTime.Now;
baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
@ -74,6 +96,7 @@ namespace Fab2ApprovalSystem.PdfGenerator {
pageNumberTemplate.ShowText(string.Empty + (writer.PageNumber - 1)); pageNumberTemplate.ShowText(string.Empty + (writer.PageNumber - 1));
pageNumberTemplate.EndText(); pageNumberTemplate.EndText();
} }
}
}
#endif #endif
}

View File

@ -8,20 +8,34 @@ using System.IO;
namespace Fab2ApprovalSystem.PdfGenerator; namespace Fab2ApprovalSystem.PdfGenerator;
/// <summary>
/// This class is responsible for rendering a html text string to a PDF document using the html renderer of iTextSharp.
/// </summary>
public class StandardPdfRenderer { public class StandardPdfRenderer {
private const int HorizontalMargin = 40; private const int HorizontalMargin = 40;
private const int VerticalMargin = 40; private const int VerticalMargin = 40;
public byte[] Render(string htmlText, string pageTitle) { public static byte[] GetPortableDocumentFormatBytes(string pageTitle, string htmlText) {
byte[] renderedBuffer; byte[] results;
using (MemoryStream memoryStream = GetPortableDocumentFormat(pageTitle, htmlText)) {
results = new byte[memoryStream.Position];
memoryStream.Position = 0;
memoryStream.Read(results, 0, results.Length);
}
return results;
}
using (MemoryStream outputMemoryStream = new()) { public static void WritePortableDocumentFormatToFile(string pageTitle, string htmlText, string path) {
using (MemoryStream memoryStream = GetPortableDocumentFormat(pageTitle, htmlText)) {
using (FileStream fileStream = new(path, FileMode.Create)) {
memoryStream.CopyTo(fileStream);
}
}
}
public static MemoryStream GetPortableDocumentFormat(string pageTitle, string htmlText) {
MemoryStream result = new();
#if !NET8 #if !NET8
using (Document pdfDocument = new Document(PageSize.A4, HorizontalMargin, HorizontalMargin, VerticalMargin, VerticalMargin)) { using (Document pdfDocument = new Document(PageSize.A4, HorizontalMargin, HorizontalMargin, VerticalMargin, VerticalMargin)) {
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDocument, outputMemoryStream); using (PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDocument, result)) {
pdfWriter.CloseStream = false; pdfWriter.CloseStream = false;
pdfWriter.PageEvent = new PrintHeaderFooter { Title = pageTitle }; pdfWriter.PageEvent = new PrintHeaderFooter { Title = pageTitle };
pdfDocument.Open(); pdfDocument.Open();
@ -30,15 +44,10 @@ public class StandardPdfRenderer {
htmlWorker.Parse(htmlViewReader); htmlWorker.Parse(htmlViewReader);
} }
} }
}
} }
#endif #endif
return result;
renderedBuffer = new byte[outputMemoryStream.Position];
outputMemoryStream.Position = 0;
outputMemoryStream.Read(renderedBuffer, 0, renderedBuffer.Length);
} }
return renderedBuffer;
}
} }

View File

@ -20,6 +20,7 @@ using System.Configuration;
namespace Fab2ApprovalSystem.Utilities; namespace Fab2ApprovalSystem.Utilities;
#if !NET8 #if !NET8
public class FileUtilities<T> : Controller // <T> => System.Web.Mvc.FileContentResult public class FileUtilities<T> : Controller // <T> => System.Web.Mvc.FileContentResult
{ {
@ -28,14 +29,22 @@ public class FileUtilities<T> : Controller // <T> => System.Web.Mvc.FileContentR
var result = File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, pathToFile); var result = File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, pathToFile);
return (T)Convert.ChangeType(result, typeof(T)); return (T)Convert.ChangeType(result, typeof(T));
} }
#else
#endif
#if NET8
public class FileUtilities<T> { public class FileUtilities<T> {
#endif #endif
public byte[] GetFile(string s) { public byte[] GetFile(string s) {
#if !NET8 #if !NET8
FileStream fs = System.IO.File.OpenRead(s); FileStream fs = System.IO.File.OpenRead(s);
#else #endif
#if NET8
FileStream fs = File.OpenRead(s); FileStream fs = File.OpenRead(s);
#endif #endif
byte[] data = new byte[fs.Length]; byte[] data = new byte[fs.Length];

View File

@ -30,7 +30,7 @@ public class ECNPdf {
public string AffectedDepartments { get; set; } public string AffectedDepartments { get; set; }
public string AffectedAreas { get; set; } public string AffectedAreas { get; set; }
public string AffectedTechnologies { get; set; } public string AffectedTechnologies { get; set; }
public string TrainingBy { get; set; } public List<int> TrainingByIDs { get; set; }
public string AcknowledgementBy { get; set; } public string AcknowledgementBy { get; set; }
public bool IsECN { get; set; } public bool IsECN { get; set; }
public bool IsTECN { get; set; } public bool IsTECN { get; set; }
@ -79,6 +79,7 @@ public class ECNPdf {
public int? ConvertedToNumber { get; set; } public int? ConvertedToNumber { get; set; }
public int? ConvertedFromNumber { get; set; } public int? ConvertedFromNumber { get; set; }
public int WorkFlowNumber { get; set; } public int WorkFlowNumber { get; set; }
public int? CategoryID { get; set; }
public bool FIChangeRequired { get; set; } public bool FIChangeRequired { get; set; }
public string NumberOfLotsAffected { get; set; } public string NumberOfLotsAffected { get; set; }
public string RecipeChange { get; set; } public string RecipeChange { get; set; }
@ -87,6 +88,7 @@ public class ECNPdf {
public ECNPdf() { public ECNPdf() {
Approvalog = new List<ECNApprovalLog>(); Approvalog = new List<ECNApprovalLog>();
Attachments = new List<string>(); Attachments = new List<string>();
TrainingByIDs = new List<int>();
} }
} }

View File

@ -34,7 +34,7 @@
</div> </div>
<div class="navbar-collapse collapse"> <div class="navbar-collapse collapse">
<ul class="nav navbar-nav"> <ul class="nav navbar-nav">
@if ((bool)@Session[GlobalVars.IS_ADMIN]) @if (@GlobalVars.IsAdmin(Session))
{ {
<li>@Html.ActionLink("Admin", "Index", "Admin")</li> <li>@Html.ActionLink("Admin", "Index", "Admin")</li>
} }

View File

@ -144,7 +144,7 @@
</div> </div>
<div class="col-sm-9"> <div class="col-sm-9">
@Html.TextBoxFor(model => model.OwnerName, new { id = "txtOwner", @class = "k-textbox", Readonly = "Readonly", style = "background-color:lightblue" }) @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))
{ {
<a href="javascript:undefined" id="lnkReassignOwner" class="linkbutton edit" title="Re-assign Owner"></a> <a href="javascript:undefined" id="lnkReassignOwner" class="linkbutton edit" title="Re-assign Owner"></a>
} }
@ -200,7 +200,7 @@
<label class="control-label pull-right">Export Control:</label> <label class="control-label pull-right">Export Control:</label>
</div> </div>
<div class="col-sm-9"> <div class="col-sm-9">
@if (ViewBag.IsOriginator == "true" || ((bool)Session[GlobalVars.IS_ADMIN])) @if (ViewBag.IsOriginator == "true" || (GlobalVars.IsAdmin(Session)))
{ {
@(Html.Kendo().DropDownList() @(Html.Kendo().DropDownList()
.Name("IsITAR") .Name("IsITAR")

View File

@ -329,7 +329,7 @@
columns.Bound(a => a.Gating).Width("50px"); columns.Bound(a => a.Gating).Width("50px");
columns.Bound(a => a.DueDate).Width("50px").Format("{0:MM/dd/yy}").Width("150px"); 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.Custom("Edit").Click("EditMeetingActionItem")).Width("70px");
//columns.Command(c => c.Destroy()).Width("40px"); //columns.Command(c => c.Destroy()).Width("40px");

View File

@ -128,7 +128,7 @@
</div> </div>
<div class="col-sm-9"> <div class="col-sm-9">
@Html.TextBoxFor(model => model.OwnerName, new { id = "txtOwner", @class = "k-textbox", Readonly = "Readonly", style = "background-color:lightblue" }) @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))
{ {
<a href="javascript:undefined" id="lnkReassignOwner" class="linkbutton edit" title="Re-assign Owner"></a> <a href="javascript:undefined" id="lnkReassignOwner" class="linkbutton edit" title="Re-assign Owner"></a>
} }

View File

@ -380,6 +380,43 @@
</div> </div>
</div> </div>
</div> </div>
<div class="col-sm-3">
<div class="row">
<div class="col-sm-3">
<label class="control-label pull-right">CA Standard Type:</label>
</div>
<div class="col-sm-9">
@(Html.Kendo().DropDownList()
.Name("CAStandardTypeList")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(new List<SelectListItem>()
{
new SelectListItem()
{
Text = "IATF16949",
Value = "IATF16949"
},
new SelectListItem()
{
Text = "ISO14001",
Value = "ISO14001"
},
new SelectListItem()
{
Text = "ISO45001",
Value = "ISO45001"
}
}
)
.OptionLabel("Select")
.Value(Model.CAStandardType)
)
</div>
</div>
</div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-sm-3"> <div class="col-sm-3">
@ -1428,7 +1465,7 @@
Additional Approvers Additional Approvers
</button> </button>
} }
else if ((((bool)Session[GlobalVars.IS_ADMIN] && (Request.IsAuthenticated))) && Model.ClosedDate == null) else if (((GlobalVars.IsAdmin(Session) && (Request.IsAuthenticated))) && Model.ClosedDate == null)
{ {
<button class="k-textbox" data-toggle="modal" id="additionalApprovers"> <button class="k-textbox" data-toggle="modal" id="additionalApprovers">
Additional Approvers Additional Approvers
@ -1438,7 +1475,7 @@
</div> </div>
<div class="panel-body bg-warning"> <div class="panel-body bg-warning">
<div class="col-sm-offset-0"> <div class="col-sm-offset-0">
@if ((bool)Session[GlobalVars.IS_ADMIN] && (Request.IsAuthenticated)) @if (GlobalVars.IsAdmin(Session) && (Request.IsAuthenticated))
{ {
@(Html.Kendo().Grid<Fab2ApprovalSystem.ViewModels.ApproversListViewModel>() @(Html.Kendo().Grid<Fab2ApprovalSystem.ViewModels.ApproversListViewModel>()
.Name("ApproversList") .Name("ApproversList")
@ -2143,7 +2180,7 @@
var currentD5D6AttachmentLinks; var currentD5D6AttachmentLinks;
var currentD7AttachmentLinks; var currentD7AttachmentLinks;
var currentRejectingSection = ''; var currentRejectingSection = '';
var currentUserId = @((int)Session[GlobalVars.SESSION_USERID]) var currentUserId = @(GlobalVars.GetUserId(Session))
var currentRequestor = @(Model.RequestorID); var currentRequestor = @(Model.RequestorID);
@ -2176,6 +2213,7 @@
$('#txtApprovedDate').attr("disabled", true); $('#txtApprovedDate').attr("disabled", true);
$('#txtRelatedMRB').attr("disabled", true); $('#txtRelatedMRB').attr("disabled", true);
$('#CATypeList').data("kendoDropDownList").enable(false); $('#CATypeList').data("kendoDropDownList").enable(false);
$('#CAStandardTypeList').data("kendoDropDownList").enable(false);
$('#d0Comments').attr("disabled", true); $('#d0Comments').attr("disabled", true);
} }
@ -3689,6 +3727,7 @@
TeamCaptainID: $("#TeamCaptainList").data("kendoDropDownList").value(), TeamCaptainID: $("#TeamCaptainList").data("kendoDropDownList").value(),
CASponsorID: $("#CASponsorList").data("kendoDropDownList").value(), CASponsorID: $("#CASponsorList").data("kendoDropDownList").value(),
CASubmitted: isCASubmitted, CASubmitted: isCASubmitted,
CAStandardType : $("#CAStandardTypeList").data("kendoDropDownList").value(),
//D0 //D0
D0Comments : $("#d0Comments").val(), D0Comments : $("#d0Comments").val(),

View File

@ -44,7 +44,7 @@
<div class="panel panel-default center-block" data-spy="affix"> <div class="panel panel-default center-block" data-spy="affix">
<input type="button" value="Back to CA List" class="btn btn-primary btn-xs" id="CAList" /> <input type="button" value="Back to CA List" class="btn btn-primary btn-xs" id="CAList" />
<input type="button" value="Section Approval Log" class="btn btn-primary btn-xs" id="ShowSectionApprovalLog" /> <input type="button" value="Section Approval Log" class="btn btn-primary btn-xs" id="ShowSectionApprovalLog" />
@if (Session[GlobalVars.IS_ADMIN] != null) @if (GlobalVars.IsAdminValueNotNull(Session))
{ {
<input type="button" value="Unlock Document" class="btn btn-primary btn-xs" id="UnlockDocumentBtn" onclick="UnlockDocument()" /> <input type="button" value="Unlock Document" class="btn btn-primary btn-xs" id="UnlockDocumentBtn" onclick="UnlockDocument()" />
} }
@ -325,6 +325,16 @@
</div> </div>
</div> </div>
</div> </div>
<div class="col-sm-3">
<div class="row">
<div class="col-sm-3">
<label class="control-label pull-right">CA Standard Type:</label>
</div>
<div class="col-sm-9">
@Html.TextBoxFor(model => model.CAStandardType, new { id = "txtCAStandardType", @class = "k-textbox", Readonly = "Readonly", style = "background-color:lightblue" })
</div>
</div>
</div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-sm-3"> <div class="col-sm-3">

View File

@ -52,7 +52,7 @@
} }
<input type="button" value="Approval Log History" class="btn btn-primary btn-xs" id="ApprovalLogHistoryData" /> <input type="button" value="Approval Log History" class="btn btn-primary btn-xs" id="ApprovalLogHistoryData" />
@if (Session[GlobalVars.IS_ADMIN] != null) @if (GlobalVars.IsAdminValueNotNull(Session))
{ {
<input type="button" value="Unlock Document" class="btn btn-primary btn-xs" id="UnlockDocumentBtn" onclick="UnlockDocument()" /> <input type="button" value="Unlock Document" class="btn btn-primary btn-xs" id="UnlockDocumentBtn" onclick="UnlockDocument()" />
} }
@ -137,7 +137,7 @@
<label class="control-label col-sm-4">Originator Name:</label> <label class="control-label col-sm-4">Originator Name:</label>
<div class="col-sm-8"> <div class="col-sm-8">
@Html.TextBoxFor(model => model.OriginatorName, new { id = "txtOriginatorName", @class = "k-textbox", disabled = "disabled", style = "background-color:lightblue" }) @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))
{ {
<a href="javascript:undefined" id="lnkReassignOriginator" class="linkbutton edit" title="Re-assign Originator"></a> <a href="javascript:undefined" id="lnkReassignOriginator" class="linkbutton edit" title="Re-assign Originator"></a>
} }
@ -210,10 +210,10 @@
@Html.TextBoxFor(model => model.Title, new { id = "txtTitle", @class = "k-textbox", style = "width:100%", disabled = "disabled" }) @Html.TextBoxFor(model => model.Title, new { id = "txtTitle", @class = "k-textbox", style = "width:100%", disabled = "disabled" })
</div> </div>
<div class="col-sm-6 col-sm-offset-4" style="color: red;"> <div class="col-sm-6 col-sm-offset-4" style="color: red;">
*(DO NOT USE Rev I, O, Q, S, X, and Z) * (DO NOT USE Rev I, O, S, X, and Z)
</div> </div>
<div class="col-sm-6 col-sm-offset-4" style="color: red;"> <div class="col-sm-6 col-sm-offset-4" style="color: red;">
Revision Y is followed by AA. YY is followed by AAA Revision Y is followed by AA-AY, AY is followed by BA-BY etc. YY is followed by AAA
</div> </div>
</div> </div>
<div class="form-group"> <div class="form-group">
@ -892,9 +892,9 @@
<div class="col-sm-offset-0"> <div class="col-sm-offset-0">
@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<Fab2ApprovalSystem.ViewModels.ApproversListViewModel>() @(Html.Kendo().Grid<Fab2ApprovalSystem.ViewModels.ApproversListViewModel>()
.Name("ApproversList") .Name("ApproversList")

View File

@ -1,5 +1,19 @@
@model Fab2ApprovalSystem.ViewModels.ECNPdf @model Fab2ApprovalSystem.ViewModels.ECNPdf
<table style="width:100%;"> @{
Layout = null;
}
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
</head>
<body class="navbar-inner">
<table style="width:100%;">
<tr> <tr>
<td> <td>
<table cellpadding="3" cellspacing="3" border="1"> <table cellpadding="3" cellspacing="3" border="1">
@ -84,6 +98,16 @@
</font> </font>
</td> </td>
</tr> </tr>
<tr>
<td>
<font size="2">
Category:&nbsp;
</font>
<font size="1">
@(ViewBag.Category)
</font>
</td>
</tr>
<tr> <tr>
<td> <td>
<font size="2"> <font size="2">
@ -97,7 +121,6 @@
</table> </table>
</td> </td>
</tr> </tr>
</table> </table>
</td> </td>
</tr> </tr>
@ -217,14 +240,13 @@
</td> </td>
</tr> </tr>
</table> </table>
</td> </td>
</tr> </tr>
<tr> <tr>
<td> <td>
<table border="1" > <table border="1">
<tr bgcolor="#c4baba" color="#000000"> <tr bgcolor="#c4baba" color="#000000">
<td> Description of Change</td> <td> Description of Change</td>
<td> Reason for Change</td> <td> Reason for Change</td>
@ -244,35 +266,6 @@
</table> </table>
</td> </td>
</tr> </tr>
@*<tr>
<td>
<table border="1">
<tr bgcolor="#c4baba" color="#000000">
<td colspan="3">Training Notification</td>
</tr>
<tr>
<td>
<table border="0">
<tr>
<td>
<font size="1">
Training:
@(Model.TrainingRequired ? "Yes" : "No")
</font>
<font size="1">
@(Model.TrainingBy.Length > 0 ? "(" + Model.TrainingBy + ")" : Model.TrainingBy)
</font>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>*@
<tr> <tr>
<td> <td>
@ -286,7 +279,7 @@
PCRB: PCRB:
</font> </font>
<font size="1"> <font size="1">
@(Model.PCRBRequired ? "Yes": "No") @(Model.PCRBRequired ? "Yes" : "No")
</font> </font>
</td> </td>
<td> <td>
@ -300,7 +293,7 @@
Metrology Change: &nbsp;&nbsp; Metrology Change: &nbsp;&nbsp;
</font> </font>
<font size="1"> <font size="1">
@(Model.MetrologyChangeRequired ? "Yes": "No") @(Model.MetrologyChangeRequired ? "Yes" : "No")
</font> </font>
</td> </td>
<td> <td>
@ -308,7 +301,7 @@
SPC Change: SPC Change:
</font> </font>
<font size="1"> <font size="1">
@(Model.SPCChangeRequired ? "Yes": "No") @(Model.SPCChangeRequired ? "Yes" : "No")
</font> </font>
</td> </td>
<td> <td>
@ -327,11 +320,35 @@
@(Model.SPNChangeRequired ? "Yes" : "No") @(Model.SPNChangeRequired ? "Yes" : "No")
</font> </font>
</td> </td>
<td></td>
</tr> </tr>
</table> </table>
</td>
</tr>
<tr>
<td>
<table border="1">
<tr bgcolor="#c4baba" color="#000000">
<td colspan="1">Training Notification</td>
</tr>
<tr style="display:block;">
<td>
<font size="2">
Training:
</font>
<font size="1">
@(Model.TrainingRequired ? "Yes" : "No")
</font>
</td>
<td>
<font size="2">
Training Notification to: &nbsp;
@(ViewBag.TrainingNotificationTo)
</font>
</td>
</tr>
</table>
</td> </td>
</tr> </tr>
@ -479,19 +496,11 @@
</tr> </tr>
} }
</table> </table>
</td> </td>
</tr> </tr>
</table>
</body>
</table> <!--main table --> </html>

View File

@ -31,7 +31,7 @@
<label class="control-label col-sm-4">Originator Name:</label> <label class="control-label col-sm-4">Originator Name:</label>
<div class="col-sm-8"> <div class="col-sm-8">
@Html.TextBoxFor(model => model.OriginatorName, new { id = "txtOriginatorName", @class = "k-textbox", disabled = "disabled", style = "background-color:lightblue" }) @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))
{ {
<a href="javascript:undefined" id="lnkReassignOriginator" class="linkbutton edit" title="Re-assign Originator"></a> <a href="javascript:undefined" id="lnkReassignOriginator" class="linkbutton edit" title="Re-assign Originator"></a>
} }

View File

@ -90,7 +90,7 @@
<label class="control-label col-sm-4">Originator Name:</label> <label class="control-label col-sm-4">Originator Name:</label>
<div class="col-sm-8"> <div class="col-sm-8">
@Html.TextBoxFor(model => model.OriginatorName, new { id = "txtOriginatorName", @class = "k-textbox", disabled = "disabled", style = "background-color:lightblue" }) @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))
{ {
<a href="javascript:undefined" id="lnkReassignOriginator" class="linkbutton edit" title="Re-assign Originator"></a> <a href="javascript:undefined" id="lnkReassignOriginator" class="linkbutton edit" title="Re-assign Originator"></a>
} }
@ -154,10 +154,10 @@
@Html.TextBoxFor(model => model.Title, new { id = "txtTitle", @class = "k-textbox", style = "width:100%" }) @Html.TextBoxFor(model => model.Title, new { id = "txtTitle", @class = "k-textbox", style = "width:100%" })
</div> </div>
<div class="col-sm-6 col-sm-offset-4" style="color: red;"> <div class="col-sm-6 col-sm-offset-4" style="color: red;">
*(DO NOT USE Rev I, O, Q, S, X, and Z) * (DO NOT USE Rev I, O, S, X, and Z)
</div> </div>
<div class="col-sm-6 col-sm-offset-4" style="color: red;"> <div class="col-sm-6 col-sm-offset-4" style="color: red;">
Revision Y is followed by AA. YY is followed by AAA Revision Y is followed by AA-AY, AY is followed by BA-BY etc. YY is followed by AAA
</div> </div>
</div> </div>
<div class="form-group"> <div class="form-group">
@ -785,9 +785,9 @@
<div class="panel-body bg-warning"> <div class="panel-body bg-warning">
<div class="col-sm-offset-0"> <div class="col-sm-offset-0">
@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<Fab2ApprovalSystem.ViewModels.ApproversListViewModel>() @(Html.Kendo().Grid<Fab2ApprovalSystem.ViewModels.ApproversListViewModel>()
.Name("ApproversList") .Name("ApproversList")

View File

@ -86,30 +86,48 @@
if (Model.IsTECN && !Model.CancellationInProgress && !Model.CancellationApproved && !Model.ExpirationInProgress if (Model.IsTECN && !Model.CancellationInProgress && !Model.CancellationApproved && !Model.ExpirationInProgress
&& !Model.ExpirationProcessed && !Model.Converted && !Model.ExpirationProcessed && !Model.Converted
&& !Model.LockedForConversion && !Model.LockedForConversion)
&& (Model.ExpirationDate > DateTime.Today || Model.ExtensionDate > DateTime.Today))
{ {
ViewBag.CanResubmit = "true"; ViewBag.CanResubmit = "true";
<input type="button" value="Change Type" class="btn btn-primary btn-xs" id="ReSubmitDocument" disabled="disabled" /> <input type="button" value="Change Type" class="btn btn-primary btn-xs" id="ReSubmitDocument" disabled="disabled" />
if (Model.ExpirationDate > DateTime.Today || Model.ExtensionDate > DateTime.Today)
{
<input type="button" value="Cancel Document" class="btn btn-primary btn-xs" id="CancelDocument" /> <input type="button" value="Cancel Document" class="btn btn-primary btn-xs" id="CancelDocument" />
} }
else
{
<input type="button" value="Return to Process" class="btn btn-primary btn-xs" id="ReturnToProcessDocument" />
}
}
else if (Model.IsTECN && !Model.CancellationInProgress && !Model.CancellationApproved && !Model.ExpirationInProgress else if (Model.IsTECN && !Model.CancellationInProgress && !Model.CancellationApproved && !Model.ExpirationInProgress
&& !Model.ExpirationProcessed && !Model.ExpirationProcessed
&& Model.ConversionApprovalInProgress == false && Model.ConversionApprovalInProgress == false)
&& (Model.ExpirationDate >= DateTime.Today || Model.ExtensionDate >= DateTime.Today)) {
if (Model.ExpirationDate > DateTime.Today || Model.ExtensionDate > DateTime.Today)
{ {
<input type="button" value="Cancel Document" class="btn btn-primary btn-xs" id="CancelDocument" /> <input type="button" value="Cancel Document" class="btn btn-primary btn-xs" id="CancelDocument" />
} }
else
{
<input type="button" value="Return to Process" class="btn btn-primary btn-xs" id="ReturnToProcessDocument" />
}
}
else if (Model.IsEmergencyTECN && !Model.CancellationInProgress && !Model.CancellationApproved && !Model.ExpirationInProgress else if (Model.IsEmergencyTECN && !Model.CancellationInProgress && !Model.CancellationApproved && !Model.ExpirationInProgress
&& !Model.ExpirationProcessed && !Model.Converted && !Model.ExpirationProcessed && !Model.Converted)
&& (Model.ExpirationDate > DateTime.Today || Model.ExtensionDate > DateTime.Today))
{ {
ViewBag.CanResubmit = "true"; ViewBag.CanResubmit = "true";
<input type="button" value="Change Type" class="btn btn-primary btn-xs" id="ReSubmitDocument" disabled="disabled" /> <input type="button" value="Change Type" class="btn btn-primary btn-xs" id="ReSubmitDocument" disabled="disabled" />
if (Model.ExpirationDate > DateTime.Today || Model.ExtensionDate > DateTime.Today)
{
<input type="button" value="Cancel Document" class="btn btn-primary btn-xs" id="CancelDocument" /> <input type="button" value="Cancel Document" class="btn btn-primary btn-xs" id="CancelDocument" />
} }
else
{
<input type="button" value="Return to Process" class="btn btn-primary btn-xs" id="ReturnToProcessDocument" />
}
}
} }
<input type="button" value="PRINT PDF" class="btn btn-primary btn-xs" id="PrintPDF" /> <input type="button" value="PRINT PDF" class="btn btn-primary btn-xs" id="PrintPDF" />
@ -155,7 +173,7 @@
<label class="control-label col-sm-4">Originator Name:</label> <label class="control-label col-sm-4">Originator Name:</label>
<div class="col-sm-6 col-sm-8"> <div class="col-sm-6 col-sm-8">
@Html.TextBoxFor(model => model.OriginatorName, new { id = "txtOriginatorName", @class = "k-textbox", disabled = "disabled", style = "background-color:lightblue" }) @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))
{ {
<a href="javascript:undefined" id="lnkReassignOriginator" class="linkbutton edit" title="Re-assign Originator"></a> <a href="javascript:undefined" id="lnkReassignOriginator" class="linkbutton edit" title="Re-assign Originator"></a>
} }
@ -242,10 +260,10 @@
@Html.TextBoxFor(model => model.Title, new { id = "txtTitle", @class = "k-textbox", style = "width:100%", disabled = "disabled" }) @Html.TextBoxFor(model => model.Title, new { id = "txtTitle", @class = "k-textbox", style = "width:100%", disabled = "disabled" })
</div> </div>
<div class="col-sm-6 col-sm-offset-4" style="color: red;"> <div class="col-sm-6 col-sm-offset-4" style="color: red;">
*(DO NOT USE Rev I, O, Q, S, X, and Z) * (DO NOT USE Rev I, O, S, X, and Z)
</div> </div>
<div class="col-sm-6 col-sm-offset-4" style="color: red;"> <div class="col-sm-6 col-sm-offset-4" style="color: red;">
Revision Y is followed by AA. YY is followed by AAA Revision Y is followed by AA-AY, AY is followed by BA-BY etc. YY is followed by AAA
</div> </div>
</div> </div>
<div class="form-group"> <div class="form-group">
@ -349,7 +367,7 @@
@if ( @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)) (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) @(Html.Kendo().DatePickerFor(model => model.ExtensionDate)
@ -962,7 +980,7 @@
Additional Approvers Additional Approvers
</button> </button>
} }
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)
{ {
<button class="k-textbox" data-toggle="modal" id="additionalApprovers"> <button class="k-textbox" data-toggle="modal" id="additionalApprovers">
Additional Approvers Additional Approvers
@ -976,9 +994,9 @@
<div class="panel-body bg-warning"> <div class="panel-body bg-warning">
<div class="col-sm-offset-0"> <div class="col-sm-offset-0">
@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<Fab2ApprovalSystem.ViewModels.ApproversListViewModel>() @(Html.Kendo().Grid<Fab2ApprovalSystem.ViewModels.ApproversListViewModel>()
.Name("ApproversList") .Name("ApproversList")
@ -1251,6 +1269,9 @@
</div> </div>
</div> </div>
@Html.Partial("_ECNCancel")
@Html.Partial("_ECNReturnToProcess")
@Html.Partial("_ECNReassignOriginator") @Html.Partial("_ECNReassignOriginator")
<script type="text/javascript"> <script type="text/javascript">
@ -2188,40 +2209,6 @@
return false; return false;
}); });
$('#CancelDocument').on('click', function () {
docType = 5;
if (confirm("Are you sure you want to Cancel this document?")) {
$.ajax({
url: "/ECN/CancelDocument",
type: "GET",
datatype: "json",
data: {
ecnNumber: $("#txtECNNumber").val(),
currentStep: 1,
documentType: docType,
ecnTypeString: ecnTypeString
},
success: function (data) {
if (data == 'Redirect') {
var url = '@Url.Action("ReadOnly", "ECN", new { issueID = "__id__" })';
url = url.replace('amp;', '');
window.location.href = url.replace('__id__', $("#txtECNNumber").val());
}
else {
// TODO alert an error message
}
},
error: function (result) {
alert("Failed on Cancel" + result);
}
});
}
return false;
});
var returnNoOfDays = function () { var returnNoOfDays = function () {
//var start = new Date($('#txSubmitDate').val()); //var start = new Date($('#txSubmitDate').val());
var start = new Date(); var start = new Date();

View File

@ -52,7 +52,7 @@
} }
<input type="button" value="Approval Log History" class="btn btn-primary btn-xs" id="ApprovalLogHistoryData" /> <input type="button" value="Approval Log History" class="btn btn-primary btn-xs" id="ApprovalLogHistoryData" />
@if (Session[GlobalVars.IS_ADMIN] != null) @if (GlobalVars.IsAdminValueNotNull(Session))
{ {
<input type="button" value="Unlock Document" class="btn btn-primary btn-xs" id="UnlockDocumentBtn" onclick="UnlockDocument()" /> <input type="button" value="Unlock Document" class="btn btn-primary btn-xs" id="UnlockDocumentBtn" onclick="UnlockDocument()" />
} }
@ -149,7 +149,7 @@
<label class="control-label col-sm-4">Originator Name:</label> <label class="control-label col-sm-4">Originator Name:</label>
<div class="col-sm-8"> <div class="col-sm-8">
@Html.TextBoxFor(model => model.OriginatorName, new { id = "txtOriginatorName", @class = "k-textbox", disabled = "disabled", style = "background-color:lightblue" }) @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))
{ {
<a href="javascript:undefined" id="lnkReassignOriginator" class="linkbutton edit" title="Re-assign Originator"></a> <a href="javascript:undefined" id="lnkReassignOriginator" class="linkbutton edit" title="Re-assign Originator"></a>
} }
@ -895,9 +895,9 @@
<div class="col-sm-offset-0"> <div class="col-sm-offset-0">
@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<Fab2ApprovalSystem.ViewModels.ApproversListViewModel>() @(Html.Kendo().Grid<Fab2ApprovalSystem.ViewModels.ApproversListViewModel>()
.Name("ApproversList") .Name("ApproversList")
@ -999,7 +999,7 @@
@{ @{
if (ViewBag.TrainingID != 0) if (ViewBag.TrainingID != 0)
{ {
Html.RenderAction("ViewTrainingPartial", "Training", new { trainingId = Convert.ToInt32(ViewBag.TrainingID), userID = Convert.ToInt32((int)Session[GlobalVars.SESSION_USERID]) }); Html.RenderAction("ViewTrainingPartial", "Training", new { trainingId = Convert.ToInt32(ViewBag.TrainingID), userID = Convert.ToInt32(GlobalVars.GetUserId(Session)) });
} }

View File

@ -0,0 +1,75 @@
<div class="modal fade" id="Cancel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title" id="myModalLabel"><center>Has the process returned to the original state?</center></h4>
</div>
<div class="modal-body">
<div class="control-group">
<div class="row">
<div class="col-sm-13">
<h4 class="modal-title">Comments (Required):</h4>
<textarea class="form-control" rows="5" id="comments" style="resize: none;"></textarea>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">No</button>
<button type="button" class="btn btn-primary" id="ConfirmCancel">Confirm Cancel (Yes)</button>
</div>
</div>
</div>
</div>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#CancelDocument").click(function (e) {
$("#comments").val("");
$("#Cancel").modal('show');
});
$('#ConfirmCancel').on('click', function () {
if ($("#comments").val() == "") {
alert("Comments are required");
return;
}
$('#ConfirmCancel').attr("disabled", true);
$.ajax({
url: "/ECN/CancelDocument",
type: "GET",
datatype: "json",
data: {
ecnNumber: $("#txtECNNumber").val(),
currentStep: 1,
documentType: 5,
ecnTypeString: ecnTypeString,
comments: $("#comments").val(),
},
success: function (data) {
$("#Cancel").modal('hide');
var url = '@Url.Action("ReadOnly", "ECN", new { issueID = "__id__" })';
url = url.replace('amp;', '');
window.location.href = url.replace('__id__', $("#txtECNNumber").val());
},
error: function (result) {
$('#ConfirmCancel').attr("disabled", false);
alert("Server error while canceling document");
}
});
});
});
</script>

View File

@ -0,0 +1,75 @@
<div class="modal fade" id="ReturnToProcess" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title" id="myModalLabel"><center>Has the process returned to the original state?</center></h4>
</div>
<div class="modal-body">
<div class="control-group">
<div class="row">
<div class="col-sm-13">
<h4 class="modal-title">Comments (Required):</h4>
<textarea class="form-control" rows="5" id="ReturnToProcessComments" style="resize: none;"></textarea>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">No</button>
<button type="button" class="btn btn-primary" id="ConfirmReturnToProcess">Confirm Return to Process (Yes)</button>
</div>
</div>
</div>
</div>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#ReturnToProcessDocument").click(function (e) {
$("#ReturnToProcessComments").val("");
$("#ReturnToProcess").modal('show');
});
$('#ConfirmReturnToProcess').on('click', function () {
if ($("#ReturnToProcessComments").val() == "") {
alert("Comments are required");
return;
}
$('#ConfirmReturnToProcess').attr("disabled", true);
$.ajax({
url: "/ECN/CancelDocument",
type: "GET",
datatype: "json",
data: {
ecnNumber: $("#txtECNNumber").val(),
currentStep: 1,
documentType: 5,
ecnTypeString: ecnTypeString,
comments: $("#ReturnToProcessComments").val(),
},
success: function (data) {
$("#ReturnToProcess").modal('hide');
var url = '@Url.Action("ReadOnly", "ECN", new { issueID = "__id__" })';
url = url.replace('amp;', '');
window.location.href = url.replace('__id__', $("#txtECNNumber").val());
},
error: function (result) {
$('#ConfirmReturnToProcess').attr("disabled", false);
alert("Server error while ReturnToProcessing document");
}
});
});
});
</script>

View File

@ -33,7 +33,7 @@
</div> </div>
<div id="alltasklistdiv" class="k-content" style="font-size: 11px;"> <div id="alltasklistdiv" class="k-content" style="font-size: 11px;">
@if ((bool)Session[GlobalVars.IS_ADMIN]) @if (GlobalVars.IsAdmin(Session))
{ {
@(Html.Kendo().Grid<Fab2ApprovalSystem.ViewModels.IssuesViewModel>() @(Html.Kendo().Grid<Fab2ApprovalSystem.ViewModels.IssuesViewModel>()
.Name("alltasklist") .Name("alltasklist")

View File

@ -38,7 +38,7 @@
columns.Bound(l => l.D8DueDate).Format("{0:MM/dd/yy}"); columns.Bound(l => l.D8DueDate).Format("{0:MM/dd/yy}");
columns.Bound(l => l.NextDueDate).Format("{0:MM/dd/yy}"); columns.Bound(l => l.NextDueDate).Format("{0:MM/dd/yy}");
columns.Bound(l => l.ClosedDate).Format("{0:MM/dd/yy}"); columns.Bound(l => l.ClosedDate).Format("{0:MM/dd/yy}");
if ((bool)Session[GlobalVars.IS_ADMIN]) if (GlobalVars.IsAdmin(Session))
columns.Template(t => { }).HeaderTemplate("").ClientTemplate(@"<a href='javascript: void(0)' class='abutton delete' onclick='deleteRowCA(this)' title='button delete'>button delete</a>"); columns.Template(t => { }).HeaderTemplate("").ClientTemplate(@"<a href='javascript: void(0)' class='abutton delete' onclick='deleteRowCA(this)' title='button delete'>button delete</a>");
}) })

View File

@ -33,7 +33,7 @@
</div> </div>
<div id="ecnTasklistdiv" class="k-content" style="font-size: 11px;"> <div id="ecnTasklistdiv" class="k-content" style="font-size: 11px;">
@if ((bool)Session[GlobalVars.IS_ADMIN]) @if (GlobalVars.IsAdmin(Session))
{ {
@(Html.Kendo().Grid<Fab2ApprovalSystem.ViewModels.IssuesViewModel>() @(Html.Kendo().Grid<Fab2ApprovalSystem.ViewModels.IssuesViewModel>()
.Name("ecnTasklist") .Name("ecnTasklist")

View File

@ -26,7 +26,7 @@
<ul class="nav navbar-nav" id="myTab"> <ul class="nav navbar-nav" id="myTab">
<li><a href=@Url.Action("Index", "Home", new {tabName = "MyTasks"})>My Tasks</a></li> <li><a href=@Url.Action("Index", "Home", new {tabName = "MyTasks"})>My Tasks</a></li>
<li><a href=@Url.Action("Index", "Home", new { tabName = "AllTasks" })>All Documents</a></li> <li><a href=@Url.Action("Index", "Home", new { tabName = "AllTasks" })>All Documents</a></li>
@*<li><a href=@Url.Action("ViewMyTrainingAssignments", "Training", new { userID = (int)Session[GlobalVars.SESSION_USERID] })>My Training</a></li>*@ @*<li><a href=@Url.Action("ViewMyTrainingAssignments", "Training", new { userID = GlobalVars.GetUserId(Session) })>My Training</a></li>*@
@*<li><a href=@Url.Action("SpecialWorkRequestList", "Home", new { tabName = "AllTasks" })>Special Work Requests</a></li>*@ @*<li><a href=@Url.Action("SpecialWorkRequestList", "Home", new { tabName = "AllTasks" })>Special Work Requests</a></li>*@
@*<li><a href="file:////temirwfp001.irworld.irf.com/UserData/QA/CommonRO/Projects/AVI Tool/">AVI Tool</a></li>*@ @*<li><a href="file:////temirwfp001.irworld.irf.com/UserData/QA/CommonRO/Projects/AVI Tool/">AVI Tool</a></li>*@
<li class="dropdown"> <li class="dropdown">
@ -44,7 +44,7 @@
@*<div class="form-group"> @*<div class="form-group">
<input type="text" class="form-control" placeholder="Search" style="font-size: 11px"> <input type="text" class="form-control" placeholder="Search" style="font-size: 11px">
</div>*@ </div>*@
@if (!(bool)Session[GlobalVars.OOO]) @if (!GlobalVars.IsOOO(Session))
{ {
<button class="btn btn-default btn-primary" data-toggle="modal" id="OOO">Out Of Office</button> <button class="btn btn-default btn-primary" data-toggle="modal" id="OOO">Out Of Office</button>
} }
@ -170,7 +170,7 @@
</div> </div>
<div id="alltasklistdiv" class="k-content" style="font-size: 11px;"> <div id="alltasklistdiv" class="k-content" style="font-size: 11px;">
@if ((bool)Session[GlobalVars.IS_ADMIN]) @if (GlobalVars.IsAdmin(Session))
{ {
@(Html.Kendo().Grid<Fab2ApprovalSystem.ViewModels.IssuesViewModel>() @(Html.Kendo().Grid<Fab2ApprovalSystem.ViewModels.IssuesViewModel>()
.Name("alltasklist") .Name("alltasklist")
@ -427,7 +427,7 @@
var issueID=""; var issueID="";
var docType = ""; var docType = "";
var submitdate = ""; var submitdate = "";
var userName = "@Session[@GlobalVars.SESSION_USERNAME].ToString()"; var userName = '@GlobalVars.GetUserName(Session)';
$(document).ready(function () { $(document).ready(function () {
}) })
@ -450,7 +450,7 @@
window.location.href = url.replace('__id__', issueID); window.location.href = url.replace('__id__', issueID);
})*@ })*@
var userid = @Session[@GlobalVars.SESSION_USERID].ToString() var userid = @GlobalVars.GetUserId(Session);
$("#IncludeAllDocuments").on("click", function () { $("#IncludeAllDocuments").on("click", function () {

View File

@ -34,7 +34,7 @@
</div> </div>
<div id="LotDispoTasklistdiv" class="k-content" style="font-size: 11px;"> <div id="LotDispoTasklistdiv" class="k-content" style="font-size: 11px;">
@if ((bool)Session[GlobalVars.IS_ADMIN]) @if (GlobalVars.IsAdmin(Session))
{ {
@(Html.Kendo().Grid<Fab2ApprovalSystem.ViewModels.IssuesViewModel>() @(Html.Kendo().Grid<Fab2ApprovalSystem.ViewModels.IssuesViewModel>()
.Name("LotDispoTasklist") .Name("LotDispoTasklist")

View File

@ -32,7 +32,7 @@
<table class="pull-right"> <table class="pull-right">
<tr> <tr>
<td class="pull-right"> <td class="pull-right">
@if ((bool)Session[GlobalVars.IS_ADMIN]) @if (GlobalVars.IsAdmin(Session))
{ {
@(Html.Kendo().Upload() @(Html.Kendo().Upload()
.Name("AddQDBFlag") .Name("AddQDBFlag")
@ -45,7 +45,7 @@
} }
</td> </td>
<td class="pull-right"> <td class="pull-right">
@if ((bool)Session[GlobalVars.IS_ADMIN]) @if (GlobalVars.IsAdmin(Session))
{ {
@(Html.Kendo().Upload() @(Html.Kendo().Upload()
.Name("RemoveQDBFlag") .Name("RemoveQDBFlag")
@ -72,7 +72,7 @@
</div> </div>
<div id="mrbTasklistdiv" class="k-content" style="font-size: 11px;"> <div id="mrbTasklistdiv" class="k-content" style="font-size: 11px;">
@if ((bool)Session[GlobalVars.IS_ADMIN]) @if (GlobalVars.IsAdmin(Session))
{ {
@(Html.Kendo().Grid<Fab2ApprovalSystem.ViewModels.IssuesViewModel>() @(Html.Kendo().Grid<Fab2ApprovalSystem.ViewModels.IssuesViewModel>()
.Name("mrbTasklist") .Name("mrbTasklist")

View File

@ -175,7 +175,7 @@
</div> </div>
@if (Convert.ToBoolean(Session[GlobalVars.CAN_CREATE_PARTS_REQUEST]) && !Convert.ToBoolean(Session[GlobalVars.IS_ADMIN])) @if (GlobalVars.GetCanCreatePartsRequest(Session) && !GlobalVars.IsAdmin(Session))
{ {
<br /><br /> <br /><br />
<div class="panel-heading" style="background-color:beige"> <div class="panel-heading" style="background-color:beige">

View File

@ -55,11 +55,11 @@
<div class="navbar-collapse collapse"> <div class="navbar-collapse collapse">
<ul class="nav navbar-nav"> <ul class="nav navbar-nav">
@*<li>@Html.ActionLink("Reports", "Index", "Reports")</li>*@ @*<li>@Html.ActionLink("Reports", "Index", "Reports")</li>*@
@if ((bool)@Session[GlobalVars.IS_ADMIN]) @if (@GlobalVars.IsAdmin(Session))
{ {
<li>@Html.ActionLink("Admin", "Index", "Admin")</li> <li>@Html.ActionLink("Admin", "Index", "Admin")</li>
} }
@if ((bool)@Session[GlobalVars.IS_MANAGER]) @if (GlobalVars.IsManager(Session))
{ {
<li>@Html.ActionLink("Manager", "Index", "Manager")</li> <li>@Html.ActionLink("Manager", "Index", "Manager")</li>
} }
@ -83,30 +83,30 @@
@*<li><a href=@Url.Action("Create", "LotDisposition")>Lot Dispostion</a></li>*@ @*<li><a href=@Url.Action("Create", "LotDisposition")>Lot Dispostion</a></li>*@
@*<li><a href=@Url.Action("Create", "MRB")>Create MRB</a></li>*@ @*<li><a href=@Url.Action("Create", "MRB")>Create MRB</a></li>*@
<li><a href=@Url.Action("Create", "ECN")>Create ECN/TECN</a></li> <li><a href=@Url.Action("Create", "ECN")>Create ECN/TECN</a></li>
@if (!string.IsNullOrWhiteSpace(Session["JWT"].ToString())) { @if (!string.IsNullOrWhiteSpace(GlobalVars.GetJWT(Session))) {
string jwt = Session["JWT"].ToString(); string jwt = GlobalVars.GetJWT(Session);
string encodedJwt = System.Net.WebUtility.UrlEncode(jwt); string encodedJwt = System.Net.WebUtility.UrlEncode(jwt);
string refreshToken = Session["RefreshToken"].ToString(); string refreshToken = GlobalVars.GetRefreshToken(Session);
string encodedRefreshToken = System.Net.WebUtility.UrlEncode(refreshToken); string encodedRefreshToken = System.Net.WebUtility.UrlEncode(refreshToken);
string wasmClientUrl = Environment.GetEnvironmentVariable("FabApprovalWasmClientUrl") ?? string wasmClientUrl = Environment.GetEnvironmentVariable("FabApprovalWasmClientUrl") ??
"https://localhost:7255"; "https://localhost:7255";
string mrbUrl = wasmClientUrl + "/redirect?jwt=" + encodedJwt + "&refreshToken=" + encodedRefreshToken + "&redirectPath=/mrb/new"; string mrbUrl = wasmClientUrl + "/redirect?jwt=" + encodedJwt + "&refreshToken=" + encodedRefreshToken + "&redirectPath=mrb/new";
<li><a href="@mrbUrl">Create MRB</a></li> <li><a href="@mrbUrl">Create MRB</a></li>
@*string pcrbUrl = wasmClientUrl + "/redirect?jwt=" + encodedJwt + "&refreshToken=" + encodedRefreshToken + "&redirectPath=/pcrb/new"; string pcrbUrl = wasmClientUrl + "/redirect?jwt=" + encodedJwt + "&refreshToken=" + encodedRefreshToken + "&redirectPath=pcrb/new";
<li><a href="@pcrbUrl">Create PCRB</a></li>*@ <li><a href="@pcrbUrl">Create PCRB</a></li>
} else { } else {
string wasmClientUrl = Environment.GetEnvironmentVariable("FabApprovalWasmClientUrl") ?? string wasmClientUrl = Environment.GetEnvironmentVariable("FabApprovalWasmClientUrl") ??
"https://localhost:7255"; "https://localhost:7255";
string mrbUrl = wasmClientUrl + "/redirect?redirectPath=/mrb/new"; string mrbUrl = wasmClientUrl + "/redirect?redirectPath=mrb/new";
<li><a href="@mrbUrl">Create MRB</a></li> <li><a href="@mrbUrl">Create MRB</a></li>
@*string pcrbUrl = wasmClientUrl + "/redirect?redirectPath=/pcrb/new"; string pcrbUrl = wasmClientUrl + "/redirect?redirectPath=pcrb/new";
<li><a href="@pcrbUrl">Create PCRB</a></li>*@ <li><a href="@pcrbUrl">Create PCRB</a></li>
} }
@*<li><a href=@Url.Action("CreateWorkRequest", "LotTraveler")>Create Special Work Request</a></li>*@ @*<li><a href=@Url.Action("CreateWorkRequest", "LotTraveler")>Create Special Work Request</a></li>*@
@*<li><a href=@Url.Action("Create", "ChangeControl")>Create PCR</a></li>*@ @*<li><a href=@Url.Action("Create", "ChangeControl")>Create PCR</a></li>*@
<li><a href=@Url.Action("Create", "Audit")>Create Audit</a></li> <li><a href=@Url.Action("Create", "Audit")>Create Audit</a></li>
<li><a href=@Url.Action("Create", "CorrectiveAction")>Create Corrective Action</a></li> <li><a href=@Url.Action("Create", "CorrectiveAction")>Create Corrective Action</a></li>
@*@if (Convert.ToBoolean(Session[GlobalVars.CAN_CREATE_PARTS_REQUEST])) @*@if (GlobalVars.GetCanCreatePartsRequest(Session))
{ {
<li><a href=@Url.Action("Create", "PartsRequest")>Create New/Repair Spare Parts Request</a></li> <li><a href=@Url.Action("Create", "PartsRequest")>Create New/Repair Spare Parts Request</a></li>
}*@ }*@
@ -118,7 +118,7 @@
@*<div class="form-group"> @*<div class="form-group">
<input type="text" class="form-control" placeholder="Search" style="font-size: 11px"> <input type="text" class="form-control" placeholder="Search" style="font-size: 11px">
</div>*@ </div>*@
@if (!(bool)Session[GlobalVars.OOO]) @if (!GlobalVars.IsOOO(Session))
{ {
<button class="btn btn-default btn-primary" data-toggle="modal" id="OOO">Out Of Office</button> <button class="btn btn-default btn-primary" data-toggle="modal" id="OOO">Out Of Office</button>
} }
@ -144,16 +144,16 @@
menu.Add().Text("My Training").Action("ViewMyTrainingAssignments", "Training"); menu.Add().Text("My Training").Action("ViewMyTrainingAssignments", "Training");
menu.Add().Text("Training Reports").Action("TrainingReports", "Training"); menu.Add().Text("Training Reports").Action("TrainingReports", "Training");
menu.Add().Text("All Documents").Action("AllDocuments", "Home"); menu.Add().Text("All Documents").Action("AllDocuments", "Home");
string jwt = Session["JWT"].ToString(); string jwt = GlobalVars.GetJWT(Session);
string encodedJwt = System.Net.WebUtility.UrlEncode(jwt); string encodedJwt = System.Net.WebUtility.UrlEncode(jwt);
string refreshToken = Session["RefreshToken"].ToString(); string refreshToken = GlobalVars.GetRefreshToken(Session);
string encodedRefreshToken = System.Net.WebUtility.UrlEncode(refreshToken); string encodedRefreshToken = System.Net.WebUtility.UrlEncode(refreshToken);
string wasmClientUrl = Environment.GetEnvironmentVariable("FabApprovalWasmClientUrl") ?? string wasmClientUrl = Environment.GetEnvironmentVariable("FabApprovalWasmClientUrl") ??
"https://localhost:7255"; "https://localhost:7255";
string mrbUrl = wasmClientUrl + "/redirect?jwt=" + encodedJwt + "&refreshToken=" + encodedRefreshToken + "&redirectPath=/mrb/all"; string mrbUrl = wasmClientUrl + "/redirect?jwt=" + encodedJwt + "&refreshToken=" + encodedRefreshToken + "&redirectPath=mrb/all";
menu.Add().Text("MRB").Url(mrbUrl); menu.Add().Text("MRB").Url(mrbUrl);
//string pcrbUrl = wasmClientUrl + "/redirect?jwt=" + encodedJwt + "&refreshToken=" + encodedRefreshToken + "&redirectPath=/pcrb/all"; string pcrbUrl = wasmClientUrl + "/redirect?jwt=" + encodedJwt + "&refreshToken=" + encodedRefreshToken + "&redirectPath=pcrb/all";
//menu.Add().Text("PCRB").Url(pcrbUrl); menu.Add().Text("PCRB").Url(pcrbUrl);
//menu.Add().Text("Special Work Requests").Action("SpecialWorkRequestList", "Home"); //menu.Add().Text("Special Work Requests").Action("SpecialWorkRequestList", "Home");
//menu.Add().Text("PCRB").Action("ChangeControlList", "Home"); //menu.Add().Text("PCRB").Action("ChangeControlList", "Home");
//menu.Add().Text("MRB").Action("MRBList", "Home"); //menu.Add().Text("MRB").Action("MRBList", "Home");
@ -279,7 +279,7 @@
var issueID=""; var issueID="";
var docType = ""; var docType = "";
var submitdate = ""; var submitdate = "";
var userName = "@Session[@GlobalVars.SESSION_USERNAME].ToString()"; var userName = '@GlobalVars.GetUserName(Session)';
$(document).ready(function () { $(document).ready(function () {
}) })
@ -302,7 +302,7 @@
window.location.href = url.replace('__id__', issueID); window.location.href = url.replace('__id__', issueID);
})*@ })*@
var userid = @Session[@GlobalVars.SESSION_USERID].ToString() var userid = @GlobalVars.GetUserId(Session);
$("#IncludeAllDocuments").on("click", function () { $("#IncludeAllDocuments").on("click", function () {

View File

@ -41,10 +41,10 @@
@(Html.Kendo().DropDownList() @(Html.Kendo().DropDownList()
.Name("OriginatorID") .Name("OriginatorID")
.BindTo(new SelectList(ViewBag.OriginatorList, "OriginatorID", "OriginatorName")) .BindTo(new SelectList(ViewBag.OriginatorList, "OriginatorID", "OriginatorName"))
.Value(@Session[GlobalVars.SESSION_USERID].ToString()) .Value(@GlobalVars.GetUserIdValue(Session))
) )
@*@Html.TextBoxFor(model => model.OriginatorID, new { id = @GlobalVars.USER_ID, Value = @Session[GlobalVars.SESSION_USERNAME].ToString();, @class = "k-textbox" })*@ @*@Html.TextBoxFor(model => model.OriginatorID, new { id = @GlobalVars.USER_ID, Value = @GlobalVars.GetUserName(Session);, @class = "k-textbox" })*@
</div> </div>
</div> </div>

View File

@ -478,9 +478,9 @@
<div class="panel-body bg-warning"> <div class="panel-body bg-warning">
<div class="col-sm-offset-0"> <div class="col-sm-offset-0">
@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<Fab2ApprovalSystem.ViewModels.ApproversListViewModel>() @(Html.Kendo().Grid<Fab2ApprovalSystem.ViewModels.ApproversListViewModel>()
.Name("ApproversList") .Name("ApproversList")

View File

@ -421,7 +421,7 @@
<div class="panel-body bg-warning"> <div class="panel-body bg-warning">
<div class="col-sm-offset-0"> <div class="col-sm-offset-0">
@if ((bool)Session[GlobalVars.IS_ADMIN] && (Request.IsAuthenticated)) @if (GlobalVars.IsAdmin(Session) && (Request.IsAuthenticated))
{ {
@(Html.Kendo().Grid<Fab2ApprovalSystem.ViewModels.ApproversListViewModel>() @(Html.Kendo().Grid<Fab2ApprovalSystem.ViewModels.ApproversListViewModel>()
.Name("ApproversList") .Name("ApproversList")

View File

@ -133,7 +133,7 @@
</div> </div>
<div class="col-sm-9"> <div class="col-sm-9">
@Html.TextBoxFor(model => model.OriginatorName, new { id = "txtOriginatorName", @class = "k-textbox", Readonly = "Readonly", style = "background-color:lightblue" }) @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))
{ {
<a href="javascript:undefined" id="lnkReassignOriginator" class="linkbutton edit" title="Re-assign Originator"></a> <a href="javascript:undefined" id="lnkReassignOriginator" class="linkbutton edit" title="Re-assign Originator"></a>
} }
@ -901,9 +901,9 @@
<div class="panel-body bg-warning"> <div class="panel-body bg-warning">
<div class="col-sm-offset-0"> <div class="col-sm-offset-0">
@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<Fab2ApprovalSystem.ViewModels.ApproversListViewModel>() @(Html.Kendo().Grid<Fab2ApprovalSystem.ViewModels.ApproversListViewModel>()
.Name("ApproversList") .Name("ApproversList")

View File

@ -125,7 +125,7 @@
</div> </div>
<div class="col-sm-9"> <div class="col-sm-9">
@Html.TextBoxFor(model => model.Originator, new { @class = "k-textbox", Readonly = "Readonly", style = "background-color:lightblue" }) @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))
{ {
<a href="javascript:undefined" id="lnkReassignOriginator" class="linkbutton edit" title="Re-assign Originator"></a> <a href="javascript:undefined" id="lnkReassignOriginator" class="linkbutton edit" title="Re-assign Originator"></a>
} }

View File

@ -166,7 +166,7 @@
</div> </div>
<div class="col-sm-9"> <div class="col-sm-9">
@Html.TextBoxFor(model => model.Originator, new { @class = "k-textbox", Readonly = "Readonly", style = "background-color:lightblue" }) @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))
{ {
<a href="javascript:undefined" id="lnkReassignOriginator" class="linkbutton edit" title="Re-assign Originator"></a> <a href="javascript:undefined" id="lnkReassignOriginator" class="linkbutton edit" title="Re-assign Originator"></a>
} }

View File

@ -146,7 +146,7 @@
</div> </div>
<div class="col-sm-9"> <div class="col-sm-9">
@Html.TextBoxFor(model => model.Originator, new { @class = "k-textbox", Readonly = "Readonly", style = "background-color:lightblue" }) @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))
{ {
<a href="javascript:undefined" id="lnkReassignOriginator" class="linkbutton edit" title="Re-assign Originator"></a> <a href="javascript:undefined" id="lnkReassignOriginator" class="linkbutton edit" title="Re-assign Originator"></a>
} }

View File

@ -152,7 +152,7 @@
</div> </div>
<div class="col-sm-9"> <div class="col-sm-9">
@Html.TextBoxFor(model => model.OriginatorName, new { id = "txtOriginatorName", @class = "k-textbox", Readonly = "Readonly", style = "background-color:lightblue" }) @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))
{ {
<a href="javascript:undefined" id="lnkReassignOriginator" class="linkbutton edit" title="Re-assign Originator"></a> <a href="javascript:undefined" id="lnkReassignOriginator" class="linkbutton edit" title="Re-assign Originator"></a>
} }
@ -818,7 +818,7 @@
</div> </div>
<div class="panel-heading"> <div class="panel-heading">
@if (((bool)Session[GlobalVars.IS_ADMIN] && (Request.IsAuthenticated))) @if ((GlobalVars.IsAdmin(Session) && (Request.IsAuthenticated)))
{ {
<button class="btn btn-warning btn-xs" data-toggle="modal" id="additionalApprovers" style="font-size:x-small"> <button class="btn btn-warning btn-xs" data-toggle="modal" id="additionalApprovers" style="font-size:x-small">
Additional Approvers Additional Approvers
@ -839,9 +839,9 @@
<div class="panel-body bg-warning"> <div class="panel-body bg-warning">
<div class="col-sm-offset-0"> <div class="col-sm-offset-0">
@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<Fab2ApprovalSystem.ViewModels.ApproversListViewModel>() @(Html.Kendo().Grid<Fab2ApprovalSystem.ViewModels.ApproversListViewModel>()
.Name("ApproversList") .Name("ApproversList")

View File

@ -196,7 +196,7 @@
</div> </div>
<div class="col-sm-9"> <div class="col-sm-9">
@Html.TextBoxFor(model => model.OriginatorName, new { id = "txtOriginatorName", @class = "k-textbox", Readonly = "Readonly", style = "background-color:lightblue" }) @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))
{ {
<a href="javascript:undefined" id="lnkReassignOriginator" class="linkbutton edit" title="Re-assign Originator"></a> <a href="javascript:undefined" id="lnkReassignOriginator" class="linkbutton edit" title="Re-assign Originator"></a>
} }

View File

@ -929,9 +929,9 @@
<div class="panel-body bg-warning"> <div class="panel-body bg-warning">
<div class="col-sm-offset-0"> <div class="col-sm-offset-0">
@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<Fab2ApprovalSystem.ViewModels.ApproversListViewModel>() @(Html.Kendo().Grid<Fab2ApprovalSystem.ViewModels.ApproversListViewModel>()
.Name("ApproversList") .Name("ApproversList")
@ -1711,7 +1711,7 @@
$("#UploadWRAttchmentRev").on('click', function (e) { $("#UploadWRAttchmentRev").on('click', function (e) {
e.preventDefault(); e.preventDefault();
var model = "@Session["CreateNewRevision"]"; var model = '@GlobalVars.GetCreateNewRevision(Session)';
wrAttachmentOperation = "Add"; wrAttachmentOperation = "Add";
if (model == "true") { if (model == "true") {
$("#WinWorkReqAttRevComments").modal('show'); $("#WinWorkReqAttRevComments").modal('show');
@ -1787,7 +1787,7 @@
data.RevisionComments = $("#revisionWRAttachComments").val(); data.RevisionComments = $("#revisionWRAttachComments").val();
var model = "@Session["CreateNewRevision"]"; var model = '@GlobalVars.GetCreateNewRevision(Session)';
if (model == "true") { if (model == "true") {
var urlString = '/LotTraveler/UpdateWorkRequestAttachmentRevision'; var urlString = '/LotTraveler/UpdateWorkRequestAttachmentRevision';
$.ajax({ $.ajax({
@ -1851,7 +1851,7 @@
function on_WorkReqAttachmentsGridSuccess() { function on_WorkReqAttachmentsGridSuccess() {
var model = "@Session["CreateNewRevision"]"; var model = '@GlobalVars.GetCreateNewRevision(Session)';
if (model == "true") { if (model == "true") {
$.ajax({ $.ajax({
@ -1887,7 +1887,7 @@
var dataItem = this.dataItem($(e.currentTarget).closest("tr")); var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
currentWrkReqAttachID = dataItem.ID; currentWrkReqAttachID = dataItem.ID;
var model = "@Session["CreateNewRevision"]"; var model = '@GlobalVars.GetCreateNewRevision(Session)';
if (model == "true") { if (model == "true") {
$("#WinWorkReqAttRevComments").modal('show'); $("#WinWorkReqAttRevComments").modal('show');
@ -1910,7 +1910,7 @@
if (confirm("Do you really wish to delete the attachment record")) { if (confirm("Do you really wish to delete the attachment record")) {
var model = "@Session["CreateNewRevision"]"; var model = '@GlobalVars.GetCreateNewRevision(Session)';
if (model == "true") { if (model == "true") {
$("#WinWorkReqAttRevComments").modal('show'); $("#WinWorkReqAttRevComments").modal('show');
} }
@ -2009,7 +2009,7 @@
if (confirm("Do you really wish to delete the record?")) { if (confirm("Do you really wish to delete the record?")) {
var model = "@Session["CreateNewRevision"]"; var model = '@GlobalVars.GetCreateNewRevision(Session)';
if (model == "true") { if (model == "true") {
$("#WinHoldStepRevisionComments").modal("show"); $("#WinHoldStepRevisionComments").modal("show");
} }
@ -2180,7 +2180,7 @@
else { else {
// save // save
$("#AddHoldStepForm").modal('hide'); $("#AddHoldStepForm").modal('hide');
var model = "@Session["CreateNewRevision"]"; var model = '@GlobalVars.GetCreateNewRevision(Session)';
if (model == "true") { if (model == "true") {
$("#WinHoldStepRevisionComments").modal("show"); $("#WinHoldStepRevisionComments").modal("show");
} }
@ -2451,7 +2451,7 @@
var dataItem = this.dataItem($(e.currentTarget).closest("tr")); var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
currentHoldStepID = dataItem.ID; currentHoldStepID = dataItem.ID;
var model = "@Session["CreateNewRevision"]"; var model = '@GlobalVars.GetCreateNewRevision(Session)';
if (model == "true") { if (model == "true") {
$("#WinHoldStepAttRevComments").modal('show'); $("#WinHoldStepAttRevComments").modal('show');
@ -2769,7 +2769,7 @@
return; return;
} }
var model = '@Session["CreateNewRevision"]'; var model = '@GlobalVars.GetCreateNewRevision(Session)';
$('#submitRevisionComments').attr("disabled", false); $('#submitRevisionComments').attr("disabled", false);
@ -2919,7 +2919,7 @@
if (confirm("Do you really wish to delete?")) { if (confirm("Do you really wish to delete?")) {
var model = '@Session["CreateNewRevision"]'; var model = '@GlobalVars.GetCreateNewRevision(Session)';
if (model == "true") if (model == "true")
$("#WinEPIRevisionComments").modal('show'); $("#WinEPIRevisionComments").modal('show');
else { else {
@ -2968,7 +2968,7 @@
var Quantity = $("#txtEPiQuantity").val(); var Quantity = $("#txtEPiQuantity").val();
$("#EPIForm").modal('hide'); $("#EPIForm").modal('hide');
var model = '@Session["CreateNewRevision"]'; var model = '@GlobalVars.GetCreateNewRevision(Session)';
if (model == "true") if (model == "true")
$("#WinEPIRevisionComments").modal('show'); $("#WinEPIRevisionComments").modal('show');

View File

@ -118,7 +118,7 @@
function SetDocType(e) { function SetDocType(e) {
var model = "@Session["CreateNewRevision"]"; var model = '@GlobalVars.GetCreateNewRevision(Session)';
if (model == "true") { if (model == "true") {
$.ajax({ $.ajax({

Some files were not shown because too many files have changed in this diff Show More