public UsersController(MyContext myContext, SendEmailService sendEmailService, IConfiguration configuration, TokenService tokenService) { this.myContext = myContext; this.sendEmailService = sendEmailService; this.configuration = configuration; this.tokenService = tokenService; }
public JsonResult EmailInvoice(int id, string email) { try { var model = GetInvoiceBalanceModel(id); var fileName = string.Format("Invoice_{0}_{1}.pdf", model.Invoice.Id, model.Invoice.Date.ToString("MM-dd-yyyy")); var client = db.Clients.FirstOrDefault(c => c.Id == model.Invoice.Client.Id); var invoiceService = new InvoiceService(); var viewAsPef = new ViewAsPdf("~/Views/Sales/Print.cshtml", model) { FileName = fileName, PageSize = Size.Letter, PageOrientation = Orientation.Portrait, PageMargins = { Left = 1, Right = 1 } }; byte[] bytesPDFData = viewAsPef.BuildPdf(ControllerContext); var stream = new MemoryStream(bytesPDFData); var emailService = new SendEmailService(db); client.Email = email; emailService.SendInvoiceToClient(model.Invoice, client, stream, fileName); return(Json(new { Result = true, Data = new { ClientId = client.Id }, Message = "The Invoice has send" })); } catch (Exception ex) { return(Json(new { Result = false, Message = ex.Message })); } }
/// <summary> /// This method sends an automated e-mail /// </summary> /// <param name="user">Userprofile of user who mail will be sent to</param> /// <param name="token">Generated encrypted token</param> /// <param name="config">E-mailconfiguration from appsettings.json</param> public static void SendPasswordForgottenEmail(ProfileDatum user, string token, IConfiguration config) { SendEmailConfiguration mailConfiguration = SendEmailConfiguration.GetEmailConfiguration(config); System.Text.StringBuilder mailcontent = new System.Text.StringBuilder(); mailcontent.Append("<img src='https://www.ruilwinkelvaals.nl/ruilwinkelvaals.nl/images/ruilwinkel/logo_ruilwinkel_vaalsWEB.jpg'style='width:20%; height:10%;'>"); mailcontent.Append("<br />"); mailcontent.Append("<br />"); mailcontent.Append(String.Format("<p>Beste {0},</p>", user.Voornaam)); mailcontent.Append(String.Format("<p>Wat vervelend dat u uw wachtwoord vergeten bent.</p>")); mailcontent.Append(String.Format("<p>Via de onderstaande link kunt u uw wachtwoord weer herstellen.</p>")); mailcontent.Append(String.Format("<p><em>Deze link is 60 minuten geldig. Bij een ongeldige link kunt u onze <a href='https://ruilwinkelvaalscore.azurewebsites.net/ForgotPassword/ForgotPassword'>wachtwoord herstelpagina</a> bezoeken om een nieuwe herstellink te ontvangen.</em></p>")); mailcontent.Append(String.Format("<p><a style='background-color:#8b0000; display:inline-block; color:white; padding:8px 16px; margin:8px 0px;border:none;cursor:pointer;border-radius:8px;font-size:12px;text-transform:uppercase;font-family:Helvetica;' href='https://ruilwinkelvaalscore.azurewebsites.net/ForgotPassword/ResetPassword?email={0}&token={1}'>Reset wachtwoord</a></p>", user.Email, token)); mailcontent.Append(String.Format("<br />")); mailcontent.Append(String.Format("<p><em>Heeft u deze email ontvangen terwijl u uw wachtwoord niet wilt herstellen? Neem dan contact met ons op via het telefoonnummer +31 6 20 74 98 86</em></p>")); mailcontent.Append(String.Format("<p>Met vriendelijke groet,</p>")); mailcontent.Append(String.Format("<p>Ruilwinkel Vaals</p>")); EmailMessage emailMessage = new EmailMessage(); emailMessage.FromAddresses.Add(new EmailAddress("Ruilwinkel Vaals", "*****@*****.**")); emailMessage.subject = "Wachtwoord herstellen"; emailMessage.ToAddresses.Add(new EmailAddress(user.Voornaam + " " + user.Achternaam, user.Email)); emailMessage.content = mailcontent.ToString(); SendEmailService sendEmailService = new SendEmailService(mailConfiguration); sendEmailService.SendMessage(emailMessage); }
public IActionResult ForgotPassword(ForgotPasswordVM forgotPasswordVM) { var Email = forgotPasswordVM.Email; var Get = employeeRepository.GetAll(); var CheckLogin = Get.FirstOrDefault(e => e.Email == forgotPasswordVM.Email); if (CheckLogin != null) { Guid newPassword = Guid.NewGuid(); Account account = new Account { NIK = CheckLogin.NIK, Password = newPassword.ToString("N").Substring(0, 8) }; accountRepository.ChangePassword(CheckLogin.NIK, account.Password); SendEmailService.GantiPassword(Email, account.Password); return(Ok(new { status = HttpStatusCode.OK, message = "New Password Sent" })); } else { return(NotFound(new { status = HttpStatusCode.NotFound, message = "No account has this email" })); } }
public BookLogService(IBookLogRepository repo, IOptions <AppSettingsModel> options, SendEmailService send, IEmailRecipientRepository emails, IMapper mapper) { this._repo = repo; this._options = options; this._send = send; this._emails = emails; this._mapper = mapper; }
public async Task <bool> SendEmailAsync(string emailTaskId, ILambdaContext context) { var s3Client = new AmazonS3Client(); var sesClient = new AmazonSimpleEmailServiceClient(); var sendEmailService = new SendEmailService(s3Client, sesClient); return(await sendEmailService.SendEmailAsync(emailTaskId)); }
/// <summary>This method should send the message</summary> /// <param name="message"></param> /// <returns></returns> public Task SendAsync(IdentityMessage message) { // Plug in your email service here to send an email. var emailService = new SendEmailService(); emailService.SendEmail(message); return(Task.FromResult(0)); }
public async Task <IActionResult> AddMeToMailList(ClientProductPageViewModel vm) { var userId = this.User.FindFirst(ClaimTypes.NameIdentifier)?.Value; var currentUser = await _userManager.FindByIdAsync(userId); SendEmailService oneEmail = new SendEmailService(); await oneEmail.SendEmailAsync(vm.MailEmailAddress, "Join us Today", "Thanks you for join us"); return(Json(new { message = "Success" })); }
private void SendAlerts(string alertMessage) { try { string tigerReserveName = string.Empty; DataSet dsGetTigerReserveName = CheckListBAL.Instance.GetTigerReserveName(TigerReserverId); if (dsGetTigerReserveName != null) { DataRow dr2 = dsGetTigerReserveName.Tables[0].Rows[0]; if (dr2[0] != DBNull.Value) { tigerReserveName = Convert.ToString(dr2["TigerReserveName"]); } } int n = 0; string EmailAddress = string.Empty; string userName = string.Empty; Alert alert = new Alert(); DataSet dsEmail = UserBAL.Instance.GetAllNTCAUsersEmail(); List <string> Emailid = new List <string>(); for (int i = 0; i < dsEmail.Tables[2].Rows.Count; i++) { if (dsEmail != null) { DataRow dr = dsEmail.Tables[2].Rows[0]; if (dr[0] != DBNull.Value) { alert.UserId = Convert.ToInt32(dsEmail.Tables[2].Rows[i]["UserId"]); alert.SentTo = Convert.ToString(dsEmail.Tables[2].Rows[i]["UserName"]); EmailAddress = Convert.ToString(dsEmail.Tables[2].Rows[i]["Email"]); } } Emailid.Add(EmailAddress); alert.Subject = tigerReserveName + ", " + ConfigurationManager.AppSettings["TryingSubmitApoAfterDueDate"]; alert.Body = tigerReserveName + ", " + alertMessage; //Remove bellow hard coded APO title once we have APO in the database alert.APOTitle = "APO 1"; alert.LoggedInUser = AuthoProvider.User; n = AlertBAL.Instance.SendAlerts(alert); if (n != 0) { string subject = alert.Subject; string body = alert.Body; SendEmailService sendEmail = new SendEmailService(); sendEmail.SendEmails(Emailid, subject, body); } } } catch (Exception ex) { LogHandler.LogFatal((ex.InnerException != null ? ex.InnerException.Message : ex.Message), ex, this.GetType()); Response.RedirectPermanent("~/ErrorPage.aspx", false); } }
public async Task Should_Use_SendGrid_ToSendEmail() { // Arrange var sendEmailInfo = new SendEmailDto { Email = "*****@*****.**", Body = "Hello there", Subject = "Test Email", FromName = "My Company", ToName = "Test User" }; var options = Options.Create(new SendGridSettings() { Key = "testKey", FromEmail = "*****@*****.**", FromName = "Mike" }); var client = new SendGridClient(options.Value.Key); var message = new SendGridMessage(); var from = new EmailAddress(options.Value.FromEmail, options.Value.FromName); var to = new EmailAddress(sendEmailInfo.Email, sendEmailInfo.ToName); var mockHttpContent = new Mock <HttpContent>(); var response = new Response(HttpStatusCode.OK, mockHttpContent.Object, null); var mockSendGridService = new Mock <ISendGridClientService>(); mockSendGridService.Setup(m => m.CreateToAddress(sendEmailInfo.Email, sendEmailInfo.ToName)) .Returns(to); mockSendGridService.Setup(m => m.CreateFromAddress()) .Returns(from); mockSendGridService.Setup(m => m.Create()).Returns(client); mockSendGridService.Setup(m => m.CreateSingleEmail(from, to, sendEmailInfo.Subject, sendEmailInfo.Body, sendEmailInfo.Body)).Returns(message); mockSendGridService.Setup(m => m.SendEmailAsync(message, client)).Returns(Task.FromResult(response)); var sut = new SendEmailService(mockSendGridService.Object); // Act await sut.SendAsync(sendEmailInfo.Email, sendEmailInfo.Subject, sendEmailInfo.Body, sendEmailInfo.ToName); // Assert mockSendGridService.Verify(m => m.SendEmailAsync(message, client), Times.Once); }
public async Task <IActionResult> ResetPasswordConfirmationPage(ResetPasswordModel model) { if (model != null) { var user = await UserManager.FindByEmailAsync(model.EmailAddress); if (user != null) { if (user.EmailConfirmed) { var token = await UserManager.GeneratePasswordResetTokenAsync(user); var url = Url.Action("ResetPassword", "Account", new { UserId = user.Id, Token = token }, Request.Scheme); await SendEmailService.SendEmail(new ServiceEmail { EmailHtmlText = $"<strong>Hello, {user.UserName}, here is your password reset link - {url}</strong>", EmailSubject = "Password reset", EmailText = $"Hello, {user.UserName}, here is your password reset link - {url}", FromEmail = "*****@*****.**", FromName = "Yevhen", ToEmail = user.Email, ToName = user.UserName }); Trace.WriteLine($"Email was send to customer {user.Id} - id"); } else { ModelState.AddModelError("", DefaultResponseMessages.EmailIsNotVerified); Trace.WriteLine($"Email was not verified for customer {user.Id} - id"); } } else { ModelState.AddModelError("", DefaultResponseMessages.CustomerIsNotFoundInDb); Trace.WriteLine($"Wrong login attempt for email {model.EmailAddress}"); } return(View("ResetPasswordConfirmationPage", model.EmailAddress)); } else { ModelState.AddModelError("", DefaultResponseMessages.EmailIsNotProvided); } return(View()); }
public void Should_Send_Email_To_Selected_People_And_Group() { //Arrange var peopleList = new List<Person> { new Person { Id = 1, Name = "Rafael", Email = "*****@*****.**" }, new Person() { Id = 2, Name = "Priscilla", Email = "*****@*****.**" } }; var developers = new List<Group> { new Group { Id = 1, Name = "Developers", Email = "*****@*****.**", Members = { new Person { Id = 3, Name = "Romulo", Email = "*****@*****.**" }, new Person { Id = 4, Name = "Lorena", Email = "*****@*****.**" } } } }; var sendEmail = new SendEmailService(new PersonRepositoryStub()); //Act sendEmail.Send(peopleList, developers); }
public async Task Should_HaveErrors_WhenRequiredInfo_NotProvided(string email, string subject, string body) { // Arrange var mockSendGridService = new Mock <ISendGridClientService>(); mockSendGridService.Setup(m => m.Status).Returns(new StatusGenericHandler()); var sut = new SendEmailService(mockSendGridService.Object); // Act await sut.SendAsync(email, subject, body); // Assert sut.Status.HasErrors.ShouldBeTrue(); }
private void SendAlertsOnSuccess(string alertMessage) { try { int n = 0; string EmailAddress = string.Empty; string userName = string.Empty; Alert alert = new Alert(); DataSet dsEmail = UserBAL.Instance.GetAllNTCAUsersEmail(TigerReserverId); for (int index = 0; index <= dsEmail.Tables.Count; index++) { List <string> Emailid = new List <string>(); for (int i = 0; i < dsEmail.Tables[index].Rows.Count; i++) { if (dsEmail != null) { DataRow dr = dsEmail.Tables[1].Rows[0]; if (dr[0] != DBNull.Value) { alert.UserId = Convert.ToInt32(dsEmail.Tables[1].Rows[i]["UserId"]); alert.SentTo = Convert.ToString(dsEmail.Tables[1].Rows[i]["UserName"]); EmailAddress = Convert.ToString(dsEmail.Tables[1].Rows[i]["Email"]); } } Emailid.Add(EmailAddress); alert.Subject = ConfigurationManager.AppSettings["AlertSubject"]; alert.Body = alertMessage; alert.LoggedInUser = ConfigurationManager.AppSettings["AlertSentBy"]; n = AlertBAL.Instance.SendAlerts(alert); if (n != 0) { string subject = alert.Subject; string body = alert.Body; SendEmailService sendEmail = new SendEmailService(); sendEmail.SendEmails(Emailid, subject, body); } } } } catch (Exception ex) { return; } }
public ActionResult Contact(ContactSubmit cSubmit) { if (ModelState.IsValid) { cSubmit.SubmitDate = DateTime.Now; db.ContactSubmits.Add(cSubmit); db.SaveChanges(); if (!System.Web.HttpContext.Current.IsDebuggingEnabled) { SendEmailService es = new SendEmailService(); es.SendOneEmail(cSubmit.Email, "*****@*****.**", "Kingsley.io - Contact Form Submission", cSubmit.Name + " (" + cSubmit.Email + ") has submited the contact form on Kingsley.io. <br /><br /><strong>Message:</strong><br />" + cSubmit.Message, true); } } return(PartialView("_ContactThanks")); }
private void SendAlerts() { try { //int userId = Convert.ToInt32(ddlName.SelectedValue); int n = 0; string EmailAddress = string.Empty; string userName = string.Empty; Alert alert = new Alert(); string userIds = mChkName.SelectedValueList; string userNames = mChkName.SelectedTextListForDB.Replace("'", ""); DataSet dsEmail = AlertBAL.Instance.GetMultipleEmailAddress(userIds); List <string> Emailid = new List <string>(); for (int i = 0; i < dsEmail.Tables[0].Rows.Count; i++) { string[] userId = userIds.Split(','); EmailAddress = Convert.ToString(dsEmail.Tables[0].Rows[i]["Email"]); Emailid.Add(EmailAddress); string[] recipiantName = userNames.Split(','); //userName = Convert.ToString(dsEmail.Tables[0].Rows[i]["UserName"]); alert.UserId = Convert.ToInt32(userId[i]); alert.SentTo = recipiantName[i].ToString(); alert.Subject = txtSubject.Text; alert.Body = txtComments.Text; //Remove bellow hard coded APO title once we have APO in the database alert.APOTitle = "APO 1"; alert.LoggedInUser = AuthoProvider.User; n = AlertBAL.Instance.SendAlerts(alert); } if (n != 0) { //List<string> Emailid = new List<string>(); //Emailid.Add(EmailAddress); string subject = alert.Subject; string body = alert.Body; SendEmailService sendEmail = new SendEmailService(); sendEmail.SendEmails(Emailid, subject, body); } } catch (Exception ex) { LogHandler.LogFatal((ex.InnerException != null ? ex.InnerException.Message : ex.Message), ex, this.GetType()); Response.RedirectPermanent("~/ErrorPage.aspx", false); } }
public Result SendEmail(MailAddress from, List <MailAddress> lTo, string subject, string body, IEnumerable <Attachment> lAttachFiles, bool isHtml = true) { try { if (from == null || string.IsNullOrEmpty(from.Address)) { from = new MailAddress(ConfigurationManager.AppSettings["RMS.KTB.SMTP.From"]); } if (string.IsNullOrEmpty(from.Address)) { throw new ArgumentNullException("from", "Please check database and Web.config > appSettings > RMS.KTB.SMTP.From "); } if (isHtml) { body = body.Replace(Environment.NewLine, "<br/>"); } var emailService = new SendEmailService(); var result = emailService.SendEmail(@from, lTo, subject, body, lAttachFiles, isHtml); if (result.IsSuccess) { return(new Result { IsSuccess = true }); } else { return(new Result { IsSuccess = false, ErrorMessage = result.ErrorMessage }); } } catch (Exception ex) { return(new Result { IsSuccess = false, ErrorMessage = ex.Message }); } }
public UsuariosController(IUsuarioRepository usuarioRepository, ITipoUsuarioRepository tipoUsuarioRepository, IEmpresaRepository empresaRepository, IUsuarioEmpresaRepository usuarioEmpresaRepository, IEnderecoRepository enderecoRepository, ITipoEmpresaRepository tipoEmpresaRepository, ITipoAtividadeCnaeRepository tipoAtividadeCnaeRepository, IAlterarCredenciaisRepository alterarCredenciaisRepository, IAlunoRepository alunoRepository, IUsuarioCandidatoAlunoRepository usuarioCandidatoAlunoRepository, IValidacaoUsuarioCandidatoRepository validacaoUsuarioCandidatoRepository, IUsuarioAdministradorRepository usuarioAdministradorRepository, IHistoricoStatusUsuarioRepository historicoStatusUsuarioRepository, IStatusUsuarioRepository statusUsuarioRepository) { _usuarioRepository = usuarioRepository; _tipoUsuarioRepository = tipoUsuarioRepository; _empresaRepository = empresaRepository; _usuarioEmpresaRepository = usuarioEmpresaRepository; _enderecoRepository = enderecoRepository; _tipoEmpresaRepository = tipoEmpresaRepository; _tipoAtividadeCnaeRepository = tipoAtividadeCnaeRepository; _alterarCredenciaisRepository = alterarCredenciaisRepository; _alunoRepository = alunoRepository; _usuarioCandidatoAlunoRepository = usuarioCandidatoAlunoRepository; _validacaoUsuarioCandidatoRepository = validacaoUsuarioCandidatoRepository; _usuarioAdministradorRepository = usuarioAdministradorRepository; _historicoStatusUsuarioRepository = historicoStatusUsuarioRepository; _statusUsuarioRepository = statusUsuarioRepository; apiRequestService = new ApiRequestService(); sendEmailService = new SendEmailService(); }
public void Should_Send_Email_To_Selected_People() { //Arrange var peopleList = new List<Person> { new Person { Id = 1, Name = "Rafael", Email = "*****@*****.**" }, new Person() { Id = 2, Name = "Priscilla", Email = "*****@*****.**" } }; var sendEmail = new SendEmailService(new PersonRepositoryStub()); //Act sendEmail.Send(peopleList); }
public void SendEmail() { var sendEmail = new SendEmailService(); sendEmail.Send(Email); }
public LoginController(UserService UserSvc, SendEmailService SendEmailSvc) { this.UserSvc = UserSvc; this.SendEmailSvc = SendEmailSvc; }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); //app.UseCors( // builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin()); app.UseSignalR( routes => { routes.MapHub <ChatHub>("/chat"); }); app.UseAuthentication(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } //app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseSpaStaticFiles(); app.UseSession(); #region InitStaticFiles Images string pathRoot = InitStaticFiles .CreateFolderServer(env, this.Configuration, new string[] { "ImagesPath" }); app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider(pathRoot), RequestPath = new PathString("/" + Configuration.GetValue <string>("ImagesUrl")) }); app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider(pathRoot), RequestPath = new PathString("/" + Configuration.GetValue <string>("ImagesHotelUrl")) }); #endregion ; if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), @"UserImages"))) { Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), @"UserImages")); } app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"UserImages")), RequestPath = new PathString("/UserImages") }); if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), @"Uploaded"))) { Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), @"Uploaded")); } app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), "Uploaded")), RequestPath = "/Uploaded" }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action=Index}/{id?}"); }); app.UseSpa(spa => { spa.Options.SourcePath = "ClientApp"; if (env.IsDevelopment()) { spa.UseReactDevelopmentServer(npmScript: "start"); } }); SeederDB.SeedDataByAS(app.ApplicationServices, env, this.Configuration); SendEmailService.SendInfoStartApp(Configuration, env); }
public TemperaturesController(IConfiguration myConfiguration, MyContext myContext, SendEmailService sendEmailService) { _configuration = myConfiguration; _context = myContext; _sendEmailService = sendEmailService; }
/// <summary> /// Method to perform login of the external customer /// </summary> /// <param name="returnUrl"></param> /// <param name="remoteError"></param> /// <returns></returns> public async Task <DefaultServiceResponse> ExternalLoginCallBack(string returnUrl = null, string remoteError = null) { var loginCallBackResult = new DefaultServiceResponse { ActionName = "Index", ControllerName = "HomePage", ResponseData = null, StatusCode = StatusCodesEnum.Ok, ValidationErrors = new List <string>() }; if (remoteError == null) { var accountDetailsFromProvider = await SignInManager.GetExternalLoginInfoAsync(); #region Check, that data is provided if (accountDetailsFromProvider != null) { // Search for the customer in our db var accountData = await UserManager.FindByEmailAsync(accountDetailsFromProvider.Principal.FindFirstValue(ClaimTypes.Email)); #region New account for our DB if (accountData == null) // new account { var serviceUser = new ServiceUser { Email = accountDetailsFromProvider.Principal.FindFirstValue(ClaimTypes.Email), UserName = accountDetailsFromProvider.Principal.FindFirstValue(ClaimTypes.GivenName) }; var userResponse = await UserManager.CreateAsync(serviceUser); #region Customer created without any error --> send him email to verify email and add password ( or not ) if (userResponse.Succeeded) { if (CheckIfWeHaveRole("User")) { await UserManager.AddToRoleAsync(serviceUser, "User"); } else { await RoleManager.CreateAsync(new IdentityRole { Id = new Guid().ToString(), Name = "User", NormalizedName = "USER" }); await UserManager.AddToRoleAsync(serviceUser, "User"); } var claims = CustomerContext.UserClaims.Select(x => x).ToList(); var newClaimId = claims.Count > 0 ? claims.Last().Id + 1 : 1; CustomerContext.UserClaims.Add(new IdentityUserClaim <string> { Id = newClaimId, ClaimType = "UploadPhoto", ClaimValue = "true", UserId = serviceUser.Id }); await CustomerContext.SaveChangesAsync(); await UserManager.AddLoginAsync(serviceUser, accountDetailsFromProvider); // Creates point in AspNetUserLogins var token = await UserManager.GenerateEmailConfirmationTokenAsync(serviceUser); var emailUrlConfirmation = UrlHelper.Action("ConfirmEmail", "Account", new { Token = token, UserId = serviceUser.Id }, Context.HttpContext.Request.Scheme); await SendEmailService.SendEmail(new ServiceEmail { FromEmail = "*****@*****.**", FromName = "Yevhen", ToEmail = serviceUser.Email, ToName = serviceUser.UserName, EmailSubject = "Thank you for register!!!", EmailHtmlText = $"<strong>Hello, {serviceUser.UserName}! Thank you for registering, please confirm your email using this link : {emailUrlConfirmation}</strong>", EmailText = $"Hello there! Thank you for registering, please confirm your email using this link : {emailUrlConfirmation}", }); loginCallBackResult.ActionName = "ConfirmPartnerRegister"; loginCallBackResult.ControllerName = "Registration"; loginCallBackResult.ResponseData = serviceUser.UserName; loginCallBackResult.StatusCode = StatusCodesEnum.RedirectNeeded; return(loginCallBackResult); } #endregion else { loginCallBackResult.ValidationErrors.Add(DefaultResponseMessages.ExternalLoginFailed); loginCallBackResult.StatusCode = StatusCodesEnum.BadDataProvided; return(loginCallBackResult); } } #endregion else { #region Customer already has account on our db, but email is not confirmed if (!accountData.EmailConfirmed) { var loginsData = await UserManager.GetLoginsAsync(accountData); if (loginsData == null) { await UserManager.AddLoginAsync(accountData, accountDetailsFromProvider); } var token = await UserManager.GenerateEmailConfirmationTokenAsync(accountData); var emailUrlConfirmation = UrlHelper.Action("ConfirmEmail", "Account", new { Token = token, UserId = accountData.Id }, Context.HttpContext.Request.Scheme); await SendEmailService.SendEmail(new ServiceEmail { FromEmail = "*****@*****.**", FromName = "Yevhen", ToEmail = accountData.Email, ToName = accountData.UserName, EmailSubject = "Thank you for register!!!", EmailHtmlText = $"<strong>Hello, {accountData.UserName}! Thank you for registering, please confirm your email using this link : {emailUrlConfirmation}</strong>", EmailText = $"Hello there! Thank you for registering, please confirm your email using this link : {emailUrlConfirmation}", }); loginCallBackResult.StatusCode = StatusCodesEnum.RedirectNeeded; loginCallBackResult.ResponseData = accountData.UserName; loginCallBackResult.ActionName = "ConfirmPartnerRegister"; loginCallBackResult.ControllerName = "Registration"; return(loginCallBackResult); } #endregion #region Email is confirmed but we need to check, that customer has row in ASPNETUSERLOGINS else { var loginReponse = await SignInManager.ExternalLoginSignInAsync(accountDetailsFromProvider.LoginProvider, accountDetailsFromProvider.ProviderKey, false); if (loginReponse.Succeeded) { loginCallBackResult.StatusCode = StatusCodesEnum.Ok; } else { await UserManager.AddLoginAsync(accountData, accountDetailsFromProvider); await SignInManager.SignInAsync(accountData, false); } loginCallBackResult.ActionName = "Index"; loginCallBackResult.ControllerName = "HomePage"; return(loginCallBackResult); } #endregion } } #endregion #region No data provided from external provider else { loginCallBackResult.ValidationErrors.Add(DefaultResponseMessages.ExternalLoginFailed); loginCallBackResult.StatusCode = StatusCodesEnum.BadDataProvided; return(loginCallBackResult); } #endregion } #region Error from external provider else { loginCallBackResult.ValidationErrors.Add(DefaultResponseMessages.ExternalLoginFailed); loginCallBackResult.StatusCode = StatusCodesEnum.RedirectNeeded; loginCallBackResult.ActionName = "Login"; loginCallBackResult.ControllerName = "Account"; return(loginCallBackResult); } #endregion }
/// <summary> /// Method to perform customer registration in case, that he provided correct data to us /// </summary> /// <returns></returns> public async Task <DefaultServiceResponse> CompleteRegistration(CustomerViewModel customer) { var responseCheckData = new DefaultServiceResponse { ActionName = "Index", ControllerName = "HomePage", ResponseData = null, StatusCode = StatusCodesEnum.BadDataProvided, ValidationErrors = new List <string>() }; var userSearchResult = await UserManager.FindByEmailAsync(customer.EmailAddress); if (userSearchResult == null) // customer has no data in our DB --> he can be registered { var user = new ServiceUser { Email = customer.EmailAddress, UserName = customer.FirstName }; var result = await UserManager.CreateAsync(user, customer.Password); if (result.Succeeded) // errors will be displayed on validation-summary { Logger.LogInformation($"Customer created, account data - {user.Email} - email, {user.UserName} - username"); if (CheckIfWeHaveRole("User")) { await UserManager.AddToRoleAsync(user, "User"); } else { await RoleManager.CreateAsync(new IdentityRole { Id = new Guid().ToString(), Name = "User" }); await UserManager.AddToRoleAsync(user, "User"); } Logger.LogInformation($"Roles added for the user - {user.UserName}"); var currentUser = await UserManager.FindByEmailAsync(user.Email); var claims = CustomerContext.UserClaims.Select(x => x).ToList(); var newClaimId = claims.Count > 0 ? claims.Last().Id + 1 : 1; CustomerContext.UserClaims.Add(new IdentityUserClaim <string> { Id = newClaimId, ClaimType = "UploadPhoto", ClaimValue = "true", UserId = currentUser.Id }); await CustomerContext.SaveChangesAsync(); Logger.LogInformation($"Claims added for the user - {user.UserName}"); var token = await UserManager.GenerateEmailConfirmationTokenAsync(currentUser); var emailUrlConfirmation = UrlHelper.Action("ConfirmEmail", "Account", new { Token = token, UserId = currentUser.Id }, Context.HttpContext.Request.Scheme); var response = await SendEmailService.SendEmail(new ServiceEmail //todo - add there logging to get the response about loggined customers { FromEmail = "*****@*****.**", FromName = "Yevhen", ToEmail = currentUser.Email, ToName = currentUser.UserName, EmailSubject = "Thank you for register!!!", EmailHtmlText = $"<strong>Hello there! Thank you for registering, please confirm your email using this link : {emailUrlConfirmation}</strong>", EmailText = $"Hello there! Thank you for registering, please confirm your email using this link : {emailUrlConfirmation}", }); responseCheckData.ResponseData = customer.FirstName; responseCheckData.ActionName = "ConfirmationPage"; responseCheckData.ControllerName = "Registration"; responseCheckData.StatusCode = StatusCodesEnum.RedirectNeeded; return(responseCheckData); } else { foreach (var error in result.Errors) { responseCheckData.ValidationErrors.Add(error.Description); } responseCheckData.StatusCode = StatusCodesEnum.BadDataProvided; return(responseCheckData); } } else { responseCheckData.ValidationErrors.Add(DefaultResponseMessages.AllreadyHasAccount); responseCheckData.StatusCode = StatusCodesEnum.BadDataProvided; return(responseCheckData); } }
public NotificationsSender() { this.emailSender = new SendEmailService(); }
public AccountRepository(MyContext myContext, SendEmailService sendEmailService, TokenService tokenService) { this._myContext = myContext; this._sendEmailService = sendEmailService; this._tokenService = tokenService; }
public UserController(UserService UserSvc, PostCommentService CommentSvc, PostService PostSvc, SendEmailService SendEmailSvc) { this.UserSvc = UserSvc; this.CommentSvc = CommentSvc; this.PostSvc = PostSvc; this.SendEmailSvc = SendEmailSvc; }
public RegisterController(UserService UserSvc, SendEmailService SendEmailSvc) { this.UserSvc = UserSvc; this.SendEmailSvc = SendEmailSvc; }
public void Visit(Person visitor) { var sendEmail = new SendEmailService(); sendEmail.Send(visitor); }
public void Visit(Person person) { var sendEmail = new SendEmailService(); sendEmail.Send(person); }