public async Task <IActionResult> EditInsuranceInformation([FromRoute] int id, [FromBody] InsuranceInformation insuranceInfo) { var errorMessage = new ErrorMessageViewModel(); var error = new { Error = errorMessage }; return(Ok()); }
private void RealErrorMessage(Exception exception) { if (InteractiveService != null) { foreach (var handler in CustomErrorHandlers) { if (handler(exception, ApplicationInfo, User, InteractiveService)) { return; } } } if (errorMessageViewModel != null) { logger.Debug("Добавляем исключение в уже созданное окно."); errorMessageViewModel.AddException(exception); } else { logger.Debug("Создание окна отправки отчета о падении."); errorMessageViewModel = new ErrorMessageViewModel(ErrorMessageModelFactory.GetModel(), InteractiveService); errorMessageViewModel.AddException(exception); var errView = new ErrorMessageView(errorMessageViewModel); errView.ShowAll(); errView.Run(); errView.Destroy(); errorMessageViewModel = null; logger.Debug("Окно отправки отчета, уничтожено."); } }
public async Task <IActionResult> ChangePassword([FromRoute] string id, [FromBody] ChangePasswordViewModel passwordViewModel) { var errorMessage = new ErrorMessageViewModel(); var error = new { Error = errorMessage }; // Get the user profile ApplicationUser user = db.ApplicationUser.Where(e => e.Id == id).SingleOrDefault(); if (user == null) { errorMessage.Message = "Could not find the user profile"; return(Json(error)); } // Update the user password IdentityResult result = await _userManager.ChangePasswordAsync(user, passwordViewModel.OldPassword, passwordViewModel.NewPassword); if (result.Succeeded) { var successMessage = new { Message = "Password has successfully been changed" }; return(Ok(successMessage)); } else { errorMessage.Message = "An error has occurred"; return(Json(error)); } }
public void ShowMessage(string message) { ErrorMessageViewModel errorMessageViewModel = new ErrorMessageViewModel(); ErrorMessage error = new ErrorMessage(errorMessageViewModel); errorMessageViewModel.Error = $"{message}"; error.ShowDialog(); }
public async Task <IActionResult> UpdateEmployee([FromRoute] string id, [FromBody] BusinessEmployeeViewModel employeeModel) { var errorMessage = new ErrorMessageViewModel(); var error = new { Error = errorMessage }; // Get the employee from the database BusinessEmployees employee = db.BusinessEmployees.Where(e => e.UserId == id).SingleOrDefault(); if (employee == null) { errorMessage.Message = "Could not find employee"; return(Json(error)); } ApplicationUser user = db.ApplicationUser.Where(e => e.Id == id).SingleOrDefault(); if (user == null) { errorMessage.Message = "Could not find user profile"; return(Json(error)); } // Update information employee.FirstName = employeeModel.FirstName; employee.LastName = employeeModel.LastName; employee.Position = employeeModel.Position; employee.CanEditLibrary = employeeModel.CanEditLibrary; user.Email = employeeModel.Email; db.Entry(employee).State = EntityState.Modified; try { await _userManager.UpdateNormalizedEmailAsync(user); db.SaveChanges(); } catch (Exception exception) { errorMessage.Message = "Could not update employee information"; return(Json(error)); } // Model data to return to view var result = new BusinessEmployeeViewModel { Id = employee.UserId, FirstName = employee.FirstName, LastName = employee.LastName, Position = employee.Position, ProfilePicture = employee.ProfilePicture, CanEditLibrary = employee.CanEditLibrary, Email = user.Email }; return(Ok(result)); }
/// <summary> /// Display error page with error message and redirect /// </summary> /// <param name="error"></param> /// <returns></returns> public IActionResult ErrorMessage(ErrorMessageViewModel error) { if (error.RedirectAction == null || error.RedirectController == null) { error.RedirectAction = "GetIndex"; error.RedirectController = "Display"; } return(View(error)); }
public ErrorMessageView(ErrorMessageViewModel viewModel) { ViewModel = viewModel ?? throw new ArgumentNullException(nameof(viewModel)); this.Build(); this.SetPosition(WindowPosition.CenterOnParent); ActionArea.ChildVisible = false; ActionArea.SetSizeRequest(0, 0); ConfigureDlg(); }
public static ViewModels.ErrorMessageViewModel HandleErrorInfo(Exception _exception, string _Controler, string _ActionResult) { ErrorMessageViewModel objErrorMessageViewModel = new ErrorMessageViewModel(); objErrorMessageViewModel.Exception = _exception; objErrorMessageViewModel.Controler = _Controler; objErrorMessageViewModel.ActionResult = _ActionResult; return(objErrorMessageViewModel); }
public IActionResult Delete(Guid id) { var product = _productsServiceClient.GetProductById(id); if (product == null) { var errorMessage = new ErrorMessageViewModel("Error", "The product was not found."); return(RedirectToAction("Error", errorMessage)); } return(View(product)); }
private ErrorMessageViewModel GetErrorMesssageViewModel(string errorMessage) { var errorMessageViewModel = new ErrorMessageViewModel(); if (!string.IsNullOrEmpty(errorMessage)) { var errorMessages = errorMessage.Split("\\n").ToList(); errorMessages.RemoveAll(x => string.IsNullOrEmpty(x)); errorMessageViewModel.ErrorMessages = errorMessages; } return(errorMessageViewModel); }
public async Task <IActionResult> GetCoworkers() { var errorMessage = new ErrorMessageViewModel(); var error = new { Error = errorMessage }; var id = ""; try { id = User.Claims.Where(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").SingleOrDefault().Value; } catch (Exception exception) { errorMessage.Message = "Id was not found"; return(BadRequest(error)); } // Get user profile BusinessEmployees user = db.BusinessEmployees.Where(e => e.UserId == id).SingleOrDefault(); if (user == null) { errorMessage.Message = "User profile was not found"; return(BadRequest(error)); } // Get a list of coworkers List <BusinessEmployees> coworkers = db.BusinessEmployees.Where(e => e.BusinessUserId == user.BusinessUserId && e.UserId != user.UserId).ToList(); List <ContactsViewModel> contacts = new List <ContactsViewModel>(); foreach (BusinessEmployees coworker in coworkers) { ContactsViewModel contact = new ContactsViewModel { Name = String.Format("{0} {1}", coworker.FirstName, coworker.LastName), Position = coworker.Position, PhoneNumber = coworker.PhoneNumber }; contacts.Add(contact); } return(Ok(contacts.ToArray())); }
public async Task <object> Login([FromBody] LoginViewModel model) { var errorMessage = new ErrorMessageViewModel(); var error = new { Error = errorMessage }; var appUser = _userManager.Users.SingleOrDefault(r => r.Email == model.Email); if (appUser == null) { errorMessage.Message = "The username and/or password you entered are not correct"; return(Json(error)); } var result = await _signInManager.PasswordSignInAsync(appUser.UserName, model.Password, false, false); if (result.Succeeded) { var userRoles = await _userManager.GetRolesAsync(appUser); // Send User Roles as List<string> to read values List <string> userRoleValues = new List <string>(); foreach (var role in userRoles) { userRoleValues.Add(role); } var jwtToken = await GenerateJwtToken(model.Email, appUser, userRoleValues); var response = new LoginResponse { Id = appUser.Id, Token = jwtToken.ToString(), Roles = userRoles.ToArray() }; return(Json(response)); } errorMessage.Message = "Invalid Login Attempt"; return(Json(error)); }
public async Task <IActionResult> Update(ProductEditDto product) { if (!ModelState.IsValid) { var errorMessage = new ErrorMessageViewModel("There was an error", "The model is invalid"); return(RedirectToAction("Error", errorMessage)); } string imageUrl = string.Empty; var originalProduct = _productsServiceClient.GetProductById(product.Id); if (originalProduct == null) { var errorMessage = new ErrorMessageViewModel("Error", "The product was not found."); return(RedirectToAction("Error", errorMessage)); } if (product.Photo != null) { imageUrl = await _imageStorageService.UploadFile(product.Photo); await _imageStorageService.DeleteFile(originalProduct.Photo); } else { imageUrl = originalProduct.Photo; } var productModel = new ProductDto { Id = product.Id, Name = product.Name, Photo = imageUrl, Price = product.Price }; _productsServiceClient.UpdateProduct(productModel); return(RedirectToAction("ProductList")); }
// // GET: /CheckOut/ErrorMessage public ActionResult ErrorMessage(ErrorCode ErrorCode, string Header, string Description, string Order) { ErrorMessageViewModel ErrorMessage = new ErrorMessageViewModel(); var order = market.Orders.SingleOrDefault(o => o.OrderId == Order); if (order != null) { var orderItems = market.OrderDetails.Where(o => o.OrderId == Order).ToList(); if (market.Orders.Find(Order).User.Email == User.Identity.Name) { for (int i = 0; i < orderItems.Count; i++) { market.OrderDetails.Remove(orderItems[i]); } market.Orders.Remove(order); market.SaveChanges(); } } ErrorMessage.ErrorCode = ErrorCode; if (Description != null) { ErrorMessage.Description = Description; } else { ErrorMessage.Description = ErrorMessage.Descriptions[(int)ErrorCode]; } if (Header != null) { ErrorMessage.Header = Header; } else { ErrorMessage.Header = ErrorMessage.Headers[(int)ErrorCode]; } return(View(ErrorMessage)); }
public async Task <IActionResult> CheckInBook([FromRoute] int id) { var errorMessage = new ErrorMessageViewModel(); var error = new { Error = errorMessage }; var book = db.Documents.Where(e => e.DocumentId == id).SingleOrDefault(); var checkedOutBook = db.Checkouts.Where(e => e.BookId == id && e.CheckedOut).SingleOrDefault(); if (book == null) { errorMessage.Message = "Could not find book"; return(Json(error)); } if (!book.CheckedOut || !checkedOutBook.CheckedOut) { errorMessage.Message = "Book is already checked in"; return(Json(error)); } // Check the books in book.CheckedOut = false; checkedOutBook.CheckedOut = false; // Update status in the database db.Entry(book).State = EntityState.Modified; db.Entry(book).State = EntityState.Modified; try { db.SaveChanges(); } catch (Exception exception) { errorMessage.Message = "Could not check in the book"; return(Json(error)); } return(Ok(book)); }
public async Task <IActionResult> DeleteEmployee([FromRoute] string id) { var errorMessage = new ErrorMessageViewModel(); var error = new { Error = errorMessage }; // Delete the user from the application user list ApplicationUser user = db.ApplicationUser.Where(e => e.Id == id).SingleOrDefault(); if (user == null) { errorMessage.Message = "Could not find user"; return(Json(error)); } // Find the employee BusinessEmployees employee = db.BusinessEmployees.Where(e => e.UserId == id).SingleOrDefault(); if (employee == null) { errorMessage.Message = "Could not find employee"; return(Json(error)); } // Remove the employee db.Remove(employee); db.Remove(user); try { db.SaveChanges(); } catch (Exception exception) { errorMessage.Message = "Could not remove employee"; return(Json(error)); } return(Accepted(employee)); }
public ActionResult Cancel(string token) { ErrorMessageViewModel ErrorMessage = new ErrorMessageViewModel(); var order = market.Orders.SingleOrDefault(o => o.PayPalToken == token); if (order != null) { var orderItems = market.OrderDetails.Where(o => o.OrderId == order.OrderId).ToList(); if (order.User.Email == User.Identity.Name) { for (int i = 0; i < orderItems.Count; i++) { market.OrderDetails.Remove(orderItems[i]); } market.Orders.Remove(order); market.SaveChanges(); } } return(RedirectToAction("Index", "RentalCart")); }
public async Task <IActionResult> Insert(ProductInsertDto product) { if (!ModelState.IsValid) { var errorMessage = new ErrorMessageViewModel("There was an error", "The model is invalid"); return(RedirectToAction("Error", errorMessage)); } var imageUrl = await _imageStorageService.UploadFile(product.Photo); var productModel = new ProductViewModel { Name = product.Name, Photo = imageUrl, Price = product.Price }; _productsServiceClient.InsertProduct(productModel); return(RedirectToAction("ProductList")); }
public ErrorWindow(Exception e) { ErrorMessageViewModel emv = new ErrorMessageViewModel(); InitializeComponent(); if (e != null) { ErrorTextBox.Text = e.Message + Environment.NewLine + Environment.NewLine + e.StackTrace; if (ApplicationViewModel.Instance.SendEmailOnException) { emv.EmailErrorMessage(ErrorTextBox.Text); } //emv.ErrorNotice += new EventHandler<SimpleMvvmToolkit.NotificationEventArgs<Exception>>(emv_ErrorNotice); //emv.SendEmailMessageCompleted += new EventHandler<SimpleMvvmToolkit.NotificationEventArgs<Exception>>(emv_SendEmailMessageCompleted); if (ApplicationViewModel.Instance.EnableExceptionDetail) { ContentStackPanel.Visibility = System.Windows.Visibility.Visible; } } }
public async Task <IActionResult> SendEmailNotification([FromBody] EmailNotificationViewModel model) { var apiKey = configuration.GetSection("SendGrid")["ApiKey"]; var client = new SendGridClient(apiKey); var from = new EmailAddress(configuration.GetSection("UserSettings")["UserEmail"]); EmailAddress to = new EmailAddress(model.Email); ErrorMessageViewModel errorMessage = new ErrorMessageViewModel(); var error = new { Error = errorMessage.Message }; if (model.Email == null || model.Subject == null || model.Content == null) { errorMessage.Message = "Email notification could not be sent"; return(Json(error)); } var htmlContent = String.IsNullOrWhiteSpace(model.Html) ? "" : model.Html; var message = MailHelper.CreateSingleEmail(from, to, model.Subject, model.Content, htmlContent); var response = await client.SendEmailAsync(message); return(Ok(response)); }
public async Task <IActionResult> GetEmployeeById(string id) { var errorMessage = new ErrorMessageViewModel(); var error = new { Error = errorMessage }; // Get the employee from the database BusinessEmployees employee = db.BusinessEmployees.Where(e => e.UserId == id).SingleOrDefault(); if (employee == null) { errorMessage.Message = "Could not find employee"; return(Json(error)); } ApplicationUser user = db.ApplicationUser.Where(e => e.Id == id).SingleOrDefault(); if (user == null) { errorMessage.Message = "Could not find user profile"; return(Json(error)); } // Get the data for the employee var employeeModel = new BusinessEmployeeViewModel { Id = employee.UserId, FirstName = employee.FirstName, LastName = employee.LastName, Email = user.Email, Position = employee.Position, PhoneNumber = employee.PhoneNumber, CanEditLibrary = employee.CanEditLibrary }; return(Ok(employeeModel)); }
public static IHtmlContent GovUkErrorMessage( this IHtmlHelper htmlHelper, ErrorMessageViewModel errorMessageViewModel) { return(htmlHelper.Partial("/GovUkDesignSystemComponents/ErrorMessage.cshtml", errorMessageViewModel)); }
public async Task <IActionResult> CheckoutBook([FromRoute] int id, [FromBody] CheckoutViewModel checkoutBook) { var errorMessage = new ErrorMessageViewModel(); var error = new { Error = errorMessage }; var userId = ""; if (!ModelState.IsValid) { errorMessage.Message = "The model is missing required fields"; return(Json(error)); } if (User == null) { errorMessage.Message = "Could not find user for claims"; return(Json(error)); } try { userId = User.Claims.Where(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").SingleOrDefault().Value; } catch (Exception exception) { errorMessage.Message = "User Id was not found"; return(Json(error)); } // Get book and check out Documents book = db.Documents.Where(e => e.DocumentId == id).SingleOrDefault(); if (book == null) { errorMessage.Message = "Could not find book"; return(Json(error)); } book.CheckedOut = true; db.Entry(book).State = EntityState.Modified; try { db.SaveChanges(); } catch (Exception exception) { errorMessage.Message = "Could not check out book"; return(Json(error)); } // Add book to checked out in database var checkedOutBook = new Checkouts { BookId = id, UserId = userId, Email = checkoutBook.Email, Name = checkoutBook.Name, PhoneNumber = checkoutBook.PhoneNumber, ReturnDate = checkoutBook.ReturnDate, CheckedOut = true }; db.Checkouts.Add(checkedOutBook); try { db.SaveChanges(); } catch (Exception exception) { errorMessage.Message = "Could not add checked out book to database"; return(Json(error)); } return(Ok(checkedOutBook)); }
public async Task <IActionResult> GetUserProfile([FromRoute] string id) { var errorMessage = new ErrorMessageViewModel(); var error = new { Error = errorMessage }; // Get the user profile ApplicationUser user = db.ApplicationUser.Where(e => e.Id == id).SingleOrDefault(); if (user == null) { errorMessage.Message = "Could not find the user profile"; return(Json(error)); } // Find the user type based on the id BusinessUsers businessUser = db.BusinessUsers.Where(e => e.UserId == id).SingleOrDefault(); if (businessUser == null) { BusinessEmployees employee = db.BusinessEmployees.Where(e => e.UserId == id).SingleOrDefault(); if (employee == null) { PersonalUsers personalUser = db.PersonalUsers.Where(e => e.UserId == id).SingleOrDefault(); if (personalUser == null) { errorMessage.Message = "Could not find the profile for the user"; return(Json(error)); } // Get the personal user details ProfileDetailsViewModel personalProfile = new ProfileDetailsViewModel { Id = personalUser.UserId, FirstName = personalUser.FirstName, LastName = personalUser.LastName, Email = user.Email, AccountType = "Personal", ProfilePicture = personalUser.ProfilePicture }; return(Ok(personalProfile)); } // Get the employer info BusinessUsers employer = db.BusinessUsers.Where(e => e.BusinessUserId == employee.BusinessUserId).SingleOrDefault(); if (employer == null) { errorMessage.Message = "Could not find the employer profile for the employee"; return(Json(error)); } // Get the employee user details EmployeeDetailsViewModel employeeProfile = new EmployeeDetailsViewModel { Id = employee.UserId, FirstName = employee.FirstName, LastName = employee.LastName, Email = user.Email, AccountType = "Employee", ProfilePicture = employee.ProfilePicture, Organization = employer.Organization, CanEditLibrary = employee.CanEditLibrary }; return(Ok(employeeProfile)); } // Get the business user details ProfileDetailsViewModel businessProfile = new ProfileDetailsViewModel { Id = businessUser.UserId, FirstName = businessUser.FirstName, LastName = businessUser.LastName, Email = user.Email, AccountType = "Business", ProfilePicture = businessUser.ProfilePicture, Organization = businessUser.Organization }; return(Ok(businessProfile)); }
public async Task <IActionResult> UpdateProfile([FromRoute] string id, [FromBody] ProfileDetailsViewModel profile) { var errorMessage = new ErrorMessageViewModel(); var error = new { Error = errorMessage }; var role = ""; if (User != null) { try { role = User.Claims.Where(c => c.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/role").SingleOrDefault().Value; if (role == null) { errorMessage.Message = "Could not find role for user"; return(Json(error)); } } catch (Exception exception) { errorMessage.Message = "Could not get role for user"; return(Json(error)); } } if (profile == null) { errorMessage.Message = "Model is missing data"; return(Json(error)); } // Find the type of user based on the role if (role == "Personal") { // Get the personal user in the database PersonalUsers personalUser = db.PersonalUsers.Where(e => e.UserId == id).SingleOrDefault(); // Update the details for the profile if (personalUser != null) { personalUser.FirstName = profile.FirstName; personalUser.LastName = profile.LastName; if (!String.IsNullOrWhiteSpace(profile.ProfilePicture)) { var fileName = await fileController.UploadImage(profile.ProfilePicture, Request); if (String.IsNullOrWhiteSpace(fileName)) { errorMessage.Message = "Image upload encountered an error"; return(Json(error)); } personalUser.ProfilePicture = fileName; } // Update record in the database db.Entry(personalUser).State = EntityState.Modified; try { db.SaveChanges(); } catch (Exception exception) { errorMessage.Message = "Could update the account information"; return(Json(error)); } return(Ok(personalUser)); } else { errorMessage.Message = "Could not find the user profile"; return(Json(error)); } } else if (role == "Business") { // Get the business user in the database BusinessUsers businessUser = db.BusinessUsers.Where(e => e.UserId == id).SingleOrDefault(); // Update the details for the profile if (businessUser != null) { businessUser.FirstName = profile.FirstName; businessUser.LastName = profile.LastName; businessUser.Organization = profile.Organization; businessUser.PhoneNumber = profile.PhoneNumber; if (!String.IsNullOrWhiteSpace(profile.ProfilePicture)) { var fileName = await fileController.UploadImage(profile.ProfilePicture, Request); if (String.IsNullOrWhiteSpace(fileName)) { errorMessage.Message = "Image upload encountered an error"; return(Json(error)); } businessUser.ProfilePicture = fileName; } // Update record in the database db.Entry(businessUser).State = EntityState.Modified; try { db.SaveChanges(); } catch (Exception exception) { errorMessage.Message = "Could update the account information"; return(Json(error)); } return(Ok(businessUser)); } else { errorMessage.Message = "Could not find the user profile"; return(Json(error)); } } else if (role == "Employee") { // Get the employee in the database BusinessEmployees employee = db.BusinessEmployees.Where(e => e.UserId == id).SingleOrDefault(); // Update the details for the profile if (employee != null) { employee.FirstName = profile.FirstName; employee.LastName = profile.LastName; employee.PhoneNumber = profile.PhoneNumber; if (!String.IsNullOrWhiteSpace(profile.ProfilePicture)) { var fileName = await fileController.UploadImage(profile.ProfilePicture, Request); if (String.IsNullOrWhiteSpace(fileName)) { errorMessage.Message = "Image upload encountered an error"; return(Json(error)); } employee.ProfilePicture = fileName; } // Update record in the database db.Entry(employee).State = EntityState.Modified; try { db.SaveChanges(); } catch (Exception exception) { errorMessage.Message = "Could update the account information"; return(Json(error)); } return(Ok(employee)); } else { errorMessage.Message = "Could not find the user profile"; return(Json(error)); } } errorMessage.Message = "An error has occurred"; return(Json(error)); }
public IActionResult Error(ErrorMessageViewModel errorMessage) { return(View(errorMessage)); }
public async Task <IActionResult> AddEmployee([FromBody] BusinessEmployeeViewModel employee) { var id = ""; var errorMessage = new ErrorMessageViewModel(); var error = new { Error = errorMessage }; try { id = User.Claims.Where(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").SingleOrDefault().Value; } catch (Exception exception) { errorMessage.Message = "Id was not found"; return(BadRequest(error)); } // Get the employer info BusinessUsers business = db.BusinessUsers.Where(e => e.UserId == id).SingleOrDefault(); if (business == null) { errorMessage.Message = "Could not get the employer info"; return(Json(error)); } // Check if the user exists ApplicationUser user = _userManager.Users.SingleOrDefault(e => e.Email.Equals(employee.Email, StringComparison.InvariantCultureIgnoreCase)); // If not, create the user identity profile if (user == null) { if (employee.Email != null) { ApplicationUser applicationUser = new ApplicationUser { UserName = employee.Email, Email = employee.Email }; // Set temporary password string password = String.Format("{0}{1}#{2}", employee.Email.First().ToString().ToUpper(), employee.Email.Substring(1), DateTime.Now.Year); IdentityResult result = await _userManager.CreateAsync(applicationUser, password); if (result.Succeeded) { await _userManager.AddToRoleAsync(applicationUser, "Employee"); await _signInManager.SignInAsync(applicationUser, false); // Add the new user to the database BusinessEmployees businessEmployee = new BusinessEmployees { FirstName = employee.FirstName, LastName = employee.LastName, Position = employee.Position, CanEditLibrary = employee.CanEditLibrary, PhoneNumber = employee.PhoneNumber, UserId = applicationUser.Id, BusinessUserId = business.BusinessUserId }; if (!String.IsNullOrWhiteSpace(employee.ProfilePicture)) { var fileName = await fileController.UploadImage(employee.ProfilePicture, Request); if (String.IsNullOrWhiteSpace(fileName)) { errorMessage.Message = "Image upload encountered an error"; return(Json(error)); } businessEmployee.ProfilePicture = fileName; } db.BusinessEmployees.Add(businessEmployee); try { db.SaveChanges(); } catch (Exception exception) { errorMessage.Message = "Could not create the business employee"; return(Json(error)); } // model data var modelData = new BusinessEmployeeViewModel { Id = businessEmployee.UserId, FirstName = businessEmployee.FirstName, LastName = businessEmployee.LastName, Position = businessEmployee.Position, ProfilePicture = businessEmployee.ProfilePicture, PhoneNumber = businessEmployee.PhoneNumber, CanEditLibrary = businessEmployee.CanEditLibrary, Email = applicationUser.Email }; return(CreatedAtAction("AddEmployee", new { id = modelData.Id }, modelData)); } // Send an email with this link ( SET UP SENDGRID TOWARDS END OF PROJECT ) //string code = await _userManager.GeneratePasswordResetTokenAsync(applicationUser); //var callbackUrl = Url.Action("ResetPassword", "Accounts", new { userId = applicationUser.Id, code }, protocol: Request.Scheme); //// Send the email //var emailNotification = new EmailNotificationViewModel //{ // Email = applicationUser.Email, // Subject = "SPINE - Password Reset", // Content = "", // Html = "Please reset your password by clicking <a href =\"" + callbackUrl + "\">here</a>" //}; //await notificationsController.SendEmailNotification(emailNotification); } else { errorMessage.Message = "Data is missing the Email field"; return(Json(error)); } } errorMessage.Message = "An error has occurred"; return(Json(error)); }
public async Task <IActionResult> GetAllEmployees() { var id = ""; var errorMessage = new ErrorMessageViewModel(); var error = new { Error = errorMessage }; try { id = User.Claims.Where(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").SingleOrDefault().Value; } catch (Exception exception) { errorMessage.Message = "Id was not found"; return(BadRequest(error)); } // Get the user BusinessUsers user = db.BusinessUsers.Where(e => e.UserId == id).SingleOrDefault(); if (user == null) { errorMessage.Message = "Could not find the business user profile"; return(Json(error)); } List <BusinessEmployees> employees = new List <BusinessEmployees>(); employees = db.BusinessEmployees.Where(e => e.BusinessUserId == user.BusinessUserId).ToList(); List <BusinessEmployeeViewModel> employeeList = new List <BusinessEmployeeViewModel>(); // Format list with required data foreach (BusinessEmployees employee in employees) { // Get the application user profile var profile = db.ApplicationUser.Where(e => e.Id == employee.UserId).SingleOrDefault(); if (profile == null) { errorMessage.Message = "Could not find the employee profile"; return(Json(error)); } // Create view model to return var businessEmployee = new BusinessEmployeeViewModel { Id = profile.Id, FirstName = employee.FirstName, LastName = employee.LastName, Email = profile.Email, Position = employee.Position, ProfilePicture = employee.ProfilePicture, PhoneNumber = employee.PhoneNumber }; employeeList.Add(businessEmployee); } return(Ok(employeeList.ToArray())); }
public static IHtmlContent GovUkErrorMessage( this IHtmlHelper htmlHelper, ErrorMessageViewModel errorMessageViewModel) { return(htmlHelper.Partial("~/Partials/ErrorMessage.cshtml", errorMessageViewModel)); }
public async Task <object> Register([FromBody] RegistrationViewModel model) { var errorMessage = new ErrorMessageViewModel(); var error = new { Error = errorMessage }; // Check for the role type upon registration string[] availableRoles = { "Personal", "Business" }; if (!availableRoles.Contains(model.Role)) { errorMessage.Message = "Invalid Role"; return(Json(error)); } // Create variable for Application User var user = new ApplicationUser { Email = model.Email, UserName = model.Email }; ApplicationUser appUser = db.ApplicationUser.Where(e => e.Email.Equals(user.Email, StringComparison.InvariantCultureIgnoreCase)).SingleOrDefault(); if (appUser != null) { errorMessage.Message = "Username is already taken."; return(Json(error)); } var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await _userManager.AddToRoleAsync(user, model.Role); await _signInManager.SignInAsync(user, false); // Profile Types BusinessUsers businessUser = new BusinessUsers(); PersonalUsers personalUser = new PersonalUsers(); // Create the user profile if (model == null) { errorMessage.Message = "No data was found"; return(Json(error)); } if (model.Role == availableRoles[0]) { // If the user role is a business user var profile = new PersonalUsers { FirstName = model.FirstName, LastName = model.LastName, UserId = user.Id }; // Add the user to the database db.PersonalUsers.Add(profile); try { db.SaveChanges(); } catch (Exception exception) { errorMessage.Message = "Could not add personal user to the database"; return(Json(error)); } personalUser = profile; } else if (model.Role == availableRoles[1]) { // If the user role is a personal user var profile = new BusinessUsers { FirstName = model.FirstName, LastName = model.LastName, Organization = model.Organization, UserId = user.Id, PhoneNumber = model.PhoneNumber }; // Add the user to the database db.BusinessUsers.Add(profile); try { db.SaveChanges(); } catch (Exception exception) { errorMessage.Message = "Could not add business user to the database"; return(Json(error)); } businessUser = profile; } // Create role list to create jwt token List <string> roleList = new List <string>() { model.Role }; var jwtToken = await GenerateJwtToken(model.Email, user, roleList); var userRoles = await _userManager.GetRolesAsync(user); // Send the user role along with the JWT Token if (model.Role == availableRoles[0]) { var response = new PersonalLoginResponse { Token = jwtToken.ToString(), Roles = userRoles.ToArray(), PersonalUser = personalUser }; return(Json(response)); } else if (model.Role == availableRoles[1]) { var response = new BusinessLoginResponse { Token = jwtToken.ToString(), Roles = userRoles.ToArray(), BusinessUser = businessUser }; return(Json(response)); } } else if (!result.Succeeded) { errorMessage.Message = "Password must have 6+ characters, at least 1 uppercase character, 1 lowercase character, 1 number, and 1 non-alphanumeric character"; return(Json(error)); } errorMessage.Message = "An error has occurred"; return(Json(error)); }