public override Task <WelcomeReply> SayWelcome(WelcomeRequest request, ServerCallContext context) { return(Task.FromResult(new WelcomeReply { Message = "WELCOME TO gRPC " + request.Name })); }
public async Task SendWelcomeEmailAsync(WelcomeRequest request, string emaildapessoa) { string FilePath = Directory.GetCurrentDirectory() + "\\HTML\\WelcomeTemplate.html"; StreamReader str = new StreamReader(FilePath); string MailText = str.ReadToEnd(); request.ToEmail = emaildapessoa; str.Close(); MailText = MailText.Replace("[email]", request.ToEmail); var email = new MimeMessage(); email.Sender = MailboxAddress.Parse(_mailSettings.Mail); email.To.Add(MailboxAddress.Parse(request.ToEmail)); email.Subject = "Seja bem-vindo(a) a melhor rede de clínicas médicas de SP."; var builder = new BodyBuilder(); builder.HtmlBody = MailText; email.Body = builder.ToMessageBody(); using var smtp = new SmtpClient(); smtp.Connect(_mailSettings.Host, _mailSettings.Port, SecureSocketOptions.StartTls); smtp.Authenticate(_mailSettings.Mail, _mailSettings.Password); await smtp.SendAsync(email); smtp.Disconnect(true); }
public async Task SendWelcomeEmailAsync(WelcomeRequest request, string confirmAccountLink, string toEmail, string firstName) { string FilePath = Directory.GetCurrentDirectory() + "\\Areas\\Identity\\Pages\\Account\\EmailTemplates\\RegistrationConfirmationEmail.html"; StreamReader str = new StreamReader(FilePath); string MailText = str.ReadToEnd(); str.Close(); // below line replaces all the html content inside the WelcomeEmail.cshtml, using Replace.[whatever is inside this], isReplacedWithThis MailText = MailText.Replace("[firstname]", firstName).Replace("[email]", toEmail).Replace("[confirm account link]", confirmAccountLink); MailMessage message = new MailMessage(); SmtpClient smtp = new SmtpClient(); message.From = new MailAddress(_mailSettings.Mail, _mailSettings.DisplayName); message.To.Add(new MailAddress(toEmail)); message.Subject = $"Please confirm your email {firstName}"; message.IsBodyHtml = true; message.Body = MailText; smtp.Port = _mailSettings.Port; smtp.Host = _mailSettings.Host; smtp.EnableSsl = true; smtp.UseDefaultCredentials = false; smtp.Credentials = new NetworkCredential(_mailSettings.Mail, _mailSettings.Password); smtp.DeliveryMethod = SmtpDeliveryMethod.Network; await smtp.SendMailAsync(message); }
private async Task <MimeMessage> CreateWelcomeMimeMessage(WelcomeRequest request) { var filePath = Directory.GetCurrentDirectory() + "\\Templates\\WelcomeTemplate.html"; StreamReader streamReader = new (filePath); var mailText = streamReader.ReadToEnd(); streamReader.Close(); mailText = mailText.Replace("[username]", request.UserName).Replace("[email]", request.ToEmail); var email = new MimeMessage { Sender = MailboxAddress.Parse(_mailSettings.Mail) }; email.To.Add(MailboxAddress.Parse(request.ToEmail)); email.Subject = $"Welcome {request.UserName}"; var builder = new BodyBuilder { HtmlBody = mailText }; email.Body = builder.ToMessageBody(); return(email); }
public async Task SendWelcomeEmailAsync(WelcomeRequest request) { // var host = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}"; string FilePath = Directory.GetCurrentDirectory() + "\\Templates\\WelcomeTemplate.html"; StreamReader str = new StreamReader(FilePath); string MailText = str.ReadToEnd(); str.Close(); MailText = MailText .Replace("[username]", request.UserName) .Replace("[email]", request.ToEmail) .Replace("[password]", request.Password) .Replace("[host]", request.Host); var email = new MimeMessage(); email.Sender = MailboxAddress.Parse(_mailSettings.Mail); email.To.Add(MailboxAddress.Parse(request.ToEmail)); email.Subject = $"ระบบตรวจราชการอิเล็กทรอนิกส์"; // email.Subject = $"Welcome {request.UserName}"; var builder = new BodyBuilder(); builder.HtmlBody = MailText; email.Body = builder.ToMessageBody(); using var smtp = new SmtpClient(); smtp.Connect(_mailSettings.Host, _mailSettings.Port, SecureSocketOptions.StartTls); smtp.Authenticate(_mailSettings.Mail, _mailSettings.Password); await smtp.SendAsync(email); smtp.Disconnect(true); }
// this is a conditional appearance when user goes to profile when he is not verified public async Task <IActionResult> OnPostSendVerificationEmailAsync([FromForm] WelcomeRequest request) { var user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } if (!ModelState.IsValid) { await LoadAsync(user); return(Page()); } var userId = await _userManager.GetUserIdAsync(user); var email = await _userManager.GetEmailAsync(user); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = userId, code = code }, protocol: Request.Scheme); await _mailService.SendWelcomeEmailAsync(request, HtmlEncoder.Default.Encode(callbackUrl), user.Email, user.FirstName); StatusMessage = "Verification email sent. Please check your email."; return(RedirectToPage()); }
private WelcomeAnswer ProcessWelcome(WelcomeRequest welcomeRequest) { var welcomeAnswer = new WelcomeAnswer(); welcomeAnswer.ClientName = player.GetType().Name.ToString() + "_" + Dns.GetHostName(); return(welcomeAnswer); }
public async Task SendRoutineOrderConfirmationEmail(WelcomeRequest request, string toEmail, string firstName, DateTime orderDate, Guid?orderNumber, string productName, decimal price, int quantity, PersonalTraining.SessionType sessionType, int lengthOfRoutine, PersonalTraining.Difficulty experienceLevel) { string FilePath = Directory.GetCurrentDirectory() + "\\Areas\\Identity\\Pages\\Account\\EmailTemplates\\OrderConfirmation.html"; StreamReader str = new StreamReader(FilePath); string MailText = str.ReadToEnd(); str.Close(); // below line replaces all the html content inside the WelcomeEmail.cshtml, using Replace.[whatever is inside this], isReplacedWithThis MailText = MailText.Replace("[firstname]", firstName).Replace("[email]", toEmail).Replace("[orderdate]", orderDate.ToString()) .Replace("[ordernumber]", orderNumber.ToString()).Replace("[productname]", productName).Replace("[price]", price.ToString()) .Replace("[quantity]", quantity.ToString()).Replace("[sessiontype]", sessionType.ToString()).Replace("[lengthofroutine]", lengthOfRoutine.ToString()).Replace("[experiencelevel]", experienceLevel.ToString()); // Finish later MailMessage message = new MailMessage(); SmtpClient smtp = new SmtpClient(); message.From = new MailAddress(_mailSettings.Mail, _mailSettings.DisplayName); message.To.Add(new MailAddress(toEmail)); message.Subject = $"TroydonFitness - Order Confirmation {firstName}"; message.IsBodyHtml = true; message.Body = MailText; smtp.Port = _mailSettings.Port; smtp.Host = _mailSettings.Host; smtp.EnableSsl = true; smtp.UseDefaultCredentials = false; smtp.Credentials = new NetworkCredential(_mailSettings.Mail, _mailSettings.Password); smtp.DeliveryMethod = SmtpDeliveryMethod.Network; await smtp.SendMailAsync(message); }
public async Task SendWelcomeEmailAsync(WelcomeRequest request) { string FilePath = Directory.GetCurrentDirectory() + "\\Templates\\WelcomeTemplate.html"; StreamReader str = new StreamReader(FilePath); string MailText = str.ReadToEnd(); str.Close(); MailText = MailText.Replace("[username]", request.UserName).Replace("[email]", request.ToEmail); var email = new MimeMessage(); email.From.Add(new MailboxAddress("Product Store Administration", _mailSettings.Mail)); email.To.Add(new MailboxAddress("", request.ToEmail)); email.Subject = $"Welcome {request.UserName}"; var builder = new BodyBuilder(); builder.HtmlBody = MailText; email.Body = builder.ToMessageBody(); using (var smtp = new SmtpClient()) { await smtp.ConnectAsync(_mailSettings.Host, _mailSettings.Port, false); await smtp.AuthenticateAsync(_mailSettings.Mail, _mailSettings.Password); await smtp.SendAsync(email); await smtp.DisconnectAsync(true); } }
public async Task <IActionResult> OnPostAsync([FromForm] WelcomeRequest request, string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); if (ModelState.IsValid) { var user = new TroydonFitnessWebsiteUser { UserName = Input.Email, Email = Input.Email, FirstName = Input.FirstName, LastName = Input.LastName, AddressLine1 = "N/A", IsAdmin = Input.IsAdmin, IsMasterAdmin = Input.IsMasterAdmin, CoolOffDate = System.DateTime.Now }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl }, protocol: Request.Scheme); // SEND WELCOME CONFIRMATION EMAIL await _mailService.SendWelcomeEmailAsync(request, HtmlEncoder.Default.Encode(callbackUrl), Input.Email, Input.FirstName); // send to require confirmation page if its enabled if (_userManager.Options.SignIn.RequireConfirmedAccount) { return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl })); } // otherwise sign in else { await _signInManager.SignInAsync(user, isPersistent : false); return(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return(Page()); }
private void SendWelcomeEmail(string email, string recipient) { WelcomeRequest request = new WelcomeRequest() { ToEmail = email, UserName = recipient }; _mailService.SendWelcomeEmailAsync(request); }
public async Task <IActionResult> SendWelcomeMail([FromForm] WelcomeRequest request) { try { await mailService.SendWelcomeEmailAsync(request); return(Ok()); } catch (Exception ex) { throw; } }
public async Task <IActionResult> SendWelcomeMail([FromForm] WelcomeRequest request) { try { await mailService.SendWelcomeEmailAsync(request); return(Ok()); } catch (Exception ex) { return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message)); } }
public async Task <IActionResult> OnPostChangeEmailAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } if (!ModelState.IsValid) { await LoadAsync(user); return(Page()); } var email = await _userManager.GetEmailAsync(user); if (Input.NewEmail != email) { var userId = await _userManager.GetUserIdAsync(user); var code = await _userManager.GenerateChangeEmailTokenAsync(user, Input.NewEmail); var callbackUrl = Url.Page( "/Account/ConfirmEmailChange", pageHandler: null, values: new { userId = userId, email = Input.NewEmail, code = code }, protocol: Request.Scheme); //await _emailSender.SendEmailAsync( // Input.NewEmail, // "Confirm your email", // $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); WelcomeRequest request = new WelcomeRequest { ToEmail = email, UserName = user.UserName, }; await _emailSender.SendVerifiedEmailAsync(request, HtmlEncoder.Default.Encode(callbackUrl), true); StatusMessage = "Confirmation link to change email sent. Please check your email."; return(RedirectToPage()); } StatusMessage = "Your email is unchanged."; return(RedirectToPage()); }
private void ProcessConnection(object param) { try { TcpClient tcpClient = param as TcpClient; Log("Connected: " + tcpClient.Client.RemoteEndPoint); // Get a stream object for reading and writing NetworkStream stream = tcpClient.GetStream(); ClientInfo client = new ClientInfo(); client.reader = new StreamReader(stream, Encoding.UTF8); client.writer = new StreamWriter(stream, Encoding.UTF8); client.writer.AutoFlush = true; client.TcpClient = tcpClient; WelcomeRequest welcome = new WelcomeRequest(); welcome.ServerId = serverId; welcome.DecisionTimeout = 60; var answer = client.Query(welcome) as WelcomeAnswer; client.ClientId = answer.ClientName; lock (ConnectedClients) { ConnectedClients.Add(client); } while (tcpClient.Connected && IsTerminated == false) { Thread.Sleep(TimeSpan.FromMilliseconds(10)); } Log("Disconnected"); lock (ConnectedClients) { ConnectedClients.Remove(client); } } catch (Exception exp) { Log("Error: " + exp.Message); } }
public async Task <IActionResult> SendWelcomeMail([FromForm] WelcomeRequest request) { request.ToEmail = "*****@*****.**"; request.UserName = "******"; try { await _mailService.SendWelcomeEmailAsync(request); _logger.LogInformation("Sending email... Correct."); return(RedirectToAction("SendWelcomeMail")); } catch (Exception ex) { _logger.LogWarning("Email doesn't send. Error: " + ex.Message); return(RedirectToAction("SendWelcomeMail")); } }
public async Task <IActionResult> OnPostSendVerificationEmailAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } if (!ModelState.IsValid) { await LoadAsync(user); return(Page()); } var userId = await _userManager.GetUserIdAsync(user); var email = await _userManager.GetEmailAsync(user); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = userId, code = code }, protocol: Request.Scheme); WelcomeRequest request = new WelcomeRequest { ToEmail = email, UserName = user.UserName, }; await _emailSender.SendVerifiedEmailAsync(request, HtmlEncoder.Default.Encode(callbackUrl), true); //await _emailSender.SendEmailAsync( // email, // "Confirm your email", // $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); StatusMessage = "Verification email sent. Please check your email."; return(RedirectToPage()); }
public async Task <IActionResult> SendMail2([FromForm] WelcomeRequest request) { try { var send = new WelcomeRequest { ToEmail = "*****@*****.**", UserName = "******" }; await mailService.SendWelcomeEmailAsync(request); return(Ok()); } catch (Exception ex) { throw ex; } }
public async Task <IActionResult> OnPostChangeEmailAsync([FromForm] WelcomeRequest request, string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); var user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } if (!ModelState.IsValid) { await LoadAsync(user); return(Page()); } var email = await _userManager.GetEmailAsync(user); if (Input.NewEmail != email) { var userId = await _userManager.GetUserIdAsync(user); var code = await _userManager.GenerateChangeEmailTokenAsync(user, Input.NewEmail); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmailChange", pageHandler: null, values: new { userId = userId, email = Input.NewEmail, code = code, returnUrl = returnUrl }, protocol: Request.Scheme); await _mailService.SendWelcomeEmailAsync(request, HtmlEncoder.Default.Encode(callbackUrl), Input.NewEmail, user.FirstName); StatusMessage = "Confirmation link to change email sent. Please check your email."; return(RedirectToPage()); } StatusMessage = "Your email is unchanged."; return(RedirectToPage()); }
public async Task <IActionResult> SendWelcomeMail([FromForm] WelcomeRequest request, string Token) { if (Token != _mailSettings.Token) { _logger.LogError("Unauthorised access attempt: " + request.ToEmail); return(Unauthorized("You need to be authorised to use this service!")); } try { _logger.LogInformation("Authorised Access"); _logger.LogInformation("Email sent to: " + request.ToEmail); await mailerService.SendWelcomeEmailAsync(request); return(Ok()); } catch (Exception ex) { _logger.LogError(ex, "Area connecting."); throw; } }
public async Task <IActionResult> OnPostAsync() { if (ModelState.IsValid) { var user = await _userManager.FindByEmailAsync(Input.Email); if (user == null || !(await _userManager.IsEmailConfirmedAsync(user))) { // Don't reveal that the user does not exist or is not confirmed return(RedirectToPage("./ForgotPasswordConfirmation")); } // For more information on how to enable account confirmation and password reset please // visit https://go.microsoft.com/fwlink/?LinkID=532713 var code = await _userManager.GeneratePasswordResetTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ResetPassword", pageHandler: null, values: new { area = "Identity", code }, protocol: Request.Scheme); WelcomeRequest request = new WelcomeRequest { ToEmail = user.Email, UserName = user.UserName, }; await _emailSender.SendVerifiedEmailAsync(request, HtmlEncoder.Default.Encode(callbackUrl), false); //await _emailSender.SendEmailAsync( // Input.Email, // "Reset Password", // $"Please reset your password by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); return(RedirectToPage("./ForgotPasswordConfirmation")); } return(Page()); }
public async Task SendVerifiedEmailAsync(WelcomeRequest request, string token, bool flag) { // If flag equal true, than this function used for Verification, else - for Forgot password string FilePath; if (flag) { FilePath = Directory.GetCurrentDirectory() + "\\wwwroot\\Templates\\VerifiedTemplate.html"; } else { FilePath = Directory.GetCurrentDirectory() + "\\wwwroot\\Templates\\ForgotPasswordTemplate.html"; } StreamReader str = new StreamReader(FilePath); string MailText = str.ReadToEnd(); str.Close(); MailText = MailText.Replace("[token]", token).Replace("[username]", request.UserName); var email = new MimeMessage(); email.From.Add(new MailboxAddress("Product Store Administration", _mailSettings.Mail)); email.To.Add(new MailboxAddress("", request.ToEmail)); email.Subject = $"Welcome {request.UserName}"; var builder = new BodyBuilder(); builder.HtmlBody = MailText; email.Body = builder.ToMessageBody(); using (var smtp = new SmtpClient()) { await smtp.ConnectAsync(_mailSettings.Host, _mailSettings.Port, false); await smtp.AuthenticateAsync(_mailSettings.Mail, _mailSettings.Password); await smtp.SendAsync(email); await smtp.DisconnectAsync(true); } }
public async Task SendWelcomeEmailAsync(WelcomeRequest request) { string FilePath = Directory.GetCurrentDirectory() + "\\Templates\\WelcomeTemplate.html"; StreamReader str = new StreamReader(FilePath); string MailText = str.ReadToEnd(); str.Close(); MailText = MailText.Replace("[username]", request.UserName).Replace("[email]", request.ToEmail); MailMessage message = new MailMessage(); SmtpClient smtp = new SmtpClient(); message.From = new MailAddress(_mailSettings.Mail, _mailSettings.DisplayName); message.To.Add(new MailAddress(request.ToEmail)); message.Subject = $"Welcome {request.UserName}"; message.IsBodyHtml = true; message.Body = MailText; smtp.Port = _mailSettings.Port; smtp.Host = _mailSettings.Host; smtp.EnableSsl = true; smtp.UseDefaultCredentials = false; smtp.Credentials = new NetworkCredential(_mailSettings.Mail, _mailSettings.Password); smtp.DeliveryMethod = SmtpDeliveryMethod.Network; await smtp.SendMailAsync(message); }
public IActionResult Post(Usuario Dados, [FromForm] WelcomeRequest request, string emaildapessoa) { try { Usuario usuarioBuscado = _UsuarioRepository.BuscarEmail(Dados.Email); if (usuarioBuscado == null) { _UsuarioRepository.Cadastrar(Dados); emaildapessoa = Dados.Email; _mailService.SendWelcomeEmailAsync(request, emaildapessoa); return(Created(HttpStatusCode.Created.ToString(), $"Usuário com o email {Dados.Email} cadastrados")); } return(BadRequest("E-mail existente")); } catch (Exception ex) { return(BadRequest(ex)); } }
public async Task SendWelcomeEmailAsync(WelcomeRequest request) { var welcomeEmail = await CreateWelcomeMimeMessage(request); await SendEmailAsync(welcomeEmail); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); if (ModelState.IsValid) { var user = new ApplicationUser { UserName = Input.UserName, Email = Input.Email, FirstName = Input.FirstName, LastName = Input.LastName, ProfilePicture = "/files/BasicUserPhoto.png", ImageUrl = "BasicUserPhoto.png" }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); string str = Enums.Roles.Basic.ToString(); await _userManager.AddToRoleAsync(user, str); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl }, protocol: Request.Scheme); WelcomeRequest request = new WelcomeRequest { ToEmail = user.Email, UserName = user.UserName }; await _emailSender.SendWelcomeEmailAsync(request); //await _emailSender.SendEmailAsync(Input.Email, "Confirm your email", // $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); if (_userManager.Options.SignIn.RequireConfirmedAccount) { return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl })); } else { await _signInManager.SignInAsync(user, isPersistent : false); return(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return(Page()); }
public async Task <IActionResult> OnPostConfirmationAsync([FromForm] WelcomeRequest request, string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { ErrorMessage = "Error loading external login information during confirmation."; return(RedirectToPage("./Login", new { ReturnUrl = returnUrl })); } if (ModelState.IsValid) { var user = new TroydonFitnessWebsiteUser { UserName = Input.Email, Email = Input.Email, FirstName = Input.FirstName }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { // Begin add claims If they exist, add claims to the user for: // Given (first) name // Locale // Picture if (info.Principal.HasClaim(c => c.Type == JwtClaimTypes.GivenName)) { await _userManager.AddClaimAsync(user, info.Principal.FindFirst(JwtClaimTypes.GivenName)); } if (info.Principal.HasClaim(c => c.Type == JwtClaimTypes.FamilyName)) { await _userManager.AddClaimAsync(user, info.Principal.FindFirst(JwtClaimTypes.FamilyName)); } if (info.Principal.HasClaim(c => c.Type == "urn:google:locale")) { await _userManager.AddClaimAsync(user, info.Principal.FindFirst("urn:google:locale")); } if (info.Principal.HasClaim(c => c.Type == "urn:google:picture")) { await _userManager.AddClaimAsync(user, info.Principal.FindFirst("urn:google:picture")); } // Include the access token in the properties var props = new AuthenticationProperties(); props.StoreTokens(info.AuthenticationTokens); props.IsPersistent = true; // end _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider); // this section allows email confirmation by clicking a link var userId = await _userManager.GetUserIdAsync(user); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = userId, code = code }, protocol: Request.Scheme); // SEND WELCOME CONFIRMATION EMAIL --- it is not getting the secret values? await _mailService.SendWelcomeEmailAsync(request, HtmlEncoder.Default.Encode(callbackUrl), Input.Email, Input.FirstName); // If account confirmation is required, we need to show the link if we don't have a real email sender if (_userManager.Options.SignIn.RequireConfirmedAccount) { return(RedirectToPage("./RegisterConfirmation", new { Email = Input.Email })); } await _signInManager.SignInAsync(user, props); //await _signInManager.SignInAsync((user, props, isPersistent: false, info.LoginProvider); return(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } ProviderDisplayName = info.ProviderDisplayName; ReturnUrl = returnUrl; return(Page()); }
// try to delete all cart items when we submit a post button public async Task <IActionResult> OnPostAsync(int?id, [FromForm] WelcomeRequest request) { var user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.")); } // create the order -- TODO Try to automatically populate user details so we can link the cart items to a specific user info, but allow edit fields (may need to inject usermanager) if (!ModelState.IsValid) { return(Page()); } CartItemsToOrder = await _context.CartItems .Where(currentCustomer => currentCustomer.PurchaserID == user.Id) // only create orders from what is in your cart .Include(o => o.Diet) .ThenInclude(pt => pt.PersonalTrainingSession) .ThenInclude(p => p.Product) .Include(o => o.Supplement) .ThenInclude(p => p.Product) .Include(o => o.TrainingEquipment) .ThenInclude(o => o.Product) .Include(o => o.TrainingRoutine) .ThenInclude(pt => pt.PersonalTrainingSession) .ThenInclude(p => p.Product) .ToListAsync(); int numberOfItemsInOrder = 0; var emptyOrder = new Order(); // TODO: See if i can redirect to newly created order using View Models or var entry = _context.Add(emptyOrder); foreach (var item in CartItemsToOrder) { // if there are items in cart if (item.CartID != 0) { // for each item that is numberOfItemsInOrder++; // if the cart is not empty and training routine is not null then take the training routine branch to extract data if (item.TrainingRoutineID != null) { OrderVM.Price = (decimal)item.TrainingRoutine.PersonalTrainingSession.Product.Price; OrderVM.Quantity = item.Quantity; OrderVM.TrainingRoutine = item.TrainingRoutine; OrderVM.TrainingRoutineID = item.TrainingRoutineID; } else if (item.DietID != null) { OrderVM.Diet = item.Diet; OrderVM.DietID = item.Diet.DietID; OrderVM.ProductName = item.Diet.PersonalTrainingSession.Product.Title; OrderVM.Price = (decimal)item.Diet.PersonalTrainingSession.Product.Price; OrderVM.Quantity = item.Quantity; } } } #region MyRegion // List<OrderVM> OrderVMList = new List<OrderVM>(); // to hold list of Customer and order details //// may need to look into making orderList of training routine and order list of others //var orderList = (from orders in _context.TrainingRoutines // join cart in _context.CartItems on orders.TrainingRoutineID equals cart.TrainingRoutineID // select new // here we select the data from relevant parts of the database // { // // All Ids // cart.TrainingRoutineID, // cart.PersonalTrainingSession.PersonalTrainingID, // cart.DietID, // cart.TrainingEquipmentID, // cart.SupplementID, // cart.PersonalTrainingSession.ProductID, // // from product // cart.PersonalTrainingSession.Product.Price, // cart.PersonalTrainingSession.Product.HasStock, // // from personal training // cart.PersonalTrainingSession.PTSessionType, // cart.PersonalTrainingSession.LengthOfRoutine, // cart.PersonalTrainingSession.ExperienceLevel, // // from training routine // cart.TrainingRoutine.Comments, // cart.TrainingRoutine.RoutineName, // // from diet // cart.Diet.Allergies, // // TODO: Remaining items later // // from cart // cart.PurchaserID, // cart.Quantity // TODO: transfer data into cart so we can see product details like we can see in training routine, or even do the same here // }) // .ToList(); //OrderVM objcvm = new OrderVM(); // ViewModel ////query getting data from database from joining two tables and storing data in customerlist //foreach (var item in orderList) //{ // objcvm.ProductName = item.RoutineName; // objcvm.Price = item.Price; // objcvm.Quantity = item.Quantity; // OrderVMList.Add(objcvm); //} #endregion // Now copy users details OrderVM.LastName = user.LastName; OrderVM.Email = user.Email; if (user.AddressLine1 != null) { OrderVM.AddressLine1 = user.AddressLine1; } else { OrderVM.AddressLine1 = string.Empty; } OrderVM.AddressLine2 = user.AddressLine2; OrderVM.City = user.City; OrderVM.State = user.State; OrderVM.Zip = user.Zip; OrderVM.State = user.State; OrderVM.PurchaserID = user.Id; OrderVM.NumberOfItemsOrdered = numberOfItemsInOrder; entry.CurrentValues.SetValues(OrderVM); await _context.SaveChangesAsync(); // pull out the order just created var orderCreated = _context.Orders.OrderByDescending(o => o.OrderID).FirstOrDefault(); // now add the ordered items into the order details table if (CartItemsToOrder != null) { numberOfItemsInOrder = 0; // now add all the items in the cart foreach (var item in CartItemsToOrder) { // if item being copied is of training routine if (item.TrainingRoutineID != null) { var emptyOrderDetail = new OrderDetail(); var entry2 = _context.Add(emptyOrderDetail); numberOfItemsInOrder++; OrderDetailVM.CurrentOrderItemNumber = numberOfItemsInOrder; // copy the order that was just created above, and assign to the order details table OrderDetailVM.OrderID = orderCreated.OrderID; OrderDetailVM.OrderDate = orderCreated.OrderDate; OrderDetailVM.PurchaserID = orderCreated.PurchaserID; OrderDetailVM.OrderNumber = Guid.NewGuid(); // now copy cart items // copy the order created to the order details OrderDetailVM.ProductID = CartItemsToOrder.FirstOrDefault().TrainingRoutine.PersonalTrainingSession.ProductID; OrderDetailVM.TrainingRoutineID = CartItemsToOrder.FirstOrDefault().TrainingRoutineID; OrderDetailVM.ProductName = CartItemsToOrder.FirstOrDefault().TrainingRoutine.PersonalTrainingSession.Product.Title; OrderDetailVM.Price = (decimal)CartItemsToOrder.FirstOrDefault().TrainingRoutine.PersonalTrainingSession.Product.Price; OrderDetailVM.Quantity = CartItemsToOrder.FirstOrDefault().Quantity; // explicitly cast to decimal from type nullable decimal? OrderDetailVM.PTSessionType = CartItemsToOrder.FirstOrDefault().TrainingRoutine.PersonalTrainingSession.PTSessionType; OrderDetailVM.LengthOfRoutine = CartItemsToOrder.FirstOrDefault().TrainingRoutine.PersonalTrainingSession.LengthOfRoutine; OrderDetailVM.ExperienceLevel = CartItemsToOrder.FirstOrDefault().TrainingRoutine.PersonalTrainingSession.ExperienceLevel; entry2.CurrentValues.SetValues(OrderDetailVM); await _context.SaveChangesAsync(); // email the order details await _mailService.SendRoutineOrderConfirmationEmail(request, user.Email, user.FirstName, OrderDetailVM.OrderDate, OrderDetailVM.OrderNumber, OrderDetailVM.ProductName, OrderDetailVM.Price, OrderDetailVM.Quantity, OrderDetailVM.PTSessionType, OrderDetailVM.LengthOfRoutine, OrderDetailVM.ExperienceLevel); } } // now delete everything in the cart _context.CartItems.RemoveRange(CartItemsToOrder); await _context.SaveChangesAsync(); } // sets the new ID to the order just created, by arranging all order items in the db by descending and querying the first one var newId = _context.OrderDetails.Where(o => o.OrderDetailID > 0).OrderByDescending(o => o.OrderID).FirstOrDefault().OrderDetailID; // redirect to the order that was just created, using the ID return(newId > 0 ? RedirectToPage("./OrderDetail", new { id = newId }) : RedirectToPage("./Orders")); // return RedirectToPage("./OrderDetail"); }