MRB webassembly

This commit is contained in:
Chase Tucker
2024-05-13 14:33:27 -07:00
parent ba8d92ea01
commit 9b7e3ef897
109 changed files with 11731 additions and 1024 deletions

View File

@ -17,7 +17,7 @@ namespace Fab2ApprovalSystem
LoginPath = new PathString("/Account/Login")
});
// Use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(

View File

@ -12,19 +12,24 @@ using Fab2ApprovalSystem.Models;
using System.Web.Security;
using Fab2ApprovalSystem.Misc;
using Fab2ApprovalSystem.DMO;
using Microsoft.AspNet.Identity.Owin;
using System.Net.Http;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Text;
namespace Fab2ApprovalSystem.Controllers
{
namespace Fab2ApprovalSystem.Controllers {
[Authorize]
public class AccountController : Controller
{
public class AccountController : Controller {
private string _apiBaseUrl;
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) {
UserManager = userManager;
}
@ -34,9 +39,8 @@ namespace Fab2ApprovalSystem.Controllers
// 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)
{
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult Login(string returnUrl) {
ViewBag.ReturnUrl = returnUrl;
return View();
}
@ -44,18 +48,32 @@ namespace Fab2ApprovalSystem.Controllers
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
try
{
//if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
//{
// return RedirectToLocal(returnUrl);
//}
UserAccountDMO userDMO = new UserAccountDMO();
public async Task<ActionResult> Login(LoginModel model, string returnUrl) {
try {
bool isLoginValid;
MembershipProvider domainProvider;
HttpClient httpClient = HttpClientFactory.Create();
httpClient.BaseAddress = new Uri(_apiBaseUrl);
AuthAttempt authAttempt = new AuthAttempt() {
LoginID = model.LoginID,
Password = model.Password
};
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "auth/login");
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)
isLoginValid = true;
@ -64,28 +82,26 @@ namespace Fab2ApprovalSystem.Controllers
#if (!DEBUG)
bool isIFX = false;
//domainProvider = Membership.Providers["NA_ADMembershipProvider"];
//isLoginValid = domainProvider.ValidateUser(model.LoginID, model.Password);
//domainProvider = Membership.Providers["NA_ADMembershipProvider"];
//isLoginValid = domainProvider.ValidateUser(model.LoginID, model.Password);
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY")
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") {
isLoginValid = true;
else
{
isLoginValid = Functions.NA_ADAuthenticate(model.LoginID, model.Password);
if (!isLoginValid)
{
isLoginValid = Functions.IFX_ADAuthenticate(model.LoginID, model.Password);
isIFX = true;
}
} else {
isLoginValid = loginResult.IsAuthenticated;
if (isLoginValid) isIFX = true;
}
#endif
if (isLoginValid)
{
if (isLoginValid) {
UserAccountDMO userDMO = new UserAccountDMO();
LoginModel user = userDMO.GetUser(model.LoginID);
if (user != null)
{
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;
@ -94,22 +110,16 @@ namespace Fab2ApprovalSystem.Controllers
Session[GlobalVars.CAN_CREATE_PARTS_REQUEST] = user.IsAdmin || PartsRequestController.CanCreatePartsRequest(user.UserID);
FormsAuthentication.SetAuthCookie(user.LoginID, true);
return RedirectToLocal(returnUrl);
}
else
{
} else {
ModelState.AddModelError("", "The user name does not exist in the DB. Please contact the System Admin");
}
}
else
{
} 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);
} 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);
}
@ -119,287 +129,87 @@ namespace Fab2ApprovalSystem.Controllers
}
////
//// POST: /Account/Login
//[HttpPost]
//[AllowAnonymous]
//[ValidateAntiForgeryToken]
//public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
//{
// if (ModelState.IsValid)
// {
// var user = await UserManager.FindAsync(model.UserName, model.Password);
// if (user != null)
// {
// await SignInAsync(user, model.RememberMe);
// return RedirectToLocal(returnUrl);
// }
// else
// {
// ModelState.AddModelError("", "Invalid username or password.");
// }
// }
// // If we got this far, something failed, redisplay form
// return View(model);
//}
//
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
public ActionResult Register() {
return View();
}
//
// POST: /Account/Register
//[HttpPost]
//[AllowAnonymous]
//[ValidateAntiForgeryToken]
//public async Task<ActionResult> Register(RegisterViewModel model)
//{
// if (ModelState.IsValid)
// {
// var user = new ApplicationUser() { UserName = model.UserName };
// var result = await UserManager.CreateAsync(user, model.Password);
// if (result.Succeeded)
// {
// await SignInAsync(user, isPersistent: false);
// return RedirectToAction("Index", "Home");
// }
// else
// {
// AddErrors(result);
// }
// }
// // If we got this far, something failed, redisplay form
// return View(model);
//}
//
// POST: /Account/Disassociate
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Disassociate(string loginProvider, string providerKey)
{
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)
{
if (result.Succeeded) {
message = ManageMessageId.RemoveLoginSuccess;
}
else
{
} 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)
#pragma warning restore IDE0060 // Remove unused parameter
{
//ViewBag.StatusMessage =
// message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
// : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
// : message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
// : message == ManageMessageId.Error ? "An error has occurred."
// : "";
//ViewBag.HasLocalPassword = HasPassword();
//ViewBag.ReturnUrl = Url.Action("Manage");
public ActionResult Manage(ManageMessageId? message) {
return View();
}
#pragma warning restore IDE0060 // Remove unused parameter
////
//// POST: /Account/Manage
//[HttpPost]
//[ValidateAntiForgeryToken]
//public async Task<ActionResult> Manage(ManageUserViewModel model)
//{
// bool hasPassword = HasPassword();
// ViewBag.HasLocalPassword = hasPassword;
// ViewBag.ReturnUrl = Url.Action("Manage");
// if (hasPassword)
// {
// if (ModelState.IsValid)
// {
// IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);
// if (result.Succeeded)
// {
// return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
// }
// else
// {
// AddErrors(result);
// }
// }
// }
// else
// {
// // User does not have a password so remove any validation errors caused by a missing OldPassword field
// ModelState state = ModelState["OldPassword"];
// if (state != null)
// {
// state.Errors.Clear();
// }
// if (ModelState.IsValid)
// {
// IdentityResult result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
// if (result.Succeeded)
// {
// return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
// }
// else
// {
// AddErrors(result);
// }
// }
// }
// // If we got this far, something failed, redisplay form
// return View(model);
//}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
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 }));
}
////
//// GET: /Account/ExternalLoginCallback
//[AllowAnonymous]
//public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
//{
// var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
// if (loginInfo == null)
// {
// return RedirectToAction("Login");
// }
// // Sign in the user with this external login provider if the user already has a login
// var user = await UserManager.FindAsync(loginInfo.Login);
// if (user != null)
// {
// await SignInAsync(user, isPersistent: false);
// return RedirectToLocal(returnUrl);
// }
// else
// {
// // If the user does not have an account, then prompt the user to create an account
// ViewBag.ReturnUrl = returnUrl;
// ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
// return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { UserName = loginInfo.DefaultUserName });
// }
//}
//
// POST: /Account/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LinkLogin(string provider)
{
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()
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId());
if (loginInfo == null)
{
public async Task<ActionResult> LinkLoginCallback() {
ExternalLoginInfo loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId());
if (loginInfo == null) {
return RedirectToAction("Manage", new { Message = ManageMessageId.Error });
}
var result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login);
if (result.Succeeded)
{
IdentityResult result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login);
if (result.Succeeded) {
return RedirectToAction("Manage");
}
return RedirectToAction("Manage", new { Message = ManageMessageId.Error });
}
//
// POST: /Account/ExternalLoginConfirmation
//[HttpPost]
//[AllowAnonymous]
//[ValidateAntiForgeryToken]
//public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
//{
// if (User.Identity.IsAuthenticated)
// {
// return RedirectToAction("Manage");
// }
// if (ModelState.IsValid)
// {
// // Get the information about the user from the external login provider
// var info = await AuthenticationManager.GetExternalLoginInfoAsync();
// if (info == null)
// {
// return View("ExternalLoginFailure");
// }
// var user = new ApplicationUser() { UserName = model.UserName };
// var result = await UserManager.CreateAsync(user);
// if (result.Succeeded)
// {
// result = await UserManager.AddLoginAsync(user.Id, info.Login);
// if (result.Succeeded)
// {
// await SignInAsync(user, isPersistent: false);
// return RedirectToLocal(returnUrl);
// }
// }
// AddErrors(result);
// }
// ViewBag.ReturnUrl = returnUrl;
// return View(model);
//}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
//AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
//AuthenticationManager.SignOut();
public ActionResult LogOff() {
FormsAuthentication.SignOut();
return RedirectToAction("Login", "Account");
}
//
// GET: /Account/ExternalLoginFailure
[AllowAnonymous]
public ActionResult ExternalLoginFailure()
{
public ActionResult ExternalLoginFailure() {
return View();
}
[ChildActionOnly]
public ActionResult RemoveAccountList()
{
var linkedAccounts = UserManager.GetLogins(User.Identity.GetUserId());
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)
{
protected override void Dispose(bool disposing) {
if (disposing && UserManager != null) {
UserManager.Dispose();
UserManager = null;
}
@ -410,71 +220,52 @@ namespace Fab2ApprovalSystem.Controllers
// Used for XSRF protection when adding external logins
private const string XsrfKey = "XsrfId";
private IAuthenticationManager AuthenticationManager
{
get
{
private IAuthenticationManager AuthenticationManager {
get {
return HttpContext.GetOwinContext().Authentication;
}
}
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
private async Task SignInAsync(ApplicationUser user, bool isPersistent) {
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
ClaimsIdentity identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
private void AddErrors(IdentityResult result) {
foreach (string error in result.Errors) {
ModelState.AddModelError("", error);
}
}
private bool HasPassword()
{
var user = UserManager.FindById(User.Identity.GetUserId());
if (user != null)
{
private bool HasPassword() {
ApplicationUser user = UserManager.FindById(User.Identity.GetUserId());
if (user != null) {
return user.PasswordHash != null;
}
return false;
}
public enum ManageMessageId
{
public enum ManageMessageId {
ChangePasswordSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
Error
}
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
private ActionResult RedirectToLocal(string returnUrl) {
if (Url.IsLocalUrl(returnUrl)) {
return Redirect(returnUrl);
}
else
{
//return RedirectToAction("HierarchicalDataTest", "Home");
} else {
return RedirectToAction("MyTasks", "Home");
//return RedirectToAction("Index", "Home", new { tabName = "MyTasks"});
}
}
private class ChallengeResult : HttpUnauthorizedResult
{
public ChallengeResult(string provider, string redirectUri) : this(provider, redirectUri, null)
{
private class ChallengeResult : HttpUnauthorizedResult {
public ChallengeResult(string provider, string redirectUri) : this(provider, redirectUri, null) {
}
public ChallengeResult(string provider, string redirectUri, string userId)
{
public ChallengeResult(string provider, string redirectUri, string userId) {
LoginProvider = provider;
RedirectUri = redirectUri;
UserId = userId;
@ -484,11 +275,9 @@ namespace Fab2ApprovalSystem.Controllers
public string RedirectUri { get; set; }
public string UserId { get; set; }
public override void ExecuteResult(ControllerContext context)
{
var properties = new AuthenticationProperties() { RedirectUri = RedirectUri };
if (UserId != null)
{
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);

View File

@ -2,23 +2,18 @@ using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Models;
using Fab2ApprovalSystem.ViewModels;
using Fab2ApprovalSystem.Utilities;
using Kendo.Mvc.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kendo.Mvc.Extensions;
using Fab2ApprovalSystem.Misc;
using System.Configuration;
using System.Threading.Tasks;
namespace Fab2ApprovalSystem.Controllers
{
namespace Fab2ApprovalSystem.Controllers {
[Authorize]
[SessionExpireFilter]
public class TrainingController : Controller
{
public class TrainingController : Controller {
UserAccountDMO userDMO = new UserAccountDMO();
AdminDMO adminDMO = new AdminDMO();
TrainingDMO trainingDMO = new TrainingDMO();
@ -26,19 +21,17 @@ namespace Fab2ApprovalSystem.Controllers
public EmailUtilities emailer = new EmailUtilities();
// GET: Training
public ActionResult Index()
{
public ActionResult Index() {
return View();
}
//public int Create(int ecnId, List<int> groupIds)
public int Create(int ecnId)
{
public int Create(int ecnId) {
ECN_DMO ecnDMO = new ECN_DMO();
//Delete old training if exists
int oldTrainingId = trainingDMO.GetTrainingId(ecnId);
if (oldTrainingId != null && oldTrainingId != 0)
{
if (oldTrainingId != null && oldTrainingId != 0) {
trainingDMO.DeleteTraining(oldTrainingId);
}
@ -47,23 +40,20 @@ namespace Fab2ApprovalSystem.Controllers
TrainingGroups = trainingDMO.GetECNAssignedTrainingGroups(ecnId);
string ECNTitle = ecnDMO.GetECN(ecnId).Title;
List<int> Trainees = new List<int>();
foreach (var group in TrainingGroups)
{
foreach (int group in TrainingGroups) {
Trainees.AddRange(trainingDMO.GetTrainees(group));
}
Trainees = (from a in Trainees select a).Distinct().ToList();
foreach (var trainee in Trainees)
{
foreach (int trainee in Trainees) {
int assignmentId = trainingDMO.CreateAssignment(trainingId, trainee);
NotifyTrainee(trainee, assignmentId, ecnId, ECNTitle);
}
return trainingId;
}
public ActionResult AddUserToTrainingAdHoc(int trainingId, int traineeId, int ecnId)
{
if ((bool)Session[GlobalVars.IS_ADMIN])
{
public ActionResult AddUserToTrainingAdHoc(int trainingId, int traineeId, int ecnId) {
if ((bool)Session[GlobalVars.IS_ADMIN]) {
//Get ECN
ECN ecn = ecnDMO.GetECN(ecnId);
@ -72,172 +62,120 @@ namespace Fab2ApprovalSystem.Controllers
//Get Training
Training training = trainingDMO.GetTraining(trainingId);
if (ecn != null)
{
if (user != null)
{
if (training != null)
{
if (!trainingDMO.IsUserAssigned(traineeId, trainingId))
{
if (training.DeletedDate == null && !ecn.Deleted)
{
if (ecn != null) {
if (user != null) {
if (training != null) {
if (!trainingDMO.IsUserAssigned(traineeId, trainingId)) {
if (training.DeletedDate == null && !ecn.Deleted) {
//Both the ECN and training still exist
if (training.CompletedDate != null)
{
if (training.CompletedDate != null) {
//Training is completed and now we need to re-open it.
trainingDMO.reOpenTraining(trainingId);
int assignmentId = trainingDMO.CreateAssignment(trainingId, traineeId);
NotifyTrainee(traineeId, assignmentId, ecnId, ecn.Title);
return Content("Success");
}
else
{
} else {
//training is still open, just add a user and notify
int assignmentId = trainingDMO.CreateAssignment(trainingId, traineeId);
NotifyTrainee(traineeId, assignmentId, ecnId, ecn.Title);
return Content("Success");
}
}
else
{
} else {
//Ecn or training task have been deleted.
return Content("Training or ECN has been deleted.");
}
}
else
{
} else {
return Content("User already has an open or completed assignment for this training.");
}
}
else
{
} else {
return Content("Invalid training id.");
}
}
else
{
} else {
return Content("invalid userId");
}
}
else
{
} else {
return Content("ECN invalid");
}
}
else
{
} else {
return Content("Not Authorized");
}
}
public ActionResult AddGroupToTrainingAdHoc(int trainingId, int groupId, int ecnId)
{
if ((bool)Session[GlobalVars.IS_ADMIN])
{
public ActionResult AddGroupToTrainingAdHoc(int trainingId, int groupId, int ecnId) {
if ((bool)Session[GlobalVars.IS_ADMIN]) {
ECN ecn = ecnDMO.GetECN(ecnId);
Training training = trainingDMO.GetTraining(trainingId);
TrainingGroup group = trainingDMO.GetTrainingGroupByID(groupId);
List<int> groupMemberIds = trainingDMO.GetTrainees(groupId);
int usersAdded = 0;
if (ecn != null)
{
if (training != null)
{
if (training.DeletedDate == null && !ecn.Deleted)
{
if (training.CompletedDate != null)
{
if (ecn != null) {
if (training != null) {
if (training.DeletedDate == null && !ecn.Deleted) {
if (training.CompletedDate != null) {
//Training is completed and now we need to re-open it.
foreach (int id in groupMemberIds)
{
foreach (int id in groupMemberIds) {
//Check to make sure user doesn't have an active assignment for this training
if (!trainingDMO.IsUserAssigned(id, trainingId))
{
if (!trainingDMO.IsUserAssigned(id, trainingId)) {
usersAdded++;
int assignmentId = trainingDMO.CreateAssignment(trainingId, id);
NotifyTrainee(id, assignmentId, ecnId, ecn.Title);
}
}
if (usersAdded > 0)
{
if (usersAdded > 0) {
trainingDMO.reOpenTraining(trainingId);
}
}
else
{
} else {
//training is still open, just add a users and notify
foreach (int id in groupMemberIds)
{
foreach (int id in groupMemberIds) {
//Check to make sure user doesn't have an active assignment for this training
if (!trainingDMO.IsUserAssigned(id, trainingId))
{
if (!trainingDMO.IsUserAssigned(id, trainingId)) {
usersAdded++;
int assignmentId = trainingDMO.CreateAssignment(trainingId, id);
NotifyTrainee(id, assignmentId, ecnId, ecn.Title);
}
}
}
if (usersAdded > 0)
{
try
{
if (usersAdded > 0) {
try {
trainingDMO.AddTrainingGroupToECN(ecnId, groupId);
}
catch (Exception e)
{
} catch (Exception e) {
return Content(e.ToString());
}
}
return Content("Success. " + usersAdded + " users added.");
}
else
{
} else {
return Content("Training or ECN has been deleted.");
}
}
else
{
} else {
return Content("Invalid training id.");
}
}
else
{
} else {
return Content("ECN invalid");
}
}
else
{
} else {
return Content("Not Authorized");
}
}
public ActionResult DeleteTrainingByECN(int ECNNumber)
{
public ActionResult DeleteTrainingByECN(int ECNNumber) {
int trainingId = trainingDMO.GetTrainingId(ECNNumber);
if (trainingId != null && trainingId != 0)
{
if (trainingId != null && trainingId != 0) {
trainingDMO.DeleteTraining(trainingId);
}
return RedirectToAction("ViewTrainings");
}
public ActionResult DeleteTrainingByID(int trainingId)
{
if (trainingId != null && trainingId != 0)
{
public ActionResult DeleteTrainingByID(int trainingId) {
if (trainingId != null && trainingId != 0) {
trainingDMO.DeleteTraining(trainingId);
}
return RedirectToAction("ViewTrainings");
}
public void NotifyTrainee(int userId, int assignmentId, int ecnId, string title)
{
try
{
public void NotifyTrainee(int userId, int assignmentId, int ecnId, string title) {
try {
string emailSentList = "";
//ECN ecn = ecnDMO.GetECN(ecnNumber);
//List<string> emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList();
string recipient = userDMO.GetUserEmailByID(userId.ToString());
string emailTemplate = "ECNTrainingAssigned.txt";
@ -248,7 +186,6 @@ namespace Fab2ApprovalSystem.Controllers
subject = "ECN# " + ecnId + " - Training Assignment Notice - " + title;
EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
//string emailparams = "";
userEmail = recipient;
string[] emailparams = new string[4];
emailparams[0] = assignmentId.ToString();
@ -260,60 +197,46 @@ namespace Fab2ApprovalSystem.Controllers
//#endif
en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);
//en.SendNotificationEmail(emailTemplate, SenderEmail, senderName, userEmail, null, subject, emailparams);
}
catch (Exception e)
{
} catch (Exception e) {
string detailedException = "";
try
{
try {
detailedException = e.InnerException.ToString();
}
catch
{
} catch {
detailedException = e.Message;
}
}
}
public ActionResult ViewTrainingPartial(int trainingID, int userID)
{
public ActionResult ViewTrainingPartial(int trainingID, int userID) {
List<TrainingAssignment> TrainingData = trainingDMO.GetTrainingAssignmentsByUser(trainingID, userID);
if (trainingID > 0)
{
if (trainingID > 0) {
ViewBag.ECNNumber = trainingDMO.GetTraining(trainingID).ECN;
}
return PartialView(TrainingData);
}
public ActionResult ViewTrainingDocsPartial(int trainingAssignmentId)
{
public ActionResult ViewTrainingDocsPartial(int trainingAssignmentId) {
ViewBag.trainingAssignmentId = trainingAssignmentId;
//IEnumerable<TrainingDocAck> attachments = ecnDMO.GetECNAttachments(ecnNumber);
IEnumerable<TrainingDocAck> attachments = trainingDMO.GetAssignedDocs(trainingAssignmentId);
return PartialView(attachments);
}
public ActionResult AcknowledgeDocument(int trainingAssignmentID, int trainingDocAckID)
{
public ActionResult AcknowledgeDocument(int trainingAssignmentID, int trainingDocAckID) {
//Check to see if acknowledgement is valid(Security Feature to protect data integrity)
if (trainingDMO.CheckValidDocAck(trainingDocAckID))
{
if (trainingDMO.CheckValidDocAck(trainingDocAckID)) {
trainingDMO.AcknowledgeDocument(trainingDocAckID);
bool isFinishedTrainingAssignment = trainingDMO.CheckTrainingAssignmentStatus(trainingAssignmentID);
if (isFinishedTrainingAssignment)
{
try
{
if (isFinishedTrainingAssignment) {
try {
trainingDMO.UpdateAssignmentStatus(trainingAssignmentID);
bool isFinishedTraining = trainingDMO.CheckTrainingStatus(trainingAssignmentID);
if (isFinishedTraining)
{
if (isFinishedTraining) {
int TrainingID = trainingDMO.GetTrainingIdByAssignment(trainingAssignmentID);
trainingDMO.UpdateTrainingStatus(TrainingID);
}
}
catch (Exception e)
{
} catch (Exception e) {
string exception = e.ToString();
return Content(exception);
}
@ -322,53 +245,38 @@ namespace Fab2ApprovalSystem.Controllers
return Content("Marked Succesfully.");
}
public ActionResult AcknowledgeReviewNoDocuments(int trainingAssignmentID)
{
try
{
public ActionResult AcknowledgeReviewNoDocuments(int trainingAssignmentID) {
try {
trainingDMO.UpdateAssignmentStatus(trainingAssignmentID);
bool isFinishedTraining = trainingDMO.CheckTrainingStatus(trainingAssignmentID);
if (isFinishedTraining)
{
if (isFinishedTraining) {
int TrainingID = trainingDMO.GetTrainingIdByAssignment(trainingAssignmentID);
trainingDMO.UpdateTrainingStatus(TrainingID);
}
}
catch (Exception e)
{
} catch (Exception e) {
string exception = e.ToString();
return Content(exception, "application/json");
}
return Json(new { test = "Succesfully saved" });
}
//public ActionResult ViewTrainings()
//{
// IEnumerable<Training> trainings = trainingDMO.GetTrainings();
// return View(trainings);
//}
public ActionResult TrainingReports()
{
public ActionResult TrainingReports() {
return View();
}
public ActionResult TrainingReportsView(int? filterType, string filterValue)
{
public ActionResult TrainingReportsView(int? filterType, string filterValue) {
ViewBag.TrainingGroups = adminDMO.GetTrainingGroups();
IEnumerable<Training> trainingList = trainingDMO.GetAllTrainings();
//Group Filter
if (filterType == 1 && filterValue != "")
{
if (filterType == 1 && filterValue != "") {
ViewBag.GroupFilter = filterValue;
List<Training> filteredTraining = new List<Training>();
foreach (var item in trainingList)
{
foreach (Training item in trainingList) {
List<int> assignedTrainingGroups = trainingDMO.GetECNAssignedTrainingGroups(item.ECN);
foreach (int id in assignedTrainingGroups)
{
if (filterValue == id.ToString())
{
foreach (int id in assignedTrainingGroups) {
if (filterValue == id.ToString()) {
filteredTraining.Add(item);
}
}
@ -377,11 +285,9 @@ namespace Fab2ApprovalSystem.Controllers
return PartialView(trainingList);
}
//Status Filter
if (filterType == 2 && filterValue != "")
{
if (filterType == 2 && filterValue != "") {
List<Training> filteredTraining = new List<Training>();
switch (filterValue)
{
switch (filterValue) {
case "1":
//Completed
filteredTraining = (from a in trainingList where a.Status == true && a.Deleted != true select a).ToList();
@ -399,13 +305,12 @@ namespace Fab2ApprovalSystem.Controllers
return PartialView(trainingList);
}
//Default return all.
else
{
else {
return PartialView(trainingList);
}
}
public ActionResult ViewTrainingAssignmentsReportView(int trainingID, string statusFilter, string groupFilter)
{
public ActionResult ViewTrainingAssignmentsReportView(int trainingID, string statusFilter, string groupFilter) {
bool? trainingStatus = trainingDMO.GetTraining(trainingID).Status;
int ECNNumber = trainingDMO.GetTraining(trainingID).ECN;
string ECNTitle = ecnDMO.GetECN(ECNNumber).Title;
@ -420,38 +325,29 @@ namespace Fab2ApprovalSystem.Controllers
//float assignmentCount = trainingAssignments.Count();
float assignmentCount = (from a in trainingAssignments where a.Deleted != true select a).Count();
float totalCompleted = 0;
foreach (var assignment in trainingAssignments)
{
if (assignment.status == true && assignment.Deleted != true)
{
foreach (TrainingAssignment assignment in trainingAssignments) {
if (assignment.status == true && assignment.Deleted != true) {
totalCompleted++;
}
}
#pragma warning disable IDE0047 // Remove unnecessary parentheses
percentComplete = (totalCompleted / assignmentCount) * 100;
#pragma warning restore IDE0047 // Remove unnecessary parentheses
percentComplete = totalCompleted / assignmentCount * 100;
ViewBag.PercentComplete = percentComplete.ToString("0.00") + "%";
if (groupFilter != "" && groupFilter != null)
{
if (groupFilter != "" && groupFilter != null) {
ViewBag.GroupFilter = groupFilter;
List<TrainingAssignment> groupFilteredTraining = new List<TrainingAssignment>();
List<int> groupMemberIds = trainingDMO.GetTrainees(Convert.ToInt32(groupFilter));
foreach (var assignment in trainingAssignments)
{
if (trainingDMO.isUserTrainingMember(Convert.ToInt32(groupFilter), assignment.UserID))
{
foreach (TrainingAssignment assignment in trainingAssignments) {
if (trainingDMO.isUserTrainingMember(Convert.ToInt32(groupFilter), assignment.UserID)) {
groupFilteredTraining.Add(assignment);
}
}
trainingAssignments = groupFilteredTraining;
}
if (statusFilter != "" && statusFilter != null)
{
if (statusFilter != "" && statusFilter != null) {
List<TrainingAssignment> filteredTraining = new List<TrainingAssignment>();
switch (statusFilter)
{
switch (statusFilter) {
case "1":
//Completed
@ -475,8 +371,8 @@ namespace Fab2ApprovalSystem.Controllers
return PartialView(trainingAssignments);
}
public ActionResult ViewTrainingAssignments(int trainingID)
{
public ActionResult ViewTrainingAssignments(int trainingID) {
bool? trainingStatus = trainingDMO.GetTraining(trainingID).Status;
int ECNNumber = trainingDMO.GetTraining(trainingID).ECN;
string ECNTitle = ecnDMO.GetECN(ECNNumber).Title;
@ -490,24 +386,21 @@ namespace Fab2ApprovalSystem.Controllers
return View(trainingAssignments);
}
/// <summary>
/// Method to return all the training assignments for a specified user
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
public ActionResult ViewMyTrainingAssignments()
{
public ActionResult ViewMyTrainingAssignments() {
int userID = (int)Session[GlobalVars.SESSION_USERID];
List<TrainingAssignment> assignments = trainingDMO.GetTrainingAssignmentsByUserID(userID);
List<ECNTrainingAssignments> ViewData = new List<ECNTrainingAssignments>();
foreach (var assignment in assignments)
{
foreach (TrainingAssignment assignment in assignments) {
Training training = trainingDMO.GetTraining(assignment.TrainingID);
if (training != null && !assignment.status)
{
if (training != null && !assignment.status) {
int ecnID = training.ECN;
ViewData.Add(new ECNTrainingAssignments
{
ViewData.Add(new ECNTrainingAssignments {
TrainingAssignmentID = assignment.ID,
ECN_ID = ecnID,
TrainingID = assignment.TrainingID,
@ -520,57 +413,48 @@ namespace Fab2ApprovalSystem.Controllers
return View(ViewData);
}
/// <summary>
/// Method to return all assigned documents for a specified training assignment
/// </summary>
/// <param name="assignmentID"></param>
/// <returns></returns>
public ActionResult ViewMyTrainingAssignment(int assignmentID, int ECNNumber)
{
public ActionResult ViewMyTrainingAssignment(int assignmentID, int ECNNumber) {
ViewBag.ECNNumber = ECNNumber;
ViewBag.AssignmentID = assignmentID;
ViewBag.IsCompleted = trainingDMO.GetAssignment(assignmentID).status;
return View(trainingDMO.GetAssignedDocs(assignmentID));
}
public ActionResult ViewTrainings(int? filterType, string filterValue)
{
public ActionResult ViewTrainings(int? filterType, string filterValue) {
IEnumerable<Training> AllTrainings = trainingDMO.GetTrainings();
ViewBag.TrainingGroups = adminDMO.GetTrainingGroups();
ViewBag.AllGroups = trainingDMO.GetTrainingGroups();
//Group Filter
if (filterType == 1 && filterValue != "")
{
if (filterType == 1 && filterValue != "") {
ViewBag.GroupFilter = filterValue;
List<Training> filteredTraining = new List<Training>();
foreach (var item in AllTrainings)
{
foreach (Training item in AllTrainings) {
List<int> assignedTrainingGroups = trainingDMO.GetECNAssignedTrainingGroups(item.ECN);
foreach (int id in assignedTrainingGroups)
{
if (filterValue == id.ToString())
{
foreach (int id in assignedTrainingGroups) {
if (filterValue == id.ToString()) {
filteredTraining.Add(item);
}
}
}
AllTrainings = filteredTraining;
return View(AllTrainings);
}
else
{
} else {
ViewBag.AllGroups = trainingDMO.GetTrainingGroups();
return View(AllTrainings);
}
}
public ActionResult ViewAllTrainings()
{
public ActionResult ViewAllTrainings() {
return View();
}
public ActionResult DeleteAssignment(int assignmentId)
{
public ActionResult DeleteAssignment(int assignmentId) {
trainingDMO.DeleteTrainingAssignment(assignmentId);
trainingDMO.DeleteTrainingDocAck(assignmentId);
@ -578,116 +462,81 @@ namespace Fab2ApprovalSystem.Controllers
//TO-DO Put this in its own method.
bool isFinishedTrainingAssignment = trainingDMO.CheckTrainingAssignmentStatus(assignmentId);
if (isFinishedTrainingAssignment)
{
try
{
if (isFinishedTrainingAssignment) {
try {
trainingDMO.UpdateAssignmentStatus(assignmentId);
bool isFinishedTraining = trainingDMO.CheckTrainingStatus(assignmentId);
if (isFinishedTraining)
{
if (isFinishedTraining) {
int TrainingID = trainingDMO.GetTrainingIdByAssignment(assignmentId);
trainingDMO.UpdateTrainingStatus(TrainingID);
}
}
catch (Exception e)
{
} catch (Exception e) {
string exception = e.ToString();
return Content(exception, "application/json");
}
}
return Json(new { test = "Succesfully saved" });
}
public ActionResult ManuallyExecuteECNTraining(int ecnId, int[] trainingGroupsIn)
{
if ((bool)Session[GlobalVars.IS_ADMIN])
{
public ActionResult ManuallyExecuteECNTraining(int ecnId, int[] trainingGroupsIn) {
if ((bool)Session[GlobalVars.IS_ADMIN]) {
List<int> newTrainingGroupIds = new List<int>(trainingGroupsIn);
//Get ECN
ECN ecn = ecnDMO.GetECN(ecnId);
if (ecn != null)
{
if (ecn.CloseDate != null)
{
if (newTrainingGroupIds.Count > 0)
{
if (ecn != null) {
if (ecn.CloseDate != null) {
if (newTrainingGroupIds.Count > 0) {
//Check each assigned group id and see if it's already saved to the ECN
List<int> assignedTrainingGroups = trainingDMO.GetECNAssignedTrainingGroups(ecnId);
IEnumerable<int> onlyNewTrainingIds = newTrainingGroupIds.Except(assignedTrainingGroups);
try
{
foreach (int trainingId in onlyNewTrainingIds)
{
try {
foreach (int trainingId in onlyNewTrainingIds) {
trainingDMO.AddTrainingGroupToECN(ecnId, trainingId);
}
trainingDMO.SetTrainingFlag(ecnId);
Create(ecnId);
return Content("Success");
}
catch (Exception e)
{
} catch (Exception e) {
return Content("Failed: " + e.Message.ToString());
}
}
else
{
} else {
return Content("There were no training groups to assign to. Please select at least one training groups.");
}
}
else
{
} else {
return Content("Selected ECN hasn't been approved yet.");
}
}
else
{
} else {
return Content("Invalid ECN");
}
}
else
{
} else {
return Content("Not Autthorized");
}
}
public ActionResult CheckECN(int ecnId)
{
public ActionResult CheckECN(int ecnId) {
ECN ecn = ecnDMO.GetECN(ecnId);
if (ecn != null)
{
if (ecn.CloseDate != null)
{
if (ecn != null) {
if (ecn.CloseDate != null) {
List<int> trainingGroupIds = trainingDMO.GetECNAssignedTrainingGroups(ecnId);
List<TrainingGroup> assignedGroups = new List<TrainingGroup>();
foreach (int trainingGroupId in trainingGroupIds)
{
foreach (int trainingGroupId in trainingGroupIds) {
TrainingGroup trainingGroup = trainingDMO.GetTrainingGroupByID(trainingGroupId);
assignedGroups.Add(trainingGroup);
}
return Json(trainingGroupIds.ToList());
}
else
{
} else {
return Content("ECN not yet approved.");
}
}
else
{
} else {
return Content("That ECN wasn't found.");
}
}
public bool RunTrainingReport()
{
public bool RunTrainingReport() {
bool isSuccess = false;
try
{
try {
string emailBody = "<h1>Mesa Approval Open Training Assignments Daily Report</h1> <br />";
emailBody += "<p>The following contains open training assignments in the Mesa Approval system. ";
emailBody += "Please ensure the following users complete their training assignments. ";
@ -696,8 +545,7 @@ namespace Fab2ApprovalSystem.Controllers
//Get all users set up to receive the training report email.
List<TrainingReportUser> trainingReportUsers = adminDMO.GetTrainingReportUsers();
List<string> emailList = new List<string>();
foreach (var user in trainingReportUsers)
{
foreach (TrainingReportUser user in trainingReportUsers) {
string userEmail = userDMO.GetUserByID(user.UserId).Email;
emailList.Add(userEmail);
}
@ -705,8 +553,7 @@ namespace Fab2ApprovalSystem.Controllers
//Get a list of open trainings
List<Training> openTrainings = trainingDMO.GetAllOpenTrainings();
foreach (Training training in openTrainings)
{
foreach (Training training in openTrainings) {
string trainingSection = "";
int trainingSectionUserCount = 0;
string ecnTitle = ecnDMO.GetECN(training.ECN).Title;
@ -715,23 +562,18 @@ namespace Fab2ApprovalSystem.Controllers
trainingSection += "<table>";
trainingSection += "<tr><th>Name</th><th>Date Assigned</th></tr>";
List<TrainingAssignment> openAssignments = trainingDMO.GetOpenAssignmentsByTrainingID(training.TrainingID);
foreach (TrainingAssignment assignment in openAssignments)
{
foreach (TrainingAssignment assignment in openAssignments) {
if (!userDMO.GetUserByID(assignment.UserID).OOO)
{
if (!userDMO.GetUserByID(assignment.UserID).OOO) {
trainingSectionUserCount++;
DateTime? assignmentDate = assignment.DateAssigned;
string DateAssigned = assignmentDate.HasValue ? assignmentDate.Value.ToString("MM/dd/yyyy") : "<not available>";
if (assignmentDate.HasValue && (DateTime.Now.Date - assignmentDate.Value.Date).TotalDays > 15)
{
if (assignmentDate.HasValue && (DateTime.Now.Date - assignmentDate.Value.Date).TotalDays > 15) {
trainingSection += "<tr><td>" + assignment.FullName + "</td><td style=\"color:red;\">" + DateAssigned + "</td>";
}
else
{
} else {
trainingSection += "<tr><td>" + assignment.FullName + "</td><td>" + DateAssigned + "</td>";
}
@ -745,13 +587,10 @@ namespace Fab2ApprovalSystem.Controllers
List<string> ccRecipients = emailList;
emailer.SendNotification("MesaFabApproval@infineon.com", ccRecipients, "Mesa Approval Daily Open Training Report", emailBody, "Daily Open Training Report");
isSuccess = true;
}
catch
{
} catch {
isSuccess = false;
}
return isSuccess;
}
}
}

View File

@ -1,11 +1,9 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using Fab2ApprovalSystem.Models;
using Dapper;
using System.Transactions;
@ -13,8 +11,7 @@ using Fab2ApprovalSystem.ViewModels;
using System.Reflection;
using Fab2ApprovalSystem.Misc;
namespace Fab2ApprovalSystem.DMO
{
namespace Fab2ApprovalSystem.DMO {
public class LotDispositionDMO
{
private IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);

View File

@ -153,6 +153,8 @@
<Compile Include="Models\ApprovalLog.cs" />
<Compile Include="Models\ApprovalLogHistory.cs" />
<Compile Include="Models\ApproveListModel.cs" />
<Compile Include="Models\AuthAttempt.cs" />
<Compile Include="Models\AuthTokens.cs" />
<Compile Include="Models\ChangeControlModel.cs" />
<Compile Include="Models\Common.cs" />
<Compile Include="Models\C_8DAuditedStandard.cs">
@ -182,6 +184,7 @@
<DesignTime>True</DesignTime>
<DependentUpon>FabApproval.edmx</DependentUpon>
</Compile>
<Compile Include="Models\LoginResult.cs" />
<Compile Include="Models\LotTravellerModel.cs" />
<Compile Include="Models\PartsRequestModels.cs" />
<Compile Include="Models\TECNNotificationsUser.cs">

View File

@ -6,10 +6,8 @@ using System.Linq;
using System.Net.Mail;
using System.Web;
namespace Fab2ApprovalSystem.Misc
{
public class EmailNotification
{
namespace Fab2ApprovalSystem.Misc {
public class EmailNotification {
#region Variabls
protected string _subject = null;
protected string _TemplatesPath = null;
@ -18,10 +16,8 @@ namespace Fab2ApprovalSystem.Misc
/// <summary>
/// Email subject
/// </summary>
public string EmailSubject
{
public string EmailSubject {
set { _subject = value; }
}
/// <summary>
@ -29,11 +25,9 @@ namespace Fab2ApprovalSystem.Misc
/// </summary>
/// <param name="FileName">File Name</param>
/// <returns>String: Containing the Entire content of the file</returns>
protected string ReadEmailFile(string FileName)
{
protected string ReadEmailFile(string FileName) {
string retVal = null;
try
{
try {
//setting the file name path
string path = _TemplatesPath + FileName;
FileInfo TheFile = new FileInfo(System.Web.HttpContext.Current.Server.MapPath(path));
@ -46,17 +40,12 @@ namespace Fab2ApprovalSystem.Misc
StreamReader sr = new StreamReader(System.Web.HttpContext.Current.Server.MapPath(@path), System.Text.Encoding.GetEncoding(1256));
retVal = sr.ReadToEnd(); // getting the entire text from the file.
sr.Close();
}
catch (Exception ex)
{
} catch (Exception ex) {
throw new Exception("Error Reading File." + ex.Message);
}
return retVal;
}
/// <summary>
/// this function will send email. it will read the mail setting from the web.config
/// </summary>
@ -66,8 +55,8 @@ namespace Fab2ApprovalSystem.Misc
/// <param name="cc">CC ids</param>
/// <param name="email_title">Email Subject</param>
/// <param name="email_body">Email Body</param>
protected void SendEmail(string SenderEmail, string SenderName, string Recep, string cc, string email_title, string email_body)
{
#pragma warning disable IDE0060 // Remove unused parameter
protected void SendEmail(string SenderEmail, string SenderName, string Recep, string cc, string email_title, string email_body) {
// creating email message
MailMessage msg = new MailMessage();
msg.IsBodyHtml = true;// email body will allow html elements
@ -87,27 +76,18 @@ namespace Fab2ApprovalSystem.Misc
msg.Subject = email_title;
msg.Body = email_body;
//create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section
SmtpClient SmtpMail = new SmtpClient("mailrelay-internal.infineon.com");
//create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section
SmtpClient SmtpMail = new SmtpClient("mailrelay-internal.infineon.com");
// sending the message.
try
{
try {
SmtpMail.Send(msg);
}
catch (Exception ex)
{
} catch (Exception ex) {
Console.WriteLine("Exception caught in CreateTestMessage2(): {0}",
ex.ToString());
}
}
#pragma warning restore IDE0060 // Remove unused parameter
/// <summary>
///
@ -119,8 +99,7 @@ namespace Fab2ApprovalSystem.Misc
/// <param name="email_title"></param>
/// <param name="email_body"></param>
/// <param name="attachmentPath"></param>
protected void SendEmailWithAttachment(string SenderEmail, string SenderName, string Recep, string cc, string email_title, string email_body, string attachmentPath)
{
protected void SendEmailWithAttachment(string SenderEmail, string SenderName, string Recep, string cc, string email_title, string email_body, string attachmentPath) {
// creating email message
MailMessage msg = new MailMessage();
msg.IsBodyHtml = true;// email body will allow html elements
@ -140,22 +119,14 @@ namespace Fab2ApprovalSystem.Misc
msg.Body = email_body;
msg.Attachments.Add(new Attachment(attachmentPath));
//create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section
SmtpClient SmtpMail = new SmtpClient();
#if(!DEBUG)
// sending the message.
SmtpMail.Send(msg);
#endif
}
/// <summary>
///
/// </summary>
@ -165,8 +136,8 @@ namespace Fab2ApprovalSystem.Misc
/// <param name="cc"></param>
/// <param name="email_title"></param>
/// <param name="email_body"></param>
protected void SendEmail(string SenderEmail, string SenderName, List<string> RecepientList, string cc, string email_title, string email_body)
{
#pragma warning disable IDE0060 // Remove unused parameter
protected void SendEmail(string SenderEmail, string SenderName, List<string> RecepientList, string cc, string email_title, string email_body) {
// creating email message
MailMessage msg = new MailMessage();
msg.IsBodyHtml = true;// email body will allow html elements
@ -175,8 +146,7 @@ namespace Fab2ApprovalSystem.Misc
//msg.From = new MailAddress(SenderEmail, SenderName);
msg.From = new MailAddress("MesaFabApproval@infineon.com", "Mesa Fab Approval");
// adding the Recepient Email ID
foreach (string recepient in RecepientList)
{
foreach (string recepient in RecepientList) {
msg.To.Add(recepient);
}
@ -188,26 +158,18 @@ namespace Fab2ApprovalSystem.Misc
msg.Subject = email_title;
msg.Body = email_body;
//create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section
SmtpClient SmtpMail = new SmtpClient();
//create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section
SmtpClient SmtpMail = new SmtpClient();
// sending the message.
try
{
try {
SmtpMail.Send(msg);
}
catch (Exception ex)
{
} catch (Exception ex) {
Console.WriteLine("Exception caught in CreateTestMessage2(): {0}",
ex.ToString());
}
}
#pragma warning restore IDE0060 // Remove unused parameter
/// <summary>
///
@ -219,8 +181,7 @@ namespace Fab2ApprovalSystem.Misc
/// <param name="email_title"></param>
/// <param name="email_body"></param>
/// <param name="attachmentPath"></param>
protected void SendEmailWithAttachment(string SenderEmail, string SenderName, List<string> RecepientList, string cc, string email_title, string email_body, string attachmentPath)
{
protected void SendEmailWithAttachment(string SenderEmail, string SenderName, List<string> RecepientList, string cc, string email_title, string email_body, string attachmentPath) {
// creating email message
MailMessage msg = new MailMessage();
msg.IsBodyHtml = true;// email body will allow html elements
@ -229,8 +190,7 @@ namespace Fab2ApprovalSystem.Misc
msg.From = new MailAddress(SenderEmail, SenderName);
// adding the Recepient Email ID
foreach (string recepient in RecepientList)
{
foreach (string recepient in RecepientList) {
if (recepient != null)
msg.To.Add(recepient);
}
@ -244,19 +204,13 @@ namespace Fab2ApprovalSystem.Misc
msg.Body = email_body;
msg.Attachments.Add(new Attachment(attachmentPath));
//create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section
SmtpClient SmtpMail = new SmtpClient();
// sending the message.
SmtpMail.Send(msg);
}
/// <summary>
///
/// </summary>
@ -267,8 +221,7 @@ namespace Fab2ApprovalSystem.Misc
/// <param name="email_title"></param>
/// <param name="email_body"></param>
/// <param name="attachments"></param>
protected void SendEmailWithAttachments(string SenderEmail, string SenderName, string Recep, string cc, string email_title, string email_body, List<string> attachments)
{
protected void SendEmailWithAttachments(string SenderEmail, string SenderName, string Recep, string cc, string email_title, string email_body, List<string> attachments) {
// creating email message
MailMessage msg = new MailMessage();
msg.IsBodyHtml = true;// email body will allow html elements
@ -286,35 +239,29 @@ namespace Fab2ApprovalSystem.Misc
//setting email subject and body
msg.Subject = email_title;
msg.Body = email_body;
foreach (string attachment in attachments)
{
foreach (string attachment in attachments) {
msg.Attachments.Add(new Attachment(attachment));
}
//create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section
SmtpClient SmtpMail = new SmtpClient();
#if(!DEBUG)
// sending the message.
SmtpMail.Send(msg);
#endif
}
/// <summary>
///
/// </summary>
/// <param name="SenderEmail"></param>
/// <param name="SenderName"></param>
/// <param name="RecepientList"></param>
/// <param name="cc"></param>
/// <param name="email_title"></param>
/// <param name="email_body"></param>
/// <param name="attachments"></param>
protected void SendEmailWithAttachments(string SenderEmail, string SenderName, List<string> RecepientList, string cc, string email_title, string email_body, List<string> attachments)
{
/// <summary>
///
/// </summary>
/// <param name="SenderEmail"></param>
/// <param name="SenderName"></param>
/// <param name="RecepientList"></param>
/// <param name="cc"></param>
/// <param name="email_title"></param>
/// <param name="email_body"></param>
/// <param name="attachments"></param>
protected void SendEmailWithAttachments(string SenderEmail, string SenderName, List<string> RecepientList, string cc, string email_title, string email_body, List<string> attachments) {
// creating email message
MailMessage msg = new MailMessage();
msg.IsBodyHtml = true;// email body will allow html elements
@ -323,8 +270,7 @@ namespace Fab2ApprovalSystem.Misc
msg.From = new MailAddress(SenderEmail, SenderName);
// adding the Recepient Email ID
foreach (string recepient in RecepientList)
{
foreach (string recepient in RecepientList) {
if (recepient != null)
msg.To.Add(recepient);
}
@ -337,44 +283,32 @@ namespace Fab2ApprovalSystem.Misc
msg.Subject = email_title;
msg.Body = email_body;
foreach (string attachment in attachments)
{
foreach (string attachment in attachments) {
msg.Attachments.Add(new Attachment(attachment));
}
//create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section
SmtpClient SmtpMail = new SmtpClient();
// sending the message.
SmtpMail.Send(msg);
}
public EmailNotification()
{
public EmailNotification() {
}
/// <summary>
/// The Constructor Function
/// </summary>
/// <param name="EmailHeaderSubject">Email Header Subject</param>
/// <param name="TemplatesPath">Emails Files Templates</param>
public EmailNotification(string EmailHeaderSubject, string TemplatesPath)
{
public EmailNotification(string EmailHeaderSubject, string TemplatesPath) {
_subject = EmailHeaderSubject;
_TemplatesPath = TemplatesPath;
}
/// <summary>
/// This function will send the email notification by reading the email template and substitute the arguments
/// </summary>
@ -386,43 +320,33 @@ namespace Fab2ApprovalSystem.Misc
/// <param name="Subject">EMail Subject</param>
/// <param name="Args">Arguments</param>
/// <returns>String: Return the body of the email to be send</returns>
public string SendNotificationEmail(string EmailTemplateFile, string SenderEmail, string SenderName, string RecepientEmail, string CC, string Subject, params string[] Args)
{
public string SendNotificationEmail(string EmailTemplateFile, string SenderEmail, string SenderName, string RecepientEmail, string CC, string Subject, params string[] Args) {
string retVal = null;
//reading the file
string FileContents = ReadEmailFile(EmailTemplateFile);
string emailBody = FileContents;
//setting formatting the string
retVal = string.Format(emailBody, Args);
try
{
try {
//check if we are in debug mode or not. to send email
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY")
{
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") {
SendEmail(SenderEmail, SenderName, GetTestRecipientsList(), CC, (!string.IsNullOrEmpty(Subject) ? Subject + " for: " + RecepientEmail : _subject), retVal);
}
else
{
} else {
#if(!DEBUG)
SendEmail(SenderEmail, SenderName, RecepientEmail, CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal);
#endif
}
}
catch (Exception ex)
{
throw ex;
} catch (Exception ex) {
throw ex;
}
return retVal;
}
/// <summary>
/// This function will send the email notification by reading the email template and substitute the arguments along with the attachments
/// </summary>
@ -435,8 +359,7 @@ namespace Fab2ApprovalSystem.Misc
/// <param name="attachmentPath"></param>
/// <param name="Args"></param>
/// <returns></returns>
public string SendNotificationEmailWithAttachment(string EmailTemplateFile, string SenderEmail, string SenderName, string RecepientEmail, string CC, string Subject, string attachmentPath, params string[] Args)
{
public string SendNotificationEmailWithAttachment(string EmailTemplateFile, string SenderEmail, string SenderName, string RecepientEmail, string CC, string Subject, string attachmentPath, params string[] Args) {
string retVal = null;
//reading the file
@ -447,32 +370,22 @@ namespace Fab2ApprovalSystem.Misc
//setting formatting the string
retVal = string.Format(emailBody, Args);
try
{
try {
//check if we are in debug mode or not. to send email
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY")
{
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") {
SendEmailWithAttachment(SenderEmail, SenderName, GetTestRecipientsList(), CC, (!string.IsNullOrEmpty(Subject) ? " TESTING ONLY -IGNORE : " + Subject + RecepientEmail : _subject), retVal, attachmentPath);
}
else
{
} else {
#if(!DEBUG)
SendEmailWithAttachment(SenderEmail, SenderName, RecepientEmail, CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal, attachmentPath);
#endif
}
}
catch (Exception ex)
{
} catch (Exception ex) {
throw ex;
}
return retVal;
}
/// <summary>
///
/// </summary>
@ -485,8 +398,7 @@ namespace Fab2ApprovalSystem.Misc
/// <param name="attachmentPath"></param>
/// <param name="Args"></param>
/// <returns></returns>
public string SendNotificationEmailWithAttachment(string EmailTemplateFile, string SenderEmail, string SenderName, List<string> RecepientEmail, string CC, string Subject, string attachmentPath, params string[] Args)
{
public string SendNotificationEmailWithAttachment(string EmailTemplateFile, string SenderEmail, string SenderName, List<string> RecepientEmail, string CC, string Subject, string attachmentPath, params string[] Args) {
string retVal = null;
//reading the file
@ -497,41 +409,28 @@ namespace Fab2ApprovalSystem.Misc
//setting formatting the string
retVal = string.Format(emailBody, Args);
try
{
try {
//check if we are in debug mode or not. to send email
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY")
{
foreach(string email in RecepientEmail)
{
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") {
foreach (string email in RecepientEmail) {
Subject += email + ";";
}
RecepientEmail.Clear();
SendEmailWithAttachment(SenderEmail, SenderName, GetTestRecipientsList(), CC, (!string.IsNullOrEmpty(Subject) ? " TESTING ONLY -IGNORE : " + Subject : _subject), retVal, attachmentPath);
}
else
{
} else {
#if (!DEBUG)
SendEmailWithAttachment(SenderEmail, SenderName, RecepientEmail, CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal, attachmentPath);
#endif
}
}
catch (Exception ex)
{
} catch (Exception ex) {
throw ex;
}
return retVal;
}
/////////============================================================
public string SendNotificationEmailWithAttachments(string EmailTemplateFile, string SenderEmail, string SenderName, string RecepientEmail, string CC, string Subject, List<string> attachments, params string[] Args)
{
public string SendNotificationEmailWithAttachments(string EmailTemplateFile, string SenderEmail, string SenderName, string RecepientEmail, string CC, string Subject, List<string> attachments, params string[] Args) {
string retVal = null;
//reading the file
@ -542,32 +441,22 @@ namespace Fab2ApprovalSystem.Misc
//setting formatting the string
retVal = string.Format(emailBody, Args);
try
{
try {
//check if we are in debug mode or not. to send email
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY")
{
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") {
SendEmailWithAttachments(SenderEmail, SenderName, GetTestRecipientsList(), CC, (!string.IsNullOrEmpty(Subject) ? " TESTING ONLY -IGNORE : " + Subject + RecepientEmail : _subject), retVal, attachments);
}
else
{
} else {
#if(!DEBUG)
SendEmailWithAttachments(SenderEmail, SenderName, RecepientEmail, CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal, attachments);
#endif
}
}
catch (Exception ex)
{
} catch (Exception ex) {
throw ex;
}
return retVal;
}
/// <summary>
///
/// </summary>
@ -580,8 +469,7 @@ namespace Fab2ApprovalSystem.Misc
/// <param name="attachmentPath"></param>
/// <param name="Args"></param>
/// <returns></returns>
public string SendNotificationEmailWithAttachments(string EmailTemplateFile, string SenderEmail, string SenderName, List<string> RecepientEmail, string CC, string Subject, List<string> attachments, params string[] Args)
{
public string SendNotificationEmailWithAttachments(string EmailTemplateFile, string SenderEmail, string SenderName, List<string> RecepientEmail, string CC, string Subject, List<string> attachments, params string[] Args) {
string retVal = null;
//reading the file
@ -592,39 +480,27 @@ namespace Fab2ApprovalSystem.Misc
//setting formatting the string
retVal = string.Format(emailBody, Args);
try
{
try {
//check if we are in debug mode or not. to send email
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY")
{
foreach(string email in RecepientEmail)
{
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") {
foreach (string email in RecepientEmail) {
Subject += email + ";";
}
RecepientEmail.Clear();
SendEmailWithAttachments(SenderEmail, SenderName, GetTestRecipientsList(), CC, (!string.IsNullOrEmpty(Subject) ? " TESTING ONLY -IGNORE : " + Subject : _subject), retVal, attachments);
}
else
{
} else {
#if (!DEBUG)
SendEmailWithAttachments(SenderEmail, SenderName, RecepientEmail, CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal, attachments);
#endif
}
}
catch (Exception ex)
{
} catch (Exception ex) {
throw ex;
}
return retVal;
}
/// <summary>
///
/// </summary>
@ -636,8 +512,7 @@ namespace Fab2ApprovalSystem.Misc
/// <param name="Subject"></param>
/// <param name="Args"></param>
/// <returns></returns>
public string SendNotificationEmail(string EmailTemplateFile, string SenderEmail, string SenderName, List<string> RecepientEmail, string CC, string Subject, params string[] Args)
{
public string SendNotificationEmail(string EmailTemplateFile, string SenderEmail, string SenderName, List<string> RecepientEmail, string CC, string Subject, params string[] Args) {
string retVal = null;
//reading the file
@ -648,33 +523,24 @@ namespace Fab2ApprovalSystem.Misc
//setting formatting the string
retVal = string.Format(emailBody, Args);
try
{
try {
//check if we are in debug mode or not. to send email
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY")
{
foreach (string email in RecepientEmail)
{
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") {
foreach (string email in RecepientEmail) {
Subject += email + ";";
}
RecepientEmail.Clear();
SendEmail(SenderEmail, SenderName, GetTestRecipientsList(), CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal);
}
else
{
} else {
#if (!DEBUG)
SendEmail(SenderEmail, SenderName, RecepientEmail, CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal);
#endif
}
}
catch (Exception ex)
{
} catch (Exception ex) {
throw ex;
}
return retVal;
}
/// <summary>
@ -683,10 +549,8 @@ namespace Fab2ApprovalSystem.Misc
/// <param name="subject"></param>
/// <param name="body"></param>
/// <param name="importance"></param>
public void SendNotificationEmailToAdmin(string subject, string body, MailPriority importance)
{
try
{
public void SendNotificationEmailToAdmin(string subject, string body, MailPriority importance) {
try {
System.Configuration.ConfigurationManager.RefreshSection("appSettings");
SmtpClient client = new SmtpClient(ConfigurationManager.AppSettings["SMTP Server"]);
@ -704,30 +568,23 @@ namespace Fab2ApprovalSystem.Misc
msg.Subject = subject;
msg.Body = temp;
msg.Priority = importance;
//#if(!DEBUG)
//#if(!DEBUG)
client.Send(msg);
//#endif
}
catch (Exception ex)
{
//#endif
} catch (Exception ex) {
throw ex;
}
}
public List<string> GetTestRecipientsList()
{
var r = new List<string>();
try
{
public List<string> GetTestRecipientsList() {
List<string> r = new List<string>();
try {
string emails = ConfigurationManager.AppSettings["Test Email Recipients"];
foreach (string s in emails.Split(';', ','))
{
foreach (string s in emails.Split(';', ',')) {
if (!String.IsNullOrWhiteSpace(s))
r.Add(s);
}
}
catch
{
} catch {
r.Add("dhuang2@infineon.com");
}
return r;

View File

@ -10,57 +10,44 @@ using System.Net.Mail;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
namespace Fab2ApprovalSystem.Misc
{
public static class Functions
{
namespace Fab2ApprovalSystem.Misc {
public static class Functions {
/// <summary>
/// Writes to the Application Event Log and sends an email notification if appropriate
/// </summary>
/// <param name="logtext"></param>
/// <param name="eventType"></param>
public static void WriteEvent(string logtext, System.Diagnostics.EventLogEntryType eventType)
{
public static void WriteEvent(string logtext, System.Diagnostics.EventLogEntryType eventType) {
//#if(!DEBUG)
EmailNotification en = new EmailNotification();
EventLog ev = new EventLog("Application");
ev.Source = "Fab Approval System";
try
{
try {
//Write to the Event Log
ev.WriteEntry(logtext, eventType);
////Send an email notification if appropriate
////Don't attempt to send an email if the error is pertaining to an email problem
if (!logtext.Contains("SendEmailNotification()"))
{
if (!logtext.Contains("SendEmailNotification()")) {
//Only send email notifications for Error and Warning level events
if (eventType == System.Diagnostics.EventLogEntryType.Error)
en.SendNotificationEmailToAdmin(ev.Source + " - Error Notification", logtext, MailPriority.High);
//else if (eventType == System.Diagnostics.EventLogEntryType.Warning)
// SendEmailNotification(ErrorRecipient(), ev.Source + " Warning Event Logged", logtext, NORMAL_PRI);
}
}
catch
{
} catch {
//throw;
}
finally
{
} finally {
ev = null;
}
//#endif
}
/// <summary>
/// Returns the FTP Server Name
/// </summary>
/// <returns></returns>
public static string FTPServer()
{
public static string FTPServer() {
ConfigurationManager.RefreshSection("appSettings");
return ConfigurationManager.AppSettings["FTP Server"];
}
@ -69,8 +56,7 @@ namespace Fab2ApprovalSystem.Misc
/// Returns the FTP User Name
/// </summary>
/// <returns></returns>
public static string FTPUser()
{
public static string FTPUser() {
ConfigurationManager.RefreshSection("appSettings");
return ConfigurationManager.AppSettings["FTP User"];
}
@ -79,8 +65,7 @@ namespace Fab2ApprovalSystem.Misc
/// Returns the FTP Password
/// </summary>
/// <returns></returns>
public static string FTPPassword()
{
public static string FTPPassword() {
ConfigurationManager.RefreshSection("appSettings");
return ConfigurationManager.AppSettings["FTP Password"];
}
@ -89,41 +74,32 @@ namespace Fab2ApprovalSystem.Misc
///
/// </summary>
/// <returns></returns>
public static string GetAttachmentFolder()
{
public static string GetAttachmentFolder() {
ConfigurationManager.RefreshSection("appSettings");
return ConfigurationManager.AppSettings["AttachmentFolder"];
}
/// <summary>
///
/// </summary>
/// <param name="oldECNNumber"></param>
/// <param name="newECNNumber"></param>
public static void CopyAttachments(int oldECNNumber, int newECNNumber)
{
public static void CopyAttachments(int oldECNNumber, int newECNNumber) {
// The Name of the Upload component is "files"
string oldFolderPath = Functions.GetAttachmentFolder() + "ECN\\" + oldECNNumber.ToString();
string newFolderPath = Functions.GetAttachmentFolder() + "ECN\\" + newECNNumber.ToString() ;
string newFolderPath = Functions.GetAttachmentFolder() + "ECN\\" + newECNNumber.ToString();
DirectoryInfo newdi = new DirectoryInfo(newFolderPath);
if (!newdi.Exists)
newdi.Create();
FileInfo[] existingFiles = new DirectoryInfo(oldFolderPath ).GetFiles();
foreach (FileInfo file in existingFiles)
{
if (!file.Name.Contains("ECNApprovalLog_" + oldECNNumber.ToString()) && !file.Name.Contains("ECNForm_" + oldECNNumber.ToString()))
FileInfo[] existingFiles = new DirectoryInfo(oldFolderPath).GetFiles();
foreach (FileInfo file in existingFiles) {
if (!file.Name.Contains("ECNApprovalLog_" + oldECNNumber.ToString()) && !file.Name.Contains("ECNForm_" + oldECNNumber.ToString()))
//var fileName = Path.GetFileName(file.FullName);
file.CopyTo(Path.Combine(newFolderPath, file.Name));
}
}
}
/// <summary>
@ -132,13 +108,11 @@ namespace Fab2ApprovalSystem.Misc
/// <param name="userID"></param>
/// <param name="pwd"></param>
/// <returns></returns>
public static bool NA_ADAuthenticate(string userID, string pwd)
{
public static bool NA_ADAuthenticate(string userID, string pwd) {
string naContainer = ConfigurationManager.AppSettings["NAContainer"];
string naDomain = ConfigurationManager.AppSettings["NADomain"];
try
{
try {
PrincipalContext contextUser = new PrincipalContext(ContextType.Domain,
naDomain,
naContainer,
@ -149,12 +123,9 @@ namespace Fab2ApprovalSystem.Misc
return false;
else
return true;
}
catch
{
} catch {
return false;
}
}
/// <summary>
@ -163,13 +134,11 @@ namespace Fab2ApprovalSystem.Misc
/// <param name="userID"></param>
/// <param name="pwd"></param>
/// <returns></returns>
public static bool IFX_ADAuthenticate(string userID, string pwd)
{
public static bool IFX_ADAuthenticate(string userID, string pwd) {
string container = ConfigurationManager.AppSettings["IFXContainer"];
string domain = ConfigurationManager.AppSettings["IFXDomain"];
try
{
try {
PrincipalContext contextUser = new PrincipalContext(ContextType.Domain,
domain,
container,
@ -180,18 +149,12 @@ namespace Fab2ApprovalSystem.Misc
return false;
else
return true;
}
catch
{
} catch {
return false;
}
}
public static string FTPSPNBatch()
{
public static string FTPSPNBatch() {
ConfigurationManager.RefreshSection("appSettings");
return ConfigurationManager.AppSettings["FTPSPNBatchFileName"];
}
@ -200,8 +163,7 @@ namespace Fab2ApprovalSystem.Misc
///
/// </summary>
/// <returns></returns>
public static string FTPSPNBatch_Test()
{
public static string FTPSPNBatch_Test() {
ConfigurationManager.RefreshSection("appSettings");
return ConfigurationManager.AppSettings["FTPSPNBatchFileName_Test"];
}
@ -211,50 +173,44 @@ namespace Fab2ApprovalSystem.Misc
/// </summary>
/// <param name="casection"></param>
/// <returns></returns>
public static string CASectionMapper(GlobalVars.CASection casection)
{
switch (casection)
{
public static string CASectionMapper(GlobalVars.CASection casection) {
switch (casection) {
case GlobalVars.CASection.Main:
return "Main";
case GlobalVars.CASection.D1:
return "D1";
case GlobalVars.CASection.D2:
return "D2";
case GlobalVars.CASection.D3:
return "D3";
case GlobalVars.CASection.D4:
return "D4";
case GlobalVars.CASection.D5:
return "D5";
case GlobalVars.CASection.D6:
return "D6";
case GlobalVars.CASection.D7:
return "D7";
case GlobalVars.CASection.D8:
return "D8";
case GlobalVars.CASection.CF: // CA Findings
return "CF";
}
return "";
}
public static string DocumentTypeMapper(GlobalVars.DocumentType docType)
{
switch (docType)
{
case GlobalVars.DocumentType.Audit:
public static string DocumentTypeMapper(GlobalVars.DocumentType docType) {
switch (docType) {
case GlobalVars.DocumentType.Audit:
return "Audit";
case GlobalVars.DocumentType.ChangeControl:
return "ChangeControl";
@ -280,17 +236,15 @@ namespace Fab2ApprovalSystem.Misc
/// </summary>
/// <param name="caNo"></param>
/// <returns></returns>
public static string ReturnCANoStringFormat(int caNo)
{
public static string ReturnCANoStringFormat(int caNo) {
string caNoString = "";
if(caNo == 0)
if (caNo == 0)
return "";
caNoString = "C" + caNo.ToString().PadLeft(5, '0');
return caNoString;
}
public static string ReturnAuditNoStringFormat(int auditNo)
{
public static string ReturnAuditNoStringFormat(int auditNo) {
string auditNoString = "";
if (auditNo == 0)
return "";
@ -298,12 +252,10 @@ namespace Fab2ApprovalSystem.Misc
return auditNoString;
}
public static string ReturnPartsRequestNoStringFormat(int PRNumber)
{
public static string ReturnPartsRequestNoStringFormat(int PRNumber) {
if (PRNumber == 0)
return "";
return String.Format("PR{0:000000}", PRNumber);
}
}
}

View File

@ -0,0 +1,7 @@
namespace Fab2ApprovalSystem.Models {
public class AuthAttempt {
public string LoginID { get; set; }
public string Password { get; set; } = "";
public AuthTokens AuthTokens { get; set; }
}
}

View File

@ -0,0 +1,6 @@
namespace Fab2ApprovalSystem.Models {
public class AuthTokens {
public string JwtToken { get; set; }
public string RefreshToken { get; set; }
}
}

View File

@ -0,0 +1,6 @@
namespace Fab2ApprovalSystem.Models {
public class LoginResult {
public bool IsAuthenticated { get; set; }
public AuthTokens AuthTokens { get; set; }
}
}

View File

@ -83,14 +83,29 @@
@*<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", "ECN")>Create ECN/TECN</a></li>
@if (!string.IsNullOrWhiteSpace(Session["JWT"].ToString())) {
string jwt = Session["JWT"].ToString();
string encodedJwt = System.Net.WebUtility.UrlEncode(jwt);
string refreshToken = Session["RefreshToken"].ToString();
string encodedRefreshToken = System.Net.WebUtility.UrlEncode(refreshToken);
string wasmClientUrl = Environment.GetEnvironmentVariable("FabApprovalWasmClientUrl") ??
"https://localhost:7255";
string mrbUrl = wasmClientUrl + "/redirect?jwt=" + encodedJwt + "&refreshToken=" + encodedRefreshToken + "&redirectPath=/mrb/new";
<li><a href="@mrbUrl">Create MRB</a></li>
} else {
string wasmClientUrl = Environment.GetEnvironmentVariable("FabApprovalWasmClientUrl") ??
"https://localhost:7255";
string mrbUrl = wasmClientUrl + "/redirect?redirectPath=/mrb/new";
<li><a href="@mrbUrl">Create MRB</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", "Audit")>Create Audit</a></li>
<li><a href=@Url.Action("Create", "CorrectiveAction")>Create Corrective Action</a></li>
@*@if (Convert.ToBoolean(Session[GlobalVars.CAN_CREATE_PARTS_REQUEST]))
{
<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>
}*@
@*<li><a href="#">Another Doc</a></li>*@
</ul>
</li>
@ -125,6 +140,14 @@
menu.Add().Text("My Training").Action("ViewMyTrainingAssignments", "Training");
menu.Add().Text("Training Reports").Action("TrainingReports", "Training");
menu.Add().Text("All Documents").Action("AllDocuments", "Home");
string jwt = Session["JWT"].ToString();
string encodedJwt = System.Net.WebUtility.UrlEncode(jwt);
string refreshToken = Session["RefreshToken"].ToString();
string encodedRefreshToken = System.Net.WebUtility.UrlEncode(refreshToken);
string wasmClientUrl = Environment.GetEnvironmentVariable("FabApprovalWasmClientUrl") ??
"https://localhost:7255";
string mrbUrl = wasmClientUrl + "/redirect?jwt=" + encodedJwt + "&refreshToken=" + encodedRefreshToken + "&redirectPath=/mrb/all";
menu.Add().Text("MRB").Url(mrbUrl);
//menu.Add().Text("Special Work Requests").Action("SpecialWorkRequestList", "Home");
//menu.Add().Text("PCRB").Action("ChangeControlList", "Home");
//menu.Add().Text("MRB").Action("MRBList", "Home");

View File

@ -11,18 +11,6 @@
<link rel="stylesheet" href="/Content/kendo/kendo.blueopal.min.css" />
<link rel="stylesheet" href="~/Content/kendogridcustom.css" />
@*<link rel="stylesheet" href="~/Scripts/jqwidgets/styles/jqx.base.css" type="text/css" />
<link rel="stylesheet" href="~/Scripts/jqwidgets/styles/jqx.energyblue.css" type="text/css" />
<link rel="stylesheet" href="~/Scripts/jqwidgets/styles/jqx.arctic.css" type="text/css" />
<script type="text/javascript" src="~/Scripts/jqwidgets/jqxcore.js"></script>
<script type="text/javascript" src="~/Scripts/jqwidgets/jqxdata.js"></script>
<script type="text/javascript" src="~/Scripts/jqwidgets/jqxbuttons.js"></script>
<script type="text/javascript" src="~/Scripts/jqwidgets/jqxscrollbar.js"></script>
<script type="text/javascript" src="~/Scripts/jqwidgets/jqxlistbox.js"></script>
<script type="text/javascript" src="~/Scripts/jqwidgets/jqxpanel.js"></script>
<script type="text/javascript" src="~/Scripts/jqwidgets/jqxtree.js"></script>*@
<style>
.k-grid .k-grid-header .k-header .k-link {
height: auto;