Tasks 184281, 184799, 184800, 184801 and 184802

Align .editorconfig files

Move Controller logic to DMO classes

GlobalVars.AppSettings = Models.AppSettings.GetFromConfigurationManager();

Question EditorConfig
Project level editorconfig
Format White Spaces
AppSetting when EnvironmentVariable not set
Corrective Actions Tests
Schedule Actions Tests
DMO Tests
Controller Tests

Get ready to use VSCode IDE
This commit is contained in:
2024-12-04 11:58:13 -07:00
parent 538b1f817e
commit b1c6903c1c
150 changed files with 29146 additions and 33456 deletions

View File

@ -0,0 +1,31 @@
#### .NET Coding Conventions ####
# Organize usings
dotnet_separate_import_directive_groups = true
dotnet_sort_system_directives_first = true
# New line preferences
csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true
csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true
csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = true
csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false
csharp_style_allow_embedded_statements_on_same_line_experimental = true
#### C# Formatting Rules ####
# New line preferences
csharp_new_line_before_catch = false
csharp_new_line_before_else = false
csharp_new_line_before_finally = false
csharp_new_line_before_members_in_anonymous_types = true
csharp_new_line_before_members_in_object_initializers = true
csharp_new_line_before_open_brace = none
csharp_new_line_between_query_expression_clauses = true
####
insert_final_newline = false
csharp_style_namespace_declarations = file_scoped:warning
dotnet_diagnostic.IDE0161.severity = warning # Question - Namespace declaration preferences
dotnet_diagnostic.IDE2000.severity = error # IDE2000: Allow multiple blank lines

View File

@ -1,367 +1,334 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Misc;
using Fab2ApprovalSystem.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using Fab2ApprovalSystem.Models;
using System.Web.Security;
using Fab2ApprovalSystem.Misc;
using Fab2ApprovalSystem.DMO;
using Microsoft.AspNet.Identity.Owin;
using System.Net.Http;
using Microsoft.Owin.Security;
using Newtonsoft.Json;
using System.Text;
using System.Net;
namespace Fab2ApprovalSystem.Controllers {
[Authorize]
public class AccountController : Controller {
private string _apiBaseUrl;
namespace Fab2ApprovalSystem.Controllers;
public AccountController()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()))) {
_apiBaseUrl = Environment.GetEnvironmentVariable("FabApprovalApiBaseUrl") ??
throw new ArgumentNullException("FabApprovalApiBaseUrl environment variable not found");
}
[Authorize]
public class AccountController : Controller {
private string _apiBaseUrl;
public AccountController(UserManager<ApplicationUser> userManager) {
UserManager = userManager;
}
public AccountController()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()))) {
_apiBaseUrl = Environment.GetEnvironmentVariable("FabApprovalApiBaseUrl") ??
throw new ArgumentNullException("FabApprovalApiBaseUrl environment variable not found");
}
public UserManager<ApplicationUser> UserManager { get; private set; }
public AccountController(UserManager<ApplicationUser> userManager) {
UserManager = userManager;
}
//
// GET: /Account/Login
[AllowAnonymous]
// try to make the browser refresh the login page every time, to prevent issues with changing usernames and the anti-forgery token validation
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult Login(string returnUrl) {
ViewBag.ReturnUrl = returnUrl;
return View();
}
public UserManager<ApplicationUser> UserManager { get; private set; }
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginModel model, string returnUrl) {
try {
bool isLoginValid;
//
// GET: /Account/Login
[AllowAnonymous]
// try to make the browser refresh the login page every time, to prevent issues with changing usernames and the anti-forgery token validation
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult Login(string returnUrl) {
ViewBag.ReturnUrl = returnUrl;
return View();
}
HttpClient httpClient = HttpClientFactory.Create();
httpClient.BaseAddress = new Uri(_apiBaseUrl);
private void SetSessionParameters(LoginResult loginResult, LoginModel user) {
Session["JWT"] = loginResult.AuthTokens.JwtToken;
Session["RefreshToken"] = loginResult.AuthTokens.RefreshToken;
AuthAttempt authAttempt = new AuthAttempt() {
LoginID = model.LoginID,
Password = model.Password
};
Session[GlobalVars.SESSION_USERID] = user.UserID;
Session[GlobalVars.SESSION_USERNAME] = user.FullName;
Session[GlobalVars.IS_ADMIN] = user.IsAdmin;
Session[GlobalVars.IS_MANAGER] = user.IsManager;
Session[GlobalVars.OOO] = user.OOO;
Session[GlobalVars.CAN_CREATE_PARTS_REQUEST] = user.IsAdmin || PartsRequestController.CanCreatePartsRequest(user.UserID);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "auth/login");
FormsAuthentication.SetAuthCookie(user.LoginID, true);
}
request.Content = new StringContent(JsonConvert.SerializeObject(authAttempt),
Encoding.UTF8,
"application/json");
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginModel model, string returnUrl) {
try {
bool isLoginValid;
HttpResponseMessage httpResponseMessage = await httpClient.SendAsync(request);
HttpClient httpClient = HttpClientFactory.Create();
httpClient.BaseAddress = new Uri(_apiBaseUrl);
if (!httpResponseMessage.IsSuccessStatusCode)
throw new Exception($"The authentication API failed, because {httpResponseMessage.ReasonPhrase}");
LoginResult loginResult = await AccountDMO.LoginAsync(httpClient, model);
string responseContent = await httpResponseMessage.Content.ReadAsStringAsync();
LoginResult loginResult = JsonConvert.DeserializeObject<LoginResult>(responseContent);
#if(DEBUG)
isLoginValid = true;
#if (DEBUG)
isLoginValid = true;
#endif
#if (!DEBUG)
bool isIFX = false;
//domainProvider = Membership.Providers["NA_ADMembershipProvider"];
//isLoginValid = domainProvider.ValidateUser(model.LoginID, model.Password);
bool isIFX = false;
//domainProvider = Membership.Providers["NA_ADMembershipProvider"];
//isLoginValid = domainProvider.ValidateUser(model.LoginID, model.Password);
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") {
isLoginValid = true;
} else {
isLoginValid = loginResult.IsAuthenticated;
if (isLoginValid) isIFX = true;
}
#endif
if (isLoginValid) {
UserAccountDMO userDMO = new UserAccountDMO();
LoginModel user = userDMO.GetUser(model.LoginID);
if (user != null) {
Session["JWT"] = loginResult.AuthTokens.JwtToken;
Session["RefreshToken"] = loginResult.AuthTokens.RefreshToken;
Session[GlobalVars.SESSION_USERID] = user.UserID;
Session[GlobalVars.SESSION_USERNAME] = user.FullName;
Session[GlobalVars.IS_ADMIN] = user.IsAdmin;
Session[GlobalVars.IS_MANAGER] = user.IsManager;
Session[GlobalVars.OOO] = user.OOO;
Session[GlobalVars.CAN_CREATE_PARTS_REQUEST] = user.IsAdmin || PartsRequestController.CanCreatePartsRequest(user.UserID);
FormsAuthentication.SetAuthCookie(user.LoginID, true);
return RedirectToLocal(returnUrl);
} else {
ModelState.AddModelError("", "The user name does not exist in the DB. Please contact the System Admin");
}
} else {
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
} catch (Exception ex) {
Functions.WriteEvent(@User.Identity.Name + " " + ex.InnerException, System.Diagnostics.EventLogEntryType.Error);
EventLogDMO.Add(new WinEventLog() { IssueID = 99999, UserID = @User.Identity.Name, DocumentType = "Login", OperationType = "Error", Comments = "Reject - " + ex.Message });
ModelState.AddModelError("", ex.Message);
}
return View(model);
// If we got this far, something failed, redisplay form
}
[HttpPost]
[AllowAnonymous]
public async Task<HttpResponseMessage> ExternalAuthSetup(AuthAttempt authAttempt) {
try {
bool isLoginValid;
HttpClient httpClient = HttpClientFactory.Create();
httpClient.BaseAddress = new Uri(_apiBaseUrl);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "auth/refresh");
request.Content = new StringContent(JsonConvert.SerializeObject(authAttempt),
Encoding.UTF8,
"application/json");
HttpResponseMessage httpResponseMessage = await httpClient.SendAsync(request);
if (!httpResponseMessage.IsSuccessStatusCode)
throw new Exception($"The authentication API failed, because {httpResponseMessage.ReasonPhrase}");
string responseContent = await httpResponseMessage.Content.ReadAsStringAsync();
LoginResult loginResult = JsonConvert.DeserializeObject<LoginResult>(responseContent);
#if(DEBUG)
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") {
isLoginValid = true;
#endif
#if (!DEBUG)
bool isIFX = false;
//domainProvider = Membership.Providers["NA_ADMembershipProvider"];
//isLoginValid = domainProvider.ValidateUser(model.LoginID, model.Password);
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") {
isLoginValid = true;
} else {
isLoginValid = loginResult.IsAuthenticated;
if (isLoginValid) isIFX = true;
}
#endif
if (isLoginValid) {
UserAccountDMO userDMO = new UserAccountDMO();
LoginModel user = userDMO.GetUser(authAttempt.LoginID);
if (user != null) {
Session["JWT"] = loginResult.AuthTokens.JwtToken;
Session["RefreshToken"] = loginResult.AuthTokens.RefreshToken;
Session[GlobalVars.SESSION_USERID] = user.UserID;
Session[GlobalVars.SESSION_USERNAME] = user.FullName;
Session[GlobalVars.IS_ADMIN] = user.IsAdmin;
Session[GlobalVars.IS_MANAGER] = user.IsManager;
Session[GlobalVars.OOO] = user.OOO;
Session[GlobalVars.CAN_CREATE_PARTS_REQUEST] = user.IsAdmin || PartsRequestController.CanCreatePartsRequest(user.UserID);
FormsAuthentication.SetAuthCookie(user.LoginID, true);
return new HttpResponseMessage(HttpStatusCode.OK);
} else {
ModelState.AddModelError("", "The user name does not exist in the DB. Please contact the System Admin");
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
} else {
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
} catch (Exception ex) {
Functions.WriteEvent(@User.Identity.Name + " " + ex.InnerException, System.Diagnostics.EventLogEntryType.Error);
EventLogDMO.Add(new WinEventLog() { IssueID = 99999, UserID = @User.Identity.Name, DocumentType = "Login", OperationType = "Error", Comments = "Reject - " + ex.Message });
ModelState.AddModelError("", ex.Message);
return new HttpResponseMessage(HttpStatusCode.InternalServerError);
}
}
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register() {
return View();
}
// POST: /Account/Disassociate
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Disassociate(string loginProvider, string providerKey) {
ManageMessageId? message = null;
IdentityResult result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey));
if (result.Succeeded) {
message = ManageMessageId.RemoveLoginSuccess;
} else {
message = ManageMessageId.Error;
isLoginValid = loginResult.IsAuthenticated;
if (isLoginValid)
isIFX = true;
}
return RedirectToAction("Manage", new { Message = message });
#endif
if (isLoginValid) {
UserAccountDMO userDMO = new UserAccountDMO();
LoginModel user = userDMO.GetUser(model.LoginID);
if (user != null) {
SetSessionParameters(loginResult, user);
return RedirectToLocal(returnUrl);
} else {
ModelState.AddModelError("", "The user name does not exist in the DB. Please contact the System Admin");
}
} else {
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
} catch (Exception ex) {
Functions.WriteEvent(GlobalVars.AppSettings, @User.Identity.Name + " " + ex.InnerException, System.Diagnostics.EventLogEntryType.Error);
EventLogDMO.Add(new WinEventLog() { IssueID = 99999, UserID = @User.Identity.Name, DocumentType = "Login", OperationType = "Error", Comments = "Reject - " + ex.Message });
ModelState.AddModelError("", ex.Message);
}
// GET: /Account/Manage
#pragma warning disable IDE0060 // Remove unused parameter
public ActionResult Manage(ManageMessageId? message) {
return View();
return View(model);
// If we got this far, something failed, redisplay form
}
[HttpPost]
[AllowAnonymous]
public async Task<HttpResponseMessage> ExternalAuthSetup(AuthAttempt authAttempt) {
try {
bool isLoginValid;
HttpClient httpClient = HttpClientFactory.Create();
httpClient.BaseAddress = new Uri(_apiBaseUrl);
LoginResult loginResult = await AccountDMO.ExternalAuthSetupAsync(httpClient, authAttempt);
#if (DEBUG)
isLoginValid = true;
#endif
#if (!DEBUG)
bool isIFX = false;
//domainProvider = Membership.Providers["NA_ADMembershipProvider"];
//isLoginValid = domainProvider.ValidateUser(model.LoginID, model.Password);
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") {
isLoginValid = true;
} else {
isLoginValid = loginResult.IsAuthenticated;
if (isLoginValid)
isIFX = true;
}
#endif
if (isLoginValid) {
UserAccountDMO userDMO = new UserAccountDMO();
LoginModel user = userDMO.GetUser(authAttempt.LoginID);
if (user != null) {
SetSessionParameters(loginResult, user);
return new HttpResponseMessage(HttpStatusCode.OK);
} else {
ModelState.AddModelError("", "The user name does not exist in the DB. Please contact the System Admin");
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
} else {
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
} catch (Exception ex) {
Functions.WriteEvent(GlobalVars.AppSettings, @User.Identity.Name + " " + ex.InnerException, System.Diagnostics.EventLogEntryType.Error);
EventLogDMO.Add(new WinEventLog() { IssueID = 99999, UserID = @User.Identity.Name, DocumentType = "Login", OperationType = "Error", Comments = "Reject - " + ex.Message });
ModelState.AddModelError("", ex.Message);
return new HttpResponseMessage(HttpStatusCode.InternalServerError);
}
}
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register() {
return View();
}
// POST: /Account/Disassociate
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Disassociate(string loginProvider, string providerKey) {
ManageMessageId? message = null;
IdentityResult result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey));
if (result.Succeeded) {
message = ManageMessageId.RemoveLoginSuccess;
} else {
message = ManageMessageId.Error;
}
return RedirectToAction("Manage", new { Message = message });
}
// GET: /Account/Manage
#pragma warning disable IDE0060 // Remove unused parameter
public ActionResult Manage(ManageMessageId? message) {
return View();
}
#pragma warning restore IDE0060 // Remove unused parameter
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl) {
// Request a redirect to the external login provider
return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
}
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl) {
// Request a redirect to the external login provider
return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
}
// POST: /Account/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LinkLogin(string provider) {
// Request a redirect to the external login provider to link a login for the current user
return new ChallengeResult(provider, Url.Action("LinkLoginCallback", "Account"), User.Identity.GetUserId());
}
// POST: /Account/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LinkLogin(string provider) {
// Request a redirect to the external login provider to link a login for the current user
return new ChallengeResult(provider, Url.Action("LinkLoginCallback", "Account"), User.Identity.GetUserId());
}
//
// GET: /Account/LinkLoginCallback
public async Task<ActionResult> LinkLoginCallback() {
ExternalLoginInfo loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId());
if (loginInfo == null) {
return RedirectToAction("Manage", new { Message = ManageMessageId.Error });
}
IdentityResult result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login);
if (result.Succeeded) {
return RedirectToAction("Manage");
}
//
// GET: /Account/LinkLoginCallback
public async Task<ActionResult> LinkLoginCallback() {
ExternalLoginInfo loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId());
if (loginInfo == null) {
return RedirectToAction("Manage", new { Message = ManageMessageId.Error });
}
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff() {
FormsAuthentication.SignOut();
return RedirectToAction("Login", "Account");
IdentityResult result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login);
if (result.Succeeded) {
return RedirectToAction("Manage");
}
// GET: /Account/ExternalLoginFailure
[AllowAnonymous]
public ActionResult ExternalLoginFailure() {
return View();
}
[ChildActionOnly]
public ActionResult RemoveAccountList() {
IList<UserLoginInfo> linkedAccounts = UserManager.GetLogins(User.Identity.GetUserId());
ViewBag.ShowRemoveButton = HasPassword() || linkedAccounts.Count > 1;
return (ActionResult)PartialView("_RemoveAccountPartial", linkedAccounts);
}
protected override void Dispose(bool disposing) {
if (disposing && UserManager != null) {
UserManager.Dispose();
UserManager = null;
}
base.Dispose(disposing);
}
#region Helpers
// Used for XSRF protection when adding external logins
private const string XsrfKey = "XsrfId";
private IAuthenticationManager AuthenticationManager {
get {
return HttpContext.GetOwinContext().Authentication;
}
}
private async Task SignInAsync(ApplicationUser user, bool isPersistent) {
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
ClaimsIdentity identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
private void AddErrors(IdentityResult result) {
foreach (string error in result.Errors) {
ModelState.AddModelError("", error);
}
}
private bool HasPassword() {
ApplicationUser user = UserManager.FindById(User.Identity.GetUserId());
if (user != null) {
return user.PasswordHash != null;
}
return false;
}
public enum ManageMessageId {
ChangePasswordSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
Error
}
private ActionResult RedirectToLocal(string returnUrl) {
if (Url.IsLocalUrl(returnUrl)) {
return Redirect(returnUrl);
} else {
return RedirectToAction("MyTasks", "Home");
}
}
private class ChallengeResult : HttpUnauthorizedResult {
public ChallengeResult(string provider, string redirectUri) : this(provider, redirectUri, null) {
}
public ChallengeResult(string provider, string redirectUri, string userId) {
LoginProvider = provider;
RedirectUri = redirectUri;
UserId = userId;
}
public string LoginProvider { get; set; }
public string RedirectUri { get; set; }
public string UserId { get; set; }
public override void ExecuteResult(ControllerContext context) {
AuthenticationProperties properties = new AuthenticationProperties() { RedirectUri = RedirectUri };
if (UserId != null) {
properties.Dictionary[XsrfKey] = UserId;
}
context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
}
}
#endregion
return RedirectToAction("Manage", new { Message = ManageMessageId.Error });
}
}
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff() {
FormsAuthentication.SignOut();
return RedirectToAction("Login", "Account");
}
// GET: /Account/ExternalLoginFailure
[AllowAnonymous]
public ActionResult ExternalLoginFailure() {
return View();
}
[ChildActionOnly]
public ActionResult RemoveAccountList() {
IList<UserLoginInfo> linkedAccounts = UserManager.GetLogins(User.Identity.GetUserId());
ViewBag.ShowRemoveButton = HasPassword() || linkedAccounts.Count > 1;
return (ActionResult)PartialView("_RemoveAccountPartial", linkedAccounts);
}
protected override void Dispose(bool disposing) {
if (disposing && UserManager != null) {
UserManager.Dispose();
UserManager = null;
}
base.Dispose(disposing);
}
#region Helpers
// Used for XSRF protection when adding external logins
private const string XsrfKey = "XsrfId";
private IAuthenticationManager AuthenticationManager {
get {
return HttpContext.GetOwinContext().Authentication;
}
}
private async Task SignInAsync(ApplicationUser user, bool isPersistent) {
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
ClaimsIdentity identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
private void AddErrors(IdentityResult result) {
foreach (string error in result.Errors) {
ModelState.AddModelError("", error);
}
}
private bool HasPassword() {
ApplicationUser user = UserManager.FindById(User.Identity.GetUserId());
if (user != null) {
return user.PasswordHash != null;
}
return false;
}
public enum ManageMessageId {
ChangePasswordSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
Error
}
private ActionResult RedirectToLocal(string returnUrl) {
if (Url.IsLocalUrl(returnUrl)) {
return Redirect(returnUrl);
} else {
return RedirectToAction("MyTasks", "Home");
}
}
private class ChallengeResult : HttpUnauthorizedResult {
public ChallengeResult(string provider, string redirectUri) : this(provider, redirectUri, null) {
}
public ChallengeResult(string provider, string redirectUri, string userId) {
LoginProvider = provider;
RedirectUri = redirectUri;
UserId = userId;
}
public string LoginProvider { get; set; }
public string RedirectUri { get; set; }
public string UserId { get; set; }
public override void ExecuteResult(ControllerContext context) {
AuthenticationProperties properties = new AuthenticationProperties() { RedirectUri = RedirectUri };
if (UserId != null) {
properties.Dictionary[XsrfKey] = UserId;
}
context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
}
}
#endregion
}

File diff suppressed because it is too large Load Diff

View File

@ -1,669 +1,310 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using Fab2ApprovalSystem.Models;
using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Misc;
using System.IO;
using System.Configuration;
using Fab2ApprovalSystem.Models;
using Fab2ApprovalSystem.Utilities;
namespace Fab2ApprovalSystem.Controllers
{
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
[SessionExpireFilter]
public class AuditController : Controller
{
AuditDMO auditDMO = new AuditDMO();
CorrectiveActionDMO caDMO = new CorrectiveActionDMO();
UserUtilities adUsers = new UserUtilities();
// GET: Audit
public ActionResult Index()
{
return View();
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
namespace Fab2ApprovalSystem.Controllers;
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
[SessionExpireFilter]
public class AuditController : Controller {
AuditDMO auditDMO;
CorrectiveActionDMO caDMO;
private readonly AppSettings _AppSettings;
public AuditController(AppSettings appSettings) {
_AppSettings = appSettings;
auditDMO = new AuditDMO(appSettings);
caDMO = new CorrectiveActionDMO(appSettings);
}
// GET: Audit
public ActionResult Index() {
return View();
}
public ActionResult Create() {
Audit audit = new Audit();
try {
// TODO: Add insert logic here
audit.OriginatorID = (int)Session[GlobalVars.SESSION_USERID];
auditDMO.InsertAudit(audit);
return RedirectToAction("Edit", new { issueID = audit.AuditNo });
} catch (Exception e) {
string detailedException = "";
try {
detailedException = e.InnerException.ToString();
} catch {
detailedException = e.Message;
}
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + audit.AuditNo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n SubmitDocument - Audit\r\n" + audit.AuditNo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
EventLogDMO.Add(new WinEventLog() { IssueID = audit.AuditNo, UserID = @User.Identity.Name, DocumentType = "Audit", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString });
throw new Exception(e.Message);
}
}
public ActionResult Edit(int issueID) {
int isITARCompliant = 1;
Audit audit = new Audit();
try {
bool isAdmin = (bool)Session[GlobalVars.IS_ADMIN];
int userId = (int)Session[GlobalVars.SESSION_USERID];
AuditEdit auditEdit = auditDMO.GetAuditEdit(issueID, audit, isAdmin, userId);
if (auditEdit.RedirectToAction)
return RedirectToAction("ReadOnlyAudit", new { auditNo = audit.AuditNo });
ViewBag.AuditAreaList = auditEdit.AuditAreaList;
ViewBag.AuditeeNames = auditEdit.AuditeeNames;
ViewBag.AuditFindingCategoryList = auditEdit.AuditFindingCategoryList;
ViewBag.AuditorList = auditEdit.AuditorList;
ViewBag.AuditTypeList = auditEdit.AuditTypeList;
ViewBag.CANoList = auditEdit.CANoList;
ViewBag.Is8DQA = auditEdit.Is8DQA;
ViewBag.IsAdmin = auditEdit.IsAdmin;
ViewBag.IsSubmitter = auditEdit.IsSubmitter;
ViewBag.MesaUsers = auditEdit.MesaUsers;
ViewBag.UserList = auditEdit.UserList;
} catch (Exception e) {
string detailedException = "";
try {
detailedException = e.InnerException.ToString();
} catch {
detailedException = e.Message;
}
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + audit.AuditNo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n Edit - Audit\r\n" + audit.AuditNo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
EventLogDMO.Add(new WinEventLog() { IssueID = audit.AuditNo, UserID = @User.Identity.Name, DocumentType = "Audit", OperationType = "Error", Comments = "Edit - " + exceptionString });
throw new Exception(e.Message);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public ActionResult Create()
{
return View(audit);
}
Audit audit = new Audit();
try
{
// TODO: Add insert logic here
audit.OriginatorID = (int)Session[GlobalVars.SESSION_USERID];
auditDMO.InsertAudit(audit);
return RedirectToAction("Edit", new { issueID = audit.AuditNo });
}
catch (Exception e)
{
string detailedException = "";
try
{
detailedException = e.InnerException.ToString();
}
catch
{
detailedException = e.Message;
}
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + audit.AuditNo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
Functions.WriteEvent(@User.Identity.Name + "\r\n SubmitDocument - Audit\r\n" + audit.AuditNo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
EventLogDMO.Add(new WinEventLog() { IssueID = audit.AuditNo, UserID = @User.Identity.Name, DocumentType = "Audit", OperationType = "Error", Comments = "SubmitDocument - " + exceptionString });
throw new Exception(e.Message);
}
[HttpPost]
public ActionResult Edit(Audit model) {
try {
var data = model;
auditDMO.UpdateAudit(model, (int)Session[GlobalVars.SESSION_USERID]);
} catch (Exception ex) {
return Content(ex.Message);
}
return Content("Successfully Saved");
}
/// <summary>
///
/// </summary>
/// <param name="issueID"></param>
/// <returns></returns>
public ActionResult Edit(int issueID)
{
int isITARCompliant = 1;
Audit audit = new Audit();
try
{
List<int> userList = auditDMO.Get8DQA();
ViewBag.MesaUsers = adUsers.GetMesaUsers();
int QAs = userList.Find(delegate(int al) { return al == (int)Session[GlobalVars.SESSION_USERID]; });
ViewBag.Is8DQA = "false";
if (QAs != 0)
{
ViewBag.Is8DQA = "true";
}
audit = auditDMO.GetAuditItem(issueID, (int)Session[GlobalVars.SESSION_USERID]);
//transform audit users from string to list, delimited by a comma.
if(audit.Auditees == null || !audit.Auditees.Contains(","))
{
ViewBag.AuditeeNames = audit.Auditees;
}
else
{
string[] auditeeNames = audit.Auditees.Split(',');
ViewBag.AuditeeNames = auditeeNames.ToList();
}
ViewBag.IsSubmitter = false;
if(audit.OriginatorID == (int)Session[GlobalVars.SESSION_USERID])
{
ViewBag.IsSubmitter = true;
}
if((bool)Session[GlobalVars.IS_ADMIN] != true)
{
ViewBag.IsAdmin = false;
}
else
{
ViewBag.IsAdmin = true;
}
if ((audit.RecordLockIndicator && audit.RecordLockedBy != (int)Session[GlobalVars.SESSION_USERID])
|| audit.AuditStatus != 0 ) //open
{
return RedirectToAction("ReadOnlyAudit", new { auditNo = audit.AuditNo });
}
if (ViewBag.IsAdmin == false && ViewBag.IsSubmitter == false)
{
return RedirectToAction("ReadOnlyAudit", new { auditNo = audit.AuditNo });
}
else
{
ViewBag.UserList = auditDMO.GetUserList();
ViewBag.AuditTypeList = auditDMO.GetAuditTypeList();
//ViewBag.AuditStandardList = auditDMO.GetAuditStandardList();
ViewBag.AuditorList = auditDMO.GetAuditorList();
ViewBag.AuditAreaList = auditDMO.GetAuditAreaList();
ViewBag.AuditFindingCategoryList = auditDMO.GetAuditFindingCategories();
ViewBag.CANoList = auditDMO.GetCorrectiveActionNoList();
}
}
catch (Exception e)
{
string detailedException = "";
try
{
detailedException = e.InnerException.ToString();
}
catch
{
detailedException = e.Message;
}
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + audit.AuditNo.ToString() + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
Functions.WriteEvent(@User.Identity.Name + "\r\n Edit - Audit\r\n" + audit.AuditNo.ToString() + "\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
EventLogDMO.Add(new WinEventLog() { IssueID = audit.AuditNo, UserID = @User.Identity.Name, DocumentType = "Audit", OperationType = "Error", Comments = "Edit - " + exceptionString });
throw new Exception(e.Message);
}
return View(audit);
public ActionResult CheckCAStatus(int auditNo) {
int dataCount = -1;
try {
dataCount = auditDMO.GetOpenCACountByAuditNo(auditNo);
} catch (Exception ex) {
throw;
}
/// <summary>
///
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
[HttpPost]
public ActionResult Edit(Audit model)
{
try
{
return Content(dataCount.ToString());
}
var data = model;
auditDMO.UpdateAudit(model, (int)Session[GlobalVars.SESSION_USERID]);
}
catch (Exception ex)
{
return Content(ex.Message);
}
public ActionResult ReadOnlyAudit(int auditNo) {
Audit audit = new Audit();
audit = auditDMO.GetAuditItemReadOnly(auditNo, (int)Session[GlobalVars.SESSION_USERID]);
return Content("Successfully Saved");
}
ViewBag.AuditTypeList = auditDMO.GetAuditTypeList();
ViewBag.AuditorList = auditDMO.GetAuditorList();
ViewBag.AuditAreaList = auditDMO.GetAuditAreaList();
ViewBag.AuditFindingCategoryList = auditDMO.GetAuditFindingCategories();
/// <summary>
///
/// </summary>
/// <param name="auditNo"></param>
/// <returns></returns>
public ActionResult CheckCAStatus(int auditNo)
{
int dataCount = -1;
try
{
dataCount = auditDMO.GetOpenCACountByAuditNo(auditNo);
}
catch (Exception ex)
{
throw;
}
return View(audit);
}
return Content(dataCount.ToString());
}
/// <summary>
///
/// </summary>
/// <param name="auditNo"></param>
/// <returns></returns>
public ActionResult ReadOnlyAudit(int auditNo)
{
Audit audit = new Audit();
audit = auditDMO.GetAuditItemReadOnly(auditNo, (int)Session[GlobalVars.SESSION_USERID]);
ViewBag.AuditTypeList = auditDMO.GetAuditTypeList();
ViewBag.AuditorList = auditDMO.GetAuditorList();
ViewBag.AuditAreaList = auditDMO.GetAuditAreaList();
ViewBag.AuditFindingCategoryList = auditDMO.GetAuditFindingCategories();
return View(audit);
}
/// <summary>
///
/// </summary>
/// <param name="AuditReportFiles"></param>
/// <param name="auditNo"></param>
/// <returns></returns>
public ActionResult AuditReportAttachSave(IEnumerable<HttpPostedFileBase> AuditReportFiles, int auditNo)
{
try
{
// The Name of the Upload component is "files"
if (AuditReportFiles != null)
{
foreach (var file in AuditReportFiles)
{
// Some browsers send file names with full path.
// We are only interested in the file name.
var fileName = Path.GetFileName(file.FileName);
var fileExtension = Path.GetExtension(file.FileName);
//var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName);
DirectoryInfo di;
var ccPhysicalPath = Functions.GetAttachmentFolder() + @"Audit\" + auditNo;
di = new DirectoryInfo(ccPhysicalPath);
if (!di.Exists)
di.Create();
var guid = Guid.NewGuid().ToString();
var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + @"Audit\" + auditNo + @"\", guid + fileExtension);
file.SaveAs(physicalPath);
AuditReportAttachment attach = new AuditReportAttachment()
{
AuditNo = auditNo,
FileGUID = guid,
FileName = fileName,
UploadedByID = (int)Session[GlobalVars.SESSION_USERID]
};
//ccDMO.InsertCCAttachment(attach);
auditDMO.InsertAuditReportAttachment(attach);
}
public ActionResult AuditReportAttachSave(IEnumerable<HttpPostedFileBase> AuditReportFiles, int auditNo) {
try {
// The Name of the Upload component is "files"
if (AuditReportFiles != null) {
int userId = (int)Session[GlobalVars.SESSION_USERID];
foreach (var file in AuditReportFiles) {
auditDMO.AuditReportAttachSave(auditNo, userId, file.FileName, file.InputStream);
}
}
catch
{
throw;
}
return Content("");
} catch {
throw;
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="auditNo"></param>
/// <returns></returns>
public ActionResult AuditReportAttachment_Read([DataSourceRequest] DataSourceRequest request, int auditNo)
{
return Json(auditDMO.GetAuditReportAttachments(auditNo).ToDataSourceResult(request));
}
return Content("");
}
public ActionResult AuditReportAttachment_Read([DataSourceRequest] DataSourceRequest request, int auditNo) {
/// <summary>
///
/// </summary>
/// <param name="attachID"></param>
[HttpPost]
public void DeleteAuditReportAttachment(int attachID)
{
auditDMO.DeleteAuditReportAttachment(attachID);
return Json(auditDMO.GetAuditReportAttachments(auditNo).ToDataSourceResult(request));
}
}
/// <summary>
///
/// </summary>
/// <param name="fileGuid"></param>
/// <param name="auditNo"></param>
/// <returns></returns>
public FileResult DownloadAuditReportAttachment(string fileGuid, int auditNo)
{
try
{
string fileName = auditDMO.GetAuditReportAttachmentFileName(fileGuid);
[HttpPost]
public void DeleteAuditReportAttachment(int attachID) {
auditDMO.DeleteAuditReportAttachment(attachID);
}
string fileExtension = fileName.Substring(fileName.LastIndexOf("."), fileName.Length - fileName.LastIndexOf("."));
string ecnFolderPath = Functions.GetAttachmentFolder() + "Audit\\" + auditNo.ToString();
var sDocument = Path.Combine(ecnFolderPath, fileGuid + fileExtension);
var FDir_AppData = Functions.GetAttachmentFolder();
if (!sDocument.StartsWith(FDir_AppData))
{
// Ensure that we are serving file only inside the Fab2ApprovalAttachments folder
// and block requests outside like "../web.config"
throw new HttpException(403, "Forbidden");
}
if (!System.IO.File.Exists(sDocument))
{
return null;
//throw new Exception("File not found");
}
return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
public FileResult DownloadAuditReportAttachment(string fileGuid, int auditNo) {
try {
string fileName, sDocument;
List<string> results = auditDMO.GetFileNameAndDocument(fileGuid, auditNo);
fileName = results[0];
sDocument = results[1];
if (string.IsNullOrEmpty(sDocument)) {
// Ensure that we are serving file only inside the Fab2ApprovalAttachments folder
// and block requests outside like "../web.config"
throw new HttpException(403, "Forbidden");
}
catch
{
// TODO - proces the error
throw;
if (!System.IO.File.Exists(sDocument)) {
return null;
//throw new Exception("File not found");
}
return File(sDocument, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
} catch {
// TODO - proces the error
throw;
}
}
public ActionResult GetAuditFindingsList([DataSourceRequest] DataSourceRequest request, int auditNo) {
return Json(auditDMO.GetAuditFindingsList(auditNo).ToDataSourceResult(request));
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="auditNo"></param>
/// <returns></returns>
public ActionResult GetAuditFindingsList([DataSourceRequest] DataSourceRequest request, int auditNo)
{
public ActionResult InsertAuditFindingsItem(AuditFindings data) {
if ((data.FindingType == "Major" || data.FindingType == "Minor") && data.CANo == 0) {
throw new ArgumentException("You must select add a CA for a Major or Minor finding.");
} else {
int userId = (int)Session[GlobalVars.SESSION_USERID];
Audit audit = auditDMO.InsertAndGetAudit(caDMO, data, userId);
return Json(auditDMO.GetAuditFindingsList(auditNo).ToDataSourceResult(request));
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
public ActionResult InsertAuditFindingsItem(AuditFindings data)
{
if ((data.FindingType == "Major" || data.FindingType == "Minor") && data.CANo == 0)
{
throw new ArgumentException("You must select add a CA for a Major or Minor finding.");
}
else
{
Audit audit = new Audit();
auditDMO.InsertAuditFindingsItem(data);
audit = auditDMO.GetAuditItem(data.AuditNo, (int)Session[GlobalVars.SESSION_USERID]);
//Transfer Finding Details to CA
if(data.CANo != 0)
{
CorrectiveAction ca = caDMO.GetCAItem(data.CANo, (int)Session[GlobalVars.SESSION_USERID]);
ca.CATitle = data.Title;
ca.CASourceID = 1;//Audit
caDMO.UpdateCorrectiveAction(ca);
}
return Json(audit, JsonRequestBehavior.AllowGet);
}
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
public ActionResult UpdateAuditFindingsItem(AuditFindings data)
{
if ((data.FindingType == "Major" || data.FindingType == "Minor") && data.CANo == 0)
{
throw new ArgumentException("You must select add a CA for a Major or Minor finding.");
}
else
{
Audit audit = new Audit();
auditDMO.UpdateAuditFindingsItem(data);
audit = auditDMO.GetAuditItem(data.AuditNo, (int)Session[GlobalVars.SESSION_USERID]);
//Transfer Finding Details to CA
if (data.CANo != 0)
{
CorrectiveAction ca = caDMO.GetCAItem(data.CANo, (int)Session[GlobalVars.SESSION_USERID]);
ca.CATitle = data.Title;
ca.CASourceID = 1;//Audit
caDMO.UpdateCorrectiveAction(ca);
}
return Json(audit, JsonRequestBehavior.AllowGet);
}
}
public ActionResult DeleteAuditFindingsItem(int auditFindingsID)
{
var af = auditDMO.GetAuditFindingsByID(auditFindingsID);
auditDMO.DeleteAuditFindingsItem(auditFindingsID);
var audit = auditDMO.GetAuditItem(af.AuditNo, (int)Session[GlobalVars.SESSION_USERID]);
return Json(audit, JsonRequestBehavior.AllowGet);
}
/// <summary>
///
/// </summary>
/// <param name="issueID"></param>
public void ReleaseLockOnDocument(int issueID)
{
try
{
auditDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], issueID);
}
catch (Exception e)
{
try
{
Functions.WriteEvent(@User.Identity.Name + "\r\n ReleaseLockOnDocument CA\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error);
}
catch { }
auditDMO.ReleaseLockOnDocument(-1, issueID);
}
}
// CA Findings ======================================================================================================================
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public ActionResult InsertCAFindingsItem(CAFindings data)
{
auditDMO.InsertCAFindings(data);
if (data.ResponsibilityOwnerID != null)
{
// send an email notification
NotifyActionItemOwner(data.AuditNo, data.ECD, data.ResponsibilityOwnerID);
}
return Content("");
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public ActionResult UpdateCAFindingsItem(CAFindings data)
{
auditDMO.UpdateCAFindings(data);
if (data.ResponsibilityOwnerID != data.CurrentResponsibilityOwnerID)
{
NotifyActionItemOwner(data.AuditNo, data.ECD, data.ResponsibilityOwnerID);
}
return Content("");
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="caNo"></param>
/// <returns></returns>
public ActionResult GetCAFindingsList([DataSourceRequest] DataSourceRequest request, int auditNo)
{
return Json(auditDMO.GetCAFindingsList(auditNo).ToDataSourceResult(request));
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="d7PAID"></param>
/// <returns></returns>
public ActionResult GetCAFindingsItemAttachments([DataSourceRequest] DataSourceRequest request, int caFindingsID)
{
return Json(auditDMO.GetCAFindingsItemAttachments(caFindingsID).ToDataSourceResult(request));
}
/// <summary>
///
/// </summary>
/// <param name="d7paID"></param>
/// <returns></returns>
public ActionResult GetCAFindingsItem(int caFindingsID)
{
var model = new CAFindings();
model = auditDMO.GetCAFindingsItem(caFindingsID);
return PartialView("_CAFindingsAttachment", model);
}
/// <summary>
///
/// </summary>
/// <param name="caFindingsID"></param>
[HttpPost]
public void DeleteCAFindingsItem(int caFindingsID)
{
auditDMO.DeleteCAFindingsItem(caFindingsID);
}
/// <summary>
///
/// </summary>
/// <param name="D7PA_Attachemnt"></param>
/// <param name="d7PAID"></param>
/// <param name="caNo"></param>
/// <returns></returns>
public ActionResult SaveCAFindings_Attachemnt(IEnumerable<HttpPostedFileBase> CAFindings_Attachemnt, int caFindingsID, int auditNo)
{
try
{
// The Name of the Upload component is "files"
if (CAFindings_Attachemnt != null)
{
foreach (var file in CAFindings_Attachemnt)
{
// Some browsers send file names with full path.
// We are only interested in the file name.
var fileName = Path.GetFileName(file.FileName);
var fileExtension = Path.GetExtension(file.FileName);
//var physicalPath = Path.Combine(Server.MapPath("~/UserUploads"), fileName);
DirectoryInfo di;
var ccPhysicalPath = Functions.GetAttachmentFolder() + @"Audit\" + auditNo;
di = new DirectoryInfo(ccPhysicalPath);
if (!di.Exists)
di.Create();
var guid = Guid.NewGuid().ToString();
var physicalPath = Path.Combine(Functions.GetAttachmentFolder() + @"Audit\" + auditNo + @"\", guid + fileExtension);
file.SaveAs(physicalPath);
AuditReportAttachment attach = new AuditReportAttachment()
{
CAFindingsID = caFindingsID,
AuditNo = auditNo,
FileGUID = guid,
FileName = fileName,
UploadedByID = (int)Session[GlobalVars.SESSION_USERID]
};
auditDMO.InsertAuditReportAttachment(attach);
}
}
}
catch
{
throw;
}
return Content("");
}
/// <summary>
///
/// </summary>
/// <param name="issueID"></param>
/// <param name="currentStep"></param>
public void NotifyActionItemOwner(int issueID, DateTime? dueDate, int? responsibleOwnerID)
{
try
{
string emailSentList = "";
//List<string> emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList();
string email = MiscDMO.GetEmail(responsibleOwnerID);
string emailTemplate = "CorrectiveActionFindingAssigned.txt";
string userEmail = string.Empty;
string subject = "5s/CA Findings";
string senderName = "CorrectiveAction";
EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
string[] emailparams = new string[5];
emailparams[0] = Functions.ReturnAuditNoStringFormat(issueID);
emailparams[1] = dueDate.ToString();
emailparams[2] = Functions.DocumentTypeMapper(GlobalVars.DocumentType.Audit);
emailparams[3] = GlobalVars.hostURL;
emailparams[4] = issueID.ToString();
userEmail = email;
en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);
emailSentList += email + ",";
try
{
EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Task Assigned for 5S/CA Findings" + ":" + email });
}
catch { }
}
catch (Exception e)
{
string detailedException = "";
try
{
detailedException = e.InnerException.ToString();
}
catch
{
detailedException = e.Message;
}
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " 5s/CAFindings:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
Functions.WriteEvent(@User.Identity.Name + "\r\n 5s/CAFindings - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "5s/CAFindings Notification - " + exceptionString });
//throw e;
}
}
public ActionResult IsCAAssignedToAudit(int caNo, int auditNo)
{
return Content(auditDMO.IsCAAssignedToAudit(caNo, auditNo).ToString());
}
}
}
public ActionResult UpdateAuditFindingsItem(AuditFindings data) {
if ((data.FindingType == "Major" || data.FindingType == "Minor") && data.CANo == 0) {
throw new ArgumentException("You must select add a CA for a Major or Minor finding.");
} else {
int userId = (int)Session[GlobalVars.SESSION_USERID];
Audit audit = auditDMO.UpdateAndGetAudit(caDMO, data, userId);
return Json(audit, JsonRequestBehavior.AllowGet);
}
}
public ActionResult DeleteAuditFindingsItem(int auditFindingsID) {
int userId = (int)Session[GlobalVars.SESSION_USERID];
Audit audit = auditDMO.DeleteAndGetAudit(auditFindingsID, userId);
return Json(audit, JsonRequestBehavior.AllowGet);
}
public void ReleaseLockOnDocument(int issueID) {
try {
auditDMO.ReleaseLockOnDocument((int)Session[GlobalVars.SESSION_USERID], issueID);
} catch (Exception e) {
try {
Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n ReleaseLockOnDocument CA\r\n" + issueID.ToString() + "\r\n" + e.Message, System.Diagnostics.EventLogEntryType.Error);
} catch { }
auditDMO.ReleaseLockOnDocument(-1, issueID);
}
}
// CA Findings ======================================================================================================================
public ActionResult InsertCAFindingsItem(CAFindings data) {
auditDMO.InsertCAFindings(data);
if (data.ResponsibilityOwnerID != null) {
// send an email notification
NotifyActionItemOwner(data.AuditNo, data.ECD, data.ResponsibilityOwnerID);
}
return Content("");
}
public ActionResult UpdateCAFindingsItem(CAFindings data) {
auditDMO.UpdateCAFindings(data);
if (data.ResponsibilityOwnerID != data.CurrentResponsibilityOwnerID) {
NotifyActionItemOwner(data.AuditNo, data.ECD, data.ResponsibilityOwnerID);
}
return Content("");
}
public ActionResult GetCAFindingsList([DataSourceRequest] DataSourceRequest request, int auditNo) {
return Json(auditDMO.GetCAFindingsList(auditNo).ToDataSourceResult(request));
}
public ActionResult GetCAFindingsItemAttachments([DataSourceRequest] DataSourceRequest request, int caFindingsID) {
return Json(auditDMO.GetCAFindingsItemAttachments(caFindingsID).ToDataSourceResult(request));
}
public ActionResult GetCAFindingsItem(int caFindingsID) {
var model = new CAFindings();
model = auditDMO.GetCAFindingsItem(caFindingsID);
return PartialView("_CAFindingsAttachment", model);
}
[HttpPost]
public void DeleteCAFindingsItem(int caFindingsID) {
auditDMO.DeleteCAFindingsItem(caFindingsID);
}
public ActionResult SaveCAFindings_Attachemnt(IEnumerable<HttpPostedFileBase> CAFindings_Attachemnt, int caFindingsID, int auditNo) {
try {
// The Name of the Upload component is "files"
if (CAFindings_Attachemnt != null) {
int userId = (int)Session[GlobalVars.SESSION_USERID];
foreach (var file in CAFindings_Attachemnt) {
auditDMO.SaveAndInsert(caFindingsID, auditNo, userId, file.FileName, file.InputStream);
}
}
} catch {
throw;
}
return Content("");
}
public void NotifyActionItemOwner(int issueID, DateTime? dueDate, int? responsibleOwnerID) {
try {
string emailTemplatesPath = ConfigurationManager.AppSettings["EmailTemplatesPath"];
string email = auditDMO.NotifyActionItemOwner(issueID, dueDate, responsibleOwnerID, emailTemplatesPath);
try {
EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Email", Comments = "Task Assigned for 5S/CA Findings" + ":" + email });
} catch { }
} catch (Exception e) {
string detailedException = "";
try {
detailedException = e.InnerException.ToString();
} catch {
detailedException = e.Message;
}
string exceptionString = e.Message.ToString().Trim().Length > 500 ? "Issue=" + issueID.ToString() + " 5s/CAFindings:" + e.Message.ToString().Substring(0, 250) : e.Message.ToString();
Functions.WriteEvent(_AppSettings, @User.Identity.Name + "\r\n 5s/CAFindings - NotifyActionItemOwner\r\n" + detailedException, System.Diagnostics.EventLogEntryType.Error);
EventLogDMO.Add(new WinEventLog() { IssueID = issueID, UserID = @User.Identity.Name, DocumentType = "Corrective Action", OperationType = "Error", Comments = "5s/CAFindings Notification - " + exceptionString });
//throw e;
}
}
public ActionResult IsCAAssignedToAudit(int caNo, int auditNo) {
return Content(auditDMO.IsCAAssignedToAudit(caNo, auditNo).ToString());
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,37 +1,36 @@
using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Misc;
using Fab2ApprovalSystem.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Misc;
namespace Fab2ApprovalSystem.Controllers
{
[Authorize]
[SessionExpireFilter]
public class ManagerController : Controller
{
UserAccountDMO userDMO = new UserAccountDMO();
AdminDMO adminDMO = new AdminDMO();
TrainingDMO trainingDMO = new TrainingDMO();
LotDispositionDMO ldDMO = new LotDispositionDMO();
namespace Fab2ApprovalSystem.Controllers;
/// <summary>
///
/// </summary>
/// <returns></returns>
public ActionResult Index()
{
[Authorize]
[SessionExpireFilter]
public class ManagerController : Controller {
if ((bool)Session[GlobalVars.IS_MANAGER])
{
var model = userDMO.GetAllUsers();
ViewBag.AllActiveUsers = userDMO.GetAllActiveUsers();
return View(model);
}
else
return Content("Not Autthorized");
}
UserAccountDMO userDMO = new UserAccountDMO();
AdminDMO adminDMO = new AdminDMO();
TrainingDMO trainingDMO = new TrainingDMO();
LotDispositionDMO ldDMO;
private readonly AppSettings _AppSettings;
public ManagerController(AppSettings appSettings) {
_AppSettings = appSettings;
ldDMO = new LotDispositionDMO(appSettings);
}
}
public ActionResult Index() {
if ((bool)Session[GlobalVars.IS_MANAGER]) {
var model = userDMO.GetAllUsers();
ViewBag.AllActiveUsers = userDMO.GetAllActiveUsers();
return View(model);
} else
return Content("Not Autthorized");
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,221 +1,194 @@
using System;
using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Misc;
using Fab2ApprovalSystem.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Misc;
using Fab2ApprovalSystem.ViewModels;
namespace Fab2ApprovalSystem.Controllers;
namespace Fab2ApprovalSystem.Controllers
{
[Authorize]
[SessionExpireFilter]
public class ReportsController : Controller
{
public const String specialNullString = "~NULL~";
[Authorize]
[SessionExpireFilter]
public class ReportsController : Controller {
public const String specialNullString = "~NULL~";
// GET: Export
public ActionResult Index()
{
UserAccountDMO userDMO = new UserAccountDMO();
ViewBag.HasITARAccess = userDMO.GetITARAccess((int)Session[GlobalVars.SESSION_USERID]);
// GET: Export
public ActionResult Index() {
UserAccountDMO userDMO = new UserAccountDMO();
ViewBag.HasITARAccess = userDMO.GetITARAccess((int)Session[GlobalVars.SESSION_USERID]);
return View();
}
return View();
}
public ActionResult Report(String id, String docType = "")
{
if (String.IsNullOrEmpty(id))
return RedirectToAction("Index");
public ActionResult Report(String id, String docType = "") {
if (String.IsNullOrEmpty(id))
return RedirectToAction("Index");
UserAccountDMO userDMO = new UserAccountDMO();
if (!userDMO.GetITARAccess((int)Session[GlobalVars.SESSION_USERID]))
return View("UnAuthorizedAccess");
UserAccountDMO userDMO = new UserAccountDMO();
if (!userDMO.GetITARAccess((int)Session[GlobalVars.SESSION_USERID]))
return View("UnAuthorizedAccess");
var m = new ReportViewModel();
var reports = GetReportList(docType);
foreach (var report in reports)
{
if (String.Equals(report.ReportID, id, StringComparison.OrdinalIgnoreCase))
{
m.ReportID = report.ReportID;
m.ReportName = report.Name;
m.Description = report.Description;
m.DocType = docType;
var m = new ReportViewModel<System.Web.Mvc.SelectListItem>();
var reports = GetReportList(docType);
foreach (var report in reports) {
if (String.Equals(report.ReportID, id, StringComparison.OrdinalIgnoreCase)) {
m.ReportID = report.ReportID;
m.ReportName = report.Name;
m.Description = report.Description;
m.DocType = docType;
var c = SetupSSRSHelperClient();
var c = SetupSSRSHelperClient();
m.Parameters = c.GetReportParameters(report.FullPath).Select(parm =>
{
var r = new ReportParameterViewModel();
r.Visible = (parm.PromptUser.HasValue == false || parm.PromptUser == true) && !String.IsNullOrEmpty(parm.Prompt);
r.Prompt = parm.Prompt;
r.Name = parm.Name;
r.HtmlID = "parm_" + parm.Name;
m.Parameters = c.GetReportParameters(report.FullPath).Select(parm => {
var r = new ReportParameterViewModel<System.Web.Mvc.SelectListItem>();
r.Visible = (parm.PromptUser.HasValue == false || parm.PromptUser == true) && !String.IsNullOrEmpty(parm.Prompt);
r.Prompt = parm.Prompt;
r.Name = parm.Name;
r.HtmlID = "parm_" + parm.Name;
if (parm.MultiValue.HasValue && parm.MultiValue.Value)
r.ControlType = ParameterControlTypes.Multiselect;
else if ((parm.ValidValues != null) && (parm.ValidValues.Length > 0))
r.ControlType = ParameterControlTypes.Dropdown;
else if (parm.DataType.Equals("DateTime", StringComparison.OrdinalIgnoreCase))
r.ControlType = ParameterControlTypes.DatePicker;
else
r.ControlType = ParameterControlTypes.Textbox;
if (parm.MultiValue.HasValue && parm.MultiValue.Value)
r.ControlType = ParameterControlTypes.Multiselect;
else if ((parm.ValidValues != null) && (parm.ValidValues.Length > 0))
r.ControlType = ParameterControlTypes.Dropdown;
else if (parm.DataType.Equals("DateTime", StringComparison.OrdinalIgnoreCase))
r.ControlType = ParameterControlTypes.DatePicker;
else
r.ControlType = ParameterControlTypes.Textbox;
r.SelectList = null;
if (parm.ValidValues != null)
{
r.SelectList = parm.ValidValues.Select(vv => {
return new SelectListItem()
{
Text = vv.Value,
Value = (vv.Key == null ? specialNullString : vv.Key),
Selected = (parm.DefaultValues != null && parm.DefaultValues.Contains(vv.Key))
};
}).ToList();
}
r.SelectList = null;
if (parm.ValidValues != null) {
r.SelectList = parm.ValidValues.Select(vv => {
return new SelectListItem() {
Text = vv.Value,
Value = (vv.Key == null ? specialNullString : vv.Key),
Selected = (parm.DefaultValues != null && parm.DefaultValues.Contains(vv.Key))
};
}).ToList();
}
r.DefaultValue = "";
if (parm.DefaultValues != null && parm.DefaultValues.Length > 0)
r.DefaultValue = parm.DefaultValues[0];
r.DefaultValue = "";
if (parm.DefaultValues != null && parm.DefaultValues.Length > 0)
r.DefaultValue = parm.DefaultValues[0];
return r;
return r;
}).ToArray();
}
}).ToArray();
}
return View(m);
}
public SSRSHelper.SSRSClient SetupSSRSHelperClient()
{
var useCfgForBindings = false;
if (String.Equals(System.Configuration.ConfigurationManager.AppSettings["SSRSBindingsByConfiguration"], "true", StringComparison.OrdinalIgnoreCase))
useCfgForBindings = true;
return View(m);
}
var c = new SSRSHelper.SSRSClient(
Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["SSRSBaseURL"]),
Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["SSRSDomain"]),
Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["SSRSUsername"]),
Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["SSRSPassword"]),
useCfgForBindings);
c.Initialize();
public SSRSHelper.SSRSClient SetupSSRSHelperClient() {
var useCfgForBindings = false;
if (String.Equals(System.Configuration.ConfigurationManager.AppSettings["SSRSBindingsByConfiguration"], "true", StringComparison.OrdinalIgnoreCase))
useCfgForBindings = true;
return c;
}
var c = new SSRSHelper.SSRSClient(
Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["SSRSBaseURL"]),
Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["SSRSDomain"]),
Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["SSRSUsername"]),
Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["SSRSPassword"]),
useCfgForBindings);
c.Initialize();
private IEnumerable<SSRSHelper.ReportInfo> GetReportList(String docType)
{
String folderName = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["SSRSFolder"]);
if (folderName.EndsWith("/"))
folderName = folderName.TrimEnd('/');
if (!String.IsNullOrWhiteSpace(docType))
folderName = folderName + "/" + docType;
return c;
}
var c = SetupSSRSHelperClient();
return c.ListReports(folderName);
}
private IEnumerable<SSRSHelper.ReportInfo> GetReportList(String docType) {
String folderName = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["SSRSFolder"]);
if (folderName.EndsWith("/"))
folderName = folderName.TrimEnd('/');
if (!String.IsNullOrWhiteSpace(docType))
folderName = folderName + "/" + docType;
public ActionResult GetReports(String docType)
{
var reports = GetReportList(docType);
var c = SetupSSRSHelperClient();
return c.ListReports(folderName);
}
return Json(new { Data =
reports.Select(r => new ReportViewModel()
{
ReportName = r.Name ?? "",
Description = r.Description ?? "",
ReportID = r.ReportID ?? "",
DocType = docType
})
},
JsonRequestBehavior.AllowGet);
}
public ActionResult GetReports(String docType) {
var reports = GetReportList(docType);
[HttpPost]
public ActionResult ExportReport(String DocType, String ReportID)
{
var c = SetupSSRSHelperClient();
var reports = GetReportList(DocType);
return Json(new {
Data =
reports.Select(r => new ReportViewModel<System.Web.Mvc.SelectListItem>() {
ReportName = r.Name ?? "",
Description = r.Description ?? "",
ReportID = r.ReportID ?? "",
DocType = docType
})
},
JsonRequestBehavior.AllowGet);
}
var report = reports.Where(r => String.Equals(r.ReportID, ReportID, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
if (report == null)
return Content("Invalid report ID");
[HttpPost]
public ActionResult ExportReport(String DocType, String ReportID) {
var c = SetupSSRSHelperClient();
var reports = GetReportList(DocType);
var reportParms = c.GetReportParameters(report.FullPath);
var report = reports.Where(r => String.Equals(r.ReportID, ReportID, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
if (report == null)
return Content("Invalid report ID");
var parms = new SSRSHelper.ReportParameterCollection();
parms.Add("DocType", DocType);
parms.Add("UserID", Convert.ToString(Session[GlobalVars.SESSION_USERID]));
parms.Add("BaseURL", GlobalVars.hostURL);
var reportParms = c.GetReportParameters(report.FullPath);
foreach (var rp in reportParms)
{
if (rp.MultiValue.HasValue && rp.MultiValue.Value)
{
foreach (String v in Request.Params.GetValues("parm_" + rp.Name))
{
parms.Add(rp.Name, v);
var parms = new SSRSHelper.ReportParameterCollection();
parms.Add("DocType", DocType);
parms.Add("UserID", Convert.ToString(Session[GlobalVars.SESSION_USERID]));
parms.Add("BaseURL", GlobalVars.hostURL);
foreach (var rp in reportParms) {
if (rp.MultiValue.HasValue && rp.MultiValue.Value) {
foreach (String v in Request.Params.GetValues("parm_" + rp.Name)) {
parms.Add(rp.Name, v);
}
} else {
String value = null;
if (Request.Params.AllKeys.Contains("parm_" + rp.Name))
value = Request.Params.GetValues("parm_" + rp.Name).FirstOrDefault();
if (value == specialNullString)
value = null;
if ((rp.AllowBlank.HasValue == false || rp.AllowBlank.Value == false) && value == "")
value = null;
if (value == null) {
if (rp.Nullable.HasValue == false || rp.Nullable.Value == false) {
if (rp.DefaultValues != null && rp.DefaultValues.Length > 0)
value = rp.DefaultValues[0];
if (value == null)
continue;
}
}
else
{
String value = null;
if (Request.Params.AllKeys.Contains("parm_" + rp.Name))
value = Request.Params.GetValues("parm_" + rp.Name).FirstOrDefault();
if (value == specialNullString)
value = null;
if ((rp.AllowBlank.HasValue == false || rp.AllowBlank.Value == false) && value == "")
value = null;
if (value == null)
{
if (rp.Nullable.HasValue == false || rp.Nullable.Value == false)
{
if (rp.DefaultValues != null && rp.DefaultValues.Length > 0)
value = rp.DefaultValues[0];
if (value == null)
continue;
}
}
parms.Add(rp.Name, value);
}
parms.Add(rp.Name, value);
}
var b = c.ExportReport(report.FullPath, @User.Identity.Name, parms, "EXCELOPENXML");
try
{
var b2 = c.FreezeExcelHeaders(b);
return File(b2, "application/octet-stream", MakeFilename(report.Name) + ".xlsx");
}
catch
{
}
return File(b, "application/octet-stream", MakeFilename(report.Name) + ".xlsx");
}
protected String MakeFilename(String reportName)
{
String r = "";
var invalidChars = System.IO.Path.GetInvalidFileNameChars();
foreach (char c in reportName)
{
if (invalidChars.Contains(c))
r += '_';
else
r += c;
}
return r;
var b = c.ExportReport(report.FullPath, @User.Identity.Name, parms, "EXCELOPENXML");
try {
var b2 = c.FreezeExcelHeaders(b);
return File(b2, "application/octet-stream", MakeFilename(report.Name) + ".xlsx");
} catch {
}
return File(b, "application/octet-stream", MakeFilename(report.Name) + ".xlsx");
}
protected String MakeFilename(String reportName) {
String r = "";
var invalidChars = System.IO.Path.GetInvalidFileNameChars();
foreach (char c in reportName) {
if (invalidChars.Contains(c))
r += '_';
else
r += c;
}
return r;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -5,87 +5,69 @@ using System.Net;
using System.Net.Http;
using System.Web.Http;
using Fab2ApprovalSystem.Models;
namespace Fab2ApprovalSystem.Controllers
{
public class WebAPIController : ApiController
{
public TrainingController trainingFunctions = new TrainingController();
public CorrectiveActionController carFunctions = new CorrectiveActionController();
public AccountController accountFunctions = new AccountController();
public HomeController homeFunctions = new HomeController();
public string Get()
{
return "Welcome To Web API";
}
public List<string> Get(int Id)
{
return new List<string> {
namespace Fab2ApprovalSystem.Controllers;
public class WebAPIController : ApiController {
public TrainingController trainingFunctions = new TrainingController();
public CorrectiveActionController carFunctions;
public AccountController accountFunctions = new AccountController();
public HomeController homeFunctions;
private readonly AppSettings _AppSettings;
public WebAPIController(AppSettings appSettings) {
_AppSettings = appSettings;
carFunctions = new CorrectiveActionController(appSettings);
homeFunctions = new HomeController(appSettings);
}
public string Get() {
return "Welcome To Web API";
}
public List<string> Get(int Id) {
return new List<string> {
"Data1",
"Data2"
};
}
public void Post()
{
}
public HttpResponseMessage Post(HttpRequestMessage request, string action)
{
switch (action)
{
case "TrainingReport":
if (trainingFunctions.RunTrainingReport())
{
return request.CreateResponse(HttpStatusCode.OK);
}
else
{
return request.CreateResponse(HttpStatusCode.InternalServerError);
}
case "CARDueDates":
if (carFunctions.ProcessCARDueDates())
{
return request.CreateResponse(HttpStatusCode.OK);
}
else
{
return request.CreateResponse(HttpStatusCode.InternalServerError);
}
case "ProcessOoO":
if (homeFunctions.ProcessOoO())
{
return request.CreateResponse(HttpStatusCode.OK);
}
else
{
return request.CreateResponse(HttpStatusCode.InternalServerError);
}
case "ExpireOoO":
if (homeFunctions.ExpireOoO())
{
return request.CreateResponse(HttpStatusCode.OK);
}
else
{
return request.CreateResponse(HttpStatusCode.InternalServerError);
}
case "ApprovalReminders":
if (homeFunctions.ApprovalsReminderNotifications())
{
return request.CreateResponse(HttpStatusCode.OK);
}
else
{
return request.CreateResponse(HttpStatusCode.InternalServerError);
}
default:
return request.CreateResponse(HttpStatusCode.InternalServerError, "Action Not Found");
}
}
public void Post() {
}
public HttpResponseMessage Post(HttpRequestMessage request, string action) {
switch (action) {
case "TrainingReport":
if (trainingFunctions.RunTrainingReport()) {
return request.CreateResponse(HttpStatusCode.OK);
} else {
return request.CreateResponse(HttpStatusCode.InternalServerError);
}
case "CARDueDates":
if (carFunctions.ProcessCARDueDates()) {
return request.CreateResponse(HttpStatusCode.OK);
} else {
return request.CreateResponse(HttpStatusCode.InternalServerError);
}
case "ProcessOoO":
if (homeFunctions.ProcessOoO()) {
return request.CreateResponse(HttpStatusCode.OK);
} else {
return request.CreateResponse(HttpStatusCode.InternalServerError);
}
case "ExpireOoO":
if (homeFunctions.ExpireOoO()) {
return request.CreateResponse(HttpStatusCode.OK);
} else {
return request.CreateResponse(HttpStatusCode.InternalServerError);
}
case "ApprovalReminders":
if (homeFunctions.ApprovalsReminderNotifications()) {
return request.CreateResponse(HttpStatusCode.OK);
} else {
return request.CreateResponse(HttpStatusCode.InternalServerError);
}
default:
return request.CreateResponse(HttpStatusCode.InternalServerError, "Action Not Found");
}
}
}
}

View File

@ -1,99 +1,81 @@
using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Models;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kendo.Mvc.Extensions;
namespace Fab2ApprovalSystem.Controllers;
namespace Fab2ApprovalSystem.Controllers
{
public class WorkflowController : Controller
{
//
//
// GET: /Workflow/Details/5
public ActionResult Details(int id)
{
return View();
}
//
// GET: /Workflow/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Workflow/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /Workflow/Edit/5
public ActionResult Edit(int id)
{
return View();
}
//
// POST: /Workflow/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /Workflow/Delete/5
public ActionResult Delete(int id)
{
return View();
}
//
// POST: /Workflow/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
public class WorkflowController : Controller {
//
//
// GET: /Workflow/Details/5
public ActionResult Details(int id) {
return View();
}
}
//
// GET: /Workflow/Create
public ActionResult Create() {
return View();
}
//
// POST: /Workflow/Create
[HttpPost]
public ActionResult Create(FormCollection collection) {
try {
// TODO: Add insert logic here
return RedirectToAction("Index");
} catch {
return View();
}
}
//
// GET: /Workflow/Edit/5
public ActionResult Edit(int id) {
return View();
}
//
// POST: /Workflow/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection) {
try {
// TODO: Add update logic here
return RedirectToAction("Index");
} catch {
return View();
}
}
//
// GET: /Workflow/Delete/5
public ActionResult Delete(int id) {
return View();
}
//
// POST: /Workflow/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection) {
try {
// TODO: Add delete logic here
return RedirectToAction("Index");
} catch {
return View();
}
}
}