public AHP.Core.Model.GenericResponse <bool> CreateUserAccount(AHP.Core.DTO.ExternalUserInfo userInfo) { AHP.Core.Model.GenericResponse <bool> response = new Core.Model.GenericResponse <bool>(); try { if (userInfo == null) { response.Success = false; response.Data = false; response.Errors.Add("User information provided is empty"); return(response); } response = _userInfoManager.CreateUser(userInfo); //send welcome email to admin if (response.Success && response.Data) { string[] toEmail = System.Configuration.ConfigurationManager.AppSettings["WelcomeEmailTo"].Split(','); //send user details email. To User _logMessages.AppendFormat("Sending email to admin {0} with user details.", string.Join(";", toEmail)); string fromEmail = System.Configuration.ConfigurationManager.AppSettings["EmailFROM"]; _logMessages.AppendFormat("Welcome email will be sent from {0}.", fromEmail); string subject = System.Configuration.ConfigurationManager.AppSettings["NewUserSubject"]; _logMessages.AppendFormat("Subject of the email is {0}.", subject); string welcomeEmailBody = System.IO.File.ReadAllText(System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/EmailTemplates/NewUserEmail.html")); welcomeEmailBody = welcomeEmailBody.Replace("{Firstname}", userInfo.Firstname); welcomeEmailBody = welcomeEmailBody.Replace("{Lastname}", userInfo.Lastname); welcomeEmailBody = welcomeEmailBody.Replace("{Email}", userInfo.Email); welcomeEmailBody = welcomeEmailBody.Replace("{Username}", userInfo.Username); welcomeEmailBody = welcomeEmailBody.Replace("{SupplierId}", userInfo.SupplierId); welcomeEmailBody = welcomeEmailBody.Replace("{Role}", userInfo.Role); welcomeEmailBody = welcomeEmailBody.Replace("{Company}", userInfo.Company); //welcomeEmailBody = welcomeEmailBody.Replace("{Birthyear}", userInfo.BirthYear.ToString()); //welcomeEmailBody = welcomeEmailBody.Replace("{Birthmonth}", userInfo.BirthMonth.ToString()); //welcomeEmailBody = welcomeEmailBody.Replace("{Zipcode}", userInfo.ZipCode); if (_emailDeliveryService.SendEmail(fromEmail, toEmail, new string[] { }, subject, welcomeEmailBody)) { response.Success = true; response.Data = true; } else { response.Success = false; response.Data = false; response.Errors.Add("User successfully created. Failed to send email to admin with user information."); } } } catch (Exception ex) { _logger.Error("Error occurred creating new user account. Error info - ", ex); response.Success = false; response.Errors.Add("Error occurred creating new user account. Please try again."); } return(response); }
public async Task <Guarantor> Add(Guarantor guarantor) { var guarantorFromDb = await _context.Users.Where(x => x.Email == guarantor.GuarantorEmail) .FirstOrDefaultAsync(); var guaranteeFromDb = await _context.Users.Where(x => x.Email == guarantor.GuaranteeEmail) .FirstOrDefaultAsync(); if (guarantorFromDb == null || (!guaranteeFromDb.CanGuarantee) || ((guarantorFromDb != null) && (guarantorFromDb.Email == guarantor.GuaranteeEmail))) { throw new AppException("Guarantor is not found"); } if (guaranteeFromDb == null) { throw new AppException("User is not found"); } if (_context.Guarantors.Any(x => (x.GuaranteeEmail == guarantor.GuaranteeEmail) && x.GuarantorEmail == guarantor.GuarantorEmail)) { throw new AppException("Guarantor has already been added"); } guarantor.Status = "Awaiting approval"; DateTime guarantorLocalTime_Nigeria = new DateTime(); string windowsTimeZone = GetWindowsFromOlson.GetWindowsFromOlsonFunc("Africa/Lagos"); guarantorLocalTime_Nigeria = TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById(windowsTimeZone)); guarantor.DateAdded = guarantorLocalTime_Nigeria; await _context.Guarantors.AddAsync(guarantor); await _context.SaveChangesAsync(); string body = "Dear " + guaranteeFromDb.FirstName + ",<br/><br/>Your request for a guarantee has been sent to " + guarantorFromDb.Email + " .<br/><br/>" + "You will receive an email from us when your guarantor provides a guarantee for you.<br/><br/>" + "Thanks,<br/>The RotatePay Team<br/>"; var message = new Message(new string[] { guaranteeFromDb.Email }, "[RotatePay] Request for Guarantee", body, null); _emailSenderService.SendEmail(message); string body1 = "Dear " + guarantorFromDb.FirstName + ",<br/><br/> " + guaranteeFromDb.FirstName + "(" + guaranteeFromDb.Email + ")" + " has requested that you provide a guarantee for their RotatePay profile.<br/><br/>" + "You can either accept or decline to provide a guarantee.<br/><br/>" + "Before you accept to provide guarantee for anyone, please ensure that you know them very well and that they can easily afford to pay their proposed contribution amount monthly.<br/><br/>" + "To provide a guarantee, please login to your RotatePay profile and check the Gaurantor secction for more information.<br/><br/>" + "Thanks,<br/>The RotatePay Team<br/>"; var message1 = new Message(new string[] { guarantorFromDb.Email }, "[RotatePay] Request for Guarantee", body1, null); _emailSenderService.SendEmail(message1); //await _logService.Create(log); return(guarantor); }
public async Task <IActionResult> Register([FromBody] RegisterDto register) { var user = new ApplicationUser { UserName = register.Email, Email = register.Email }; var result = await _userManager.CreateAsync(user, register.Password); if (result.Succeeded) { register.WasSuccessful = true; var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Page( "/Account/ConfirmEmail", //Not built yet pageHandler: null, values: new { userId = user.Id, code = code }, protocol: Request.Scheme); await _emailSenderService.SendEmail(register.Email, "Confirm your email", $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); } else { register.WasSuccessful = false; } return(Ok(register)); }
public async Task <User> Add(Transaction transaction) { var user = await _context.Users.Where(x => x.Email == transaction.Email).FirstOrDefaultAsync(); if (user == null) { throw new AppException("User is not found"); } DateTime transactionLocalDate_Nigeria = new DateTime(); string windowsTimeZone = GetWindowsFromOlson.GetWindowsFromOlsonFunc("Africa/Lagos"); transactionLocalDate_Nigeria = TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById(windowsTimeZone)); transaction.DateAdded = transactionLocalDate_Nigeria; await _context.Transactions.AddAsync(transaction); await _context.SaveChangesAsync(); //ThreadPool.QueueUserWorkItem(o => { string body = "Dear " + user.FirstName + ",<br/><br/>We have confirmed your payment of <b>" + transaction.AmountPaid + "</b>.<br/><br/>" + "For more information, check the transactions section of your online profile.<br/><br/>" + "Thanks,<br/>The RotatePay Team<br/>"; var message = new Message(new string[] { transaction.Email }, "[RotatePay] Payment Notification Confirmed", body, null); _emailSenderService.SendEmail(message); //}); //await _logService.Create(log); return(user); }
public async Task <IActionResult> RegisterStudent([FromBody] RegisterUserViewModel user) { var isParamValid = accountService.CheckRegisterToken(user.RegisterToken); if (isParamValid) { var result = await accountService.RegisterStudentAsync(user); if (result == bool.TrueString) { var student = await userManager.FindByNameAsync(user.Username); var code = await userManager.GenerateEmailConfirmationTokenAsync(student); var callbackUrl = Url.Action("Confirm", "Account", new { userId = student.Id, token = code }, HttpContext.Request.Scheme); await emailSender.SendEmail(user.Email, "Confirm", $"<a href='{callbackUrl}'>Confirm your email</a>"); return(Ok()); } return(BadRequest(result)); } return(BadRequest("Invalid Token")); }
public async Task <IActionResult> CriarConta([FromBody] ClienteViewDTO model) { _logger.LogDebug("A executar api/cliente/criar -> Post"); if (model is null) { _logger.LogWarning("O objeto ClienteViewDTO é null!"); return(BadRequest(nameof(model))); } try { ServiceResult resultado = _clienteBusiness.CriarConta(model); if (resultado.Sucesso) { _logger.LogInformation($"O {model.Nome}, com Email {model.Email} e Número de Telemóvel {model.NumTelemovel} registou-se com sucesso."); ServiceResult <Email> resultadoEmails = _clienteBusiness.GetEmailCodigoValidacao(model.Email, _webHostEnvironment.ContentRootPath); if (resultadoEmails.Sucesso) { await _emailSenderService.SendEmail(model.Email, resultadoEmails.Resultado); _logger.LogInformation("Email do Código de Confirmação enviado com sucesso."); return(Ok()); } else { _logger.LogInformation("Ocorreu um erro na leitura do Email do Código de Confirmação."); return(BadRequest(resultadoEmails.Erros)); } } else { _logger.LogInformation("Ocorreu um erro ao criar conta."); return(BadRequest(resultado.Erros)); } } catch (ArgumentNullException e) { _logger.LogError(e, e.Message); return(BadRequest(e.Message)); } catch (Exception e) { _logger.LogError(e, e.Message); return(StatusCode(500)); } }
public async Task <IActionResult> Register(RegisterUserViewModel registerUserViewModel) { if (ModelState.IsValid) { var user = new ApplicationUser() { Email = registerUserViewModel.Email, UserName = registerUserViewModel.Email, City = registerUserViewModel.City }; var result = await _userManager.CreateAsync(user, registerUserViewModel.Password); if (result.Succeeded) { var token = await _userManager.GenerateEmailConfirmationTokenAsync(user); var confirmationLink = Url.Action("ConfirmEmail", "Accounts", new { UserId = user.Id, token = token }, Request.Scheme); _logger.Log(LogLevel.Warning, confirmationLink); if (_signInManager.IsSignedIn(User) && User.IsInRole("Admin")) { return(RedirectToAction("ListOfUsers", "Adminstration")); } //await _signInManager.SignInAsync(user, isPersistent: false); //return RedirectToAction("index", "home"); string link = "<a href = '" + confirmationLink + "'>Click here to confirm your account</a>"; _emailSenderService.SendEmail(registerUserViewModel.Email, "Account Successfully Created", link); ViewBag.ErrorTitle = "Registration Successful"; ViewBag.ErrorMessage = "Before you can login, please confirm your email by clicking on the confirmation link we have emailed you."; return(View("Error")); } foreach (var error in result.Errors) { ModelState.AddModelError("", error.Description); } } return(View(registerUserViewModel)); }
public IActionResult AcceptPrescription(int id) { var result = _prescriptionRepo.AcceptCreated(id); var emailResult = _prescriptionRepo.Get(id); if (!result.IsSuccess) { return(RedirectToPrescriptionDetails(id, result.FailureMessage)); } if (!emailResult.IsSuccess) { return(RedirectToPrescriptionDetails(id, result.FailureMessage)); } var emailMsg = result.Value; var email = emailResult.Value.Email; _emailSenderService.SendEmail(email, "Rejestracja recepty", emailMsg); return(RedirectToPrescriptionDetails(id)); }
public async Task SendMessages(Appointment appointment) { foreach (var admin in appointmentService.GivesAllAdmin()) { await slackService.SendSlackMessage(admin.Email, $"You have 1 new appointment with the following details: \n Timeslot: {appointment.TimeSlot}, \n ServiceType: {appointment.ServiceType}, \n Date: {appointment.Date}"); } foreach (var admin in appointmentService.GivesAllAdmin()) { await slackService.CreateSlackReminder(admin.Email, $"You have 1 new appointment with the following details: \n Timeslot: {appointment.TimeSlot}, \n ServiceType: {appointment.ServiceType}, \n Date: {appointment.Date}", appointment.TimeSlot, appointment.Date); } emailService.SendEmail(appointment.User.Email, appointment.User.Name); }
public async Task SendMentorInviteEmail(Mentor mentor, string token) { var mentorInviteEmailModel = new MentorInviteEmailModel { FirstName = mentor.FirstName, LastName = mentor.LastName, IconUrl = _webHostService.GetWebIconUrl(), RegistrationUrl = _webHostService.GetRegistrationUrl(token) }; var body = await _razorViewToStringRenderer.RenderViewToStringAsync(Templates.MentorInviteView, mentorInviteEmailModel); await _emailSenderService.SendEmail(new EmailMessage(new List <string> { mentor.Email }, "Student mentor registration", body)); }
public async Task <IActionResult> Register(UserModel model) { try { var roles = _rolesService.GetRolesClient(); if (roles == null) { _logger.LogError("Roles Null"); } model.RolesId = roles.Id; var id = Guid.NewGuid(); _userClientService.CreatedUserCliet(model, id); _emailSenderService.SendEmail(model.Email, Constants.SubjectCreatedAccount, Constants.BodyCreatedAccount); Statistics statistics = new Statistics() { Action = (int)Action.CreatedUser, ActionName = "Đăng ký tài khoản", CreatedDate = DateTime.Now, Id = Guid.NewGuid(), ModifyDate = DateTime.Now }; _statisticsService.InsertStatistics(statistics); var userInfor = new UserInfor() { Address = model.Address, BirthDay = model.Birthday, Gender = model.Gender, UserId = id }; _userInfroService.CreatedUserInfor(userInfor); return(Ok(new Result() { Code = (int)HttpStatusCode.OK, Data = null, Error = "Tạo tài khoản thành công" })); } catch (Exception ex) { _logger.LogError("Lỗi tạo tài khoản: " + ex); return(Ok(new Result() { Code = (int)HttpStatusCode.InternalServerError, Data = null, Error = "Lỗi tạo tài khoản" })); } }
public async Task <IActionResult> SendInvoice(int orderId) { var order = orderService.GetOrderById(orderId); var client = clientService.GetClientById(order.IdClient); var infos = deliveryInfoService.GetOrderDeliveryInfo(orderId); var orderProducts = productOrderService.GetOrderProducts(order); var signatureBase64String = Convert.ToBase64String(infos.SignatureImageBase64); var dto = new List <OrderProductDto>(); foreach (var prod in orderProducts) { var product = productService.GetProductById(prod.IdProduct); dto.Add(new OrderProductDto { Product = product, ProductImage = productImageService.GetProductImages(product).FirstOrDefault(), OrderProduct = prod }); } var invoiceViewModel = new InvoiceDto { Order = order, DeliveryInfo = infos, Client = client, OrderProducts = dto, SignatureBase64String = signatureBase64String }; string body = await _razorViewToStringRenderer.RenderViewToStringAsync("/Views/Order/Invoice.cshtml", invoiceViewModel); await emailSenderService.SendEmail(client.Email, "Facture", body); order.WithBill = false; orderService.EditOrder(order); TempData["Message"] = "Facture envoyée à " + client.FirstName + " " + client.LastName; return(RedirectToAction("DeliveredOrders")); }
public Customer RegisterCustomer(RegisterCustomerDTO dto) { if (!dBContext.Customers.Any(x => x.EmailId.Equals(dto.EmailId))) { var customer = new Customer() { EmailId = dto.EmailId, Address = dto.Address, ContactNumber = dto.Contact, Password = dto.Password, Name = dto.UserName, CountryId = dto.CountryId, StateId = dto.StateId, Username = dto.UserName, PinCode = dto.Pincode, IsEmailVerified = false }; dBContext.Customers.Add(customer); Random generator = new Random(); String code = generator.Next(0, 999999).ToString("D6"); dBContext.EmailVerification.Add(new EmailVerification() { Code = code, Email = dto.EmailId }); dBContext.SaveChanges(); var link = "https://localhost:44397/Account/VerifyEmail?email=" + dto.EmailId + "&code=" + code; if (_emailSenderService != null) { _emailSenderService.SendEmail(dto.EmailId, dto.UserName, "Your are register successfully", link, "https://pbs.twimg.com/media/Ed0u4lSVoAAcPVN?format=png&name=small"); } return(customer); } else { return(null); } }
public bool PostNeedHelpMessage(Customer customer) { bool response = false; try { string template; using (var emailTemplateReader = new StreamReader(System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/EmailTemplates/CustomerIssue.html"))) { template = emailTemplateReader.ReadToEnd(); } _logMessages.AppendFormat("Requesting need help message for user. Email {0}, FirstName {1}, Selected Issue {2}, Issue Description {3}", customer.Email, customer.FirstName, customer.SelectedIssue, customer.IssueDescription); response = _emailService.SendEmail(customer, template); _logMessages.Append("Email request send successfully"); } catch (System.Exception ex) { _logMessages.AppendFormat("Error occurred sending email. Exception info {0}", ex.Message); Elmah.ErrorLog.GetDefault(null).Log(new Elmah.Error(ex)); } _logger.Info(_logMessages.ToString()); return(response); }
public async Task <IActionResult> SendCode(SendCodeViewModel model) { if (!ModelState.IsValid) { return(View()); } var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return(View("Error")); } if (model.SelectedProvider == "Authenticator") { return(RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, model.ReturnUrl, model.RememberMe })); } // Email used // Generate the token and send it var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider); if (string.IsNullOrWhiteSpace(code)) { return(View("Error")); } var message = "Your security code is: " + code; if (model.SelectedProvider == "Email") { await _emailSender.SendEmail(await _userManager.GetEmailAsync(user), "Security Code", message, "Hi Sir"); } return(RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, model.ReturnUrl, model.RememberMe })); }
public async Task <User> Create(User user, string password) { // validation if (string.IsNullOrWhiteSpace(password)) { throw new AppException("Password is required"); } if (_context.Users.Any(x => x.Email == user.Email)) { throw new AppException("Email '" + user.Email + "' is not available"); } if (user.FirstName.Length < 5) { throw new AppException("First name is too short"); } if (user.FirstName.Length > 15) { throw new AppException("First name is too long"); } if (user.Email.ToUpper().Contains("ROTATE") || user.FirstName.ToUpper().Contains("ROTATE") || user.Email.ToUpper().Contains("PAY") || user.FirstName.ToUpper().Contains("PAY")) { throw new AppException("Surname or Firstname is not available"); } byte[] passwordHash, passwordSalt; CreatePasswordHash(password, out passwordHash, out passwordSalt); user.PasswordHash = passwordHash; user.PasswordSalt = passwordSalt; user.Role = "User"; user.ImageNames = "......profilePictureRTPay......officialIDCardRTPay......utilityBillRTPay"; //......bankStatementRTPay......workIDCardRTPay"; DateTime userLocalDate_Nigeria = new DateTime(); string windowsTimeZone = GetWindowsFromOlson.GetWindowsFromOlsonFunc("Africa/Lagos"); userLocalDate_Nigeria = TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById(windowsTimeZone)); user.DateAdded = userLocalDate_Nigeria; user.DateEdited = userLocalDate_Nigeria; user.LastSeen = userLocalDate_Nigeria; int length = GlobalVariables.RandomStringLength(); var randomKey = ""; var keyIsAlreadyPresent = true; do { randomKey = GlobalVariables.RandomString(length); keyIsAlreadyPresent = _context.Users.Any(x => x.HiDee == randomKey); } while (keyIsAlreadyPresent); user.HiDee = randomKey; //ThreadPool.QueueUserWorkItem(o => { var url = GlobalVariables.URL + "/vaccount?em=" + user.Email + "&vc=" + user.EmailConfirmationCode; var link = $"<a href='{url}'>Click here</a>"; string body = "Dear " + user.FirstName + ",<br/><br/>Thank you for registering with RotatePay.<br/><br/>" + "Click on the link below to confirm your email address. <br/><br/>" + link + "<br/><br/>" + " If the link above can not be clicked, copy and paste the url below in your browser<br/>" + url + "<br/><br/><br/>" + "Thanks,<br/>The RotatePay Team<br/>"; var message = new Message(new string[] { user.Email }, "[RotatePay] Confirm your email address", body, null); _emailSenderService.SendEmail(message); //}); await _context.Users.AddAsync(user); await _context.SaveChangesAsync(); //await _logService.Create(log); return(user); }
public async Task <User> Add(PaymentNotification paymentNotification, IFormFile[] images) { var user = await _context.Users.Where(x => x.Email == paymentNotification.Email).FirstOrDefaultAsync(); if (user == null) { throw new AppException("User is not found"); } if (images != null) { for (int i = 0; i < images.Length; i++) { if (images[i] != null && images[i].Length > 0) { var file = images[i]; if (file.Length > 0) { if (!file.ContentType.StartsWith("image")) { var fileLength = file.Length / 1024; var maxFileLength = 5120; if (fileLength > maxFileLength) { throw new AppException("Uploaded file must not be more than 5MB!"); } } } } } } if (images != null) { for (int i = 0; i < images.Length; i++) { Bitmap originalFile = null; Bitmap resizedFile = null; int imgWidth = 0; int imgHeigth = 0; if ((i == 0) && (images[i] != null) && (images[i].Length > 0)) { var uploads = Path.GetFullPath(Path.Combine(GlobalVariables.ImagePath, @"images\payment")); var file = images[i]; if (file.Length > 0) { var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim(); string uniqueFileName = paymentNotification.FirstName.Substring(0, 5) + i + DateTime.Now + file.FileName; string uniqueFileNameTrimmed = uniqueFileName.Replace(":", "").Replace("-", "").Replace(" ", "").Replace("/", ""); using (var fileStream = new FileStream(Path.Combine(uploads, uniqueFileNameTrimmed), FileMode.Create)) { await file.CopyToAsync(fileStream); paymentNotification.ImageNames = uniqueFileNameTrimmed; if (file.ContentType.StartsWith("image")) { int width = 200; int height = 200; originalFile = new Bitmap(fileStream); resizedFile = ResizeImage.GetResizedImage(fileStream, width, height, width, height); } } if (resizedFile != null) { imgWidth = resizedFile.Width; imgHeigth = resizedFile.Height; using (var fileStreamUp = new FileStream(Path.Combine(uploads, uniqueFileNameTrimmed), FileMode.Create)) { resizedFile.Save(fileStreamUp, ImageFormat.Jpeg); } } } } } } DateTime paymentNotificationLocalDate_Nigeria = new DateTime(); string windowsTimeZone = GetWindowsFromOlson.GetWindowsFromOlsonFunc("Africa/Lagos"); paymentNotificationLocalDate_Nigeria = TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById(windowsTimeZone)); paymentNotification.DateAdded = paymentNotificationLocalDate_Nigeria; int length = GlobalVariables.RandomStringLengthShort(); var randomKey = ""; var keyIsAlreadyPresent = true; do { randomKey = GlobalVariables.RandomString(length); keyIsAlreadyPresent = _context.PaymentNotifications.Any(x => x.Reference == randomKey); } while (keyIsAlreadyPresent); paymentNotification.Reference = randomKey; paymentNotification.Confirmed = "No"; paymentNotification.UpdateAllowed = true; await _context.PaymentNotifications.AddAsync(paymentNotification); if (paymentNotification.TransactionType == "Activation") { user.ActivationRequested = true; _context.Users.Update(user); } await _context.SaveChangesAsync(); //ThreadPool.QueueUserWorkItem(o => { string body = "Dear " + paymentNotification.FirstName + ",<br/><br/>Thank you for submitting your payment notification.<br/><br/>" + "We will confirm your payment and update your online profile.<br/><br/>" + "You will also receive an email from us as soon as we have confirmed your payment<br/><br/>" + "Thanks,<br/>The RotatePay Team<br/>"; var message = new Message(new string[] { paymentNotification.Email }, "[RotatePay] Payment Notification Received", body, null); _emailSenderService.SendEmail(message); string body1 = paymentNotification.FirstName + "(" + paymentNotification.Email + ") has submitted the payment notification form.<br/><br/><br/>"; var message1 = new Message(new string[] { GlobalVariables.AdminEmail }, "[RotatePay] Payment receipt by " + paymentNotification.Email, body1, images); _emailSenderService.SendEmail(message1); //}); //await _logService.Create(log); return(user); }
public async Task <IActionResult> OrderNow(List <OrderDTo> orders) { try { var claimsIdentity = _httpContextAccessor.HttpContext.User.Claims; var userId = claimsIdentity.FirstOrDefault(x => x.Type == "UserId").Value; var email = claimsIdentity.FirstOrDefault(x => x.Type == "Email").Value; var statusProduct = _statusCartsService.GetStatusCartsClient(); var orderId = Guid.NewGuid(); Order order = new Order(); order.UserId = Guid.Parse(userId); order.Id = orderId; List <OrderDetails> orderDetails = new List <OrderDetails>(); List <ProductOrder> productOrders = new List <ProductOrder>(); var total = 0; var totalCost = 0f; foreach (var item in orders) { OrderDetails details = new OrderDetails() { Id = new Guid(), OrderId = orderId, ProductId = item.ProductId, Quantity = item.Quantity, TotalCost = item.TotalCost, StatusCartId = statusProduct.Id }; totalCost += item.TotalCost; total += item.Quantity; _orderDetailsService.AddOrderDetails(details); orderDetails.Add(details); } order.TotalQuantity = total; order.TotalCost = totalCost; order.Processed = 0; _orderService.AddOrder(order); _unitOfWork.Commit(); HttpContext.Session.Clear(); _emailSenderService.SendEmail(email, Constants.SubjectOrder, Constants.BodyOrder); Statistics statistics = new Statistics() { Action = (int)Action.Order, ActionName = "Mua hàng", CreatedDate = DateTime.Now, Id = Guid.NewGuid(), ModifyDate = DateTime.Now }; _statisticsService.InsertStatistics(statistics); return(Ok(new Result() { Message = "success", Code = (int)HttpStatusCode.OK, Data = "Đặt hàng thành công", Error = null })); } catch (Exception ex) { _logger.LogError("Đặt hàng thất bại: " + ex); return(Ok(new Result() { Message = "success", Code = (int)HttpStatusCode.OK, Data = null, Error = "Đặt hàng thất bại" })); } }
private void DoLoadAndProcess(int?schedulerId = null, bool isSync = false) { List <NotificationEmailData> emails; using (var unitOfWork = CreateUnitOfWork()) { var emailFromDb = unitOfWork.Schedulers.GetEmailsToProcess(schedulerId, isSync); emails = MapNotificationEmails(emailFromDb); } foreach (var emailData in emails) { try { using (var unitOfWork = CreateUnitOfWork()) { var notificationEmail = unitOfWork.Schedulers.GetNotificationEmail(emailData.Id); notificationEmail.ProcessedDate = DateTime.Now; notificationEmail.LastAttemptDate = DateTime.Now; notificationEmail.LastAttemptError = null; notificationEmail.AttemptsCount++; using (var tran = unitOfWork.BeginTransaction()) { unitOfWork.SaveChanges(); _emailSenderService.SendEmail( MapEmailAddresses(emailData.ToEmailAddresses), emailData.Subject, emailData.BodyHtml, new SendEmailArgs { EmailsCc = MapEmailAddresses(emailData.ToCcEmailAddresses), EmailsBcc = MapEmailAddresses(emailData.ToBccEmailAddresses), Attachments = emailData.Attachments.ToDictionary(m => m.FileName, m => m.GetFileBytes()) }); tran.Commit(); } } } catch (Exception ex) { LogHolder.MainLog.Error(ex, "Error send email - " + emailData.Id); try { using (var unitOfWork = CreateUnitOfWork()) { var notificationEmail = unitOfWork.Schedulers.GetNotificationEmail(emailData.Id); notificationEmail.LastAttemptDate = DateTime.Now; notificationEmail.LastAttemptError = ex.GetBaseException().Message; notificationEmail.AttemptsCount++; if (isSync || notificationEmail.AttemptsCount > MAX_ATTEMPTS_COUNT) { notificationEmail.ProcessedDate = DateTime.Now; } unitOfWork.SaveChanges(); } } catch (Exception e) { LogHolder.MainLog.Error(e, "Error occured while saving email data in failed state - " + emailData.Id); } if (isSync) { throw; } } } }
public ActionResult <Order> AddNewOrder(OrderForCreationDto orderDto) { var client = clientService.GetClientById(orderDto.ClientId); if (client == null) { return(NotFound()); } //Calculate delivery price double deliveryPrice; if (orderDto.Distance >= 0 && orderDto.Distance <= 10) { deliveryPrice = 2; } else { if (orderDto.Distance > 10 && orderDto.Distance <= 25) { deliveryPrice = 5; } else { deliveryPrice = 10; } } var cartProducts = cartProductService.GetCartProducts(orderDto.ClientId); double totalPrice = 0; foreach (var prod in cartProducts) { var product = productService.GetProductById(prod.ProductId); if (product != null) { //The following code line wont work if the amount can't be converted to int totalPrice += Math.Floor(1000 * (product.Price * Convert.ToInt32(prod.Amount))) / 1000; } } var order = orderService.AddOrder(new Order { IdClient = client.Id, DeliveryPrice = deliveryPrice, OrderPrice = totalPrice, OrderTime = DateTime.Now, Status = EnumOrderStatus.Pending, WithBill = orderDto.WithBill }); foreach (var prod in cartProducts) { //Add each product that was in the cart to the table ProductOrder var product = productService.GetProductById(prod.ProductId); if (product != null) { var orderProduct = productOrderService.AddProduct(new ProductOrder { IdProduct = product.Id, Amount = prod.Amount, IdOrder = order.Id }); } } //Empty the client cart cartProductService.RemoveAllProducts(client.Id); //Send email to admins var admin = adminService.GetAdminByEmail("*****@*****.**"); if (admin != null) { var msg = "<span>Bonjour <strong>" + admin.FirstName + " " + admin.LastName + "</strong>,</span>" + "<br />" + "<p>Une nouvelle commande a été enregistrée.</p>" + "<p>Connectez-vous à l'application pour avoir plus de détails en cliquant <a href='https://localhost:44352/Order/PendingOrders'>ici</a></p>"; emailSenderService.SendEmail(admin.Email, "Nouvelle commande", msg); } return(Ok(order)); }
//https://localhost:44348/api/service/sendemail public async Task <IActionResult> SendEmail(EmailMessageDTO emailMessageDTO) { await _emailSenderService.SendEmail(emailMessageDTO); return(Ok()); }
public async Task <JsonResult> UpdateAccountIdentity(AccountIdentityVM identity) { _logger.LogInformation("AccountController.UpdateAccountIdentity - hidrogenianId=" + identity.Id); var validation = await _reCaptchaService.IsHumanRegistration(identity.CaptchaToken); if (!validation.Result) { return(new JsonResult(validation)); } var verification = VerifyIdentityData(identity); if (verification.Count != 0) { var messages = identity.GenerateErrorMessages(verification); return(new JsonResult(new { Result = RESULTS.FAILED, Message = messages })); } var(key, value) = await _accountService.UpdateIdentityForHidrogenian(identity); if (!key) { return(new JsonResult(new { Result = RESULTS.FAILED, Message = "Account not found with the given data. Please try again." })); } if (value == null) { return(new JsonResult(new { Result = RESULTS.FAILED, Message = "An error occurred while attempting to update your account. Please try again." })); } var oldIdentity = value.Value.Key; var newIdentity = value.Value.Value; var hidrogenian = new HidrogenianVM { Id = newIdentity.Id, Token = _authService.GenerateRandomToken() }; if (!newIdentity.EmailConfirmed) { if (await _userService.SetAccountConfirmationToken(hidrogenian)) { var profile = await _profileService.GetPublicProfileFor(newIdentity.Id); string emailTemplate; using (var reader = File.OpenText(PROJECT_FOLDER + @"HtmlTemplates/EmailChanged.html")) { emailTemplate = await reader.ReadToEndAsync(); }; emailTemplate = emailTemplate.Replace("[HidrogenianName]", profile.FullName); emailTemplate = emailTemplate.Replace("[HidrogenianEmail]", newIdentity.Email); emailTemplate = emailTemplate.Replace("[CONFIRM-TOKEN]", hidrogenian.Token); var emailChangedEmail = new EmailParamVM { ReceiverName = profile.FullName, ReceiverAddress = hidrogenian.Email, Subject = "Hidrogen - Confirm your email", Body = emailTemplate }; if (await _emailService.SendEmail(emailChangedEmail)) { await _accountService.ReverseIdentityChanges(oldIdentity); return(new JsonResult(new { Result = RESULTS.INTERRUPTED, Message = "The confirmation email was failed to send. Your changes was not applied. Please try again." })); } } } if (!string.IsNullOrEmpty(newIdentity.PhoneNumber) && !newIdentity.PhoneConfirmed) { //Send SMS to confirm phone number } return(new JsonResult(new { Result = RESULTS.SUCCESS, Message = newIdentity })); }