diff --git a/.editorconfig b/.editorconfig index 86a1191..ba0c8d2 100644 --- a/.editorconfig +++ b/.editorconfig @@ -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 diff --git a/.gitignore b/.gitignore index a5bd507..4edfdda 100644 --- a/.gitignore +++ b/.gitignore @@ -337,3 +337,6 @@ ASALocalRun/ !.vscode/tasks.json !.vscode/launch.json !.vscode/extensions.json +.vscode + +.env diff --git a/Fab2ApprovalSystem.sln b/Fab2ApprovalSystem.sln index 8c7200d..e5b15ec 100644 --- a/Fab2ApprovalSystem.sln +++ b/Fab2ApprovalSystem.sln @@ -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 diff --git a/Fab2ApprovalSystem/App_Start/Startup.Auth.cs b/Fab2ApprovalSystem/App_Start/Startup.Auth.cs index e2c195a..0eb7843 100644 --- a/Fab2ApprovalSystem/App_Start/Startup.Auth.cs +++ b/Fab2ApprovalSystem/App_Start/Startup.Auth.cs @@ -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( diff --git a/Fab2ApprovalSystem/Controllers/AccountController.cs b/Fab2ApprovalSystem/Controllers/AccountController.cs index 2f6ecc5..6ca9721 100644 --- a/Fab2ApprovalSystem/Controllers/AccountController.cs +++ b/Fab2ApprovalSystem/Controllers/AccountController.cs @@ -12,19 +12,24 @@ using Fab2ApprovalSystem.Models; using System.Web.Security; using Fab2ApprovalSystem.Misc; using Fab2ApprovalSystem.DMO; +using Microsoft.AspNet.Identity.Owin; +using System.Net.Http; +using Newtonsoft.Json; +using System.Net.Http.Headers; +using System.Text; -namespace Fab2ApprovalSystem.Controllers -{ +namespace Fab2ApprovalSystem.Controllers { [Authorize] - public class AccountController : Controller - { + public class AccountController : Controller { + private string _apiBaseUrl; + public AccountController() - : this(new UserManager(new UserStore(new ApplicationDbContext()))) - { + : this(new UserManager(new UserStore(new ApplicationDbContext()))) { + _apiBaseUrl = Environment.GetEnvironmentVariable("FabApprovalApiBaseUrl") ?? + throw new ArgumentNullException("FabApprovalApiBaseUrl environment variable not found"); } - public AccountController(UserManager userManager) - { + public AccountController(UserManager userManager) { UserManager = userManager; } @@ -34,9 +39,8 @@ namespace Fab2ApprovalSystem.Controllers // GET: /Account/Login [AllowAnonymous] // try to make the browser refresh the login page every time, to prevent issues with changing usernames and the anti-forgery token validation - [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] - public ActionResult Login(string returnUrl) - { + [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] + public ActionResult Login(string returnUrl) { ViewBag.ReturnUrl = returnUrl; return View(); } @@ -44,18 +48,32 @@ namespace Fab2ApprovalSystem.Controllers [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] - public ActionResult Login(LoginModel model, string returnUrl) - { - try - { - //if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe)) - //{ - // return RedirectToLocal(returnUrl); - //} - - UserAccountDMO userDMO = new UserAccountDMO(); + public async Task 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(responseContent); #if(DEBUG) isLoginValid = true; @@ -64,28 +82,26 @@ namespace Fab2ApprovalSystem.Controllers #if (!DEBUG) bool isIFX = false; - //domainProvider = Membership.Providers["NA_ADMembershipProvider"]; - //isLoginValid = domainProvider.ValidateUser(model.LoginID, model.Password); + //domainProvider = Membership.Providers["NA_ADMembershipProvider"]; + //isLoginValid = domainProvider.ValidateUser(model.LoginID, model.Password); - if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") + if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") { isLoginValid = true; - else - { - isLoginValid = Functions.NA_ADAuthenticate(model.LoginID, model.Password); - if (!isLoginValid) - { - isLoginValid = Functions.IFX_ADAuthenticate(model.LoginID, model.Password); - isIFX = true; - } + } else { + isLoginValid = loginResult.IsAuthenticated; + if (isLoginValid) isIFX = true; + } #endif - if (isLoginValid) - { + if (isLoginValid) { + UserAccountDMO userDMO = new UserAccountDMO(); LoginModel user = userDMO.GetUser(model.LoginID); - if (user != null) - { + if (user != null) { + Session["JWT"] = loginResult.AuthTokens.JwtToken; + Session["RefreshToken"] = loginResult.AuthTokens.RefreshToken; + Session[GlobalVars.SESSION_USERID] = user.UserID; Session[GlobalVars.SESSION_USERNAME] = user.FullName; Session[GlobalVars.IS_ADMIN] = user.IsAdmin; @@ -94,22 +110,16 @@ namespace Fab2ApprovalSystem.Controllers Session[GlobalVars.CAN_CREATE_PARTS_REQUEST] = user.IsAdmin || PartsRequestController.CanCreatePartsRequest(user.UserID); FormsAuthentication.SetAuthCookie(user.LoginID, true); + return RedirectToLocal(returnUrl); - } - else - { + } else { ModelState.AddModelError("", "The user name does not exist in the DB. Please contact the System Admin"); } - } - else - { + } else { ModelState.AddModelError("", "The user name or password provided is incorrect."); } - } - - catch (Exception ex) - { - Functions.WriteEvent(@User.Identity.Name + " " + ex.InnerException , System.Diagnostics.EventLogEntryType.Error); + } catch (Exception ex) { + Functions.WriteEvent(@User.Identity.Name + " " + ex.InnerException, System.Diagnostics.EventLogEntryType.Error); EventLogDMO.Add(new WinEventLog() { IssueID = 99999, UserID = @User.Identity.Name, DocumentType = "Login", OperationType = "Error", Comments = "Reject - " + ex.Message }); ModelState.AddModelError("", ex.Message); } @@ -119,287 +129,87 @@ namespace Fab2ApprovalSystem.Controllers } - //// - //// POST: /Account/Login - //[HttpPost] - //[AllowAnonymous] - //[ValidateAntiForgeryToken] - //public async Task 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 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 Disassociate(string loginProvider, string providerKey) - { + public async Task Disassociate(string loginProvider, string providerKey) { ManageMessageId? message = null; IdentityResult result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey)); - if (result.Succeeded) - { + if (result.Succeeded) { message = ManageMessageId.RemoveLoginSuccess; - } - else - { + } else { message = ManageMessageId.Error; } return RedirectToAction("Manage", new { Message = message }); } - // // GET: /Account/Manage #pragma warning disable IDE0060 // Remove unused parameter - public ActionResult Manage(ManageMessageId? message) -#pragma warning restore IDE0060 // Remove unused parameter - { - //ViewBag.StatusMessage = - // message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed." - // : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set." - // : message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed." - // : message == ManageMessageId.Error ? "An error has occurred." - // : ""; - //ViewBag.HasLocalPassword = HasPassword(); - //ViewBag.ReturnUrl = Url.Action("Manage"); + public ActionResult Manage(ManageMessageId? message) { return View(); } +#pragma warning restore IDE0060 // Remove unused parameter - //// - //// POST: /Account/Manage - //[HttpPost] - //[ValidateAntiForgeryToken] - //public async Task 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 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 LinkLoginCallback() - { - var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId()); - if (loginInfo == null) - { + public async Task 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 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 linkedAccounts = UserManager.GetLogins(User.Identity.GetUserId()); ViewBag.ShowRemoveButton = HasPassword() || linkedAccounts.Count > 1; return (ActionResult)PartialView("_RemoveAccountPartial", linkedAccounts); } - protected override void Dispose(bool disposing) - { - if (disposing && UserManager != null) - { + protected override void Dispose(bool disposing) { + if (disposing && UserManager != null) { UserManager.Dispose(); UserManager = null; } @@ -410,71 +220,52 @@ namespace Fab2ApprovalSystem.Controllers // Used for XSRF protection when adding external logins private const string XsrfKey = "XsrfId"; - private IAuthenticationManager AuthenticationManager - { - get - { + private IAuthenticationManager AuthenticationManager { + get { return HttpContext.GetOwinContext().Authentication; } } - private async Task SignInAsync(ApplicationUser user, bool isPersistent) - { + private async Task SignInAsync(ApplicationUser user, bool isPersistent) { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); - var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); + ClaimsIdentity identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity); } - private void AddErrors(IdentityResult result) - { - foreach (var error in result.Errors) - { + private void AddErrors(IdentityResult result) { + foreach (string error in result.Errors) { ModelState.AddModelError("", error); } } - private bool HasPassword() - { - var user = UserManager.FindById(User.Identity.GetUserId()); - if (user != null) - { + private bool HasPassword() { + ApplicationUser user = UserManager.FindById(User.Identity.GetUserId()); + if (user != null) { return user.PasswordHash != null; } return false; } - public enum ManageMessageId - { + public enum ManageMessageId { ChangePasswordSuccess, SetPasswordSuccess, RemoveLoginSuccess, Error } - private ActionResult RedirectToLocal(string returnUrl) - { - if (Url.IsLocalUrl(returnUrl)) - { + private ActionResult RedirectToLocal(string returnUrl) { + if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); - } - else - { - - //return RedirectToAction("HierarchicalDataTest", "Home"); - + } else { return RedirectToAction("MyTasks", "Home"); - //return RedirectToAction("Index", "Home", new { tabName = "MyTasks"}); } } - private class ChallengeResult : HttpUnauthorizedResult - { - public ChallengeResult(string provider, string redirectUri) : this(provider, redirectUri, null) - { + private class ChallengeResult : HttpUnauthorizedResult { + public ChallengeResult(string provider, string redirectUri) : this(provider, redirectUri, null) { } - public ChallengeResult(string provider, string redirectUri, string userId) - { + public ChallengeResult(string provider, string redirectUri, string userId) { LoginProvider = provider; RedirectUri = redirectUri; UserId = userId; @@ -484,11 +275,9 @@ namespace Fab2ApprovalSystem.Controllers public string RedirectUri { get; set; } public string UserId { get; set; } - public override void ExecuteResult(ControllerContext context) - { - var properties = new AuthenticationProperties() { RedirectUri = RedirectUri }; - if (UserId != null) - { + public override void ExecuteResult(ControllerContext context) { + AuthenticationProperties properties = new AuthenticationProperties() { RedirectUri = RedirectUri }; + if (UserId != null) { properties.Dictionary[XsrfKey] = UserId; } context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider); diff --git a/Fab2ApprovalSystem/Controllers/TrainingController.cs b/Fab2ApprovalSystem/Controllers/TrainingController.cs index 15d1204..278f32e 100644 --- a/Fab2ApprovalSystem/Controllers/TrainingController.cs +++ b/Fab2ApprovalSystem/Controllers/TrainingController.cs @@ -2,23 +2,18 @@ using Fab2ApprovalSystem.DMO; using Fab2ApprovalSystem.Models; using Fab2ApprovalSystem.ViewModels; using Fab2ApprovalSystem.Utilities; -using Kendo.Mvc.UI; using System; using System.Collections.Generic; using System.Linq; -using System.Web; using System.Web.Mvc; using Kendo.Mvc.Extensions; using Fab2ApprovalSystem.Misc; using System.Configuration; -using System.Threading.Tasks; -namespace Fab2ApprovalSystem.Controllers -{ +namespace Fab2ApprovalSystem.Controllers { [Authorize] [SessionExpireFilter] - public class TrainingController : Controller - { + public class TrainingController : Controller { UserAccountDMO userDMO = new UserAccountDMO(); AdminDMO adminDMO = new AdminDMO(); TrainingDMO trainingDMO = new TrainingDMO(); @@ -26,19 +21,17 @@ namespace Fab2ApprovalSystem.Controllers public EmailUtilities emailer = new EmailUtilities(); // GET: Training - public ActionResult Index() - { + public ActionResult Index() { return View(); } + //public int Create(int ecnId, List groupIds) - public int Create(int ecnId) - { + public int Create(int ecnId) { ECN_DMO ecnDMO = new ECN_DMO(); //Delete old training if exists int oldTrainingId = trainingDMO.GetTrainingId(ecnId); - if (oldTrainingId != null && oldTrainingId != 0) - { + if (oldTrainingId != null && oldTrainingId != 0) { trainingDMO.DeleteTraining(oldTrainingId); } @@ -47,23 +40,20 @@ namespace Fab2ApprovalSystem.Controllers TrainingGroups = trainingDMO.GetECNAssignedTrainingGroups(ecnId); string ECNTitle = ecnDMO.GetECN(ecnId).Title; List Trainees = new List(); - foreach (var group in TrainingGroups) - { + foreach (int group in TrainingGroups) { Trainees.AddRange(trainingDMO.GetTrainees(group)); } Trainees = (from a in Trainees select a).Distinct().ToList(); - foreach (var trainee in Trainees) - { + foreach (int trainee in Trainees) { int assignmentId = trainingDMO.CreateAssignment(trainingId, trainee); NotifyTrainee(trainee, assignmentId, ecnId, ECNTitle); } + return trainingId; } - public ActionResult AddUserToTrainingAdHoc(int trainingId, int traineeId, int ecnId) - { - if ((bool)Session[GlobalVars.IS_ADMIN]) - { + public ActionResult AddUserToTrainingAdHoc(int trainingId, int traineeId, int ecnId) { + if ((bool)Session[GlobalVars.IS_ADMIN]) { //Get ECN ECN ecn = ecnDMO.GetECN(ecnId); @@ -72,172 +62,120 @@ namespace Fab2ApprovalSystem.Controllers //Get Training Training training = trainingDMO.GetTraining(trainingId); - if (ecn != null) - { - if (user != null) - { - if (training != null) - { - if (!trainingDMO.IsUserAssigned(traineeId, trainingId)) - { - if (training.DeletedDate == null && !ecn.Deleted) - { + if (ecn != null) { + if (user != null) { + if (training != null) { + if (!trainingDMO.IsUserAssigned(traineeId, trainingId)) { + if (training.DeletedDate == null && !ecn.Deleted) { //Both the ECN and training still exist - if (training.CompletedDate != null) - { + if (training.CompletedDate != null) { //Training is completed and now we need to re-open it. trainingDMO.reOpenTraining(trainingId); int assignmentId = trainingDMO.CreateAssignment(trainingId, traineeId); NotifyTrainee(traineeId, assignmentId, ecnId, ecn.Title); return Content("Success"); - } - else - { + } else { //training is still open, just add a user and notify int assignmentId = trainingDMO.CreateAssignment(trainingId, traineeId); NotifyTrainee(traineeId, assignmentId, ecnId, ecn.Title); return Content("Success"); } - } - else - { + } else { //Ecn or training task have been deleted. return Content("Training or ECN has been deleted."); } - } - else - { + } else { return Content("User already has an open or completed assignment for this training."); } - } - else - { + } else { return Content("Invalid training id."); } - } - else - { + } else { return Content("invalid userId"); } - } - else - { + } else { return Content("ECN invalid"); } - } - else - { + } else { return Content("Not Authorized"); } } - public ActionResult AddGroupToTrainingAdHoc(int trainingId, int groupId, int ecnId) - { - if ((bool)Session[GlobalVars.IS_ADMIN]) - { + public ActionResult AddGroupToTrainingAdHoc(int trainingId, int groupId, int ecnId) { + if ((bool)Session[GlobalVars.IS_ADMIN]) { ECN ecn = ecnDMO.GetECN(ecnId); Training training = trainingDMO.GetTraining(trainingId); TrainingGroup group = trainingDMO.GetTrainingGroupByID(groupId); List 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 emailIst = ldDMO.GetApproverEmailList(@issueID, currentStep).Distinct().ToList(); string recipient = userDMO.GetUserEmailByID(userId.ToString()); string emailTemplate = "ECNTrainingAssigned.txt"; @@ -248,7 +186,6 @@ namespace Fab2ApprovalSystem.Controllers subject = "ECN# " + ecnId + " - Training Assignment Notice - " + title; EmailNotification en = new EmailNotification(subject, ConfigurationManager.AppSettings["EmailTemplatesPath"]); - //string emailparams = ""; userEmail = recipient; string[] emailparams = new string[4]; emailparams[0] = assignmentId.ToString(); @@ -260,60 +197,46 @@ namespace Fab2ApprovalSystem.Controllers //#endif en.SendNotificationEmail(emailTemplate, GlobalVars.SENDER_EMAIL, senderName, userEmail, null, subject, emailparams); - //en.SendNotificationEmail(emailTemplate, SenderEmail, senderName, userEmail, null, subject, emailparams); - } - catch (Exception e) - { + } catch (Exception e) { string detailedException = ""; - try - { + try { detailedException = e.InnerException.ToString(); - } - catch - { + } catch { detailedException = e.Message; } } } - public ActionResult ViewTrainingPartial(int trainingID, int userID) - { + public ActionResult ViewTrainingPartial(int trainingID, int userID) { List 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 attachments = ecnDMO.GetECNAttachments(ecnNumber); IEnumerable attachments = trainingDMO.GetAssignedDocs(trainingAssignmentId); return PartialView(attachments); } - public ActionResult AcknowledgeDocument(int trainingAssignmentID, int trainingDocAckID) - { + + public ActionResult AcknowledgeDocument(int trainingAssignmentID, int trainingDocAckID) { //Check to see if acknowledgement is valid(Security Feature to protect data integrity) - if (trainingDMO.CheckValidDocAck(trainingDocAckID)) - { + if (trainingDMO.CheckValidDocAck(trainingDocAckID)) { trainingDMO.AcknowledgeDocument(trainingDocAckID); bool isFinishedTrainingAssignment = trainingDMO.CheckTrainingAssignmentStatus(trainingAssignmentID); - if (isFinishedTrainingAssignment) - { - try - { + if (isFinishedTrainingAssignment) { + try { trainingDMO.UpdateAssignmentStatus(trainingAssignmentID); bool isFinishedTraining = trainingDMO.CheckTrainingStatus(trainingAssignmentID); - if (isFinishedTraining) - { + if (isFinishedTraining) { int TrainingID = trainingDMO.GetTrainingIdByAssignment(trainingAssignmentID); trainingDMO.UpdateTrainingStatus(TrainingID); } - } - catch (Exception e) - { + } catch (Exception e) { string exception = e.ToString(); return Content(exception); } @@ -322,53 +245,38 @@ namespace Fab2ApprovalSystem.Controllers return Content("Marked Succesfully."); } - public ActionResult AcknowledgeReviewNoDocuments(int trainingAssignmentID) - { - try - { + + public ActionResult AcknowledgeReviewNoDocuments(int trainingAssignmentID) { + try { trainingDMO.UpdateAssignmentStatus(trainingAssignmentID); bool isFinishedTraining = trainingDMO.CheckTrainingStatus(trainingAssignmentID); - if (isFinishedTraining) - { + if (isFinishedTraining) { int TrainingID = trainingDMO.GetTrainingIdByAssignment(trainingAssignmentID); trainingDMO.UpdateTrainingStatus(TrainingID); } - } - catch (Exception e) - { + } catch (Exception e) { string exception = e.ToString(); return Content(exception, "application/json"); } return Json(new { test = "Succesfully saved" }); } - //public ActionResult ViewTrainings() - //{ - // IEnumerable 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 trainingList = trainingDMO.GetAllTrainings(); //Group Filter - if (filterType == 1 && filterValue != "") - { + if (filterType == 1 && filterValue != "") { ViewBag.GroupFilter = filterValue; List filteredTraining = new List(); - foreach (var item in trainingList) - { + foreach (Training item in trainingList) { List assignedTrainingGroups = trainingDMO.GetECNAssignedTrainingGroups(item.ECN); - foreach (int id in assignedTrainingGroups) - { - if (filterValue == id.ToString()) - { + foreach (int id in assignedTrainingGroups) { + if (filterValue == id.ToString()) { filteredTraining.Add(item); } } @@ -377,11 +285,9 @@ namespace Fab2ApprovalSystem.Controllers return PartialView(trainingList); } //Status Filter - if (filterType == 2 && filterValue != "") - { + if (filterType == 2 && filterValue != "") { List filteredTraining = new List(); - switch (filterValue) - { + switch (filterValue) { case "1": //Completed filteredTraining = (from a in trainingList where a.Status == true && a.Deleted != true select a).ToList(); @@ -399,13 +305,12 @@ namespace Fab2ApprovalSystem.Controllers return PartialView(trainingList); } //Default return all. - else - { + else { return PartialView(trainingList); } } - public ActionResult ViewTrainingAssignmentsReportView(int trainingID, string statusFilter, string groupFilter) - { + + public ActionResult ViewTrainingAssignmentsReportView(int trainingID, string statusFilter, string groupFilter) { bool? trainingStatus = trainingDMO.GetTraining(trainingID).Status; int ECNNumber = trainingDMO.GetTraining(trainingID).ECN; string ECNTitle = ecnDMO.GetECN(ECNNumber).Title; @@ -420,38 +325,29 @@ namespace Fab2ApprovalSystem.Controllers //float assignmentCount = trainingAssignments.Count(); float assignmentCount = (from a in trainingAssignments where a.Deleted != true select a).Count(); float totalCompleted = 0; - foreach (var assignment in trainingAssignments) - { - if (assignment.status == true && assignment.Deleted != true) - { + foreach (TrainingAssignment assignment in trainingAssignments) { + if (assignment.status == true && assignment.Deleted != true) { totalCompleted++; } } -#pragma warning disable IDE0047 // Remove unnecessary parentheses - percentComplete = (totalCompleted / assignmentCount) * 100; -#pragma warning restore IDE0047 // Remove unnecessary parentheses + percentComplete = totalCompleted / assignmentCount * 100; ViewBag.PercentComplete = percentComplete.ToString("0.00") + "%"; - if (groupFilter != "" && groupFilter != null) - { + if (groupFilter != "" && groupFilter != null) { ViewBag.GroupFilter = groupFilter; List groupFilteredTraining = new List(); List 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 filteredTraining = new List(); - switch (statusFilter) - { + switch (statusFilter) { case "1": //Completed @@ -475,8 +371,8 @@ namespace Fab2ApprovalSystem.Controllers return PartialView(trainingAssignments); } - public ActionResult ViewTrainingAssignments(int trainingID) - { + + public ActionResult ViewTrainingAssignments(int trainingID) { bool? trainingStatus = trainingDMO.GetTraining(trainingID).Status; int ECNNumber = trainingDMO.GetTraining(trainingID).ECN; string ECNTitle = ecnDMO.GetECN(ECNNumber).Title; @@ -490,24 +386,21 @@ namespace Fab2ApprovalSystem.Controllers return View(trainingAssignments); } + /// /// Method to return all the training assignments for a specified user /// /// /// - public ActionResult ViewMyTrainingAssignments() - { + public ActionResult ViewMyTrainingAssignments() { int userID = (int)Session[GlobalVars.SESSION_USERID]; List assignments = trainingDMO.GetTrainingAssignmentsByUserID(userID); List ViewData = new List(); - foreach (var assignment in assignments) - { + foreach (TrainingAssignment assignment in assignments) { Training training = trainingDMO.GetTraining(assignment.TrainingID); - if (training != null && !assignment.status) - { + if (training != null && !assignment.status) { int ecnID = training.ECN; - ViewData.Add(new ECNTrainingAssignments - { + ViewData.Add(new ECNTrainingAssignments { TrainingAssignmentID = assignment.ID, ECN_ID = ecnID, TrainingID = assignment.TrainingID, @@ -520,57 +413,48 @@ namespace Fab2ApprovalSystem.Controllers return View(ViewData); } + /// /// Method to return all assigned documents for a specified training assignment /// /// /// - 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 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 filteredTraining = new List(); - foreach (var item in AllTrainings) - { + foreach (Training item in AllTrainings) { List assignedTrainingGroups = trainingDMO.GetECNAssignedTrainingGroups(item.ECN); - foreach (int id in assignedTrainingGroups) - { - if (filterValue == id.ToString()) - { + foreach (int id in assignedTrainingGroups) { + if (filterValue == id.ToString()) { filteredTraining.Add(item); } } } AllTrainings = filteredTraining; return View(AllTrainings); - } - else - { + } else { ViewBag.AllGroups = trainingDMO.GetTrainingGroups(); return View(AllTrainings); } - - } - public ActionResult ViewAllTrainings() - { + public ActionResult ViewAllTrainings() { return View(); } - public ActionResult DeleteAssignment(int assignmentId) - { + + public ActionResult DeleteAssignment(int assignmentId) { trainingDMO.DeleteTrainingAssignment(assignmentId); trainingDMO.DeleteTrainingDocAck(assignmentId); @@ -578,116 +462,81 @@ namespace Fab2ApprovalSystem.Controllers //TO-DO Put this in its own method. bool isFinishedTrainingAssignment = trainingDMO.CheckTrainingAssignmentStatus(assignmentId); - if (isFinishedTrainingAssignment) - { - try - { + if (isFinishedTrainingAssignment) { + try { trainingDMO.UpdateAssignmentStatus(assignmentId); bool isFinishedTraining = trainingDMO.CheckTrainingStatus(assignmentId); - if (isFinishedTraining) - { + if (isFinishedTraining) { int TrainingID = trainingDMO.GetTrainingIdByAssignment(assignmentId); trainingDMO.UpdateTrainingStatus(TrainingID); } - } - catch (Exception e) - { + } catch (Exception e) { string exception = e.ToString(); return Content(exception, "application/json"); } - - - } return Json(new { test = "Succesfully saved" }); } - public ActionResult ManuallyExecuteECNTraining(int ecnId, int[] trainingGroupsIn) - { - if ((bool)Session[GlobalVars.IS_ADMIN]) - { + + public ActionResult ManuallyExecuteECNTraining(int ecnId, int[] trainingGroupsIn) { + if ((bool)Session[GlobalVars.IS_ADMIN]) { List newTrainingGroupIds = new List(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 assignedTrainingGroups = trainingDMO.GetECNAssignedTrainingGroups(ecnId); IEnumerable 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 trainingGroupIds = trainingDMO.GetECNAssignedTrainingGroups(ecnId); List assignedGroups = new List(); - 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 = "

Mesa Approval Open Training Assignments Daily Report


"; emailBody += "

The following contains open training assignments in the Mesa Approval system. "; emailBody += "Please ensure the following users complete their training assignments. "; @@ -696,8 +545,7 @@ namespace Fab2ApprovalSystem.Controllers //Get all users set up to receive the training report email. List trainingReportUsers = adminDMO.GetTrainingReportUsers(); List emailList = new List(); - foreach (var user in trainingReportUsers) - { + foreach (TrainingReportUser user in trainingReportUsers) { string userEmail = userDMO.GetUserByID(user.UserId).Email; emailList.Add(userEmail); } @@ -705,8 +553,7 @@ namespace Fab2ApprovalSystem.Controllers //Get a list of open trainings List openTrainings = trainingDMO.GetAllOpenTrainings(); - foreach (Training training in openTrainings) - { + foreach (Training training in openTrainings) { string trainingSection = ""; int trainingSectionUserCount = 0; string ecnTitle = ecnDMO.GetECN(training.ECN).Title; @@ -715,23 +562,18 @@ namespace Fab2ApprovalSystem.Controllers trainingSection += ""; trainingSection += ""; List 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") : ""; - if (assignmentDate.HasValue && (DateTime.Now.Date - assignmentDate.Value.Date).TotalDays > 15) - { + if (assignmentDate.HasValue && (DateTime.Now.Date - assignmentDate.Value.Date).TotalDays > 15) { trainingSection += ""; - } - else - { + } else { trainingSection += ""; } @@ -745,13 +587,10 @@ namespace Fab2ApprovalSystem.Controllers List ccRecipients = emailList; emailer.SendNotification("MesaFabApproval@infineon.com", ccRecipients, "Mesa Approval Daily Open Training Report", emailBody, "Daily Open Training Report"); isSuccess = true; - } - catch - { + } catch { isSuccess = false; } return isSuccess; } } - } diff --git a/Fab2ApprovalSystem/DMO/LotDispositionDMO.cs b/Fab2ApprovalSystem/DMO/LotDispositionDMO.cs index 281b692..a2531a5 100644 --- a/Fab2ApprovalSystem/DMO/LotDispositionDMO.cs +++ b/Fab2ApprovalSystem/DMO/LotDispositionDMO.cs @@ -1,11 +1,9 @@ using System; using System.Collections.Generic; -using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; -using System.Web; using Fab2ApprovalSystem.Models; using Dapper; using System.Transactions; @@ -13,8 +11,7 @@ using Fab2ApprovalSystem.ViewModels; using System.Reflection; using Fab2ApprovalSystem.Misc; -namespace Fab2ApprovalSystem.DMO -{ +namespace Fab2ApprovalSystem.DMO { public class LotDispositionDMO { private IDbConnection db = new SqlConnection(GlobalVars.DB_CONNECTION_STRING); diff --git a/Fab2ApprovalSystem/Fab2ApprovalSystem.csproj b/Fab2ApprovalSystem/Fab2ApprovalSystem.csproj index 38342ab..a7dfc48 100644 --- a/Fab2ApprovalSystem/Fab2ApprovalSystem.csproj +++ b/Fab2ApprovalSystem/Fab2ApprovalSystem.csproj @@ -153,6 +153,8 @@ + + @@ -182,6 +184,7 @@ True FabApproval.edmx + diff --git a/Fab2ApprovalSystem/Misc/EmailNotification.cs b/Fab2ApprovalSystem/Misc/EmailNotification.cs index 1c53d8b..26ee095 100644 --- a/Fab2ApprovalSystem/Misc/EmailNotification.cs +++ b/Fab2ApprovalSystem/Misc/EmailNotification.cs @@ -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 /// /// Email subject /// - public string EmailSubject - { + public string EmailSubject { set { _subject = value; } - } /// @@ -29,11 +25,9 @@ namespace Fab2ApprovalSystem.Misc /// /// File Name /// String: Containing the Entire content of the file - 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; } + /// /// this function will send email. it will read the mail setting from the web.config /// @@ -66,8 +55,8 @@ namespace Fab2ApprovalSystem.Misc /// CC ids /// Email Subject /// Email Body - protected void SendEmail(string SenderEmail, string SenderName, string Recep, string cc, string email_title, string email_body) - { +#pragma warning disable IDE0060 // Remove unused parameter + protected void SendEmail(string SenderEmail, string SenderName, string Recep, string cc, string email_title, string email_body) { // creating email message MailMessage msg = new MailMessage(); msg.IsBodyHtml = true;// email body will allow html elements @@ -87,27 +76,18 @@ namespace Fab2ApprovalSystem.Misc msg.Subject = email_title; msg.Body = email_body; - - - //create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section - SmtpClient SmtpMail = new SmtpClient("mailrelay-internal.infineon.com"); + //create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section + SmtpClient SmtpMail = new SmtpClient("mailrelay-internal.infineon.com"); // sending the message. - try - { + try { SmtpMail.Send(msg); - } - catch (Exception ex) - { + } catch (Exception ex) { Console.WriteLine("Exception caught in CreateTestMessage2(): {0}", ex.ToString()); } - - - - } - +#pragma warning restore IDE0060 // Remove unused parameter /// /// @@ -119,8 +99,7 @@ namespace Fab2ApprovalSystem.Misc /// /// /// - 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 - - - } - - - - /// /// /// @@ -165,8 +136,8 @@ namespace Fab2ApprovalSystem.Misc /// /// /// - protected void SendEmail(string SenderEmail, string SenderName, List RecepientList, string cc, string email_title, string email_body) - { +#pragma warning disable IDE0060 // Remove unused parameter + protected void SendEmail(string SenderEmail, string SenderName, List RecepientList, string cc, string email_title, string email_body) { // creating email message MailMessage msg = new MailMessage(); msg.IsBodyHtml = true;// email body will allow html elements @@ -175,8 +146,7 @@ namespace Fab2ApprovalSystem.Misc //msg.From = new MailAddress(SenderEmail, SenderName); msg.From = new MailAddress("MesaFabApproval@infineon.com", "Mesa Fab Approval"); // adding the Recepient Email ID - foreach (string recepient in RecepientList) - { + foreach (string recepient in RecepientList) { msg.To.Add(recepient); } @@ -188,26 +158,18 @@ namespace Fab2ApprovalSystem.Misc msg.Subject = email_title; msg.Body = email_body; - - //create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section - SmtpClient SmtpMail = new SmtpClient(); + //create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section + SmtpClient SmtpMail = new SmtpClient(); // sending the message. - try - { + try { SmtpMail.Send(msg); - } - catch (Exception ex) - { + } catch (Exception ex) { Console.WriteLine("Exception caught in CreateTestMessage2(): {0}", ex.ToString()); } - - - - - } +#pragma warning restore IDE0060 // Remove unused parameter /// /// @@ -219,8 +181,7 @@ namespace Fab2ApprovalSystem.Misc /// /// /// - protected void SendEmailWithAttachment(string SenderEmail, string SenderName, List RecepientList, string cc, string email_title, string email_body, string attachmentPath) - { + protected void SendEmailWithAttachment(string SenderEmail, string SenderName, List 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); - - - - } - /// /// /// @@ -267,8 +221,7 @@ namespace Fab2ApprovalSystem.Misc /// /// /// - protected void SendEmailWithAttachments(string SenderEmail, string SenderName, string Recep, string cc, string email_title, string email_body, List attachments) - { + protected void SendEmailWithAttachments(string SenderEmail, string SenderName, string Recep, string cc, string email_title, string email_body, List attachments) { // creating email message MailMessage msg = new MailMessage(); msg.IsBodyHtml = true;// email body will allow html elements @@ -286,35 +239,29 @@ namespace Fab2ApprovalSystem.Misc //setting email subject and body msg.Subject = email_title; msg.Body = email_body; - foreach (string attachment in attachments) - { + foreach (string attachment in attachments) { msg.Attachments.Add(new Attachment(attachment)); } - //create a Smtp Mail which will automatically get the smtp server details from web.config mailSettings section SmtpClient SmtpMail = new SmtpClient(); #if(!DEBUG) // sending the message. SmtpMail.Send(msg); #endif - - - } - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - protected void SendEmailWithAttachments(string SenderEmail, string SenderName, List RecepientList, string cc, string email_title, string email_body, List attachments) - { + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + protected void SendEmailWithAttachments(string SenderEmail, string SenderName, List RecepientList, string cc, string email_title, string email_body, List 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() { } - /// /// The Constructor Function /// /// Email Header Subject /// Emails Files Templates - public EmailNotification(string EmailHeaderSubject, string TemplatesPath) - { + public EmailNotification(string EmailHeaderSubject, string TemplatesPath) { _subject = EmailHeaderSubject; _TemplatesPath = TemplatesPath; } - - /// /// This function will send the email notification by reading the email template and substitute the arguments /// @@ -386,43 +320,33 @@ namespace Fab2ApprovalSystem.Misc /// EMail Subject /// Arguments /// String: Return the body of the email to be send - public string SendNotificationEmail(string EmailTemplateFile, string SenderEmail, string SenderName, string RecepientEmail, string CC, string Subject, params string[] Args) - { + public string SendNotificationEmail(string EmailTemplateFile, string SenderEmail, string SenderName, string RecepientEmail, string CC, string Subject, params string[] Args) { string retVal = null; //reading the file string FileContents = ReadEmailFile(EmailTemplateFile); - + string emailBody = FileContents; //setting formatting the string retVal = string.Format(emailBody, Args); - try - { + try { //check if we are in debug mode or not. to send email - if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") - { + if (GlobalVars.DBConnection.ToUpper() == "TEST" || GlobalVars.DBConnection.ToUpper() == "QUALITY") { SendEmail(SenderEmail, SenderName, GetTestRecipientsList(), CC, (!string.IsNullOrEmpty(Subject) ? Subject + " for: " + RecepientEmail : _subject), retVal); - } - else - { + } else { #if(!DEBUG) SendEmail(SenderEmail, SenderName, RecepientEmail, CC, (!string.IsNullOrEmpty(Subject) ? Subject : _subject), retVal); #endif } - } - catch (Exception ex) - { - throw ex; + } catch (Exception ex) { + throw ex; } return retVal; - - } - /// /// This function will send the email notification by reading the email template and substitute the arguments along with the attachments /// @@ -435,8 +359,7 @@ namespace Fab2ApprovalSystem.Misc /// /// /// - 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; - - } - - /// /// /// @@ -485,8 +398,7 @@ namespace Fab2ApprovalSystem.Misc /// /// /// - public string SendNotificationEmailWithAttachment(string EmailTemplateFile, string SenderEmail, string SenderName, List RecepientEmail, string CC, string Subject, string attachmentPath, params string[] Args) - { + public string SendNotificationEmailWithAttachment(string EmailTemplateFile, string SenderEmail, string SenderName, List 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 attachments, params string[] Args) - { + public string SendNotificationEmailWithAttachments(string EmailTemplateFile, string SenderEmail, string SenderName, string RecepientEmail, string CC, string Subject, List 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; - - } - - /// /// /// @@ -580,8 +469,7 @@ namespace Fab2ApprovalSystem.Misc /// /// /// - public string SendNotificationEmailWithAttachments(string EmailTemplateFile, string SenderEmail, string SenderName, List RecepientEmail, string CC, string Subject, List attachments, params string[] Args) - { + public string SendNotificationEmailWithAttachments(string EmailTemplateFile, string SenderEmail, string SenderName, List RecepientEmail, string CC, string Subject, List 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; - - } - - - /// /// /// @@ -636,8 +512,7 @@ namespace Fab2ApprovalSystem.Misc /// /// /// - public string SendNotificationEmail(string EmailTemplateFile, string SenderEmail, string SenderName, List RecepientEmail, string CC, string Subject, params string[] Args) - { + public string SendNotificationEmail(string EmailTemplateFile, string SenderEmail, string SenderName, List 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; - - } /// @@ -683,10 +549,8 @@ namespace Fab2ApprovalSystem.Misc /// /// /// - 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 GetTestRecipientsList() - { - var r = new List(); - try - { + public List GetTestRecipientsList() { + List r = new List(); + 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; diff --git a/Fab2ApprovalSystem/Misc/Functions.cs b/Fab2ApprovalSystem/Misc/Functions.cs index f409aa0..c565e25 100644 --- a/Fab2ApprovalSystem/Misc/Functions.cs +++ b/Fab2ApprovalSystem/Misc/Functions.cs @@ -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 { /// /// Writes to the Application Event Log and sends an email notification if appropriate /// /// /// - 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 - } - /// /// Returns the FTP Server Name /// /// - 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 /// /// - 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 /// /// - public static string FTPPassword() - { + public static string FTPPassword() { ConfigurationManager.RefreshSection("appSettings"); return ConfigurationManager.AppSettings["FTP Password"]; } @@ -89,41 +74,32 @@ namespace Fab2ApprovalSystem.Misc /// /// /// - public static string GetAttachmentFolder() - { + public static string GetAttachmentFolder() { ConfigurationManager.RefreshSection("appSettings"); return ConfigurationManager.AppSettings["AttachmentFolder"]; - } - /// /// /// /// /// - public static void CopyAttachments(int oldECNNumber, int newECNNumber) - { + public static void CopyAttachments(int oldECNNumber, int newECNNumber) { // The Name of the Upload component is "files" string oldFolderPath = Functions.GetAttachmentFolder() + "ECN\\" + oldECNNumber.ToString(); - string newFolderPath = Functions.GetAttachmentFolder() + "ECN\\" + newECNNumber.ToString() ; + string newFolderPath = Functions.GetAttachmentFolder() + "ECN\\" + newECNNumber.ToString(); DirectoryInfo newdi = new DirectoryInfo(newFolderPath); - + if (!newdi.Exists) newdi.Create(); - - FileInfo[] existingFiles = new DirectoryInfo(oldFolderPath ).GetFiles(); - foreach (FileInfo file in existingFiles) - { - if (!file.Name.Contains("ECNApprovalLog_" + oldECNNumber.ToString()) && !file.Name.Contains("ECNForm_" + oldECNNumber.ToString())) + FileInfo[] existingFiles = new DirectoryInfo(oldFolderPath).GetFiles(); + foreach (FileInfo file in existingFiles) { + if (!file.Name.Contains("ECNApprovalLog_" + oldECNNumber.ToString()) && !file.Name.Contains("ECNForm_" + oldECNNumber.ToString())) //var fileName = Path.GetFileName(file.FullName); file.CopyTo(Path.Combine(newFolderPath, file.Name)); - - } - - + } } /// @@ -132,13 +108,11 @@ namespace Fab2ApprovalSystem.Misc /// /// /// - public static bool NA_ADAuthenticate(string userID, string pwd) - { + public static bool NA_ADAuthenticate(string userID, string pwd) { string naContainer = ConfigurationManager.AppSettings["NAContainer"]; string naDomain = ConfigurationManager.AppSettings["NADomain"]; - try - { + try { PrincipalContext contextUser = new PrincipalContext(ContextType.Domain, naDomain, naContainer, @@ -149,12 +123,9 @@ namespace Fab2ApprovalSystem.Misc return false; else return true; - } - catch - { + } catch { return false; } - } /// @@ -163,13 +134,11 @@ namespace Fab2ApprovalSystem.Misc /// /// /// - public static bool IFX_ADAuthenticate(string userID, string pwd) - { + public static bool IFX_ADAuthenticate(string userID, string pwd) { string container = ConfigurationManager.AppSettings["IFXContainer"]; string domain = ConfigurationManager.AppSettings["IFXDomain"]; - try - { + try { PrincipalContext contextUser = new PrincipalContext(ContextType.Domain, domain, container, @@ -180,18 +149,12 @@ namespace Fab2ApprovalSystem.Misc return false; else return true; - } - catch - { + } catch { return false; } - } - - - public static string FTPSPNBatch() - { + public static string FTPSPNBatch() { ConfigurationManager.RefreshSection("appSettings"); return ConfigurationManager.AppSettings["FTPSPNBatchFileName"]; } @@ -200,8 +163,7 @@ namespace Fab2ApprovalSystem.Misc /// /// /// - public static string FTPSPNBatch_Test() - { + public static string FTPSPNBatch_Test() { ConfigurationManager.RefreshSection("appSettings"); return ConfigurationManager.AppSettings["FTPSPNBatchFileName_Test"]; } @@ -211,50 +173,44 @@ namespace Fab2ApprovalSystem.Misc /// /// /// - public static string CASectionMapper(GlobalVars.CASection casection) - { - switch (casection) - { + public static string CASectionMapper(GlobalVars.CASection casection) { + switch (casection) { case GlobalVars.CASection.Main: return "Main"; case GlobalVars.CASection.D1: return "D1"; - + case GlobalVars.CASection.D2: return "D2"; - + case GlobalVars.CASection.D3: return "D3"; - + case GlobalVars.CASection.D4: return "D4"; - + case GlobalVars.CASection.D5: return "D5"; - + case GlobalVars.CASection.D6: return "D6"; - + case GlobalVars.CASection.D7: return "D7"; - + case GlobalVars.CASection.D8: return "D8"; case GlobalVars.CASection.CF: // CA Findings return "CF"; - - } return ""; } - public static string DocumentTypeMapper(GlobalVars.DocumentType docType) - { - switch (docType) - { - case GlobalVars.DocumentType.Audit: + public static string DocumentTypeMapper(GlobalVars.DocumentType docType) { + switch (docType) { + case GlobalVars.DocumentType.Audit: return "Audit"; case GlobalVars.DocumentType.ChangeControl: return "ChangeControl"; @@ -280,17 +236,15 @@ namespace Fab2ApprovalSystem.Misc /// /// /// - public static string ReturnCANoStringFormat(int caNo) - { + public static string ReturnCANoStringFormat(int caNo) { string caNoString = ""; - if(caNo == 0) + if (caNo == 0) return ""; caNoString = "C" + caNo.ToString().PadLeft(5, '0'); return caNoString; } - public static string ReturnAuditNoStringFormat(int auditNo) - { + public static string ReturnAuditNoStringFormat(int auditNo) { string auditNoString = ""; if (auditNo == 0) return ""; @@ -298,12 +252,10 @@ namespace Fab2ApprovalSystem.Misc return auditNoString; } - public static string ReturnPartsRequestNoStringFormat(int PRNumber) - { + public static string ReturnPartsRequestNoStringFormat(int PRNumber) { if (PRNumber == 0) return ""; return String.Format("PR{0:000000}", PRNumber); } } - } diff --git a/Fab2ApprovalSystem/Models/AuthAttempt.cs b/Fab2ApprovalSystem/Models/AuthAttempt.cs new file mode 100644 index 0000000..005f48e --- /dev/null +++ b/Fab2ApprovalSystem/Models/AuthAttempt.cs @@ -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; } + } +} diff --git a/Fab2ApprovalSystem/Models/AuthTokens.cs b/Fab2ApprovalSystem/Models/AuthTokens.cs new file mode 100644 index 0000000..969eb98 --- /dev/null +++ b/Fab2ApprovalSystem/Models/AuthTokens.cs @@ -0,0 +1,6 @@ +namespace Fab2ApprovalSystem.Models { + public class AuthTokens { + public string JwtToken { get; set; } + public string RefreshToken { get; set; } + } +} diff --git a/Fab2ApprovalSystem/Models/LoginResult.cs b/Fab2ApprovalSystem/Models/LoginResult.cs new file mode 100644 index 0000000..1b0f2f0 --- /dev/null +++ b/Fab2ApprovalSystem/Models/LoginResult.cs @@ -0,0 +1,6 @@ +namespace Fab2ApprovalSystem.Models { + public class LoginResult { + public bool IsAuthenticated { get; set; } + public AuthTokens AuthTokens { get; set; } + } +} diff --git a/Fab2ApprovalSystem/Views/Home/_HomeLayout.cshtml b/Fab2ApprovalSystem/Views/Home/_HomeLayout.cshtml index 9b2c9de..4de7078 100644 --- a/Fab2ApprovalSystem/Views/Home/_HomeLayout.cshtml +++ b/Fab2ApprovalSystem/Views/Home/_HomeLayout.cshtml @@ -83,14 +83,29 @@ @*
  • Lot Dispostion
  • *@ @*
  • Create MRB
  • *@
  • Create ECN/TECN
  • + @if (!string.IsNullOrWhiteSpace(Session["JWT"].ToString())) { + string jwt = Session["JWT"].ToString(); + string encodedJwt = System.Net.WebUtility.UrlEncode(jwt); + string refreshToken = Session["RefreshToken"].ToString(); + string encodedRefreshToken = System.Net.WebUtility.UrlEncode(refreshToken); + string wasmClientUrl = Environment.GetEnvironmentVariable("FabApprovalWasmClientUrl") ?? + "https://localhost:7255"; + string mrbUrl = wasmClientUrl + "/redirect?jwt=" + encodedJwt + "&refreshToken=" + encodedRefreshToken + "&redirectPath=/mrb/new"; +
  • Create MRB
  • + } else { + string wasmClientUrl = Environment.GetEnvironmentVariable("FabApprovalWasmClientUrl") ?? + "https://localhost:7255"; + string mrbUrl = wasmClientUrl + "/redirect?redirectPath=/mrb/new"; +
  • Create MRB
  • + } @*
  • Create Special Work Request
  • *@ @*
  • Create PCR
  • *@
  • Create Audit
  • Create Corrective Action
  • @*@if (Convert.ToBoolean(Session[GlobalVars.CAN_CREATE_PARTS_REQUEST])) - { -
  • Create New/Repair Spare Parts Request
  • - }*@ + { +
  • Create New/Repair Spare Parts Request
  • + }*@ @*
  • Another Doc
  • *@ @@ -125,6 +140,14 @@ menu.Add().Text("My Training").Action("ViewMyTrainingAssignments", "Training"); menu.Add().Text("Training Reports").Action("TrainingReports", "Training"); menu.Add().Text("All Documents").Action("AllDocuments", "Home"); + string jwt = Session["JWT"].ToString(); + string encodedJwt = System.Net.WebUtility.UrlEncode(jwt); + string refreshToken = Session["RefreshToken"].ToString(); + string encodedRefreshToken = System.Net.WebUtility.UrlEncode(refreshToken); + string wasmClientUrl = Environment.GetEnvironmentVariable("FabApprovalWasmClientUrl") ?? + "https://localhost:7255"; + string mrbUrl = wasmClientUrl + "/redirect?jwt=" + encodedJwt + "&refreshToken=" + encodedRefreshToken + "&redirectPath=/mrb/all"; + menu.Add().Text("MRB").Url(mrbUrl); //menu.Add().Text("Special Work Requests").Action("SpecialWorkRequestList", "Home"); //menu.Add().Text("PCRB").Action("ChangeControlList", "Home"); //menu.Add().Text("MRB").Action("MRBList", "Home"); diff --git a/Fab2ApprovalSystem/Views/MRB/Edit.cshtml b/Fab2ApprovalSystem/Views/MRB/Edit.cshtml index 5ebd915..585b8ef 100644 --- a/Fab2ApprovalSystem/Views/MRB/Edit.cshtml +++ b/Fab2ApprovalSystem/Views/MRB/Edit.cshtml @@ -11,18 +11,6 @@ -@* - - - - - - - - - - - *@
    NameDate Assigned
    " + assignment.FullName + "" + DateAssigned + "
    " + assignment.FullName + "" + DateAssigned + "