29 Commits

Author SHA1 Message Date
2dbb541c1a MRB webassembly 2024-07-11 09:11:01 -07:00
c97ce37238 Added note about removing TECN from POU when cancelled 2024-07-10 09:33:29 -07:00
10dbd08cd2 Added ECN approvers note to other affected views 2024-06-14 09:09:45 -07:00
1b7e482ad4 Removed duplicated tasks 2024-06-12 08:14:39 -07:00
cbcd3ee53a Added ECN approvers note 2024-06-11 09:40:31 -07:00
fe981c4c04 Add note about red dates in training report 2024-05-15 07:06:39 -07:00
3e6fc3fdb3 Assignments late in report after 15 days 2024-05-14 14:01:25 -07:00
1b17cd75c2 Removing PCRB and MRB modules 2024-05-08 08:26:30 -07:00
5d701ded55 Broadening notifications for cancelled TECNs 2023-11-01 09:18:39 -07:00
0289e62e9f Rejected CA notifications include who and why 2023-10-31 20:07:50 +01:00
d6af4b6ef9 Added validation for required field at CA Ready via Jquery in the edit page. 2023-10-30 23:39:38 +01:00
4e04d4666d Use same local attachment folder location in dev and prod 2023-10-30 17:19:20 +01:00
88af83cf96 Prepended Create for MRB and ECN 2023-10-30 17:19:20 +01:00
e8ec36fe3e Updated ECN approval caption 2023-10-30 17:19:20 +01:00
4b83a89cb0 Changed server addresses in links 2023-10-30 17:19:20 +01:00
ca651191c8 Switching to internal mailrealy 2023-10-30 17:19:20 +01:00
ffe6cd7c63 Prepended Create for MRB and ECN 2023-10-16 14:16:41 -07:00
e1675fe9e9 Updated ECN approval caption 2023-10-09 11:43:08 -07:00
a3053eadf6 Removed ITAR check 2023-10-03 10:14:54 -07:00
7cc645c188 Changed url schema to use ssl 2023-09-20 14:28:38 -07:00
fbeb8b3cf7 Corrected prod site url config 2023-09-20 14:22:34 -07:00
27728bd0c4 Corrected email template placeholders 2023-09-20 14:12:02 -07:00
7330647172 Limiting training report to only run in production 2023-09-20 09:28:08 -07:00
167db67027 Creating OOOTrainingReport scheduled job 2023-09-18 16:09:03 -07:00
9c5c938157 Loosening 6DValidate permissions 2023-09-18 11:42:01 -07:00
989d0f401e Update azure-pipelines.yml for Azure Pipelines 2023-09-15 21:28:41 +00:00
15c7a15b8e Update azure-pipelines.yml for Azure Pipelines 2023-09-15 20:43:45 +00:00
7e4a17845c Updated Nuget package source for development 2023-09-15 20:24:57 +00:00
1f96c01a5b Trying JFrog 2023-09-08 22:44:12 +00:00
163 changed files with 8167 additions and 1455 deletions

View File

@ -1,74 +1,229 @@
# EditorConfig is awesome:http://EditorConfig.org
# top-most EditorConfig file
# Remove the line below if you want to inherit .editorconfig settings from higher directories
root = true
[*]
# Don't use tabs for indentation.
# (Please don't specify an indent_size here; that has too many unintended consequences.)
indent_style = space
charset = utf-8
# Where supported, trim trailing whitespace on all lines.
trim_trailing_whitespace = true
# Where supported (e.g. in VS Code but not VS), add a final newline to files.
insert_final_newline = true
# Code files
[*.{cs,csx,vb,vbx}]
indent_size = 4
dotnet_sort_system_directives_first = true:warning
# Xml project files
[*.{*proj,vcxproj.filters,projitems}]
indent_size = 2
# Xml config files
[*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct,tasks,xml,yml}]
indent_size = 2
# JSON files
[*.json]
indent_size = 2
# PowerShell
[*.{ps1,psm1}]
indent_size = 4
# Shell
[*.sh]
indent_size = 4
end_of_line = lf
# Dotnet code style settings:
# C# files
[*.cs]
# Sort using and Import directives with System.* appearing first
#### Core EditorConfig Options ####
# Indentation and spacing
indent_size = 4
indent_style = space
tab_width = 4
# New line preferences
end_of_line = crlf
insert_final_newline = false
#### .NET Coding Conventions ####
# Organize usings
dotnet_separate_import_directive_groups = true
dotnet_sort_system_directives_first = true
file_header_template = unset
# Don't use this. qualifier
dotnet_style_qualification_for_field = false:suggestion
dotnet_style_qualification_for_property = false:suggestion
# this. and Me. preferences
dotnet_style_qualification_for_event = true
dotnet_style_qualification_for_field = true
dotnet_style_qualification_for_method = true
dotnet_style_qualification_for_property = true
# use int x = .. over Int32
dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion
# Language keywords vs BCL types preferences
dotnet_style_predefined_type_for_locals_parameters_members = true
dotnet_style_predefined_type_for_member_access = true
# use int.MaxValue over Int32.MaxValue
dotnet_style_predefined_type_for_member_access = true:suggestion
# Parentheses preferences
dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:error
dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:error
dotnet_style_parentheses_in_other_operators = never_if_unnecessary
dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:error
# Require var all the time.
csharp_style_var_for_built_in_types = false:suggestion
csharp_style_var_when_type_is_apparent = false:suggestion
csharp_style_var_elsewhere = false:suggestion
# Modifier preferences
dotnet_style_require_accessibility_modifiers = for_non_interface_members
# Disallow throw expressions.
csharp_style_throw_expression = false:suggestion
# Expression-level preferences
dotnet_style_coalesce_expression = false
dotnet_style_collection_initializer = true
dotnet_style_explicit_tuple_names = true:error
dotnet_style_namespace_match_folder = true
dotnet_style_null_propagation = true
dotnet_style_object_initializer = true
dotnet_style_operator_placement_when_wrapping = beginning_of_line
dotnet_style_prefer_auto_properties = true
dotnet_style_prefer_compound_assignment = true
dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion
dotnet_style_prefer_conditional_expression_over_return = true:suggestion
dotnet_style_prefer_foreach_explicit_cast_in_source = when_strongly_typed
dotnet_style_prefer_inferred_anonymous_type_member_names = false
dotnet_style_prefer_inferred_tuple_names = false
dotnet_style_prefer_is_null_check_over_reference_equality_method = true
dotnet_style_prefer_simplified_boolean_expressions = true
dotnet_style_prefer_simplified_interpolation = true
# Newline settings
csharp_new_line_before_open_brace = all
csharp_new_line_before_else = true
csharp_new_line_before_catch = true
csharp_new_line_before_finally = true
csharp_new_line_before_members_in_object_initializers = true
# Field preferences
dotnet_style_readonly_field = true:warning
# Parameter preferences
dotnet_code_quality_unused_parameters = all:error
# Suppression preferences
dotnet_remove_unnecessary_suppression_exclusions = none
# New line preferences
dotnet_style_allow_multiple_blank_lines_experimental = false:error
dotnet_style_allow_statement_immediately_after_block_experimental = false:warning
#### C# Coding Conventions ####
# var preferences
csharp_style_var_elsewhere = false:error
csharp_style_var_for_built_in_types = false:error
csharp_style_var_when_type_is_apparent = false:error
# Expression-bodied members
csharp_style_expression_bodied_accessors = false
csharp_style_expression_bodied_constructors = false
csharp_style_expression_bodied_indexers = false
csharp_style_expression_bodied_lambdas = true
csharp_style_expression_bodied_local_functions = false
csharp_style_expression_bodied_methods = when_on_single_line:suggestion
csharp_style_expression_bodied_operators = false
csharp_style_expression_bodied_properties = false
# Pattern matching preferences
csharp_style_pattern_matching_over_as_with_null_check = false
csharp_style_pattern_matching_over_is_with_cast_check = false
csharp_style_prefer_extended_property_pattern = true
csharp_style_prefer_not_pattern = true
csharp_style_prefer_pattern_matching = true
csharp_style_prefer_switch_expression = false
# Null-checking preferences
csharp_style_conditional_delegate_call = false
# Modifier preferences
csharp_prefer_static_local_function = false
csharp_preferred_modifier_order = public,private,protected,internal,file,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,required,volatile,async
csharp_style_prefer_readonly_struct = true:warning
csharp_style_prefer_readonly_struct_member = true
# Code-block preferences
csharp_prefer_braces = when_multiline:error
csharp_prefer_simple_using_statement = false
csharp_style_namespace_declarations = file_scoped:error
csharp_style_prefer_method_group_conversion = true:suggestion
csharp_style_prefer_top_level_statements = true:error
# Expression-level preferences
csharp_prefer_simple_default_expression = true
csharp_style_deconstructed_variable_declaration = false
csharp_style_implicit_object_creation_when_type_is_apparent = false
csharp_style_inlined_variable_declaration = true
csharp_style_prefer_index_operator = false:error
csharp_style_prefer_local_over_anonymous_function = true:error
csharp_style_prefer_null_check_over_type_check = true
csharp_style_prefer_range_operator = false:error
csharp_style_prefer_tuple_swap = true
csharp_style_prefer_utf8_string_literals = true
csharp_style_throw_expression = false
csharp_style_unused_value_assignment_preference = unused_local_variable
csharp_style_unused_value_expression_statement_preference = unused_local_variable
# 'using' directive preferences
csharp_using_directive_placement = outside_namespace:error
# 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:error
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
# Indentation preferences
csharp_indent_block_contents = true
csharp_indent_braces = false
csharp_indent_case_contents = true
csharp_indent_case_contents_when_block = true
csharp_indent_labels = one_less_than_current
csharp_indent_switch_labels = true
# Space preferences
csharp_space_after_cast = false
csharp_space_after_colon_in_inheritance_clause = true
csharp_space_after_comma = true
csharp_space_after_dot = false
csharp_space_after_keywords_in_control_flow_statements = true
csharp_space_after_semicolon_in_for_statement = true
csharp_space_around_binary_operators = before_and_after
csharp_space_around_declaration_statements = false
csharp_space_before_colon_in_inheritance_clause = true
csharp_space_before_comma = false
csharp_space_before_dot = false
csharp_space_before_open_square_brackets = false
csharp_space_before_semicolon_in_for_statement = false
csharp_space_between_empty_square_brackets = false
csharp_space_between_method_call_empty_parameter_list_parentheses = false
csharp_space_between_method_call_name_and_opening_parenthesis = false
csharp_space_between_method_call_parameter_list_parentheses = false
csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
csharp_space_between_method_declaration_name_and_open_parenthesis = false
csharp_space_between_method_declaration_parameter_list_parentheses = false
csharp_space_between_parentheses = false
csharp_space_between_square_brackets = false
# Wrapping preferences
csharp_preserve_single_line_blocks = true
csharp_preserve_single_line_statements = true
#### Naming styles ####
# Naming rules
dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion
dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i
dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.types_should_be_pascal_case.symbols = types
dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case
dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members
dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case
# Symbol specifications
dotnet_naming_symbols.interface.applicable_kinds = interface
dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.interface.required_modifiers =
dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.types.required_modifiers =
dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.non_field_members.required_modifiers =
# Naming styles
dotnet_naming_style.pascal_case.required_prefix =
dotnet_naming_style.pascal_case.required_suffix =
dotnet_naming_style.pascal_case.word_separator =
dotnet_naming_style.pascal_case.capitalization = pascal_case
dotnet_naming_style.begins_with_i.required_prefix = I
dotnet_naming_style.begins_with_i.required_suffix =
dotnet_naming_style.begins_with_i.word_separator =
dotnet_naming_style.begins_with_i.capitalization = pascal_case

3
.gitignore vendored
View File

@ -337,3 +337,6 @@ ASALocalRun/
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.vscode
.env

View File

@ -1,20 +1,20 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27130.2020
# Visual Studio Version 17
VisualStudioVersion = 17.9.34616.47
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Fab2ApprovalSystem", "Fab2ApprovalSystem\Fab2ApprovalSystem.csproj", "{AAE52608-4DD1-4732-92BD-CC8915DEC71E}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MesaFabApproval.API", "MesaFabApproval.API\MesaFabApproval.API.csproj", "{852E528D-015A-43B5-999D-F281E3359E5E}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MesaFabApproval.Shared", "MesaFabApproval.Shared\MesaFabApproval.Shared.csproj", "{2C16014D-B04E-46AF-AB4C-D2691D44A339}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MesaFabApproval.Client", "MesaFabApproval.Client\MesaFabApproval.Client.csproj", "{34D52F44-A81F-4247-8180-16E204824A07}"
ProjectSection(ProjectDependencies) = postProject
{2C16014D-B04E-46AF-AB4C-D2691D44A339} = {2C16014D-B04E-46AF-AB4C-D2691D44A339}
EndProjectSection
EndProject
Global
GlobalSection(TeamFoundationVersionControl) = preSolution
SccNumberOfProjects = 2
SccEnterpriseProvider = {4CA58AB2-18FA-4F8D-95D4-32DDF27D184C}
SccTeamFoundationServer = http://tfs.intra.infineon.com:8080/tfs/manufacturingit
SccLocalPath0 = .
SccProjectUniqueName1 = Fab2ApprovalSystem\\Fab2ApprovalSystem.csproj
SccProjectName1 = Fab2ApprovalSystem
SccLocalPath1 = Fab2ApprovalSystem
EndGlobalSection
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
@ -24,8 +24,23 @@ Global
{AAE52608-4DD1-4732-92BD-CC8915DEC71E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AAE52608-4DD1-4732-92BD-CC8915DEC71E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AAE52608-4DD1-4732-92BD-CC8915DEC71E}.Release|Any CPU.Build.0 = Release|Any CPU
{852E528D-015A-43B5-999D-F281E3359E5E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{852E528D-015A-43B5-999D-F281E3359E5E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{852E528D-015A-43B5-999D-F281E3359E5E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{852E528D-015A-43B5-999D-F281E3359E5E}.Release|Any CPU.Build.0 = Release|Any CPU
{2C16014D-B04E-46AF-AB4C-D2691D44A339}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2C16014D-B04E-46AF-AB4C-D2691D44A339}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2C16014D-B04E-46AF-AB4C-D2691D44A339}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2C16014D-B04E-46AF-AB4C-D2691D44A339}.Release|Any CPU.Build.0 = Release|Any CPU
{34D52F44-A81F-4247-8180-16E204824A07}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{34D52F44-A81F-4247-8180-16E204824A07}.Debug|Any CPU.Build.0 = Debug|Any CPU
{34D52F44-A81F-4247-8180-16E204824A07}.Release|Any CPU.ActiveCfg = Release|Any CPU
{34D52F44-A81F-4247-8180-16E204824A07}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {A966A184-1FCD-4B6A-978C-5907CC12406B}
EndGlobalSection
EndGlobal

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,20 +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;
}
@ -36,8 +40,7 @@ namespace Fab2ApprovalSystem.Controllers
[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)
{
public ActionResult Login(string returnUrl) {
ViewBag.ReturnUrl = returnUrl;
return View();
}
@ -45,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;
@ -68,58 +85,23 @@ namespace Fab2ApprovalSystem.Controllers
//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)
{
//Check ITAR Permissions from AD group
#if(!DEBUG)
try
{
bool hasITARAccess = false;
//========TEMP CODE - NEEDS TO BE DELETED
//Functions.WriteEvent("Using DB for EC Auth for user " + model.LoginID, System.Diagnostics.EventLogEntryType.Information);
//hasITARAccess = userDMO.GetEC_AD_Users(model.LoginID);
//=============END OF TEMP CODE
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY")
{
hasITARAccess = true;
}
else
{
hasITARAccess = Functions.NA_HasITARAccess(model.LoginID, model.Password);
if (!hasITARAccess) // check the IFX domain
hasITARAccess = Functions.IFX_HasITARAccess(model.LoginID, model.Password);
}
userDMO.UpdateInsertITARAccess(model.LoginID, hasITARAccess ? "1" : "0");
}
catch (Exception ex)
{
ModelState.AddModelError("", "Not a member of the EC Domain" + ex.Message);
return View(model);
}
#endif
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;
@ -128,23 +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);
}
@ -154,285 +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
public ActionResult Manage(ManageMessageId? message)
{
//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");
#pragma warning disable IDE0060 // Remove unused parameter
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;
}
@ -443,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;
@ -517,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

@ -1870,9 +1870,9 @@ namespace Fab2ApprovalSystem.Controllers
int assigneeId = ca.D1AssigneeID;
int requestorId = ca.RequestorID;
int qaId = ca.QAID;
NotifySectionRejection(issueID, assigneeId, dSection);
NotifySectionRejection(issueID, requestorId, dSection);
NotifySectionRejection(issueID, qaId, dSection);
NotifySectionRejection(issueID, assigneeId, userID, dSection, comments);
NotifySectionRejection(issueID, requestorId, userID, dSection, comments);
NotifySectionRejection(issueID, qaId, userID, dSection, comments);
return Content("Successfully Saved");
}
@ -1893,11 +1893,14 @@ namespace Fab2ApprovalSystem.Controllers
return Content(e.Message);
}
}
public void NotifySectionRejection(int issueID, int userId, string section)
public void NotifySectionRejection(int issueID, int recipientUserId, int loggedInUserId, string section, string comment)
{
try
{
string userEmail = userDMO.GetUserEmailByID(userId.ToString());
LoginModel recipient = userDMO.GetUserByID(recipientUserId);
string recipientEmail = recipient.Email;
LoginModel loggedInUser = userDMO.GetUserByID(loggedInUserId);
string emailTemplate = "CorrectiveActionSectionRejection.txt";
//string userEmail = string.Empty;
@ -1906,16 +1909,18 @@ namespace Fab2ApprovalSystem.Controllers
//subject = "Corrective Action Assignment";
EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]);
string[] emailparams = new string[4];
string[] emailparams = new string[6];
emailparams[0] = Functions.ReturnCANoStringFormat(issueID);
emailparams[1] = issueID.ToString();
emailparams[2] = GlobalVars.hostURL;
emailparams[3] = section;
emailparams[4] = loggedInUser.FirstName + " " + loggedInUser.LastName;
emailparams[5] = comment;
//#if(DEBUG)
// userEmail = "rkotian1@irf.com";
//#endif
en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams);
en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, recipientEmail, null, subject, emailparams);
try
{

View File

@ -31,6 +31,7 @@ namespace Fab2ApprovalSystem.Controllers
ECN_DMO ecnDMO = new ECN_DMO();
WorkflowDMO wfDMO = new WorkflowDMO();
TrainingDMO trainingDMO = new TrainingDMO();
UserAccountDMO userDMO = new UserAccountDMO();
//
@ -2115,6 +2116,12 @@ namespace Fab2ApprovalSystem.Controllers
string emailSentList = "";
List<string> emailIst = MiscDMO.GetTECNCancelledApprovalNotifyList(ecnNumber).Distinct().ToList();
List<int> notificationUserList = ecnDMO.GetTECNNotificationUsers().ToList();
foreach (int userId in notificationUserList)
{
string email = userDMO.GetUserEmailByID(userId.ToString());
if (email != null && !emailIst.Contains(email)) emailIst.Add(email);
}
string emailTemplate = "TECNCancelled.txt";
string userEmail = string.Empty;

View File

@ -126,7 +126,7 @@ namespace Fab2ApprovalSystem.Controllers
try
{
ViewBag.ActiveTabName = tabName;
IEnumerable<IssuesViewModel> data = ldDMO.GetTaskList((int)Session[GlobalVars.SESSION_USERID]);
List<IssuesViewModel> data = ldDMO.GetTaskList((int)Session[GlobalVars.SESSION_USERID]).Distinct().ToList();
return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
@ -141,7 +141,7 @@ namespace Fab2ApprovalSystem.Controllers
try
{
ViewBag.ActiveTabName = tabName;
IEnumerable<OpenActionItemViewModel> data = ldDMO.GetMyOpenActionItems((int)Session[GlobalVars.SESSION_USERID]);
List<OpenActionItemViewModel> data = ldDMO.GetMyOpenActionItems((int)Session[GlobalVars.SESSION_USERID]).Distinct().ToList();
return Json(data.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
catch (Exception ex)

View File

@ -2,25 +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;
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();
@ -28,47 +21,39 @@ 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);
}
int trainingId = trainingDMO.Create(ecnId);
List<int> TrainingGroups = new List<int>();
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);
@ -77,178 +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";
@ -259,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();
@ -271,119 +197,86 @@ 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);
}
}
}
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);
}
}
@ -392,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();
@ -414,16 +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;
@ -438,36 +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++;
}
}
percentComplete = (totalCompleted / assignmentCount) * 100;
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
@ -491,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;
@ -506,90 +386,75 @@ 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,
DateAssigned = assignment.DateAssigned,
DateCompleted = assignment.DateCompleted,
Status = assignment.status
});
}
}
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);
@ -597,124 +462,90 @@ 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. Please ensure the following users complete their training assignments.</p><br />";
emailBody += "<p>The following contains open training assignments in the Mesa Approval system. ";
emailBody += "Please ensure the following users complete their training assignments. ";
emailBody += "Dates in red font identify past due training tasks.</p><br />";
emailBody += "<style>table,th,td{border: 1px solid black;}</style>";
//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);
}
@ -722,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;
@ -732,18 +562,20 @@ 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) {
trainingSection += "<tr><td>" + assignment.FullName + "</td><td style=\"color:red;\">" + DateAssigned + "</td>";
} else {
trainingSection += "<tr><td>" + assignment.FullName + "</td><td>" + DateAssigned + "</td>";
}
trainingSection += "</tr>";
}
@ -755,75 +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
{
isSuccess = false;
}
return isSuccess;
}
public bool RunOOOTrainingReport()
{
bool isSuccess = false;
try
{
string emailBody = "<h1>Mesa Approval Open Training Assignments Report - OOO</h1> <br />";
emailBody += "<p>The following contains open training assignments in the Mesa Approval system for out of office users.";
emailBody += " Please ensure they complete their training assignments promptly upon their return.</p><br />";
emailBody += "<style>table,th,td{border: 1px solid black;}</style>";
//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)
//{
// string userEmail = userDMO.GetUserByID(user.UserId).Email;
// emailList.Add(userEmail);
//}
emailList.Add("Chase.Tucker@infineon.com");
//Get a list of open trainings
List<Training> openTrainings = trainingDMO.GetAllOpenTrainings();
foreach (Training training in openTrainings)
{
string trainingSection = "";
int trainingSectionUserCount = 0;
string ecnTitle = ecnDMO.GetECN(training.ECN).Title;
trainingSection += "<h3>" + training.ECN + " - " + ecnTitle + "</h3>";
trainingSection += "<table>";
trainingSection += "<tr><th>Name</th><th>Date Assigned</th></tr>";
List<TrainingAssignment> openAssignments = trainingDMO.GetOpenAssignmentsByTrainingID(training.TrainingID);
foreach (TrainingAssignment assignment in openAssignments)
{
if (userDMO.GetUserByID(assignment.UserID).OOO)
{
trainingSectionUserCount++;
DateTime? assignmentDate = assignment.DateAssigned;
string DateAssigned = assignmentDate.HasValue ? assignmentDate.Value.ToString("MM/dd/yyyy") : "<not available>";
trainingSection += "<tr><td>" + assignment.FullName + "</td><td>" + DateAssigned + "</td>";
trainingSection += "</tr>";
}
}
trainingSection += "</table>";
if (trainingSectionUserCount > 0) emailBody += trainingSection;
}
string recipientEmail = "";
List<string> ccRecipients = emailList;
emailer.SendNotification("MesaFabApproval@infineon.com", ccRecipients, "Mesa Approval Open Training Report - OOO", emailBody, "Open Training Report - OOO");
isSuccess = true;
}
catch
{
} catch {
isSuccess = false;
}
return isSuccess;
}
}
}

View File

@ -45,15 +45,6 @@ namespace Fab2ApprovalSystem.Controllers
{
return request.CreateResponse(HttpStatusCode.InternalServerError);
}
case "TrainingReportOOO":
if (trainingFunctions.RunOOOTrainingReport())
{
return request.CreateResponse(HttpStatusCode.OK);
}
else
{
return request.CreateResponse(HttpStatusCode.InternalServerError);
}
case "CARDueDates":
if (carFunctions.ProcessCARDueDates())
{

View File

@ -8,12 +8,13 @@ using System.Web;
using Dapper;
using Fab2ApprovalSystem.Models;
using System.Text;
using Fab2ApprovalSystem.Misc;
namespace Fab2ApprovalSystem.DMO
{
public class AdminDMO
{
private IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
private IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
private static FabApprovalTrainingEntities FabApprovalDB = new FabApprovalTrainingEntities();
/// <summary>

View File

@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
@ -7,13 +7,14 @@ using System.Data.SqlClient;
using Fab2ApprovalSystem.Models;
using Dapper;
using System.Configuration;
using Fab2ApprovalSystem.Misc;
namespace Fab2ApprovalSystem.DMO
{
public static class ApprovalLogDMO
{
private static IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
private static IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
public static void Add(ApprovalLog appLog)
{

View File

@ -11,12 +11,13 @@ using System.Linq;
using System.Text;
using System.Transactions;
using System.Web;
using Fab2ApprovalSystem.Misc;
namespace Fab2ApprovalSystem.DMO
{
public class AuditDMO
{
private IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
private IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
WorkflowDMO wfDMO = new WorkflowDMO();
/// <summary>

View File

@ -1,4 +1,5 @@
using Dapper;
using Fab2ApprovalSystem.Misc;
using Fab2ApprovalSystem.Models;
using Fab2ApprovalSystem.ViewModels;
using System;
@ -15,7 +16,7 @@ namespace Fab2ApprovalSystem.DMO
{
public class ChangeControlDMO
{
private IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
private IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
WorkflowDMO wfDMO = new WorkflowDMO();
/// <summary>

View File

@ -18,7 +18,7 @@ namespace Fab2ApprovalSystem.DMO
public class CorrectiveActionDMO
{
private IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
private IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
WorkflowDMO wfDMO = new WorkflowDMO();
public CorrectiveAction InsertCA(CorrectiveAction ca)

View File

@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
@ -7,6 +7,7 @@ using System.Data.SqlClient;
using Fab2ApprovalSystem.Models;
using Dapper;
using System.Configuration;
using Fab2ApprovalSystem.Misc;
namespace Fab2ApprovalSystem.DMO
{
@ -15,7 +16,7 @@ namespace Fab2ApprovalSystem.DMO
/// </summary>
public static class ECNTypeChangeLogDMO
{
private static IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
private static IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
/// <summary>
///

View File

@ -18,7 +18,7 @@ namespace Fab2ApprovalSystem.DMO
{
public class ECN_DMO
{
private IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
private IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
WorkflowDMO wfDMO = new WorkflowDMO();
@ -599,6 +599,13 @@ namespace Fab2ApprovalSystem.DMO
return approverList;
}
public IEnumerable<int> GetTECNNotificationUsers()
{
string sql = "select T.UserId from TECNNotificationsUsers T";
var result = this.db.Query<int>(sql).ToList();
return result;
}
/// <summary>

View File

@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
@ -18,7 +18,7 @@ namespace Fab2ApprovalSystem.DMO
public static class EventLogDMO
{
private static IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
private static IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
//public static void Add(WinEventLog eventLog)
//{

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,11 +11,10 @@ using Fab2ApprovalSystem.ViewModels;
using System.Reflection;
using Fab2ApprovalSystem.Misc;
namespace Fab2ApprovalSystem.DMO
{
namespace Fab2ApprovalSystem.DMO {
public class LotDispositionDMO
{
private IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
private IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
//LotDispositionDMO ldDMO = new LotDispositionDMO();
WorkflowDMO wfDMO = new WorkflowDMO();
@ -1355,7 +1352,7 @@ namespace Fab2ApprovalSystem.DMO
internal IEnumerable<Comments> GetComments(int issueID)
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
return db.Query<Comments>("GetComments", new { @IssueID = issueID}, commandType: CommandType.StoredProcedure).ToList();
}

View File

@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
@ -17,7 +17,7 @@ namespace Fab2ApprovalSystem.DMO
{
public class LotTravelerDMO
{
private IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
private IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
WorkflowDMO wfDMO = new WorkflowDMO();
/// <summary>

View File

@ -1,4 +1,4 @@
using Fab2ApprovalSystem.Models;
using Fab2ApprovalSystem.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
@ -17,7 +17,7 @@ namespace Fab2ApprovalSystem.DMO
public class MRB_DMO
{
private IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
private IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
WorkflowDMO wfDMO = new WorkflowDMO();
/// <summary>
///

View File

@ -23,7 +23,7 @@ namespace Fab2ApprovalSystem.DMO
/// <returns></returns>
public static IEnumerable<Lot> SearchLots(string searchText, string searchBy)
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
IEnumerable<Lot> lotList;
string sql = "";
@ -56,7 +56,7 @@ namespace Fab2ApprovalSystem.DMO
}
public static IEnumerable<int> GetUserIDsBySubRoleID(int subRoleID)
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
IEnumerable<int> userList;
string sql = "";
@ -74,7 +74,7 @@ namespace Fab2ApprovalSystem.DMO
/// <returns></returns>
public static IEnumerable<Lot> SearchLTLots(string searchText, string searchBy)
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
string sql = "";
@ -96,7 +96,7 @@ namespace Fab2ApprovalSystem.DMO
/// <returns></returns>
public static IEnumerable<WIPPart> SearchLTParts(string searchText)
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
StringBuilder sql = new StringBuilder();
sql.Append("SELECT PartNumber + '~' + SiliconPart + '~' + ProcessFlow + '~' + PartDescription AS WIPPartData ");
sql.Append("FROM vWIPPartData WHERE PartNumber LIKE '%" + searchText + "%' ORDER BY PartNumber");
@ -120,8 +120,7 @@ namespace Fab2ApprovalSystem.DMO
/// <param name="lot"></param>
public static void GetLotInformation(Lot lot)
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
//IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnectionProd"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
StringBuilder qryLotInfo = new StringBuilder();
qryLotInfo.Append("SELECT WP_STATUS , WP_LOT_NO, WP_PART_NUMBER, MP_PRODUCT_FAMILY, MP_DESCRIPTION, ");
qryLotInfo.Append("WP_CURRENT_QTY, WP_CURRENT_LOCATION, DieLotNumber, DiePartNo, DieCount, MP_QUALITY_CODE FROM SPNLot ");
@ -260,7 +259,7 @@ namespace Fab2ApprovalSystem.DMO
public static IEnumerable<UserProfile> GetUserList()
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
StringBuilder sql = new StringBuilder();
sql.Append("SELECT FirstName + ' ' + LastName AS FullName, U.UserID AS UserId ");
@ -279,7 +278,7 @@ namespace Fab2ApprovalSystem.DMO
/// <returns></returns>
public static List<string> GetApproverEmailListByDocument(int issueID, byte step, int documentType)
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
var parameters = new DynamicParameters();
parameters.Add("@DocumentTypeID", documentType);
@ -305,7 +304,7 @@ namespace Fab2ApprovalSystem.DMO
public static List<ApproversListViewModel> GetApproversListByDocument(int issueID, byte step, int documentType)
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
var parameters = new DynamicParameters();
parameters.Add("@DocumentTypeID", documentType);
@ -317,7 +316,7 @@ namespace Fab2ApprovalSystem.DMO
public static IEnumerable<ApprovalModel> GetApprovalsByDocument(int issueID, int documentType)
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
var parameters = new DynamicParameters();
parameters.Add("@DocumentTypeID", documentType);
@ -336,7 +335,7 @@ namespace Fab2ApprovalSystem.DMO
/// <returns></returns>
public static IEnumerable<LoginModel> GetApprovedApproversListByDocument(int issueID, int currentStep, int documentType)
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
return db.Query<LoginModel>("GetApprovedApproversListByDocument", new { @DocumentTypeID = documentType, @IssueID = issueID, @Step = currentStep }, commandType: CommandType.StoredProcedure).ToList();
}
@ -351,7 +350,7 @@ namespace Fab2ApprovalSystem.DMO
/// <returns></returns>
public static List<ApproversListViewModel> GetPendingApproversListByDocument(int issueID, byte step, int documentType)
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
var parameters = new DynamicParameters();
parameters.Add("@DocumentTypeID", documentType);
parameters.Add("@IssueID", issueID);
@ -368,7 +367,7 @@ namespace Fab2ApprovalSystem.DMO
/// <returns></returns>
public static List<string> GetEmergencyTECNApprovalNotifyList(int ecnNumber)
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
var parameters = new DynamicParameters();
parameters.Add("@ECNNumber", ecnNumber);
var approverList = db.Query<string>("ECNGetETECNApprovalNotificationList", parameters, commandType: CommandType.StoredProcedure).ToList();
@ -382,7 +381,7 @@ namespace Fab2ApprovalSystem.DMO
/// <returns></returns>
public static List<string> GetTECNCancelledApprovalNotifyList(int ecnNumber)
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
var parameters = new DynamicParameters();
parameters.Add("@ECNNumber", ecnNumber);
var approverList = db.Query<string>("ECN_TECNCancelledApprovalNotifyList", parameters, commandType: CommandType.StoredProcedure).ToList();
@ -397,7 +396,7 @@ namespace Fab2ApprovalSystem.DMO
/// <returns></returns>
public static List<string> GetFabGroupNotifyList(int workRequestID)
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
var parameters = new DynamicParameters();
parameters.Add("@WorkRequestID", workRequestID);
var notifyList = db.Query<string>("LTFabGroupApprovalNotificationList", parameters, commandType: CommandType.StoredProcedure).ToList();
@ -412,7 +411,7 @@ namespace Fab2ApprovalSystem.DMO
/// <returns></returns>
public static List<string> GetWorkRequestRevisionNotifyList(int notificationType, int workRequestID, int userID)
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
var parameters = new DynamicParameters();
parameters.Add("@NotificationType", notificationType);
parameters.Add("@UserID", userID);
@ -431,7 +430,7 @@ namespace Fab2ApprovalSystem.DMO
/// <returns></returns>
public static List<string> GetWorkRequestApprovedNotifyList(int notificationType, int workRequestID, int userID)
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
var parameters = new DynamicParameters();
parameters.Add("@NotificationType", notificationType);
parameters.Add("@UserID", userID);
@ -449,7 +448,7 @@ namespace Fab2ApprovalSystem.DMO
/// <returns></returns>
public static List<string> GetLotTravelerCreationAndRevisionNotifyList(int ltLotID, int workRequestID, int userID)
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
var parameters = new DynamicParameters();
parameters.Add("@LotID", ltLotID);
parameters.Add("@UserID", userID);
@ -470,7 +469,7 @@ namespace Fab2ApprovalSystem.DMO
public static int EnableOOOStatus(int oooUserID, int delegatedTo, DateTime startDate, DateTime endDate)
{
int returnValue = 0;
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
var parameters = new DynamicParameters();
parameters.Add("@OOOUserID", oooUserID);
@ -498,7 +497,7 @@ namespace Fab2ApprovalSystem.DMO
/// <param name="endDate"></param>
public static void ExpireOOOStatus(int oooUserID)
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
var parameters = new DynamicParameters();
parameters.Add("@OOOUserID", oooUserID);
@ -512,7 +511,7 @@ namespace Fab2ApprovalSystem.DMO
/// <returns></returns>
public static List<Department> GetDepartments()
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
var departments = db.Query<Department>("GetDepartments", null, commandType: CommandType.StoredProcedure).ToList();
return departments;
@ -524,7 +523,7 @@ namespace Fab2ApprovalSystem.DMO
/// <returns></returns>
public static List<AffectedModule> GetModules()
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
var modules = db.Query<AffectedModule>("GetModules", null, commandType: CommandType.StoredProcedure).ToList();
return modules;
@ -537,7 +536,7 @@ namespace Fab2ApprovalSystem.DMO
/// <param name="lot"></param>
public static void GetLTLotInformation(LTLot lot)
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
StringBuilder qryLotInfo = new StringBuilder();
//qryLotInfo.Append("SELECT DISTINCT ");
//qryLotInfo.Append("WP_LOT_NO, WP_CURRENT_QTY, WP.WP_PART_NUMBER, MP_DESCRIPTION, WP_PROCESS, WO_LOCATION, WO_OPER_NO, WP_STATUS ");
@ -591,7 +590,7 @@ namespace Fab2ApprovalSystem.DMO
public static string GetEmail(int? userID)
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
var parameters = new DynamicParameters();
parameters.Add("@UserID", userID);
var email = db.Query<string>("GetEmail", parameters, commandType: CommandType.StoredProcedure).Single();
@ -606,7 +605,7 @@ namespace Fab2ApprovalSystem.DMO
/// <returns></returns>
public static List<string> Get8DEmailListForClosureNotification(int issueID)
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
var parameters = new DynamicParameters();
@ -618,7 +617,7 @@ namespace Fab2ApprovalSystem.DMO
public static CredentialsStorage GetCredentialsInfo(string serverName, string credentialType) // TODO - need to use an enum for the credentialType
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
var parameters = new DynamicParameters();
parameters.Add("@ServerName", serverName);
parameters.Add("@CredentialType", credentialType);
@ -628,13 +627,13 @@ namespace Fab2ApprovalSystem.DMO
public List<ApproveListModel> GetApprovalReminderList()
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
var approvals = db.Query<ApproveListModel>("GetApprovalForNotifcation", null, commandType: CommandType.StoredProcedure).ToList();
return approvals;
}
public void UpdateApprovalNotifyDate(int approvalId)
{
IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
var parameters = new DynamicParameters();
parameters.Add("@ApprovalId", approvalId);
db.Query<CredentialsStorage>("UpdateApprovalLastNotifyDate", param: parameters, commandType: CommandType.StoredProcedure).Single();

View File

@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
@ -14,7 +14,7 @@ namespace Fab2ApprovalSystem.DMO
{
public class PartsRequestDMO
{
private IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
private IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
WorkflowDMO wfDMO = new WorkflowDMO();

View File

@ -8,12 +8,13 @@ using System.Web;
using Dapper;
using Fab2ApprovalSystem.Models;
using System.Text;
using Fab2ApprovalSystem.Misc;
namespace Fab2ApprovalSystem.DMO
{
public class TrainingDMO
{
private IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
private IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
private static FabApprovalTrainingEntities FabApprovalDB = new FabApprovalTrainingEntities();
public int Create(int issueId)
@ -372,8 +373,11 @@ namespace Fab2ApprovalSystem.DMO
FabApprovalTrainingEntities db = new FabApprovalTrainingEntities();
Training training = (from a in db.Trainings where a.TrainingID == trainingId select a).FirstOrDefault();
if (training != null)
{
training.Deleted = true;
training.DeletedDate = DateTime.Now;
}
List<TrainingAssignment> trainingAssignments = (from a in db.TrainingAssignments where a.TrainingID == trainingId select a).ToList();
db.SaveChanges();

View File

@ -8,13 +8,13 @@ using System.Web;
using Dapper;
using Fab2ApprovalSystem.Models;
using System.Text;
using Fab2ApprovalSystem.Misc;
namespace Fab2ApprovalSystem.DMO
{
public class UserAccountDMO
{
private IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
private IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
//public List<LoginModel> GetUser(string loginID)

View File

@ -18,7 +18,7 @@ namespace Fab2ApprovalSystem.DMO
{
public class WorkflowDMO
{
private IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString);
private IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING);
//delegate TResult MathFunction<T1, T2, TResult>(T1 var1, T2 var2);

View File

@ -13,7 +13,7 @@ Title: {1}
<br/>
<br/>
https://messa016ec.ec.local/{0}/Edit?IssueID={2}
https://messa016ec.infineon.com/{0}/Edit?IssueID={2}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -7,7 +7,7 @@
Please log on to the Approval website to view the assignment and act accordingly
<br/><br/>
https://messa016ec.ec.local/CorrectiveAction/Edit?issueID={4}
https://messa016ec.infineon.com/CorrectiveAction/Edit?issueID={4}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -3,7 +3,7 @@
<br/><br/>
Corrective Action# {0} is ready for your approval. Please log on to the Approval website and review this item for <strong>FINAL Approval or Rejection</strong>.
<br/><br/>
https://messa016ec.ec.local/CorrectiveAction/Edit?issueID={1}
https://messa016ec.infineon.com/CorrectiveAction/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -7,7 +7,7 @@ Corrective Action# {0} has been assigned to you.
Please log on to the Approval website to view the assignment and act accordingly
<br/><br/>
https://messa016ec.ec.local/CorrectiveAction/Edit?issueID={3}
https://messa016ec.infineon.com/CorrectiveAction/Edit?issueID={3}
<br/><br/>
D3 Due Date: {4}
<br/>

View File

@ -6,7 +6,7 @@ Corrective Action {0} has been completed
<br/><br/>
https://messa016ec.ec.local/CorrectiveAction/Edit?issueID={2}
https://messa016ec.infineon.com/CorrectiveAction/Edit?issueID={2}
<br/><br/>
Thank you for your effort. Follow up date has been set for {3}
<br/><br/>

View File

@ -8,7 +8,7 @@ Action needs to be completed by {1}
Please log on to the Approval website to view the assignment and act accordingly
<br/><br/>
https://messa016ec.ec.local/Audit/Edit?issueID={4}
https://messa016ec.infineon.com/Audit/Edit?issueID={4}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -3,7 +3,7 @@
<br/><br/>
Corrective Action# {0} Re-Assigned to you for you approval. Please log on to the Approval website and review this item for Approval or Rejection.
<br/><br/>
https://messa016ec.ec.local/CorrectiveAction/Edit?issueID={1}
https://messa016ec.infineon.com/CorrectiveAction/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -9,7 +9,7 @@ Reason For Reject:
<br/><br/>
Please log on to the Approval website and review this item for re-submission.
<br/><br/>
https://messa016ec.ec.local/CorrectiveAction/Edit?issueID={1}
https://messa016ec.infineon.com/CorrectiveAction/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -1,13 +1,13 @@
<font size="2" face="verdana">
*****Please DO NOT reply to this email*****
<br/><br/>
Corrective Action# {1} section {3} has been approved.
Corrective Action# {0} section {3} has been approved.
<br/><br/>
Please log on to the Approval website to view the section and act accordingly
<br/><br/>
https://messa016ec.ec.local/CorrectiveAction/Edit?issueID={0}
https://messa016ec.infineon.com/CorrectiveAction/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -7,7 +7,7 @@ Corrective Action# {0} section {3} has been assigned to you for approval.
Please log on to the Approval website to view the assignment and act accordingly
<br/><br/>
https://messa016ec.ec.local/CorrectiveAction/Edit?issueID={1}
https://messa016ec.infineon.com/CorrectiveAction/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -1,13 +1,16 @@
<font size="2" face="verdana">
*****Please DO NOT reply to this email*****
<br/><br/>
Corrective Action# {0} section {3} has been rejected.
Corrective Action# {0} section {3} has been rejected by {4}.
<br/><br/>
Rejection reason: {5}
<br/><br/>
Please log on to the Approval website to view the section and act accordingly
<br/><br/>
https://messa016ec.ec.local/CorrectiveAction/Edit?issueID={1}
{2}/CorrectiveAction/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -7,7 +7,7 @@ Corrective Action# {1} section D5/D6/D7(Corrective/Preventitive Actions) has bee
Please log on to the Approval website to view the section and act accordingly
<br/><br/>
https://messa016ec.ec.local/CorrectiveAction/Edit?issueID={0}
https://messa016ec.infineon.com/CorrectiveAction/Edit?issueID={0}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -3,7 +3,7 @@
<br/><br/>
Corrective Action# {0} section {4} is {3}. Please log on to the Approval website and review this item for <strong>completion</strong>.
<br/><br/>
https://messa016ec.ec.local/CorrectiveAction/Edit?issueID={1}
https://messa016ec.infineon.com/CorrectiveAction/Edit?issueID={1}
<br/><br/>
D3 Due Date: {5}
<br/>

View File

@ -3,7 +3,7 @@
<br/><br/>
{3}# {0} Delegated to you for your approval. Please log on to the Approval website and review this item for Approval or Rejection.
<br/><br/>
https://messa016ec.ec.local/{3}/Edit?issueID={1}
https://messa016ec.infineon.com/{3}/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -5,7 +5,7 @@
<br/><br/>
Rejection Comment: {5}
<br/><br/>
https://messa016ec.ec.local/ECN/Edit?issueID={1}
https://messa016ec.infineon.com/ECN/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -3,7 +3,7 @@
<br/><br/>
ECN# {1} was Approved.
<br/><br/>
https://messa016ec.ec.local/ECN/Edit?issueID={1}
https://messa016ec.infineon.com/ECN/Edit?issueID={1}
<br/><br/>
Thank you!

View File

@ -3,7 +3,7 @@
<br/><br/>
{3}# {0} is ready for your approval. Please log on to the Approval website and review this item for Approval or Rejection.
<br/><br/>
https://messa016ec.ec.local/ECN/Edit?issueID={1}
https://messa016ec.infineon.com/ECN/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -3,7 +3,7 @@
<br/><br/>
{3}# {0} Re-Assigned to you for your approval. Please log on to the Approval website and review this item for Approval or Rejection.
<br/><br/>
https://messa016ec.ec.local/ECN/Edit?issueID={1}
https://messa016ec.infineon.com/ECN/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -5,7 +5,7 @@
<br/><br/>
Comments: {4}
<br/><br/>
https://messa016ec.ec.local/ECN/Edit?issueID={1}
https://messa016ec.infineon.com/ECN/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -5,7 +5,7 @@
<br/><br/>
Rejection Comment: {5}
<br/><br/>
https://messa016ec.ec.local/ECN/Edit?issueID={1}
https://messa016ec.infineon.com/ECN/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -3,7 +3,7 @@
<br/><br/>
A new training assignment has been assigned to you for ECN# {1}
<br/><br/>
Please click here to view: <a href="https://messa016ec.ec.local/Training/ViewMyTrainingAssignment?assignmentID={0}&ECNNumber={1}">Click Here.</a>
Please click here to view: <a href="https://messa016ec.infineon.com/Training/ViewMyTrainingAssignment?assignmentID={0}&ECNNumber={1}">Click Here.</a>
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -4,7 +4,7 @@
{3}# {0} has been Approved. The expiration date is {4}
Please review the approved ETECN form in the attachment.
<br/><br/>
https://messa016ec.ec.local/ECN/Edit?issueID={1}
https://messa016ec.infineon.com/ECN/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -3,7 +3,7 @@
<br/><br/>
Lot Disposition# {0} is ready for your approval. Please log on to the Approval website and review this item for Approval or Rejection.
<br/><br/>
https://messa016ec.ec.local/LotDisposition/Edit?issueID={1}
https://messa016ec.infineon.com/LotDisposition/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -3,7 +3,7 @@
<br/><br/>
Lot Disposition# {0} Re-Assigned to you for you approval. Please log on to the Approval website and review this item for Approval or Rejection.
<br/><br/>
https://messa016ec.ec.local/LotDisposition/Edit?issueID={1}
https://messa016ec.infineon.com/LotDisposition/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -3,7 +3,7 @@
<br/><br/>
Lot Disposition# {0} was rejected by {3}. Please log on to the Approval website and review this item for re-submission.
<br/><br/>
https://messa016ec.ec.local/LotDisposition/Edit?issueID={1}
https://messa016ec.infineon.com/LotDisposition/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -3,7 +3,7 @@
<br/><br/>
Lot Traveler for Lot# {3} , Request# {0} has a been created. Please login in to the Fab Approval System to review the change.
<br/><br/>
https://messa016ec.ec.local/LotTraveler/Edit?issueID={1}
https://messa016ec.infineon.com/LotTraveler/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact the site administrator.

View File

@ -3,7 +3,7 @@
<br/><br/>
Lot Traveler for Lot# {3} , Request# {0} has a new Revision. Please login in to the Fab Approval System to review the change.
<br/><br/>
https://messa016ec.ec.local/LotTraveler/Edit?issueID={1}
https://messa016ec.infineon.com/LotTraveler/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact the site administrator.

View File

@ -3,7 +3,7 @@
<br/><br/>
MRB# {0} is ready for your approval. Please log on to the Approval website and review this item for Approval.
<br/><br/>
https://messa016ec.ec.local/MRB/Edit?issueID={1}
https://messa016ec.infineon.com/MRB/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -3,7 +3,7 @@
<br/><br/>
{3}# {0} is ready for your approval. Please log on to the Approval website and review this item for Approval or Rejection.
<br/><br/>
https://messa016ec.ec.local/PartsRequest/Edit?issueID={1}
https://messa016ec.infineon.com/PartsRequest/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -3,7 +3,7 @@
<br/><br/>
{3}# {0} has been completed.
<br/><br/>
https://messa016ec.ec.local/PartsRequest/Edit?issueID={1}
https://messa016ec.infineon.com/PartsRequest/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -3,7 +3,7 @@
<br/><br/>
{3}# {0} Re-Assigned to you for you approval. Please log on to the Approval website and review this item for Approval or Rejection.
<br/><br/>
https://messa016ec.ec.local/PartsRequest/Edit?issueID={1}
https://messa016ec.infineon.com/PartsRequest/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -3,7 +3,7 @@
<br/><br/>
{3}# {0} was rejected by {4}. Please log on to the Approval website and review this item for re-submission.
<br/><br/>
https://messa016ec.ec.local/PartsRequest/Edit?issueID={1}
https://messa016ec.infineon.com/PartsRequest/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -4,7 +4,7 @@
{3}# {0} has been automatically Cancelled, because it has been converted to ECN# {5}. The cancellation date is {4}
Please review the cancelled TECN and the new ECN in the attachments.
<br/><br/>
https://messa016ec.ec.local/ECN/Edit?issueID={1}
https://messa016ec.infineon.com/ECN/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -3,7 +3,7 @@
<br/><br/>
{3}# {0} is ready for your Cancellation. Please log on to the Approval website and review this item for Approval of Cancellation.
<br/><br/>
https://messa016ec.ec.local/ECN/Edit?issueID={1}
https://messa016ec.infineon.com/ECN/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

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

View File

@ -3,7 +3,7 @@
<br/><br/>
{3}# {0} is ready for your Expiration Approval. Please log on to the Approval website and review this item for Approval of Expiration
<br/><br/>
https://messa016ec.ec.local/ECN/Edit?issueID={1}
https://messa016ec.infineon.com/ECN/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -4,7 +4,7 @@
{3}# {0} has Expired. The expiration date is {4}
Please review the expired TECN form in the attachment.
<br/><br/>
https://messa016ec.ec.local/ECN/Edit?issueID={1}
https://messa016ec.infineon.com/ECN/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -3,7 +3,7 @@
<br/><br/>
{4}# {0} Extension was rejected by {3}. Please log on to the Approval website and review this item for re-submission.
<br/><br/>
https://messa016ec.ec.local/ECN/Edit?issueID={1}
https://messa016ec.infineon.com/ECN/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -3,7 +3,7 @@
<br/><br/>
Work Request# {0} has been Approved.
<br/><br/>
https://messa016ec.ec.local/LotTraveler/Edit?issueID={1}
https://messa016ec.infineon.com/LotTraveler/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -3,7 +3,7 @@
<br/><br/>
Work Request# {0} is ready for your approval. Please log on to the Approval website and review this item for Approval or Rejection.
<br/><br/>
https://messa016ec.ec.local/LotTraveler/Edit?issueID={1}
https://messa016ec.infineon.com/LotTraveler/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -3,7 +3,7 @@
<br/><br/>
Work Request# {0} Re-Assigned to you for you approval. Please log on to the Approval website and review this item for Approval or Rejection.
<br/><br/>
https://messa016ec.ec.local/LotTraveler/Edit?issueID={1}
https://messa016ec.infineon.com/LotTraveler/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -3,7 +3,7 @@
<br/><br/>
Work Request# {0} was rejected by {3}. Please log on to the Approval website and review this item for re-submission.
<br/><br/>
https://messa016ec.ec.local/LotTraveler/Edit?issueID={1}
https://messa016ec.infineon.com/LotTraveler/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact a site administrator.

View File

@ -3,7 +3,7 @@
<br/><br/>
Work Request# {0} has a new Revision. Please login in to the Fab Approval System to review the change.
<br/><br/>
https://messa016ec.ec.local/LotTraveler/Edit?issueID={1}
https://messa016ec.infineon.com/LotTraveler/Edit?issueID={1}
<br/><br/>
If you have any questions or trouble logging on please contact the site administrator.

View File

@ -20,10 +20,14 @@
<IISExpressAnonymousAuthentication />
<IISExpressWindowsAuthentication />
<IISExpressUseClassicPipelineMode />
<SccProjectName>SAK</SccProjectName>
<SccLocalPath>SAK</SccLocalPath>
<SccAuxPath>SAK</SccAuxPath>
<SccProvider>SAK</SccProvider>
<SccProjectName>
</SccProjectName>
<SccLocalPath>
</SccLocalPath>
<SccAuxPath>
</SccAuxPath>
<SccProvider>
</SccProvider>
<UseGlobalApplicationHostFile />
<Use64BitIISExpress>true</Use64BitIISExpress>
<TargetFrameworkProfile />
@ -130,6 +134,7 @@
<Compile Include="Global.asax.cs">
<DependentUpon>Global.asax</DependentUpon>
</Compile>
<Compile Include="JobSchedules\OOOTrainingReportJobSchedule.cs" />
<Compile Include="Misc\DemoHelper.cs" />
<Compile Include="Misc\Documentum.cs" />
<Compile Include="Misc\EmailNotification.cs" />
@ -148,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">
@ -177,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">
@ -248,6 +256,7 @@
<Compile Include="ViewModels\LTMaterial.cs" />
<Compile Include="ViewModels\OOOViewModel.cs" />
<Compile Include="ViewModels\ReportsViewModels.cs" />
<Compile Include="Jobs\OOOTrainingReportJob.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="Content\bootstrap-theme.css" />
@ -1966,6 +1975,9 @@
<PackageReference Include="Owin">
<Version>1.0.0</Version>
</PackageReference>
<PackageReference Include="Quartz">
<Version>3.7.0</Version>
</PackageReference>
<PackageReference Include="Respond">
<Version>1.2.0</Version>
</PackageReference>

View File

@ -11,6 +11,7 @@ using System.Web.Security;
using System.Configuration;
using Fab2ApprovalSystem.DMO;
using System.Web.Http;
using Fab2ApprovalSystem.JobSchedules;
namespace Fab2ApprovalSystem
{
@ -24,14 +25,12 @@ namespace Fab2ApprovalSystem
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//string DevAttachmentUrl = ConfigurationManager.AppSettings["DevAttachmentURl"].ToString();
//string ProdAttachmentUrl = ConfigurationManager.AppSettings["ProdAttachmentURL"].ToString();
string connectionstring = ConfigurationManager.ConnectionStrings["FabApprovalConnection"].ConnectionString.ToString();
GlobalVars.hostURL = HttpRuntime.AppDomainAppVirtualPath;
string hostName = System.Net.Dns.GetHostEntry("").HostName;
GlobalVars.IS_INFINEON_DOMAIN = hostName.ToLower().Contains("infineon");
string DevWebSiteUrl = ConfigurationManager.AppSettings["DevWebSiteURL"].ToString();
string ProdWebSiteUrl = ConfigurationManager.AppSettings["ProdWebSiteURL"].ToString();
string ProdWebSiteUrlEC = ConfigurationManager.AppSettings["ProdWebSiteURLEC"].ToString();
string ProdWebSiteUrlStealth = ConfigurationManager.AppSettings["ProdWebSiteURLStealth"].ToString();
GlobalVars.SENDER_EMAIL = "FabApprovalSystem@Infineon.com"; // put in the Config File
if (ConfigurationManager.AppSettings["Notification Sender"] != null)
@ -40,13 +39,24 @@ namespace Fab2ApprovalSystem
GlobalVars.NDriveURL = ConfigurationManager.AppSettings["NDrive"].ToString();
GlobalVars.WSR_URL = ConfigurationManager.AppSettings["WSR_URL"].ToString();
GlobalVars.CA_BlankFormsLocation = ConfigurationManager.AppSettings["CA_BlankFormsLocation"].ToString();
GlobalVars.DBConnection = connectionstring.ToUpper().Contains("TEST") ? "TEST" : connectionstring.ToUpper().Contains("QUALITY") ? "QUALITY" : "PROD";
//GlobalVars.AttachmentUrl = connectionstring.ToUpper().Contains("TEST") ? @"http://" + DevAttachmentUrl + "/" : @"http://" + ProdAttachmentUrl + "/"; ;
GlobalVars.hostURL = connectionstring.ToUpper().Contains("TEST") ? @"http://" + DevWebSiteUrl : @"http://" + ProdWebSiteUrl ;
#if (!DEBUG)
OOOTrainingReportJobSchedule.Start();
if (GlobalVars.IS_INFINEON_DOMAIN) {
GlobalVars.DB_CONNECTION_STRING = ConfigurationManager.ConnectionStrings["FabApprovalConnectionStealth"].ConnectionString.ToString();
GlobalVars.hostURL = @"https://" + ProdWebSiteUrlStealth;
} else {
GlobalVars.DB_CONNECTION_STRING = ConfigurationManager.ConnectionStrings["FabApprovalConnectionEC"].ConnectionString.ToString();
GlobalVars.hostURL = @"https://" + ProdWebSiteUrlEC;
}
#else
GlobalVars.DB_CONNECTION_STRING = ConfigurationManager.ConnectionStrings["FabApprovalConnectionDev"].ConnectionString.ToString();
GlobalVars.hostURL = @"https://" + DevWebSiteUrl;
#endif
GlobalVars.DBConnection = GlobalVars.DB_CONNECTION_STRING.ToUpper().Contains("TEST") ? "TEST" : GlobalVars.DB_CONNECTION_STRING.ToUpper().Contains("QUALITY") ? "QUALITY" : "PROD";
}

View File

@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Fab2ApprovalSystem.Workers;
using Quartz.Impl;
using Quartz;
namespace Fab2ApprovalSystem.JobSchedules
{
public class OOOTrainingReportJobSchedule
{
public static void Start()
{
ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
IScheduler scheduler = schedulerFactory.GetScheduler().GetAwaiter().GetResult();
scheduler.Start();
IJobDetail oooTrainingReportJob = JobBuilder.Create<OOOTrainingReportJob>()
.WithIdentity("oooTrainingReportJob", "trainingReportGroup")
.Build();
ITrigger oooTrainingReportTrigger = TriggerBuilder.Create()
.WithIdentity("oooTrainingReportTrigger", "trainingReportGroup")
.WithCronSchedule("0 0 12 ? * 2 *")
.ForJob(oooTrainingReportJob)
.Build();
scheduler.ScheduleJob(oooTrainingReportJob, oooTrainingReportTrigger);
}
}
}

View File

@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Fab2ApprovalSystem.DMO;
using Fab2ApprovalSystem.Models;
using Fab2ApprovalSystem.Utilities;
using Quartz;
namespace Fab2ApprovalSystem.Workers
{
public class OOOTrainingReportJob:IJob
{
UserAccountDMO userDMO = new UserAccountDMO();
AdminDMO adminDMO = new AdminDMO();
TrainingDMO trainingDMO = new TrainingDMO();
ECN_DMO ecnDMO = new ECN_DMO();
public EmailUtilities emailer = new EmailUtilities();
async Task IJob.Execute(IJobExecutionContext context)
{
await Task.Run(() => {
string emailBody = "<h1>Mesa Approval Open Training Assignments Report - OOO</h1> <br />";
emailBody += "<p>The following contains open training assignments in the Mesa Approval system for out of office users.";
emailBody += " Please ensure they complete their training assignments promptly upon their return.</p><br />";
emailBody += "<style>table,th,td{border: 1px solid black;}</style>";
//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)
{
string userEmail = userDMO.GetUserByID(user.UserId).Email;
emailList.Add(userEmail);
}
//emailList.Add("Chase.Tucker@infineon.com");
//Get a list of open trainings
List<Training> openTrainings = trainingDMO.GetAllOpenTrainings();
foreach (Training training in openTrainings)
{
string trainingSection = "";
int trainingSectionUserCount = 0;
string ecnTitle = ecnDMO.GetECN(training.ECN).Title;
trainingSection += "<h3>" + training.ECN + " - " + ecnTitle + "</h3>";
trainingSection += "<table>";
trainingSection += "<tr><th>Name</th><th>Date Assigned</th></tr>";
List<TrainingAssignment> openAssignments = trainingDMO.GetOpenAssignmentsByTrainingID(training.TrainingID);
foreach (TrainingAssignment assignment in openAssignments)
{
if (userDMO.GetUserByID(assignment.UserID).OOO)
{
trainingSectionUserCount++;
DateTime? assignmentDate = assignment.DateAssigned;
string DateAssigned = assignmentDate.HasValue ? assignmentDate.Value.ToString("MM/dd/yyyy") : "<not available>";
trainingSection += "<tr><td>" + assignment.FullName + "</td><td>" + DateAssigned + "</td>";
trainingSection += "</tr>";
}
}
trainingSection += "</table>";
if (trainingSectionUserCount > 0) emailBody += trainingSection;
}
string recipientEmail = "";
List<string> ccRecipients = emailList;
emailer.SendNotification("MesaFabApproval@infineon.com", ccRecipients, "Mesa Approval Open Training Report - OOO", emailBody, "Open Training Report - OOO");
});
}
}
}

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-external.infineon.com");
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();
// 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,21 +239,16 @@ 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>
@ -313,8 +261,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, List<string> RecepientList, string cc, string email_title, string email_body, List<string> attachments)
{
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,8 +320,7 @@ 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
@ -398,31 +331,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") {
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)
{
} 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,184 +74,31 @@ namespace Fab2ApprovalSystem.Misc
///
/// </summary>
/// <returns></returns>
public static string GetAttachmentFolder()
{
public static string GetAttachmentFolder() {
ConfigurationManager.RefreshSection("appSettings");
if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY")
{
return ConfigurationManager.AppSettings["AttachmentFolderTest"];
}
else
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)
{
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>
///
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
public static bool CheckITARAccess(string userID)
{
MembershipProvider domainProvider = Membership.Providers["ADMembershipProvider"];
MembershipUser mu = domainProvider.GetUser(userID, false);
if (mu == null)
return false;
else
return true;
}
/// <summary>
///
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
public static bool NA_HasITARAccess(string userID, string pwd)
{
string ECDomain = ConfigurationManager.AppSettings["ECDomain"];
string ECADGroup = ConfigurationManager.AppSettings["ECADGroup"];
string naContainer = ConfigurationManager.AppSettings["NAContainer"];
string naDomain = ConfigurationManager.AppSettings["NADomain"];
//WriteEvent("NA - Before PrincipalContext for EC for " + userID, System.Diagnostics.EventLogEntryType.Information);
PrincipalContext contextGroup = new PrincipalContext(ContextType.Domain, ECDomain);
//WriteEvent("NA - After PrincipalContext for EC for " + userID, System.Diagnostics.EventLogEntryType.Information);
//WriteEvent("NA - Before PrincipalContext for NA for " + userID, System.Diagnostics.EventLogEntryType.Information);
PrincipalContext contextUser = new PrincipalContext(ContextType.Domain,
naDomain,
naContainer,
ContextOptions.Negotiate, userID, pwd);
//WriteEvent("NA - After PrincipalContext for NA for " + userID, System.Diagnostics.EventLogEntryType.Information);
//WriteEvent("NA - Before check user in EC group for " + userID, System.Diagnostics.EventLogEntryType.Information);
GroupPrincipal gp = GroupPrincipal.FindByIdentity(contextGroup, ECADGroup);
//WriteEvent("NA - After check user in EC group for " + userID, System.Diagnostics.EventLogEntryType.Information);
//WriteEvent("NA - Before check user in NA group for " + userID, System.Diagnostics.EventLogEntryType.Information);
UserPrincipal up = UserPrincipal.FindByIdentity(contextUser, userID);
//WriteEvent("NA - After check user in NA group for " + userID, System.Diagnostics.EventLogEntryType.Information);
if (null == up)
{
//WriteEvent("NA - User not in NA for " + userID, System.Diagnostics.EventLogEntryType.Information);
return false;
}
else
{
//WriteEvent("NA - Member of EC group is " + up.IsMemberOf(gp).ToString() + " for " + userID, System.Diagnostics.EventLogEntryType.Information);
return up.IsMemberOf(gp);
}
}
//public static bool NA_GetUsers()
//{
// //string ECDomain = ConfigurationManager.AppSettings["ECDomain"];
// //string ECADGroup = ConfigurationManager.AppSettings["ECADGroup"];
// string naContainer = ConfigurationManager.AppSettings["NAContainer"];
// string naDomain = ConfigurationManager.AppSettings["NADomain"];
// //WriteEvent("NA - Before PrincipalContext for EC for " + userID, System.Diagnostics.EventLogEntryType.Information);
// //PrincipalContext contextGroup = new PrincipalContext(ContextType.Domain, ECDomain);
// //WriteEvent("NA - After PrincipalContext for EC for " + userID, System.Diagnostics.EventLogEntryType.Information);
// //WriteEvent("NA - Before PrincipalContext for NA for " + userID, System.Diagnostics.EventLogEntryType.Information);
// PrincipalContext contextUser = new PrincipalContext(ContextType.Domain,
// naDomain,
// naContainer,
// ContextOptions.Negotiate, userID, pwd);
// //WriteEvent("NA - After PrincipalContext for NA for " + userID, System.Diagnostics.EventLogEntryType.Information);
// //WriteEvent("NA - Before check user in EC group for " + userID, System.Diagnostics.EventLogEntryType.Information);
// GroupPrincipal gp = GroupPrincipal.FindByIdentity(contextGroup, ECADGroup);
// //WriteEvent("NA - After check user in EC group for " + userID, System.Diagnostics.EventLogEntryType.Information);
// //WriteEvent("NA - Before check user in NA group for " + userID, System.Diagnostics.EventLogEntryType.Information);
// UserPrincipal up = UserPrincipal.FindByIdentity(contextUser, userID);
// //WriteEvent("NA - After check user in NA group for " + userID, System.Diagnostics.EventLogEntryType.Information);
// if (null == up)
// {
// //WriteEvent("NA - User not in NA for " + userID, System.Diagnostics.EventLogEntryType.Information);
// return false;
// }
// else
// {
// //WriteEvent("NA - Member of EC group is " + up.IsMemberOf(gp).ToString() + " for " + userID, System.Diagnostics.EventLogEntryType.Information);
// return up.IsMemberOf(gp);
// }
//}
public static bool IFX_HasITARAccess(string userID, string pwd)
{
string ECDomain = ConfigurationManager.AppSettings["ECDomain"];
string ECADGroup = ConfigurationManager.AppSettings["ECADGroup"];
string ifxcontainer = ConfigurationManager.AppSettings["IFXContainer"];
string ifxdomain = ConfigurationManager.AppSettings["IFXDomain"];
//WriteEvent("IFX - Before PrincipalContext for EC for user " + userID, System.Diagnostics.EventLogEntryType.Information);
PrincipalContext contextGroup = new PrincipalContext(ContextType.Domain, ECDomain);
//WriteEvent("IFX - After PrincipalContext for EC for user " + userID, System.Diagnostics.EventLogEntryType.Information);
//WriteEvent("IFX - Before PrincipalContext for IFX for user " + userID, System.Diagnostics.EventLogEntryType.Information);
PrincipalContext contextUser = new PrincipalContext(ContextType.Domain,
ifxdomain,
ifxcontainer,
ContextOptions.Negotiate, userID, pwd);
//WriteEvent("IFX - After PrincipalContext for IFX for user " + userID, System.Diagnostics.EventLogEntryType.Information);
//WriteEvent("IFX - Before check user in EC group for " + userID, System.Diagnostics.EventLogEntryType.Information);
GroupPrincipal gp = GroupPrincipal.FindByIdentity(contextGroup, ECADGroup);
//WriteEvent("IFX - After check user in EC group for " + userID, System.Diagnostics.EventLogEntryType.Information);
//WriteEvent("IFX - Before check user in IFX for " + userID, System.Diagnostics.EventLogEntryType.Information);
UserPrincipal up = UserPrincipal.FindByIdentity(contextUser, userID);
//WriteEvent("IFX - After check user in IFX for " + userID, System.Diagnostics.EventLogEntryType.Information);
if (null == up)
{
//WriteEvent("IFX - not a member of IFX for " + userID, System.Diagnostics.EventLogEntryType.Information);
return false;
}
else
{
//WriteEvent("IFX - Member of EC group is " + up.IsMemberOf(gp).ToString() + " for " + userID, System.Diagnostics.EventLogEntryType.Information);
return up.IsMemberOf(gp);
}
}
@ -276,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,
@ -293,12 +123,9 @@ namespace Fab2ApprovalSystem.Misc
return false;
else
return true;
}
catch
{
} catch {
return false;
}
}
/// <summary>
@ -307,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,
@ -324,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"];
}
@ -344,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"];
}
@ -355,10 +173,8 @@ 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";
@ -387,17 +203,13 @@ namespace Fab2ApprovalSystem.Misc
return "D8";
case GlobalVars.CASection.CF: // CA Findings
return "CF";
}
return "";
}
public static string DocumentTypeMapper(GlobalVars.DocumentType docType)
{
switch (docType)
{
public static string DocumentTypeMapper(GlobalVars.DocumentType docType) {
switch (docType) {
case GlobalVars.DocumentType.Audit:
return "Audit";
case GlobalVars.DocumentType.ChangeControl:
@ -424,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 "";
@ -442,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

@ -20,8 +20,10 @@ namespace Fab2ApprovalSystem.Misc
public const string CAN_CREATE_PARTS_REQUEST = "CanCreatePartsRequest";
public static bool USER_ISADMIN = false;
public static bool IS_INFINEON_DOMAIN = false;
public static string hostURL = "";
public static string DBConnection = "TEST";
public static string DB_CONNECTION_STRING = "";
public static string AttachmentUrl = "";
public static string NDriveURL = "";

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

@ -1,4 +1,4 @@
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
@ -12,9 +12,16 @@ namespace Fab2ApprovalSystem.Models
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using Fab2ApprovalSystem.Misc;
public partial class FabApprovalSystemEntitiesAll : DbContext
{
#if (DEBUG)
private static string ENTITY_NAME = "FabApprovalSystemEntitiesAllDev";
#else
private static string ENTITY_NAME = GlobalVars.IS_INFINEON_DOMAIN ? "FabApprovalSystemEntitiesAllInfineon" : "FabApprovalSystemEntitiesAllEC";
#endif
public FabApprovalSystemEntitiesAll()
: base("name=FabApprovalSystemEntitiesAll")
{

View File

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

View File

@ -1,4 +1,4 @@
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
@ -12,11 +12,18 @@ namespace Fab2ApprovalSystem.Models
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using Fab2ApprovalSystem.Misc;
public partial class FabApprovalTrainingEntities : DbContext
{
#if (DEBUG)
private static string ENTITY_NAME = "FabApprovalTrainingEntitiesDev";
#else
private static string ENTITY_NAME = GlobalVars.IS_INFINEON_DOMAIN ? "FabApprovalTrainingEntitiesStealth" : "FabApprovalTrainingEntitiesEC";
#endif
public FabApprovalTrainingEntities()
: base("name=FabApprovalTrainingEntities")
: base("name=" + ENTITY_NAME)
{
}

View File

@ -1,6 +1,9 @@
using System.Web.Http;
using Fab2ApprovalSystem.Workers;
using Microsoft.Owin;
using Owin;
using Quartz;
using Quartz.Impl;
[assembly: OwinStartupAttribute(typeof(Fab2ApprovalSystem.Startup))]
namespace Fab2ApprovalSystem
@ -10,6 +13,22 @@ namespace Fab2ApprovalSystem
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
IScheduler scheduler = schedulerFactory.GetScheduler().GetAwaiter().GetResult();
IJobDetail oooTrainingReportJob = JobBuilder.Create<OOOTrainingReportJob>()
.WithIdentity("oooTrainingReportJob", "trainingReportGroup")
.Build();
ITrigger oooTrainingReportTrigger = TriggerBuilder.Create()
.WithIdentity("oooTrainingReportTrigger", "trainingReportGroup")
.WithCronSchedule("15 13 * * MON")
.ForJob(oooTrainingReportJob)
.Build();
scheduler.ScheduleJob(oooTrainingReportJob, oooTrainingReportTrigger);
}
public void Configuration(IAppBuilder app)
{

View File

@ -35,7 +35,7 @@ namespace Fab2ApprovalSystem.Utilities
msg.Subject = email_title;
msg.Body = email_body;
SmtpClient SmtpMail = new SmtpClient("mailrelay-external.infineon.com");
SmtpClient SmtpMail = new SmtpClient("mailrelay-internal.infineon.com");
SmtpMail.Send(msg);

View File

@ -2235,10 +2235,6 @@
if ($('#D6Validated').is(':checked'))
$('#D6Validated').attr("disabled",true);
if (currentUserId != currentRequestor)
$('#D6Validated').attr("disabled", true);
if ($('#D8Completed').is(':checked')) {
$('#D8Completed').attr("disabled", true);
$('#txtD8TeamRecognition').attr("disabled", true);
@ -3130,7 +3126,7 @@
$('#D5Completed').prop('checked', false);
return;
}
TriggerSectionApproval('D5D6D7')
TriggerSectionApproval('D5D6D7');
}
else {
$('#D5Completed').prop('checked', false);
@ -3174,7 +3170,7 @@
})
$('#D6Validated').on('change', function () {
data = ReturnModelObject();
if (currentUserId == data.RequestorID) {
if (currentUserId == data.RequestorID || '@ViewBag.Is8DQA' == "true" || '@ViewBag.CanCompleteCA' == "true") {
if (!checkCanCompleteCA()) {
$('#D6Validated').prop('checked', false);
$('#cover-spin').hide(0);
@ -3198,7 +3194,7 @@
else {
$('#D6Validated').prop('checked', false);
alert('Only the 8D requestor can validate')
alert('Only the 8D requestor or QA can validate')
$('#cover-spin').hide(0);
return;
@ -3457,6 +3453,47 @@
}
$("#CASubmitted").on('click', function () {
var submittedValue = $("#CASubmitted").val();
if (submittedValue) {
//If checkbox is now selected as true
caAssignee = $("#D1AssigneeList").val();
caQa = $("#D1QAList").val();
title = $("#txtCATitle").val();
caSource = $("#CASourceList").val();
caDueDate = $("#txtD8DueDate").val();
caRequestor = $("#RequestorList").val();
var errorMessage = '';
if (caAssignee == '') {
errorMessage += 'CA Assignee is missing! \n'
}
if (caQa == '') {
errorMessage += 'CA QA is missing! \n'
}
if (title == '') {
errorMessage += 'CA Title is missing! \n'
}
if (caSource == '') {
errorMessage += 'CA Source is missing! \n'
}
if (caDueDate == '') {
errorMessage += 'CA D8 Due Date is missing! \n'
}
if (caRequestor == '') {
errorMessage += 'CA Requestor is missing! \n'
}
if (errorMessage != '') {
//Uncheck CA Ready Checkbox
//Display reason what's missing'
$("#CASubmitted").prop('checked', false);
alert('Error! Not able to select CA Ready!\n The following fields must be completed:\n ' + errorMessage);
}
}
});
$("#SaveCorrectiveAction").on('click', function (e) {
$('#cover-spin').show(0);
e.preventDefault();

View File

@ -209,6 +209,12 @@
<div class="col-sm-6 col-sm-6">
@Html.TextBoxFor(model => model.Title, new { id = "txtTitle", @class = "k-textbox", style = "width:100%", disabled = "disabled" })
</div>
<div class="col-sm-6 col-sm-offset-4" style="color: red;">
*(DO NOT USE Rev I, O, Q, S, X, and Z)
</div>
<div class="col-sm-6 col-sm-offset-4" style="color: red;">
Revision Y is followed by AA. YY is followed by AAA
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4">Approvers:</label>
@ -220,6 +226,9 @@
.HtmlAttributes(new { disabled = "disabled" })
)
</div>
<div class="col-sm-6 col-sm-offset-4" style="color:red;">
ECN: Qualtiy and Dept. Specific<br />MRB: Quality, Production, Engineering, OPC<br />PCRB: Quality, Production, Engineering, Dept. Specific (scope of change)
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4">Affected Areas:</label>

View File

@ -171,7 +171,7 @@
)
</div>
<div class="col-sm-6 col-sm-offset-4" style="color:red;">
Add minimum of Quality, Si Production, and Dept Specfic
ECN: Qualtiy and Dept. Specific<br />MRB: Quality, Production, Engineering, OPC<br />PCRB: Quality, Production, Engineering, Dept. Specific (scope of change)
</div>
</div>
<div class="form-group">

View File

@ -241,6 +241,12 @@
<div class="col-sm-6 col-sm-6">
@Html.TextBoxFor(model => model.Title, new { id = "txtTitle", @class = "k-textbox", style = "width:100%", disabled = "disabled" })
</div>
<div class="col-sm-6 col-sm-offset-4" style="color: red;">
*(DO NOT USE Rev I, O, Q, S, X, and Z)
</div>
<div class="col-sm-6 col-sm-offset-4" style="color: red;">
Revision Y is followed by AA. YY is followed by AAA
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4">Approvers:</label>
@ -252,7 +258,9 @@
.HtmlAttributes(new { disabled = "disabled" })
)
</div>
<div class="col-sm-6 col-sm-offset-4" style="color:red;">
ECN: Qualtiy and Dept. Specific<br />MRB: Quality, Production, Engineering, OPC<br />PCRB: Quality, Production, Engineering, Dept. Specific (scope of change)
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4">Affected Areas:</label>

View File

@ -81,10 +81,10 @@
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Create New<b class="caret"></b></a>
<ul class="dropdown-menu" style="font-size: 11px">
@*<li><a href=@Url.Action("Create", "LotDisposition")>Lot Dispostion</a></li>*@
<li><a href=@Url.Action("Create", "MRB")>MRB</a></li>
<li><a href=@Url.Action("Create", "ECN")>ECN/TECN</a></li>
@*<li><a href=@Url.Action("Create", "MRB")>Create MRB</a></li>*@
<li><a href=@Url.Action("Create", "ECN")>Create ECN/TECN</a></li>
@*<li><a href=@Url.Action("CreateWorkRequest", "LotTraveler")>Create Special Work Request</a></li>*@
<li><a href=@Url.Action("Create", "ChangeControl")>Create PCR</a></li>
@*<li><a href=@Url.Action("Create", "ChangeControl")>Create PCR</a></li>*@
<li><a href=@Url.Action("Create", "Audit")>Create Audit</a></li>
<li><a href=@Url.Action("Create", "CorrectiveAction")>Create Corrective Action</a></li>
@*@if (Convert.ToBoolean(Session[GlobalVars.CAN_CREATE_PARTS_REQUEST]))
@ -125,9 +125,17 @@
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");
//menu.Add().Text("PCRB").Action("ChangeControlList", "Home");
//menu.Add().Text("MRB").Action("MRBList", "Home");
//menu.Add().Text("LotDisposition").Action("LotDispositionList", "Home");
menu.Add().Text("ECN").Action("ECNList", "Home");
menu.Add().Text("Audit").Action("AuditList", "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;

View File

@ -186,7 +186,7 @@
var CurrAssignmentID = '';
var CurrId = '';
function documentClick(attachmentID, ecnNumber, trainingDockAckID, assignmentID) {
//window.open('http://messa016ec.ec.local:8021/ECN/DownloadFile?attachmentID=' + attachmentID + '&ecnNumber=' + ecnNumber, '_blank');
//window.open('http://messa016ec.infineon.com/ECN/DownloadFile?attachmentID=' + attachmentID + '&ecnNumber=' + ecnNumber, '_blank');
window.open('/ECN/DownloadFile?attachmentID=' + attachmentID + '&ecnNumber=' + ecnNumber, '_blank');
CurrAssignmentID = assignmentID;
CurrId = trainingDockAckID;

View File

@ -15,8 +15,9 @@
providerName="System.Data.SqlClient" />-->
<!--<add name="FabApprovalConnection" connectionString="Data Source=TEMTSV01EC.ec.local\Test1,49651;Integrated Security=False;Initial Catalog=FabApprovalSystem_Test;User ID=dbreaderwriterFABApproval;Password=90!2017-Tuesday27Vq;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False"
providerName="System.Data.SqlClient" />-->
<add name="FabApprovalConnection" connectionString="Data Source=Messv01ec.ec.local\PROD1,53959;Integrated Security=False;Initial Catalog=FabApprovalSystem;User ID=MES_FI_DBAdmin;Password=Takeittothelimit1;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False" providerName="System.Data.SqlClient" />
<add name="FabApprovalConnectionDev" connectionString="Data Source=Messv01ec.ec.local\PROD1,53959;Integrated Security=False;Initial Catalog=FabApprovalSystem;User ID=MES_FI_DBAdmin;Password=Takeittothelimit1;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False" providerName="System.Data.SqlClient" />
<add name="FabApprovalConnectionEC" connectionString="Data Source=Messv01ec.ec.local\PROD1,53959;Integrated Security=False;Initial Catalog=FabApprovalSystem;User ID=MES_FI_DBAdmin;Password=Takeittothelimit1;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False" providerName="System.Data.SqlClient" />
<add name="FabApprovalConnectionStealth" connectionString="Data Source=MESSQLEC1.infineon.com\PROD1,53959;Integrated Security=False;Initial Catalog=FabApprovalSystem;User ID=fab_approval_admin;Password=Fabapprovaladmin2023;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False" providerName="System.Data.SqlClient" />
<add name="FabApprovalConnectionDev" connectionString="Data Source=MESTSV02EC.infineon.com\TEST1,50572;Integrated Security=False;Initial Catalog=FabApprovalSystem;User ID=fab_approval_admin_test;Password=Fab_approval_admin_test2023!;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False" providerName="System.Data.SqlClient" />
<!--<add name="FabApprovalConnection" connectionString="Data Source=TEMTSV01EC.ec.local\Test1,49651;Integrated Security=False;Initial Catalog=FabApprovalSystem_Quality;User ID=dbreaderwriterFABApproval;Password=90!2017-Tuesday27Vq;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False"
providerName="System.Data.SqlClient" />-->
@ -28,8 +29,12 @@
<!--<add name="SAMDBConnectionString" connectionString="data Source=TEM-CDB02.IRWORLD.IRF.COM\TEMSQL02;Integrated Security=True;Initial Catalog=SAM;Persist Security Info=True"
providerName="System.Data.SqlClient" />-->
<add name="FabApprovalSystemEntities" connectionString="metadata=res://*/Models.FabApprovalDB.csdl|res://*/Models.FabApprovalDB.ssdl|res://*/Models.FabApprovalDB.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=Messv01ec.ec.local\PROD1,53959;initial catalog=FabApprovalSystem;persist security info=True;user id=MES_FI_DBAdmin;password=Takeittothelimit1;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
<add name="FabApprovalTrainingEntities" connectionString="metadata=res://*/Models.TrainingDB.csdl|res://*/Models.TrainingDB.ssdl|res://*/Models.TrainingDB.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=Messv01ec.ec.local\PROD1,53959;initial catalog=FabApprovalSystem;integrated security=False;user id=MES_FI_DBAdmin;password=Takeittothelimit1;connect timeout=15;encrypt=False;trustservercertificate=False;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
<add name="FabApprovalSystemEntitiesAll" connectionString="metadata=res://*/Models.FabApproval.csdl|res://*/Models.FabApproval.ssdl|res://*/Models.FabApproval.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=Messv01ec.ec.local\PROD1,53959;initial catalog=FabApprovalSystem;integrated security=False;user id=MES_FI_DBAdmin;password=Takeittothelimit1;connect timeout=15;encrypt=False;trustservercertificate=False;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
<add name="FabApprovalTrainingEntitiesEC" connectionString="metadata=res://*/Models.TrainingDB.csdl|res://*/Models.TrainingDB.ssdl|res://*/Models.TrainingDB.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=Messv01ec.ec.local\PROD1,53959;initial catalog=FabApprovalSystem;integrated security=False;user id=MES_FI_DBAdmin;password=Takeittothelimit1;connect timeout=15;encrypt=False;trustservercertificate=False;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
<add name="FabApprovalTrainingEntitiesStealth" connectionString="metadata=res://*/Models.TrainingDB.csdl|res://*/Models.TrainingDB.ssdl|res://*/Models.TrainingDB.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MESSQLEC1.infineon.com\PROD1,53959;initial catalog=FabApprovalSystem;integrated security=False;user id=fab_approval_admin;password=Fabapprovaladmin2023;connect timeout=15;encrypt=False;trustservercertificate=False;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
<add name="FabApprovalTrainingEntitiesDev" connectionString="metadata=res://*/Models.TrainingDB.csdl|res://*/Models.TrainingDB.ssdl|res://*/Models.TrainingDB.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MESTSV02EC.infineon.com\TEST1,50572;initial catalog=FabApprovalSystem;integrated security=False;user id=fab_approval_admin_test;password=Fab_approval_admin_test2023!;connect timeout=15;encrypt=False;trustservercertificate=False;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
<add name="FabApprovalSystemEntitiesAllEC" connectionString="metadata=res://*/Models.FabApproval.csdl|res://*/Models.FabApproval.ssdl|res://*/Models.FabApproval.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=Messv01ec.ec.local\PROD1,53959;initial catalog=FabApprovalSystem;integrated security=False;user id=MES_FI_DBAdmin;password=Takeittothelimit1;connect timeout=15;encrypt=False;trustservercertificate=False;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
<add name="FabApprovalSystemEntitiesAllInfineon" connectionString="metadata=res://*/Models.FabApproval.csdl|res://*/Models.FabApproval.ssdl|res://*/Models.FabApproval.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MESSQLEC1.infineon.com\PROD1,53959;initial catalog=FabApprovalSystem;integrated security=False;user id=fab_approval_admin;password=Fabapprovaladmin2023;connect timeout=15;encrypt=False;trustservercertificate=False;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
<add name="FabApprovalSystemEntitiesAllDev" connectionString="metadata=res://*/Models.FabApproval.csdl|res://*/Models.FabApproval.ssdl|res://*/Models.FabApproval.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MESTSV02EC.infineon.com\TEST1,50572;initial catalog=FabApprovalSystem;integrated security=False;user id=fab_approval_admin_test;password=Fab_approval_admin_test2023!;connect timeout=15;encrypt=False;trustservercertificate=False;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
@ -57,8 +62,9 @@
<add key="SPNMRBHoldFlagDirectory" value="D:\Websites\SPNMRBHoldFlag\" />
<add key="SPNMRBHoldFlagFTPLogDirectory" value="D:\Websites\SPNMRBHoldFlagFTPLog\" />
<add key="LotTempPipeLine" value="D:\Websites\FabApprovalTempPipeLine\" />
<add key="DevWebSiteURL" value="mestsa05ec.ec.local:8065" />
<add key="ProdWebSiteURL" value="messa016ec.ec.local:8021" />
<add key="DevWebSiteURL" value="mestsa05ec.infineon.com" />
<add key="ProdWebSiteURLEC" value="messa016ec.ec.local" />
<add key="ProdWebSiteURLStealth" value="messa016ec.infineon.com" />
<!--<add key="ECDomain" value="TEMSCEC01.ec.local"/>-->
<add key="ECDomain" value="ELSSREC01.ec.local" />
<add key="ECADGroup" value="EC-MES-ALL-Users-R-L" />
@ -74,12 +80,13 @@
<add key="SSRSPassword" value="" />-->
<add key="SSRSFolder" value="/Fab2Approval/Test/" />
<add key="SSRSBindingsByConfiguration" value="false" />
<add key="Test Email Recipients" value="chase.tucker@infineon.com"/>
</appSettings>
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<!--<network host="SMTP.INTRA.INFINEON.COM" port="25" defaultCredentials="true" />-->
<network host="mailrelay-external.infineon.com" port="25" defaultCredentials="true" />
<network host="mailrelay-internal.infineon.com" port="25" defaultCredentials="true" />
</smtp>
</mailSettings>
</system.net>
@ -89,7 +96,7 @@
</authentication>
<sessionState mode="InProc" timeout="86400" />
<compilation debug="true" targetFramework="4.8" />
<httpRuntime targetFramework="4.5" maxRequestLength="1048576" requestValidationMode="2.0" />
<httpRuntime targetFramework="4.8" maxRequestLength="1048576" requestValidationMode="2.0" />
<membership>
<providers>
<!--<add name="ADMembershipProvider"

View File

@ -0,0 +1,13 @@
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "8.0.6",
"commands": [
"dotnet-ef"
],
"rollForward": false
}
}
}

View File

@ -0,0 +1,20 @@
using System.Net.Mail;
namespace MesaFabApproval.API.Clients;
public interface ISmtpClientWrapper {
void Send(MailMessage message);
}
public class SmtpClientWrapper : ISmtpClientWrapper {
private SmtpClient _client;
public SmtpClientWrapper(SmtpClient client) {
_client = client ??
throw new ArgumentNullException("SmtpClient not injected");
}
public void Send(MailMessage message) {
_client.Send(message);
}
}

View File

@ -0,0 +1,401 @@
using MesaFabApproval.API.Services;
using MesaFabApproval.Shared.Models;
using MesaFabApproval.Shared.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace MesaFabApproval.API.Controllers;
[ApiController]
[Authorize]
public class ApprovalController : ControllerBase {
private readonly ILogger<ApprovalController> _logger;
private readonly IApprovalService _approvalService;
private readonly IMonInWorkerClient _monInClient;
public ApprovalController(ILogger<ApprovalController> logger, IApprovalService approvalService,
IMonInWorkerClient monInClient) {
_logger = logger ?? throw new ArgumentNullException("ILogger not injected");
_approvalService = approvalService ?? throw new ArgumentNullException("IApprovalService not injected");
_monInClient = monInClient ?? throw new ArgumentNullException("IMonInWorkerClient not injected");
}
[HttpPost]
[Route("approval")]
public async Task<IActionResult> CreateApproval(Approval approval) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation("Attempting to generate a new approval");
if (approval is null) throw new ArgumentNullException("Approval cannot be null");
await _approvalService.CreateApproval(approval);
return Ok();
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot create new approval, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "CreateApproval";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
[HttpGet]
[Route("approval/issue")]
public async Task<IActionResult> GetApprovalsForIssueId(int issueId, bool bypassCache) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation($"Attempting to get approvals for issue {issueId}");
if (issueId <= 0) throw new ArgumentException($"{issueId} is not a valid issue ID");
IEnumerable<Approval> approvals = await _approvalService.GetApprovalsForIssueId(issueId, bypassCache);
return Ok(approvals);
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot get approvals, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "GetApprovalsForIssueId";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
[HttpGet]
[Route("approval/user")]
public async Task<IActionResult> GetApprovalsForUserId(int userId, bool bypassCache) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation($"Attempting to get approvals for user ID {userId}");
if (userId <= 0) throw new ArgumentException($"{userId} is not a valid user ID");
IEnumerable<Approval> approvals = await _approvalService.GetApprovalsForUserId(userId, bypassCache);
return Ok(approvals);
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot get approvals, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "GetApprovalsForUserId";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
[HttpGet]
[Route("approval/members")]
public async Task<IActionResult> GetApprovalGroupMembers(int subRoleId) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation($"Attempting to get approval group members for group {subRoleId}");
if (subRoleId <= 0) throw new ArgumentException($"{subRoleId} is not a valid sub role ID");
IEnumerable<User> members = await _approvalService.GetApprovalGroupMembers(subRoleId);
return Ok(members);
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot get approval group members, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "GetApprovalsGroupMembers";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
[HttpPut]
[Route("approval")]
public async Task<IActionResult> UpdateApproval(Approval approval) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation($"Attempting to update approval");
if (approval is null) throw new ArgumentNullException($"approval cannot be null");
await _approvalService.UpdateApproval(approval);
return Ok();
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot update approval, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "UpdateApproval";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
[HttpPut]
[Route("approval/approve")]
public async Task<IActionResult> Approve(Approval approval) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation($"attempting to submit approval");
if (approval is null) throw new ArgumentNullException($"approval cannot be null");
await _approvalService.Approve(approval);
return Ok();
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot approve, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "Approve";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
[HttpPut]
[Route("approval/deny")]
public async Task<IActionResult> Deny(Approval approval) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation($"attempting to deny approval");
if (approval is null) throw new ArgumentNullException($"approval cannot be null");
await _approvalService.Deny(approval);
return Ok();
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Approval denial failed, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "Deny";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
[HttpGet]
[Route("approval/roleId")]
public async Task<IActionResult> GetRoleIdForRoleName(string roleName) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation($"Attempting to get role ID by role name");
if (string.IsNullOrWhiteSpace(roleName)) throw new ArgumentException("role name cannot be null or empty");
int roleId = await _approvalService.GetRoleIdForRoleName(roleName);
return Ok(roleId);
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot get role ID, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "GetRoleIdForRoleName";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
[HttpGet]
[Route("approval/subRoles")]
public async Task<IActionResult> GetSubRolesForSubRoleName(string subRoleName, int roleId) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation($"Attempting to get sub roles by sub role name");
if (string.IsNullOrWhiteSpace(subRoleName)) throw new ArgumentException("sub role name cannot be null or empty");
if (roleId <= 0) throw new ArgumentException($"{roleId} is not a valid role ID");
IEnumerable<SubRole> subRoles = await _approvalService.GetSubRolesForSubRoleName(subRoleName, roleId);
return Ok(subRoles);
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot get role ID, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "GetSubRoleIdForSubRoleName";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
}

View File

@ -0,0 +1,120 @@
using System.Security.Authentication;
using MesaFabApproval.Shared.Models;
using MesaFabApproval.Shared.Services;
using MesaFabApprovalAPI.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace MesaFabApproval.API.Controllers;
[ApiController]
public class AuthenticationController : ControllerBase {
private readonly ILogger<AuthenticationController> _logger;
private readonly IMonInWorkerClient _monInClient;
private readonly IAuthenticationService _authenticationService;
public AuthenticationController(ILogger<AuthenticationController> logger,
IMonInWorkerClient monInClient,
IAuthenticationService authenticationService) {
_logger = logger ?? throw new ArgumentNullException("ILogger not injected");
_monInClient = monInClient ?? throw new ArgumentNullException("IMonInWorkerClient not injected");
_authenticationService = authenticationService ??
throw new ArgumentNullException("IAuthenticationService not injected");
}
[HttpPost]
[AllowAnonymous]
[Route("auth/login")]
public async Task<IActionResult> Login(AuthAttempt login) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation("Attempting to perform authentication");
if (login is null) throw new ArgumentNullException("Login cannot be null");
LoginResult loginResult = await _authenticationService.AuthenticateUser(login);
if (loginResult.IsAuthenticated)
return Ok(loginResult);
return Unauthorized();
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = $"Invalid argument. {ex.Message}";
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot authenticate user, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "Login";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
[HttpPost]
[AllowAnonymous]
[Route("auth/refresh")]
public async Task<IActionResult> Refresh(AuthAttempt authAttempt) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation("Attempting to refresh auth tokens");
if (authAttempt is null) throw new ArgumentNullException("AuthAttempt cannot be null");
if (authAttempt.AuthTokens is null) throw new ArgumentNullException("AuthTokens cannot be null");
LoginResult loginResult = await _authenticationService.RefreshAuthTokens(authAttempt);
return Ok(loginResult);
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = $"Invalid argument. {ex.Message}";
return BadRequest(errorMessage);
} catch (AuthenticationException ex) {
_logger.LogInformation($"Unable to refresh tokens, because {ex.Message}");
return Unauthorized();
} catch (Exception ex) {
isArgumentError = true;
errorMessage = $"Cannot authenticate user, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "RefreshTokens";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
}

View File

@ -0,0 +1,705 @@
using MesaFabApproval.API.Services;
using MesaFabApproval.Shared.Models;
using MesaFabApproval.Shared.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
namespace MesaFabApproval.API.Controllers;
[ApiController]
[Authorize]
public class MRBController : ControllerBase {
private readonly ILogger<MRBController> _logger;
private readonly IMRBService _mrbService;
private readonly IMonInWorkerClient _monInClient;
public MRBController(ILogger<MRBController> logger, IMRBService mrbService, IMonInWorkerClient monInClient) {
_logger = logger ?? throw new ArgumentNullException("ILogger not injected");
_mrbService = mrbService ?? throw new ArgumentNullException("IMRBService not injected");
_monInClient = monInClient ?? throw new ArgumentNullException("IMonInWorkerClient not injected");
}
[HttpPost]
[Route("mrb/new")]
public async Task<IActionResult> CreateNewMRB(MRB mrb) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation("Attempting to generate a new MRB");
if (mrb is null) throw new ArgumentNullException("MRB cannot be null");
await _mrbService.CreateNewMRB(mrb);
return Ok();
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot create new MRB, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "CreateNewMRB";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
[HttpGet]
[Route("mrb/all")]
public async Task<IActionResult> GetAllMRBs() {
DateTime start = DateTime.Now;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation("Attempting to get all MRBs");
IEnumerable<MRB> allMrbs = await _mrbService.GetAllMRBs();
return Ok(allMrbs);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot get all MRBs, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "GetAllMRBs";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
[HttpGet]
[Route("mrb/getById")]
public async Task<IActionResult> GetMRBById(int id) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation("Attempting to get an MRB by Id");
if (id <= 0) throw new ArgumentException("Invalid MRB number");
MRB mrb = await _mrbService.GetMRBById(id);
return Ok(mrb);
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot get MRB by Id, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "GetMRBbyId";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
[HttpGet]
[Route("mrb/getByTitle")]
public async Task<IActionResult> GetMRBByTitle(string title, bool bypassCache) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation("Attempting to get an MRB by Title");
if (string.IsNullOrWhiteSpace(title)) throw new ArgumentException("Title cannot be null or emtpy");
MRB mrb = await _mrbService.GetMRBByTitle(title, bypassCache);
return Ok(mrb);
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot get MRB by title, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "GetMRBbyTitle";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
[HttpPut]
[Route("mrb")]
public async Task<IActionResult> UpdateMRB(MRB mrb) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation("Attempting to update an MRB");
if (mrb is null) throw new ArgumentNullException("MRB cannot be null");
await _mrbService.UpdateMRB(mrb);
return Ok();
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot update MRB, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "UpdateMRB";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
[HttpPost]
[Route("mrbAction")]
public async Task<IActionResult> CreateMRBAction(MRBAction mrbAction) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation("Attempting to generate a new MRB");
if (mrbAction is null) throw new ArgumentNullException("MRB action cannot be null");
await _mrbService.CreateMRBAction(mrbAction);
return Ok();
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot create new MRB action, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "CreateNewMRBAction";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
[HttpGet]
[Route("mrbAction")]
public async Task<IActionResult> GetMRBActionsForMRB(int mrbNumber, bool bypassCache) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation("Attempting to get all MRBs");
if (mrbNumber <= 0) throw new ArgumentException($"{mrbNumber} is not a valid MRB number");
IEnumerable<MRBAction> mrbActions = await _mrbService.GetMRBActionsForMRB(mrbNumber, bypassCache);
return Ok(mrbActions);
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot get all MRBs, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "GetMRBActionsForMRB";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
[HttpPut]
[Route("mrbAction")]
public async Task<IActionResult> UpdateMRBAction(MRBAction mrbAction) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation("Attempting to update an MRB action");
if (mrbAction is null) throw new ArgumentNullException("MRB action cannot be null");
await _mrbService.UpdateMRBAction(mrbAction);
return Ok();
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot update MRB action, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "UpdateMRBAction";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
[HttpDelete]
[Route("mrbAction")]
public async Task<IActionResult> DeleteMRBAction(int mrbActionID, int mrbNumber) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation($"Attempting to delete MRB action {mrbActionID}");
if (mrbActionID <= 0) throw new ArgumentException($"{mrbActionID} is not a valid MRB ActionID");
if (mrbNumber <= 0) throw new ArgumentException($"{mrbNumber} is not a valid MRBNumber");
await _mrbService.DeleteMRBAction(mrbActionID, mrbNumber);
return Ok();
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot delete MRB action, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "DeleteMRBAction";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
[HttpGet]
[Route("mrb/attachments")]
public async Task<IActionResult> GetAttachmentsForMRB(int mrbNumber, bool bypassCache) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation($"Attempting to get MRB attachments for MRB {mrbNumber}");
if (mrbNumber <= 0) throw new ArgumentException($"{mrbNumber} is not a valid MRB number");
List<MRBAttachment> attachments = (await _mrbService.GetAllAttachmentsForMRB(mrbNumber, bypassCache)).ToList();
return Ok(attachments);
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot get attachments for MRB {mrbNumber}, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "GetMRBAttachments";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
[HttpPost]
[Route("mrb/attach")]
public async Task<IActionResult> SaveMRBAttachment([FromForm] IEnumerable<IFormFile> files, int mrbNumber) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation("Attempting to save MRB attachments");
if (files is null) throw new ArgumentNullException("Files cannot be null");
if (files.Count() <= 0) throw new ArgumentException("Files cannot be empty");
if (mrbNumber <= 0) throw new ArgumentException($"{mrbNumber} is not a valid MRB number");
IEnumerable<UploadResult> uploadResults = (await _mrbService.UploadAttachments(files, mrbNumber)).ToList();
return Ok(uploadResults);
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot save MRB attachments, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "SaveMRBAttachments";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
[AllowAnonymous]
[HttpGet]
[Route("mrb/attachmentFile")]
public async Task<IActionResult> GetMRBAttachmentFile(string path, string fileName) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation("Attempting to get MRB attachment file");
if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException("Path cannot be null or empty");
if (!System.IO.File.Exists(path)) throw new ArgumentException("No file exists at provided path");
if (string.IsNullOrWhiteSpace(fileName)) throw new ArgumentException("Filename cannot be null or empty");
byte[] fs = System.IO.File.ReadAllBytes(path);
const string defaultContentType = "application/octet-stream";
FileExtensionContentTypeProvider contentTypeProvider = new FileExtensionContentTypeProvider();
if (!contentTypeProvider.TryGetContentType(path, out string? contentType)) {
contentType = defaultContentType;
}
return new FileContentResult(fs, contentType) {
FileDownloadName = fileName
};
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot get MRB attachment file, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "GetMRBAttachmentFile";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
[HttpDelete]
[Route("mrb/attach")]
public async Task<IActionResult> DeleteMRBAttachment(MRBAttachment attachment) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation("Attempting to delete MRB attachment");
if (attachment is null) throw new ArgumentNullException("Attachment cannot be null");
await _mrbService.DeleteAttachment(attachment);
return Ok();
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot get MRB attachment file, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "DeleteMRBAttachment";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
[HttpPost]
[Route("mrb/notify/new-approvals")]
public async Task<IActionResult> NotifyNewApprovals(MRB mrb) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation("Attempting to notify new approvers");
if (mrb is null) throw new ArgumentNullException("MRB cannot be null");
await _mrbService.NotifyNewApprovals(mrb);
return Ok();
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Unable to notify new approvers, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "NotifyNewMRBApprovers";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
[HttpPost]
[Route("mrb/notify/approvers")]
public async Task<IActionResult> NotifyApprovers(MRBNotification notification) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation("Attempting to notify approvers");
if (notification is null) throw new ArgumentNullException("notification cannot be null");
if (notification.MRB is null) throw new ArgumentNullException("MRB cannot be null");
if (string.IsNullOrWhiteSpace(notification.Message)) throw new ArgumentException("message cannot be null or empty");
await _mrbService.NotifyApprovers(notification);
return Ok();
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Unable to notify approvers, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "NotifyMRBApprovers";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
[HttpPost]
[Route("mrb/notify/originator")]
public async Task<IActionResult> NotifyOriginator(MRBNotification notification) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation("Attempting to notify originator");
if (notification is null) throw new ArgumentNullException("MRBNotification cannot be null");
if (notification.MRB is null) throw new ArgumentNullException("MRB cannot be null");
if (string.IsNullOrWhiteSpace(notification.Message)) throw new ArgumentException("Message cannot be null or empty");
await _mrbService.NotifyOriginator(notification);
return Ok();
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = ex.Message;
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Unable to notify originator, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "NotifyMRBOriginator";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
}

View File

@ -0,0 +1,223 @@
using MesaFabApproval.API.Services;
using MesaFabApproval.Shared.Models;
using MesaFabApproval.Shared.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
namespace MesaFabApproval.API.Controllers;
[ApiController]
public class UserController : ControllerBase {
private readonly ILogger<UserController> _logger;
private readonly IMonInWorkerClient _monInClient;
private readonly IMemoryCache _cache;
private readonly IUserService _userService;
public UserController(ILogger<UserController> logger,
IMonInWorkerClient monInClient,
IMemoryCache cache,
IUserService userService) {
_logger = logger ?? throw new ArgumentNullException("ILogger not injected");
_monInClient = monInClient ?? throw new ArgumentNullException("IMonInWorkerClient not injected");
_cache = cache ?? throw new ArgumentNullException("IMemoryCache not injected");
_userService = userService ?? throw new ArgumentNullException("IUserService not injected");
}
[HttpGet]
[Route("/user/loginId")]
[Authorize]
public async Task<IActionResult> GetUserByLoginId(string loginId) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation("Attempting to get user by LoginID");
if (string.IsNullOrWhiteSpace(loginId))
throw new ArgumentException("LoginID cannot be null or empty");
User? user = _cache.Get<User>($"user{loginId}");
if (user is null) {
user = await _userService.GetUserByLoginId(loginId);
_cache.Set($"user{loginId}", user, DateTimeOffset.Now.AddDays(1));
}
if (user is not null) return Ok(user);
throw new Exception($"User with LoginID {loginId} not found");
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = $"Invalid argument. {ex.Message}";
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot get user by LoginID, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "GetUserByLoginId";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
[HttpGet]
[Route("/user/userId")]
[Authorize]
public async Task<IActionResult> GetUserByUserId(int userId) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation("Attempting to get user by LoginID");
if (userId <= 0) throw new ArgumentException($"{userId} is not a valid user ID");
User? user = _cache.Get<User>($"user{userId}");
if (user is null) {
user = await _userService.GetUserByUserId(userId);
_cache.Set($"user{userId}", user, DateTimeOffset.Now.AddDays(1));
}
if (user is not null) return Ok(user);
throw new Exception($"User with UserID {userId} not found");
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = $"Invalid argument. {ex.Message}";
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot get user by User ID, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "GetUserByUserId";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
[HttpGet]
[Route("/users/active")]
[Authorize]
public async Task<IActionResult> GetAllActiveUsers() {
DateTime start = DateTime.Now;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation("Attempting to get all active users");
IEnumerable<User>? activeUsers = _cache.Get<IEnumerable<User>>($"activeUsers");
if (activeUsers is null) {
activeUsers = await _userService.GetAllActiveUsers();
_cache.Set($"activeUsers", activeUsers, DateTimeOffset.Now.AddDays(1));
}
if (activeUsers is not null) return Ok(activeUsers);
throw new Exception($"No active users found");
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot get all active users, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "GetAllActiveUsers";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
[HttpGet]
[Route("/approver")]
[Authorize]
public async Task<IActionResult> GetApproverUserIdsForSubRoleCategoryItem(string subRoleCategoryItem) {
DateTime start = DateTime.Now;
bool isArgumentError = false;
bool isInternalError = false;
string errorMessage = "";
try {
_logger.LogInformation("Attempting to get approver user IDs");
if (string.IsNullOrWhiteSpace(subRoleCategoryItem))
throw new ArgumentException("SubRoleCategoryItem cannot be null or empty");
IEnumerable<int>? approverUserIds = _cache.Get<IEnumerable<int>>($"approvers{subRoleCategoryItem}");
if (approverUserIds is null) {
approverUserIds = await _userService.GetApproverUserIdsBySubRoleCategoryItem(subRoleCategoryItem);
_cache.Set($"approvers{subRoleCategoryItem}", approverUserIds, DateTimeOffset.Now.AddDays(1));
}
if (approverUserIds is not null) return Ok(approverUserIds);
throw new Exception($"Approvers for SubRoleCategoryItem {subRoleCategoryItem} not found");
} catch (ArgumentException ex) {
isArgumentError = true;
errorMessage = $"Invalid argument. {ex.Message}";
return BadRequest(errorMessage);
} catch (Exception ex) {
isInternalError = true;
errorMessage = $"Cannot get approver user IDs, because {ex.Message}";
return Problem(errorMessage);
} finally {
string metricName = "GetApproverUserIds";
DateTime end = DateTime.Now;
double millisecondsDiff = (end - start).TotalMilliseconds;
_monInClient.PostAverage(metricName + "Latency", millisecondsDiff);
if (isArgumentError) {
_logger.LogWarning(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Ok);
} else if (isInternalError) {
_logger.LogError(errorMessage);
_monInClient.PostStatus(metricName, StatusValue.Critical);
} else {
_monInClient.PostStatus(metricName, StatusValue.Ok);
}
}
}
}

View File

@ -0,0 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="Dapper.Contrib" Version="2.0.78" />
<PackageReference Include="dotenv.net" Version="3.1.3" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.5" />
<PackageReference Include="Microsoft.Data.SqlClient" Version="5.2.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="8.0.0" />
<PackageReference Include="NLog" Version="5.3.2" />
<PackageReference Include="NLog.Web.AspNetCore" Version="5.3.11" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
<PackageReference Include="System.DirectoryServices.AccountManagement" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MesaFabApproval.Shared\MesaFabApproval.Shared.csproj" />
</ItemGroup>
<ItemGroup>
<Reference Include="System.DirectoryServices.AccountManagement">
<HintPath>..\..\..\..\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.8\System.DirectoryServices.AccountManagement.dll</HintPath>
</Reference>
</ItemGroup>
</Project>

View File

@ -0,0 +1,127 @@
using MesaFabApproval.Shared.Services;
using NLog.Web;
using MesaFabApprovalAPI.Services;
using Microsoft.OpenApi.Models;
using dotenv.net;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.AspNetCore.Authorization;
using MesaFabApproval.API.Services;
using NLog.Extensions.Logging;
using MesaFabApproval.API.Clients;
using System.Net.Mail;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
DotEnv.Load();
builder.Logging.ClearProviders();
builder.Logging.SetMinimumLevel(LogLevel.Trace);
builder.Logging.AddNLog();
builder.Services.AddMemoryCache();
string jwtIssuer = Environment.GetEnvironmentVariable("FabApprovalJwtIssuer") ??
throw new ArgumentNullException("FabApprovalJwtIssuer environment variable not found");
string jwtAudience = Environment.GetEnvironmentVariable("FabApprovalJwtAudience") ??
throw new ArgumentNullException("FabApprovalJwtAudience environment variable not found");
string jwtKey = Environment.GetEnvironmentVariable("FabApprovalJwtKey") ??
throw new ArgumentNullException("FabApprovalJwtKey environment variable not found");
builder.Services.AddAuthentication(options => {
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options => {
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters {
ValidateIssuerSigningKey = true,
ValidIssuer = jwtIssuer,
ValidateAudience = false,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
ClockSkew = TimeSpan.Zero
};
});
builder.Services.AddAuthorization(options => {
options.DefaultPolicy = new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser()
.Build();
});
builder.Services.AddHttpClient();
builder.Services.AddScoped<IDbConnectionService, DbConnectionService>();
builder.Services.AddScoped<IDalService, DalService>();
builder.Services.AddScoped<SmtpClient>((serviceProvider) => {
return new SmtpClient("mailrelay-external.infineon.com");
});
builder.Services.AddScoped<ISmtpClientWrapper, SmtpClientWrapper>();
builder.Services.AddScoped<ISmtpService, SmtpService>();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IMonInWorkerClient, MonInWorkerClient>();
builder.Services.AddScoped<IAuthenticationService, AuthenticationService>();
builder.Services.AddScoped<IMRBService, MRBService>();
builder.Services.AddScoped<IApprovalService, ApprovalService>();
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c => {
c.SwaggerDoc("v1", new OpenApiInfo {
Title = "Mesa Fab Approval API",
Version = "v1"
});
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme {
In = ParameterLocation.Header,
Description = "Please insert JWT with Bearer into field",
Name = "Authorization",
Type = SecuritySchemeType.ApiKey
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement {
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] { }
}
});
});
builder.Services.AddCors(options => {
options.AddDefaultPolicy(
builder => {
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
WebApplication app = builder.Build();
app.UseCors();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<DeleteExistingFiles>false</DeleteExistingFiles>
<ExcludeApp_Data>false</ExcludeApp_Data>
<LaunchSiteAfterPublish>true</LaunchSiteAfterPublish>
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
<PublishProvider>FileSystem</PublishProvider>
<PublishUrl>bin\Release\net8.0\publish\</PublishUrl>
<WebPublishMethod>FileSystem</WebPublishMethod>
<_TargetId>Folder</_TargetId>
<SiteUrlToLaunchAfterPublish />
<TargetFramework>net8.0</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<ProjectGuid>852e528d-015a-43b5-999d-f281e3359e5e</ProjectGuid>
<SelfContained>true</SelfContained>
</PropertyGroup>
</Project>

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